From 7003c5b9309f5e92c2f5b5fcb2e8b34be2840e22 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Tue, 13 Oct 2026 10:50:32 -0600 Subject: [PATCH 001/531] TEXTEDIT on an MTEXT opens it in the in-place editor (part of #842) Double-clicking an MTEXT (#868) starts TEXTEDIT, which only asked for the new text on the command line, with its formatting codes. Now TEXTEDIT on an MTEXT reports it as the text being edited, so the in-place editor (#792) opens on it with its text and formats; OK writes the edited contents back, and TEXTEDIT goes on asking for objects as before. An editor emptied while editing keeps the text, as an empty answer does. The editor also takes keyboard focus when it opens on existing text, with the caret at the end: it only did so for an empty box, so typing into an existing text went to the command line. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify2.rs | 15 ++++++- crates/ui-egui/src/mtext_editor.rs | 63 ++++++++++++++++++++++++++---- 2 files changed, 69 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index 5562f969c..e94d7f124 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -2203,12 +2203,18 @@ struct TextEditM { single: bool, /// Asking for the edit mode. mode: bool, + /// The MTEXT being edited, for the in-place editor (#842). + mtext: Option, } impl Interactive for TextEditM { fn name(&self) -> &'static str { "TEXTEDIT" } + /// 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()) + } fn prompt(&self, _s: &Session) -> Prompt { if self.mode { let current = if self.single { "Single" } else { "Multiple" }; @@ -2233,7 +2239,12 @@ impl Interactive for TextEditM { match (&self.h, i) { (None, Input::Point(p)) => { let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; - let old = text_of(&curves::entity(s, h)?.kind).ok_or_else(|| other("Select a text, mtext, attribute definition or dimension."))?; + let kind = curves::entity(s, h)?.kind; + let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, attribute definition or dimension."))?; + self.mtext = match kind { + EntityKind::MText(m) => Some(m), + _ => None, + }; self.h = Some((h, old)); Ok(Step::Continue) } @@ -2243,10 +2254,12 @@ impl Interactive for TextEditM { set_text(s, h, &t)?; self.edits.push((h, before)); self.h = None; + self.mtext = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (Some(_), Input::Enter) => { self.h = None; + self.mtext = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (None, Input::Enter) => Ok(Step::Done), diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 9e7db5803..b46b5f04d 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -2,7 +2,8 @@ //! 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. +//! [`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; @@ -36,6 +37,9 @@ 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, } fn state_id() -> egui::Id { @@ -55,7 +59,8 @@ fn color32(c: MTextColor) -> Color32 { Color32::from_rgb(rgb.0, rgb.1, rgb.2) } -/// Show the editor while MTEXT collects its text; clears its state when it isn't running. +/// Show the editor while MTEXT, or TEXTEDIT on an MTEXT, collects its text; clears its state +/// when neither is running. pub fn show(app: &mut CadApp, ctx: &egui::Context) { let mtext = app.session.editing_mtext(); let asking = app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point); @@ -66,14 +71,17 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { 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 mut st = ctx.data_mut(|d| d.get_temp::(state_id())).unwrap_or_else(|| { - let mut fmt = Formatted::default(); + // 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(&mt.contents) }; if let Some(f) = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).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; } } - State { fmt, typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None } + // 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 } }); 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); @@ -122,8 +130,12 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { Done::Ok => { 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. if !st.fmt.is_empty() { let _ = app.session.input(cadcraft_engine::Input::Text(st.fmt.to_contents())); + } else if app.session.running.as_ref().is_some_and(|r| r.id == "textedit") { + let _ = app.session.input(cadcraft_engine::Input::Enter); } if app.session.running.as_ref().is_some_and(|r| r.id == "mtext") { let _ = app.session.input(cadcraft_engine::Input::Enter); @@ -376,9 +388,8 @@ fn ruler(ui: &mut egui::Ui, st: &mut State, px: f32, width: f32, base_h: f64) { fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, t: &Tokens) { let id = edit_id(); - if let Some(at) = st.caret.take() - && let Some(mut s) = egui::TextEdit::load_state(ui.ctx(), 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); } @@ -436,9 +447,10 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, .char_limit(cadcraft_engine::mtext_edit::MAX_CHARS) .layouter(&mut layouter) .show(ui); - if !out.response.has_focus() && buf.is_empty() && st.fmt.is_empty() { + if !out.response.has_focus() && (!st.focused || (buf.is_empty() && st.fmt.is_empty())) { out.response.request_focus(); } + st.focused = true; if out.response.changed() { let typing = st.typing.clone(); st.fmt.set_text(&buf, &typing); @@ -495,4 +507,39 @@ 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. + #[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!(), + } + } } From 950453c7fdf79168441aee638eeadea4991e919f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 20:15:38 +0200 Subject: [PATCH 002/531] docs: re-audit gaps.md and the parity docs against main e707ab4d Redo of the earlier audit after ~100 PRs landed on 2026-10-13. Every change cites a merged PR, a file or a count taken from the code; claims that could not be verified are left as they were. Percentages and hours are not re-scored (listed in the PR description). Corrected: REFEDIT (#818), dynamic block references (#838-#883), Block Editor, MLEADEREDIT/ALIGN/COLLECT (#816), in-place MTEXT editor (#792), AutoLISP (#855), MVIEW Restore and model-space PDF margins (#633), SpaceMouse 2D navigation (#650), ACIS data kept on save (#781), attribute modes (#876), polyline offset bulges (#825), acadrust 0.6.4 (#859), twelve interface catalogs with re-measured row counts, closed winit PRs #110-#119, PR/issue counts and test counts, and ui-parity rows that earlier work had already closed. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 46 ++++++++++++++------------- docs/file-format-parity.md | 25 ++++++++------- docs/gaps.md | 63 +++++++++++++++++++------------------ docs/geometry-parity.md | 19 +++++------ docs/hardware-parity.md | 13 ++++---- docs/localization-parity.md | 63 ++++++++++++++++++++----------------- docs/localization.md | 25 ++++++++++----- docs/plotters.md | 5 ++- docs/roadmap.md | 39 ++++++++++++----------- docs/target-app-parity.md | 23 +++++++------- docs/ui-parity.md | 59 ++++++++++++++++++---------------- 11 files changed, 205 insertions(+), 175 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c88aecc99..ac27059a0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,16 +2,18 @@ **Stage: pre-alpha** · next: alpha, ~2 points (38% → 40% ready for real work) and ~125–190 Opus 5.5 hours away (the four failing core workflows of the [alpha gate](docs/roadmap.md#alpha-gate)) -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (hours to ~95% for each readiness number) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audit against main e707ab4d: why-pre-alpha text, languages, upcoming list and progress log; headline numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 CADCraft targets full parity with AutoCAD (2D drafting first, then annotation, layouts and plotting, DWG, parametrics and 3D), plus what AutoCAD doesn't have: agent control over MCP, a scriptable CLI, a web build, Linux and FreeBSD builds, and a free licence. **Why pre-alpha:** four of AutoCAD's five core workflows fail the [alpha gate](docs/roadmap.md#alpha-gate). -Precise drafting lacks object snap tracking and has stubbed TRIM/EXTEND/OFFSET options; blocks -can't be edited in a block editor (REFEDIT edits them in place, xrefs not yet); plots ignore plot styles; and a DWG saved by -CADCraft drops everything it doesn't model and has never been checked in +Precise drafting still has approximate ellipse and spline intersections and a few stubbed prompt options +(object snap tracking, TRIM/EXTEND/OFFSET options and typed snap overrides have landed); dynamic blocks can't be +authored and xrefs can't be edited in place or clipped (the Block Editor, REFEDIT and dynamic block editing have landed); +plots go only to PDF, PNG and SVG files (plot styles and the Plot dialog have landed); and a DWG saved by +CADCraft drops what acadrust doesn't model and has never been checked in AutoCAD. Dimensioning passes. Ready for real work (≈ 38%) is also under the ~40% alpha bar. Beta is ≈ 600–930 h away. @@ -80,44 +82,45 @@ Hours are Opus 5.5 agent wall-clock hours, calibrated on this repo's own build: ## Languages -AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus partial -Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity.md). +AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus twelve partial +catalogs (Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish and Arabic). Detail: [localization-parity.md](docs/localization-parity.md). | Language | Status | UI translated | |---|---|---:| | English | full | 100% | -| Simplified Chinese | none | 0% | -| Spanish | none | 0% | +| Simplified Chinese | partial | 1,112 catalog rows | +| Spanish | partial | 1,239 catalog rows | | Hindi | none | 0% | -| Arabic | none | 0% | -| French | none | 0% | -| Portuguese | none | 0% | +| Arabic | partial | 1,229 catalog rows | +| French | partial | 1,003 catalog rows | +| Portuguese (Brazilian) | partial | 1,240 catalog rows | | Indonesian | none | 0% | | Japanese | none | 0% | -| German | partial | ≈ 100% of the catalog (989 rows) | -| Korean | none | 0% | +| German | partial | 1,030 catalog rows | +| Korean | partial | 1,235 catalog rows | | Vietnamese | none | 0% | -Other languages shipped: Ukrainian and German (989 catalog rows each; Ukrainian landed with #36), Brazilian Portuguese, Spanish, Czech, Russian, French, Simplified Chinese and Italian (1,227 rows, 2026-10-12); engine messages stay English. +Other languages shipped: Ukrainian (1,322 rows, the reference catalog, #36), Czech (1,214), Russian (1,004), Italian (1,231) and Swedish (1,235), counted 2026-10-13; engine messages stay English. Each catalog lags the reference by 86–319 rows added since it landed ([localization-parity.md](docs/localization-parity.md)). ## Upcoming Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md). -1. Gate and land: fix fmt on main, run `cargo xtask ci` on every PR, land the 47 open PRs (15–25 h). -2. Stop losing data on save; native MULTILEADER; save DWG/DXF at a chosen version (30–45 h). +1. Gate and land: run `cargo xtask ci` on every PR (open PR #847; fmt on main is fixed), land the 89 open PRs (15–25 h). +2. Stop losing data on save (DXF done, #528; native MULTILEADER, #459, and the save version, #421, done; through DWG, acadrust still drops some content) (30–45 h). 3. Real-file DWG/DXF corpus and a black-box check in AutoCAD (10–15 h + owner). -4. Precision input: object snap tracking, extension/parallel snaps, FROM/M2P/TK, snap overrides, - editable dynamic input (25–35 h). -5. Unstub prompt options in TRIM/EXTEND, OFFSET, ROTATE, PLINE, SPLINE, MTEXT, MLEADER (15–25 h). -6. Autosave, recovery, AUDIT, RECOVER (10–15 h). +4. ~~Precision input: object snap tracking, extension/parallel snaps, FROM/M2P/TK, snap overrides, + editable dynamic input.~~ Done (#379, #441, #60, #519; `snap/tracking.rs`, `pointmod.rs`, `dyninput.rs`). +5. ~~Unstub prompt options in TRIM/EXTEND, OFFSET, ROTATE, PLINE, SPLINE, MTEXT, MLEADER.~~ Done (#397, #408, #547); the stubs left are in gaps F1. +6. ~~Autosave, recovery, AUDIT, RECOVER.~~ Done on the desktop (#406, #416); the web build has no autosave (gaps F4). 7. Exact ellipse/spline geometry and correct polyline offsets (30–50 h). -8. Xrefs, block editor, groups, then dynamic blocks (80–120 h). +8. Xrefs, block editor, groups, then dynamic blocks (80–120 h): xrefs (#525), groups (#417), the Block Editor (#824, #833, #885), REFEDIT (#818) and dynamic block references (#838–#883) landed; left: dynamic-block authoring, XCLIP, editing an xref in place. ## Progress log | Date | Entry | |---|---| +| 2026-10-13 | Re-audit against main: 102 PRs merged on 2026-10-13 alone (132 since 2026-10-12), among them REFEDIT, REFSET and REFCLOSE (#818), the Block Editor (#824, #833, #885), dynamic block references (#838, #853, #860, #878, #883), AutoLISP (#855), MLEADEREDIT/ALIGN/COLLECT (#816), the in-place MTEXT editor (#792), object transparency (#764), Hatch and Gradient dialogs (#753), Open Recent (#864), damaged DWGs opened partially (#859), ACIS data kept on save (#781), zoom and pan regenerated in the background (#903) and the Arabic, Swedish, Korean, Italian, Chinese and Spanish catalogs. Headline percentages and hours are from 2026-10-10 and were not re-measured. | | 2026-10-12 | TRIM: a pick after a closed polyline's last cut keeps only the complementary run instead of an extra circuit of the outline (#726) | | 2026-10-12 | HATCHEDIT refuses an explicit bad `scale` or `angle` before it edits anything, so a rejected request leaves the drawing, undo and redo as they were (#724) | | 2026-10-10 | Merged main: Ukrainian interface (#36, first string catalog), Dynamic Input pointer boxes with Tab and relative entry (#60), press-drag selection windows (#63), WIPEOUT and hatch gradients kept through DXF/DWG save (#147, #162), SETVAR DIM* as style overrides (#129), UNITS dialog (#38), close-window save prompt (#47), DIMANGULAR on circles (#20), cargo fmt fixed on main. UI/UX 40% → 43% (dynamic input 15% → 45%), localization 3% → 5%; ready for real work ≈ 37% → 38% (weighted 37.2% → 37.7%), mainstream 27% → 28%, essentials 45% → 46%. Beta is now ~37 points away; hours unchanged within rounding. | @@ -133,6 +136,7 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md) | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d: why-pre-alpha text, languages table and note (twelve catalogs), upcoming list (items 4–6 struck, 1, 2 and 8 updated), progress-log entry; headline numbers unchanged | | 2026-10-12 | trivial | Progress log: closed-polyline TRIM (#726) | | 2026-10-12 | trivial | Progress log: HATCHEDIT numeric validation (#724) | | 2026-10-10 | minor | Merged main's changes (Ukrainian catalog, dynamic input pointer boxes, DXF fixes); UI/UX and localization numbers updated | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5b3a94ce8..fc2aece7f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (multiline attributes read, drawn and written) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audit against main e707ab4d: acadrust 0.6.4, ACIS data, attribute modes, dynamic block row, SCRIPT, test count; percentages not re-measured) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -31,10 +31,10 @@ below, and ≈ 20–40 h for 3D exchange formats that wait for 3D modelling. AutoCAD 2027 opens every DWG version from R2.0 onward and saves 2018 (AC1032, still the current DWG format), 2013, 2010, 2007, 2004, 2000 and R14. CADCraft reads DWG by converting it to DXF -with the `acadrust` 0.6.3 crate and reading that DXF; it saves by writing its own R2000 DXF and +with the `acadrust` 0.6.4 crate (failsafe mode: a damaged DWG opens with the unreadable records left out and a note saying so, #859) and reading that DXF; it saves by writing its own R2000 DXF and converting it to a DWG of the chosen version (#421): SAVEAS `version`, else the drawing's own version (the file's `$ACADVER`, 2018 for a new drawing), at least 2004 unless 2000 is asked for. -The bridge repairs two acadrust 0.6.3 gaps in 2010+ DWG: merged table cells and table-style +The bridge repairs two acadrust gaps in 2010+ DWG (measured with 0.6.3): merged table cells and table-style title/header suppression. | DWG version | Code | AutoCAD 2027 | CADCraft read | CADCraft write | Tested how | @@ -72,20 +72,20 @@ early (#175), but the throughput problem remains. **DWG ≈ 30% read, ≈ 15% wr |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137) | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137); Verify, Preset and Lock position modes kept (#876) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | | LEADER | yes | yes | | | MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides and annotative scale contexts not kept | | HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD) | | | HATCH gradient | yes | yes (#162, fixes #80) | | | SOLID, TRACE, 3DFACE | yes | yes | | -| ACAD_TABLE | yes | yes (entity + block) | | +| ACAD_TABLE | yes; cell text from AutoCAD files is readable (cell height, style scale, MTEXT; #806) | yes (entity + block) | | | VIEWPORT | yes | yes; frozen-layer lists kept (#150), also as standard group 341 layer handles that other programs read | DWG: the DXF→DWG converter does not yet write group 341 (frozen layers survive a CADCraft round trip via xdata); VP layer colour overrides lost (#99, PR #197) | | IMAGE | yes, with IMAGEDEF | yes, with IMAGEDEF and IMAGEDEF_REACTOR | no attach command or display of the picture yet (FF10) | | WIPEOUT | yes | yes (#147, fixes #79) | | | MLINE (+ MLINESTYLE), HELIX, TOLERANCE | yes (#510, #420) | yes | | -| REGION | other programs' REGIONs (ACIS data) kept as Unknown | our regions are written as closed polylines tagged with CADCraft xdata (#510; ACIS has no public spec) | | -| 3DSOLID, BODY, SURFACE, MESH, SHAPE, UNDERLAY, OLE2FRAME, LIGHT, CAMERA, SECTION, POINTCLOUD, proxy entities | kept as Unknown (raw tags) | written back as read, with their CLASS records (#528); **dropped by DWG save** (acadrust) | only their layer follows edits | +| REGION | other programs' REGIONs (ACIS data) kept as Unknown; the ACIS data of 2013+ files (`ACDSDATA`) is kept with them (#781) | our regions are written as closed polylines tagged with CADCraft xdata (#510; ACIS has no public spec) | | +| 3DSOLID, BODY, SURFACE, MESH, SHAPE, UNDERLAY, OLE2FRAME, LIGHT, CAMERA, SECTION, POINTCLOUD, proxy entities | kept as Unknown (raw tags) | written back as read, with their CLASS records (#528); 3DSOLID, REGION and BODY keep their ACIS data (`ACDSDATA`) in files of 2013 and later, in DXF and DWG (#781); the other kinds are **dropped by DWG save** (acadrust) | only their layer follows edits | | Header variables | all read | 36 written | AutoCAD writes about 280 | | Tables: LAYER (+ transparency, description), LTYPE, STYLE, DIMSTYLE, BLOCK_RECORD | yes | yes | | | Tables: VPORT, VIEW, UCS, APPID | yes | yes: saved viewport configurations (#504), named views, UCSs | UCS elevation lost | @@ -93,7 +93,7 @@ early (#175), but the throughput problem remains. **DWG ≈ 30% read, ≈ 15% wr | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read | not editable | | Foreign xdata, extension dictionaries, reactors, unmodelled objects, colour books | kept raw (#528); an entity's xdata is part of the entity, so COPY, MIRROR, ARRAY and paste keep it on the copies (EXPLODE pieces don't) | written back, handles remapped, references to deleted objects dropped | through DWG: xdata on table records and blocks, entity colour books and reactors, custom-class objects lost (acadrust) | -| Objects: dynamic block data (ACAD_EVALUATION_GRAPH, BLOCK…PARAMETER, BLOCK…ACTION, grips) | read into a model (`dynblock`, `blocks.dynamic`): parameters, visibility states, value sets, stretch and lookup actions; references: their dynamic block, values and custom properties (`blocks.reference`, Properties ▸ Custom, read-only); kept raw (#528) | written back as read; a changed visibility state is written as AutoCAD writes it (a new anonymous block with its `AcDbBlockRepBTag`, the objects' `AcDbBlockRepETag`, the reference's representation data) | visibility states (and lookups that set only them) can be changed (`blocks.reference.set`, Properties ▸ Custom); distances, positions and the actions they drive not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block) | +| Objects: dynamic block data (ACAD_EVALUATION_GRAPH, BLOCK…PARAMETER, BLOCK…ACTION, grips) | read into a model (`dynblock`, `blocks.dynamic`): parameters, visibility states, value sets, stretch and lookup actions; references: their dynamic block, values and custom properties (`blocks.reference`, Properties ▸ Custom); kept raw (#528) | written back as read; a changed reference is written as AutoCAD writes it (a new anonymous block with its `AcDbBlockRepBTag`, the objects' `AcDbBlockRepETag`, the reference's representation data) | visibility states, lookups (both ways), distances and positions can be changed (`blocks.reference.set`, Properties ▸ Custom, #860, #878), running the stretch and move actions that follow, and their grips show and drag (#883); polar, XY, rotation, alignment and flip parameters and the scale, rotate, flip, array and polar stretch actions are read but not applied (`dynblock/apply.rs`); no authoring; DWG open and save keep it too (checked with an AutoCAD dynamic block; open PR #1000 keeps the C++ class names the file gives) | | Handles and owners | entity handles kept; others regenerated | consistent | stable across CADCraft re-saves (#495); other programs' table and object handles renumbered once | **DXF ≈ 50% read, ≈ 30% write** (estimated; weights: common 2D entities 50%, annotation objects @@ -112,19 +112,19 @@ early (#175), but the throughput problem remains. **DWG ≈ 30% read, ≈ 15% wr | DWF/DWFx export, DWF underlay | yes | no | 10–15 | | DGN import/export/underlay | yes | no (needs a public spec; owner decision) | 25–40 | | WMF, EPS, ACIS SAT, STL, FBX, IGES/STEP (Windows), 3DS | various | no; most are 3D and wait for M11 | 20–40 | -| SHX fonts (`.shx`, big fonts) | read | **not parsed**: our stroke font or FONTALT stands in, so text metrics differ from AutoCAD | 8–12 | +| SHX fonts (`.shx`, big fonts) | read | **not parsed**: our stroke font or FONTALT stands in, so text metrics differ from AutoCAD (wide East Asian characters fill square big-font cells, #861) | 8–12 | | Linetype (`.lin`) and hatch pattern (`.pat`) files | load user files | user files load (#552); linetype shape (SHX) elements are skipped | 1–2 | | Plot styles (`.ctb`, `.stb`), plotter configs (`.pc3`), `.pmp` | yes | plot style tables in our own JSON format ([plot-styles.md](plot-styles.md)) and kept in the drawing; plotter devices with papers and printable areas in our own JSON format ([plotters.md](plotters.md), #564); binary `.ctb`/`.stb`/`.pc3`/`.pmp` not read (no public spec) | 4–8 | -| Scripts (`.scr`) | SCRIPT | script text through the CLI, MCP and control channel; no SCRIPT command reading a `.scr` file | 1–2 | +| Scripts (`.scr`) | SCRIPT | the SCRIPT command runs a `.scr` file (#693), as do the CLI, MCP and control channel | 0–1 | | Aliases (`.pgp`), CUI(x), workspaces | yes | user alias files and ALIASEDIT (#552); no CUI(x) or workspaces | 4–8 | | SVG import (`.svg`, `.svgz`) | yes (via scripts) | OPEN reads shapes, paths, groups and Inkscape layers into entities (#636); no CSS classes, `use`, fills, text or images | 2–4 | -| AutoLISP (`.lsp`, `.fas`, `.vlx`), `.dll`/`.arx` plug-ins | yes | `.lsp` loads (APPLOAD, `(load)`, a dropped file; #758); no Visual LISP ActiveX (`vlax-`), DCL dialogs or reactors; `.fas`/`.vlx` are compiled and undocumented; no `.dll`/`.arx` | see [gaps.md](gaps.md) (E1) | +| AutoLISP (`.lsp`, `.fas`, `.vlx`), `.dll`/`.arx` plug-ins | yes | `.lsp` loads (APPLOAD, `(load)`, a dropped file; #855, closing #758); no Visual LISP ActiveX (`vlax-`), DCL dialogs or reactors; `.fas`/`.vlx` are compiled and undocumented; no `.dll`/`.arx` | see [gaps.md](gaps.md) (E1) | | Data extraction (`.csv`, `.xls`) and data links | yes | DATAEXTRACTION/EATTEXT to CSV or a table (#433); table data links read CSV (#534); no `.xls`, no `.dxe` templates | 3–5 | | eTransmit (`.zip` packages) | yes | no | 4–6 | ## Tests -`crates/io/src/tests.rs` has 36 tests (round trips of entities, styles, associativity, tables, +`crates/io/src/tests.rs` has 75 tests (`#[test]` count, 2026-10-13) (round trips of entities, styles, associativity, tables, constraints, non-ASCII text, DWG round trips, hostile input). **All inputs are synthetic**: inline strings or our own writer's output. No test opens a file made by another program, and no external validator runs in CI (ezdxf's audit was run by hand once, 2026-10-06). The next step is @@ -135,6 +135,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d: acadrust 0.6.4 and partial opening of damaged DWGs (#859); ACIS data of solids, regions and bodies kept on save (#781); attribute modes (#876); dynamic block row (distances, positions, actions, lookups, grips: #878, #883); ACAD_TABLE cell text (#806); SCRIPT reads `.scr` (#693); AutoLISP PR number (#855); io test count 36 → 75 | | 2026-10-12 | minor | PDF output: object transparency plotted as PDF alpha (`/ExtGState` `/ca` `/CA`) when the page setup's or the plot's "Plot transparency" is on; PNG plots blend it, SVG uses `opacity`; plots without it are unchanged byte for byte | | 2026-10-12 | minor | DXF/DWG save: the Model layout's plot settings are written as CADCraft plots model space, drawing extents scaled to fit (PLOTSETTINGS 74 = 1, 75 = 0), instead of plot type 5 "Layout information", which other programs' Plot dialogs can't use for model space | | 2026-10-12 | minor | VIEWPORT frozen layers also written and read as AutoCAD's group 341 layer handles, so third-party viewers honour per-viewport freezing in DXF (DWG converter gap noted) | diff --git a/docs/gaps.md b/docs/gaps.md index 0adb80f12..fef513a2e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (multiline attributes read, drawn and saved: F17 narrowed) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audited against main e707ab4d: top-10 rows 1–4 and 6, F1, F2, F9, F10, F14, F15, F17, F20, U11, U13, H1–H3, H5, L1–L4, S3, S5, P2, P3 and E1 corrected) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -13,35 +13,35 @@ do them first. | # | Gap | Why it ranks here | Est. | Doc | |---|---|---|---|---| -| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | -| 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 36 file tests are synthetic; nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) | -| 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset ignores bulges) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) | -| 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be edited in place or clipped** (xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | +| 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors; the ACIS data of 3D solids, regions and bodies is kept, #781) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | +| 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 75 file tests (`crates/io/src/tests.rs`) use synthetic data (the real-file runs in PRs #781 and #859 were manual and are not committed); nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) | +| 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset recomputes arc bulges since #825 but has no loop cleanup) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) | +| 4 | **[alpha blocker]** **No dynamic-block authoring or XCLIP; xrefs can't be edited in place** (REFEDIT, REFSET and REFCLOSE edit block references in place, #818; dynamic block references are read and edited, #838–#883; xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | | 5 | **No autosave in the web build** (the desktop app has SAVETIME autosave, Drawing Recovery, AUDIT and RECOVER since #406) | Browser users lose unsaved work when the tab or the browser goes down | 3–5 | [features](#features) | -| 6 | **No CI runs the Rust tests on pull requests** (`cargo fmt` on main is fixed) | open PRs land without a gate; regressions go unseen | 2–3 | [stability](#stability) | +| 6 | **No CI runs the Rust tests on pull requests** (`cargo fmt` on main is fixed; PR #847 adds the workflow and is open) | open PRs land without a gate; regressions go unseen | 2–3 | [stability](#stability) | ## Features | # | Gap | Evidence | User impact | Est. | |---|---|---|---|---| -| F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | -| F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations, -LAYER MATerial, stAte and rEconcile, LAYOUT Template and SAveas. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs`, `cmd/layer/prompts.rs`, `cmd/layout/prompts.rs` | Low: the most-used commands are done | 1–3 | +| F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #818, closing issue #813); an xref is refused with a message. Left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips; polar, XY, rotation, alignment and flip parameters and the scale, rotate, flip, array and polar stretch actions are read but not applied, `doc/src/dynblock/apply.rs`). BEDIT (with the Edit Block Definition dialog, which also starts new blocks), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no AUDITCTL `.adt` log and no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 3–5 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMTFILL/DIMTFILLCLR, DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | | F8 | TOLERANCE leftovers (feature control frames landed, #420: model, our own symbol drawing, DXF, command-line prompts, explode, grips): no Geometric Tolerance dialog, no LEADER/QLEADER tolerance annotation, no in-place editing of a frame's contents | `cmd/tolerance.rs` | Low-medium (mechanical) | 2–4 | -| F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 5 fields (block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `tables.rs:417` | Medium | 8–12 | -| F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing MTEXT cannot be edited (no DDEDIT/MTEDIT), stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 | +| F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 6 settings (arrow size, text height, landing gap, dogleg, text style, annotative; block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `cmd/mleader_edit.rs`, `doc/src/tables.rs` | Medium | 8–12 | +| F9 | MTEXT is typed in an on-canvas editor with a formatting toolbar (font, height, bold, italic, underline, overline, colour, alignment, lists, tab and special characters) and a ruler for indents and tab stops (#532); left: the box does not lay the text out by the indents, tabs, columns or font weights while typing (bold shows wider, overline is not drawn), no justification (attachment) or columns controls in the editor, existing TEXT and MTEXT are edited as plain text on the command line with TEXTEDIT (alias DDEDIT; a double-click starts it, #868), and the in-place editor for existing MTEXT is open PR #1002; stacked fractions and other codes show as placeholders; no fields (FIELD, UPDATEFIELD) and no spell check (SPELL): open PR #551. Paragraph indents, tabs, bullets, numbering and columns landed (#547) | `ui-egui/mtext_editor.rs`, `engine/mtext_edit.rs` | Medium | 10–18 | | F11 | Tables (cell styles, formulas, TABLEDIT, TABLEEXPORT, table breaking and CSV data links landed, #534): formulas aren't read from or written as AutoCAD FIELD objects (other programs see values); number formats apply to formula results only; cell text doesn't wrap; custom cell styles, breaks and data links travel as CADCraft xdata (not through DWG); data links read CSV only (no Excel ranges, no write-back, not on the web); no cell-style tab in the Table Style dialog | `cmd/table/*`, `io/dxf_table.rs` | Low-medium | 6–10 | | F12 | Annotative scaling done (#468): scale list (SCALELISTEDIT), CANNOSCALE, OBJECTSCALE, ANNOALLVISIBLE/ANNOAUTOSCALE, viewport scale, DXF, status bar list. Left: per-scale positions (ANNORESET is a no-op), a viewport annotation scale apart from its viewport scale, annotative objects inside blocks and old LEADERs, AutoCAD files' per-object scale contexts (read as not annotative) | `cmd/annoscale.rs`, `doc/src/anno.rs` | Low-medium | 4–8 | -| F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; model-space PDF plots keep the default margins (a device paper's margins apply to layouts and PNG plots); no system printers (H3); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 | +| F14 | **[alpha blocker]** Plotting leftovers: binary `.ctb`/`.stb`/`.pc3` files can't be read; no system printers (H3; CUPS printing on macOS and Linux is open PR #755); the page setup's "Plot transparency" is not saved in DXF/DWG (the public DXF Reference has no plot layout flag for it), so it lasts for the session and in JSON only. The Plot dialog (#160), Plot Preview and PUBLISH (#186), plot styles (CTB and STB, [plot-styles.md](plot-styles.md), #410) with their end, join and fill styles, plotter devices with paper sizes and printable areas ([plotters.md](plotters.md), #564), and plotted transparency (page setup and Plot dialog option, PLOTTRANSPARENCYOVERRIDE) landed | `io/src/plotter.rs`, `cmd/plotters.rs` | Medium | 4–8 | | F13 | Hatch: 23 patterns (AutoCAD ~85; ours must stay original); the Hatch and Gradient and Hatch Edit dialogs have no Preview or Inherit Properties and can't add or remove boundaries of an existing hatch (HPDLGMODE 0 keeps HATCH on the command line), no MPolygon; HATCHEDIT can't add or remove boundaries; a hatch copied with its boundary isn't linked to the copy; HPGAPTOL closes gaps between curve ends only | `doc/src/library.rs`, `cmd/hatch.rs`, `cmd/hatch/edit.rs` | Medium | 8–12 | -| F15 | Viewports: MVIEW Restore prints "not available yet" (named viewport configurations into a layout, see U11); a clipped viewport and its clip boundary move and scale separately. Polygonal, object and clipped viewports, VPCLIP, MVIEW ON/OFF/Lock/2/3/4 and the status-bar scale list landed (#453) | `cmd/layout/viewports.rs` | Low | 2–4 | +| F15 | Viewports: a clipped viewport and its clip boundary move and scale separately. Polygonal, object and clipped viewports, VPCLIP, MVIEW ON/OFF/Lock/2/3/4/Restore (a saved viewport configuration into a layout, #633) and the status-bar scale list landed (#453) | `cmd/layout/viewports.rs` | Low | 2–4 | | F16 | Groups: no group bounding box or single grip when a group is selected (GROUPDISPLAYMODE), copying a whole group does not make a new group, no Object Grouping dialog (GROUP, GROUPEDIT, UNGROUP, -GROUP, PICKSTYLE group selection and the DXF/DWG round trip landed, #417); PICKSTYLE's associative-hatch bit is stored but unused | `cmd/groups.rs` | Low | 2–4 | -| F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): no verify, preset or lock-position modes, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | +| F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): the Verify, Preset and Lock position modes are kept in files and Lock position is applied by INSERT and ATTSYNC (#876), but INSERT doesn't act on Verify or Preset, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | | F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 | -| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export | `ui-egui/src/options/` | Low | 2–4 | +| F20 | OPTIONS dialog done (#531, closing #23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. The autosave interval and location, the default save version and the time-sensitive right-click toggle are on Open and Save and User Preferences too (`options/dialog.rs`). Left: right-click customization beyond that toggle, AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export | `ui-egui/src/options/` | Low | 2–4 | | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT has no Merged Tee and tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data); PURGE skips multiline styles | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | | F22 | Inquiry leftovers (COUNT across spaces and nested blocks, the QuickCalc palette and COMPARE landed, #563; MASSPROP on regions, #510): COMPARE compares the tab shown, not every layout at once, and has no COMPAREEXPORT report; QuickCalc keeps its history and variables for the session only | `file/compare.rs`, `palettes/quickcalc.rs` | Low | 3–5 | | F23 | No Sheet Set Manager, eTransmit, Share, Traces, Markup Import, Activity Insights | menu items uncovered | Low-medium (team workflows) | 40–70 | @@ -58,9 +58,9 @@ Detail and evidence: [ui-parity.md](ui-parity.md). | U6 | Selection: lasso; selection cycling (a list of overlapping objects, SELECTIONCYCLING); the CLass keyword; isolation saved with the drawing (OBJECTISOLATIONMODE 1) and the status-bar isolate button. Press-drag windows (#63), the W, C, F, WP and CP keywords (#226), BOX, AUto, SIngle, Multiple, Group, Add, Remove and Undo, SELECTSIMILAR, and ISOLATEOBJECTS/HIDEOBJECTS/UNISOLATEOBJECTS (#428) landed | Medium | 3–5 | | U7 | Right-click menus: no in-place layout tab rename or Move or Copy dialog, no Select All Layouts, no Paste to command line; palette menus are on the Layers rows and the Properties background only. The command menu (held right-click: Enter, Cancel, Recent Input, options, Snap Overrides, Pan/Zoom), the selection menu with object edits, command line, drawing tab, layout tab and palette menus landed (#512) | Low | 1–2 | | U10 | SETVAR covers about 150 of ~1,000 variables (UNDO options, MREDO and UNDOCTL, and header variables such as CIRCLERAD, OFFSETDIST, POLYSIDES, HPNAME and the dimension variables in SETVAR ? landed, #461; typing a bare variable name as a command runs SETVAR on it) | Low-medium | 3–5 | -| U11 | MVIEW Restore (a saved viewport configuration into a layout); VIEW Orthographic, UCS and background settings; view twist is kept but not shown (Zoom Realtime and Dynamic, ZOOMFACTOR, named views (VIEW) and tiled model viewports with saved configurations (VPORTS) landed in #463) | Low | 1–2 | +| U11 | VIEW Orthographic, UCS and background settings; view twist is kept but not shown (Zoom Realtime and Dynamic, ZOOMFACTOR, named views (VIEW) and tiled model viewports with saved configurations (VPORTS) landed in #463) | Low | 1–2 | | U12 | Workspaces, navigation bar, CUI customisation, alias editor, ViewCube drag (#7) | Low-medium | 15–25 | -| U13 | `.dxf` from Finder fails to open on macOS (#158) (window controls fixed, #161) | Medium | 1–2 | +| U13 | `.dxf` from Finder fails to open on macOS (#158; fix in open PRs #683 and #899) (window controls fixed, #161) | Medium | 1–2 | ## File formats @@ -89,11 +89,11 @@ Detail: [hardware-parity.md](hardware-parity.md). | # | Gap | Est. | |---|---|---| -| H1 | 3Dconnexion SpaceMouse (needs the device and 3D views) | 6–10 + human | -| H2 | Multi-monitor: floating palettes on other screens, per-monitor DPI (PR #110 for Windows 11 DPI) | 4–6 | -| H3 | Plotters and system printers (PC3 devices) beyond PDF files | 6–10 | +| H1 | 3Dconnexion SpaceMouse: 2D pan and zoom through raw HID on Windows and Linux landed (#650, Tools ▸ 3D Mouse; PR #983 open); none on macOS or the web, no 3D navigation (needs 3D views), not yet checked on a physical device in #650 | 6–10 + human | +| H2 | Multi-monitor: floating palettes on other screens, per-monitor DPI (the Windows 11 DPI fix is in open PR #668, which replaced the closed PR #110) | 4–6 | +| H3 | System printers (PC3 devices) beyond PDF, PNG and SVG plotter devices (CUPS printing on macOS and Linux is open PR #755) | 6–10 | | H4 | Pen tablets / digitizer (TABLET) | 3–5 + human | -| H5 | Screen magnifier tracking (#39, PR #187) | 1–2 | +| H5 | Screen magnifier tracking: the system-cursor option landed (PR #187); issue #39 is still open | 1–2 | ## Localization @@ -101,34 +101,34 @@ Detail: [localization-parity.md](localization-parity.md). | # | Gap | Est. | |---|---|---| -| L1 | Catalog covers the UI (989 rows, #36) but not engine diagnostics, CLI/MCP replies or command history | 4–6 | -| L2 | AutoCAD for Mac's other languages (zh-Hans, es, fr, ja, ko, it; de landed 2026-10-11) plus pt, hi, ar, id, vi from the standard's list | 35–55 + native review | -| L3 | Complex-script shaping for Devanagari and other Indic scripts in drawing text; RTL (mirrored) UI. Arabic-script shaping and bidi in drawing text landed (#287) | 20–30 | -| L4 | IME fixes on every platform (PRs #110–#119); vertical text styles | 6–10 | +| L1 | Catalog covers the UI (Ukrainian reference catalog: 1,322 rows, #36) but not engine diagnostics, CLI/MCP replies or command history | 4–6 | +| L2 | Japanese from AutoCAD for Mac's list, plus hi, id and vi from the standard's list (de, es, fr, it, ko, zh-Hans, pt-BR, ar, cs, ru, sv, uk landed: 12 catalogs in `i18n/`); the landed catalogs still need native review | 13–21 + native review | +| L3 | Complex-script shaping for Devanagari and other Indic scripts in drawing text; RTL (mirrored) UI (the Arabic catalog shipped without mirroring; reading its labels right to left is open PR #996). Arabic-script shaping and bidi in drawing text landed (#287) | 20–30 | +| L4 | IME fixes on every platform (PRs #110–#119 were closed unmerged; the consolidated winit PR #668 is open); vertical text styles | 6–10 | ## Stability | # | Gap | Evidence | Est. | |---|---|---|---| -| S1 | No CI runs `cargo xtask ci` on pull requests (only packaging lint and release builds) | `.github/workflows/` | 2–3 | +| S1 | No CI runs `cargo xtask ci` on pull requests (only packaging lint and release builds; PR #847 adds it and is open) | `.github/workflows/` | 2–3 | | S2 | ~~`cargo fmt --check` fails on main~~ fixed on main (8fceaaf) | — | 0 | -| S3 | 40 open PRs, many community bug fixes awaiting review | `gh pr list` | 10–20 | +| S3 | 89 open PRs (2026-10-13), many community bug fixes awaiting review | `gh pr list` | 10–20 | | S4 | Open correctness issues: extents union far-apart geometry (#166), lines not visible mid-command (#44), browser plot shows raw PDF bytes (#134) (closing a tab and browser saves fixed, #76, #133) | issues | 4–6 | -| S5 | No smoke test of every command through the UI (PR #42 proposes one) | — | 6–10 | +| S5 | No smoke test of every command through the UI (open PR #42 proposes one) | — | 6–10 | ## Platforms | # | Gap | Est. | |---|---|---| | P1 | Web build: plot shows raw PDF bytes (#134), no DWG (File > Open and save downloads fixed, #55, #133) | 3–5 | -| P2 | Windows and Linux get little runtime testing; Linux Mint mouse delay (#25); Windows magnifier (#39) | 6–10 | -| P3 | macOS file associations: opening `.dxf` from Finder fails (#158) | 1–2 | +| P2 | Windows and Linux get little runtime testing; Linux Mint mouse delay (#25: the vsync fix landed, #183, the issue is open); Windows magnifier (#39: system-cursor option landed, #187, the issue is open) | 6–10 | +| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; open PRs #683 and #899) | 1–2 | ## Ecosystem and automation | # | Gap | Est. | |---|---|---| -| E1 | AutoLISP beyond the core (#758 landed the language, `command`, entity lists, selection sets, `get…` input, APPLOAD, `(load)`, `c:` commands and `acad.lsp`/`acaddoc.lsp` at startup): Visual LISP ActiveX (`vlax-`, `vla-`), DCL dialogs, reactors, an APPLOAD dialog with a Startup Suite, UCS-aware `trans` | 30–50 | +| E1 | AutoLISP beyond the core (#855, closing #758, landed the language, `command`, entity lists, selection sets, `get…` input, APPLOAD, `(load)`, `c:` commands and `acad.lsp`/`acaddoc.lsp` at startup): Visual LISP ActiveX (`vlax-`, `vla-`), DCL dialogs, reactors, an APPLOAD dialog with a Startup Suite, UCS-aware `trans` | 30–50 | | E3 | Express Tools equivalents (TXT2MTXT, BREAKLINE, BURST, NCOPY exists, SUPERHATCH, Move/Copy/Rotate) | 30–50 | | E4 | Plug-in API (owner decision: Rust/WASM plug-ins rather than ObjectARX/.NET) | 30–50 | | E5 | CUI customisation and alias (`.pgp`) editor | 15–25 | @@ -145,6 +145,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d (PR #819 redone): REFEDIT (#818), dynamic block references (#838–#883), MLEADEREDIT/ALIGN/COLLECT (#816), the in-place MTEXT editor (#792), AutoLISP (#855), MVIEW Restore and model-space plot margins (#633), SpaceMouse 2D navigation (#650), ACIS data kept on save (#781), attribute modes (#876), polyline offset bulges (#825) and 12 interface catalogs (Arabic, Chinese, Spanish, French, Russian, Italian, Korean, Swedish and others); stale PR numbers (#813, #758, #110–#119) corrected; counts refreshed (75 file tests, 89 open PRs, 1,322 Ukrainian catalog rows); hours not re-estimated | | 2026-10-12 | minor | Object transparency (entity, ByLayer, ByBlock) is drawn: on screen (TRANSPARENCYDISPLAY, on by default), in PNG/SVG exports, and in plots when the page setup's "Plot transparency" is on (PDF alpha, PNG blending, SVG opacity; PLOTTRANSPARENCYOVERRIDE): F14 narrowed | | 2026-10-12 | minor | Hatch and Gradient dialog (HATCH, GRADIENT; HPDLGMODE) and Hatch Edit dialog (HATCHEDIT, right-click, double-click a hatch): F13 narrowed to Preview, Inherit Properties and boundary add/remove in edit mode | | 2026-10-12 | minor | A bare system variable name typed at the command line (ORTHOMODE, GRIDMODE…) runs SETVAR on that variable, as in AutoCAD; U10 narrowed | diff --git a/docs/geometry-parity.md b/docs/geometry-parity.md index 06115fbcd..bf04163e0 100644 --- a/docs/geometry-parity.md +++ b/docs/geometry-parity.md @@ -1,6 +1,6 @@ # Geometry parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (property-based and hostile-input test suite for geometry landed) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audit against main e707ab4d: polyline offset bulges, HPGAPTOL, MASSPROP on regions, spline fit cap, test counts; percentages not re-measured) · **Target:** Autodesk AutoCAD 2027 CAD users trust numbers: a trimmed endpoint, an offset, an intersection or an area is either right to the last displayed digit or the tool is unusable for production drawings. This document @@ -10,8 +10,8 @@ in [ui-parity.md](ui-parity.md); dimension and hatch behaviour in [gaps.md](gaps **Headline (estimated): geometry ≈ 40% (weighted below: 41%), of which the constraint solver ≈ 50%.** Everything built from lines, arcs and circles is exact. Ellipses and splines are handled by tessellating them, so -intersections, offsets, trims and snaps on them are approximations; polyline offsets don't -recompute arc bulges or clean up loops; tolerances are absolute, so very large or very small +intersections, offsets, trims and snaps on them are approximations; polyline offsets recompute +arc bulges (#825) but don't clean up loops; tolerances are absolute, so very large or very small drawings behave differently from mid-sized ones. 3D geometry doesn't exist. Remaining: **≈ 90–140 Opus 5.5 hours** for 2D precision and the solver, plus the 3D kernel (M11, see [target-app-parity.md](target-app-parity.md)). @@ -47,7 +47,7 @@ constraints 10%. | Circle, arc, bulge polyline | yes | yes, exact | | Ellipse, elliptical arc | yes | yes (center, major axis, ratio, parameters) | | Spline: CV form, rational, any degree | yes | yes: rational B-spline, basis-function evaluation | -| Spline: fit points | degree 3 with end tangents, knot parameterisation (chord, square root, uniform), fit tolerance | cubic, chord-length, averaged knots, dense solve; **no end tangents, no knot parameterisation choice, no fit tolerance** (`geom/src/spline.rs:31-88`) | +| Spline: fit points | degree 3 with end tangents, knot parameterisation (chord, square root, uniform), fit tolerance | cubic, chord-length, averaged knots, dense solve (above 4,096 fit points the points are used as control points instead, #773); **no end tangents, no knot parameterisation choice, no fit tolerance** (`geom/src/spline.rs:31-88`) | | Spline: closed/periodic | periodic | "closed" appends the first point and refits; **not periodic** (`modify2.rs:647`) | | Spline editing: knot insertion, split, refine, rebuild, convert to polyline | SPLINEDIT, grips | knot insertion and splitting (`curves.rs:539-622`); refine/rebuild partial | | Helix | yes | **no** | @@ -73,7 +73,7 @@ constraints 10%. | Circle, arc | exact | exact (radius change) | | Ellipse | spline approximation within tolerance | **a polyline** from tessellation at 1e-3 × major axis | | Spline | spline approximation within tolerance | tessellate at 1e-3, offset vertices along normals, keep about 40 points, refit: **lossy** | -| Polyline with arcs | exact, with self-intersection trimming, OFFSETGAPTYPE (extend, fillet, chamfer) | segments offset and joined at neighbours' intersections; **arc bulges not recomputed** after endpoints move (comment at L413), **no loop cleanup**, collapsed segments not removed; OFFSETGAPTYPE only echoed | +| Polyline with arcs | exact, with self-intersection trimming, OFFSETGAPTYPE (extend, fillet, chamfer) | segments offset and joined at neighbours' intersections; arc bulges are recomputed from the joined endpoints (#825), **no loop cleanup**, collapsed segments not removed; OFFSETGAPTYPE only echoed | | Options: Through, Erase, Layer, Multiple | yes | see [gaps.md](gaps.md) | ## Trim, extend, fillet, chamfer, break, join, lengthen (≈ 70%) @@ -99,7 +99,7 @@ Where line and arc are supported the results are exact. | Tangent points, common tangents | every curve | circles and arcs only (`curve.rs:170-183`) | | AREA: circle, ellipse | exact | exact area (ellipse perimeter by Ramanujan, not exact); an open elliptical arc has no area, like an arc | | AREA: polyline with arcs | exact (bulge segments) | **tessellated at 1e-4** (`curve.rs:491`) | -| MASSPROP (regions: area, perimeter, centroid, moments) | exact on regions and solids | shoelace over a tessellated circle, polyline or first hatch loop (`utility.rs:310-352`); no regions | +| MASSPROP (regions: area, perimeter, centroid, moments) | exact on regions and solids | works on regions (#510, `inquiry/regions.rs`); other objects not re-checked in this pass (shoelace over a tessellated circle, polyline or first hatch loop on 2026-10-10) | | LIST/DIST/ID precision | full double | full double | ## Hatch boundaries (≈ 45%) @@ -107,7 +107,7 @@ Where line and arc are supported the results are exact. `geom/src/region.rs`: curves are polygonised, crossings split on a grid, vertices merged at `tol`, a ray picks the edge and the face is traced by sharpest left turn; islands by connectivity (including islands made of separate lines, #163). Caps: 60,000 segments, 4,096 -islands. Missing: **gap tolerance (HPGAPTOL)**, true arcs and curves in boundaries (boundaries +islands. Gap tolerance (HPGAPTOL) bridges gaps between open curve ends only (`build_gap`). Missing: true arcs and curves in boundaries (boundaries come out tessellated, so a hatched circle's boundary is a polygon), island detection modes beyond the default, boundary sets, and retained associative boundaries for every case. Pattern lines are scanline families clipped against the tessellated loops (`render/src/hatch.rs`). @@ -126,7 +126,7 @@ lines are scanline families clipped against the tessellated loops (`render/src/h ## Tests -`#[test]` counts on 2026-10-10: geom 28, constraints 22, render 50, engine 174. A property-based +`#[test]` counts (occurrences under `crates/`) on 2026-10-13: geom 84, constraints 36, render 134, engine 948 (2026-10-10, counted differently: geom 28, constraints 22, render 50, engine 174). A property-based and hostile-input suite for geometry numerics landed 2026-10-12 (`crates/geom/src/property_tests.rs`): a deterministic xorshift generator (no new dependency) drives a few thousand cases per property — intersections lie on both curves and are symmetric, circle pairs match the closed form, closest @@ -140,7 +140,7 @@ coordinates to 1e-9 relative. 1. Exact ellipse and spline intersection and closest point (subdivision + Newton with a relative tolerance); use them in snaps, TRIM, EXTEND, BREAK. 15–25 h. -2. Polyline offset with bulge recomputation, self-intersection cleanup and OFFSETGAPTYPE; +2. Polyline offset with self-intersection cleanup and OFFSETGAPTYPE (bulge recomputation done, #825); spline/ellipse offset as fitted splines within a tolerance. 15–25 h. 3. A tolerance context relative to the drawing's extents, and a known-answer test suite at origin and at 1e6–1e7 coordinates. 8–12 h. @@ -155,6 +155,7 @@ Total ≈ 90–140 h; items 1–6 parallelise across two or three agents. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d: polyline offset recomputes arc bulges (#825); spline fits above 4,096 points use control points (#773); HPGAPTOL bridges open ends; MASSPROP on regions; test counts re-measured; percentages not re-measured | | 2026-10-12 | trivial | TRIM on a closed polyline keeps only the complementary run when the pick lies past the last cut (#726) | | 2026-10-12 | minor | Property-based and hostile-input tests for geometry numerics landed (`crates/geom/src/property_tests.rs`): intersections, closest points, three-point arcs, bounds, vector identities; hostile f64s never panic; known answers at 1e6–1e7 | | 2026-10-10 | major | First geometry-precision audit: tolerances, curves, intersections, offsets, modify commands, measurement, hatch, solver | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 742677370..35b21b6a7 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,12 +1,12 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (zoom and pan regenerate in the background) · **Target:** Autodesk AutoCAD 2027 (Mac and Windows) +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audit against main e707ab4d: SpaceMouse 2D navigation, magnifier option, winit PR state, plotter devices; the 45% is not re-measured) · **Target:** Autodesk AutoCAD 2027 (Mac and Windows) The hardware AutoCAD uses and how CADCraft compares, per platform. Work items: [gaps.md](gaps.md#hardware). **Headline (estimated): hardware ≈ 45%.** 2D GPU drawing, HiDPI and trackpads are covered on -every platform. Missing: 3D mice, tablets/digitizers, GPU-accelerated 3D (there is no 3D), and +every platform. Missing: 3D navigation with a 3D mouse (2D pan and zoom landed on Windows and Linux, #650), tablets/digitizers, GPU-accelerated 3D (there is no 3D), and any deliberate multi-monitor handling. Remaining: **≈ 15–25 Opus 5.5 hours**, plus a human with the devices to test 3D mice and tablets. @@ -20,15 +20,15 @@ requirements and graphics-performance documentation. Nothing was benchmarked in | CPU fallback | software mode | yes (`tiny-skia` rasteriser) | yes | yes | — | | GPU for 3D (shaded visual styles, ray-traced rendering) | yes | no (no 3D) | no | no | no | | Low-latency presentation | yes | vsync or low-latency via `CADCRAFT_VSYNC` | same | no vsync queue so the crosshair keeps up (#183) | browser-controlled | -| HiDPI / Retina, display scaling | yes | yes (egui points per pixel) | yes; a Windows 11 DPI fix is queued upstream (PR #110) | yes | yes | +| HiDPI / Retina, display scaling | yes | yes (egui points per pixel) | yes; the Windows 11 DPI fix is in open PR #668 (PR #110 was closed in its favour) | yes | yes | | Multi-monitor (palettes on other screens, per-monitor DPI) | yes | not handled deliberately; one window | same | same | — | | Trackpad pan, pinch zoom | yes (Mac) | yes, with trackpad vs wheel detection (#58) | wheel only (precision touchpad untested) | wheel; delay reported on Linux Mint (#25) | browser events | | Magic Mouse | yes | treated as a trackpad | — | — | — | | Wheel mouse, middle-button pan | yes | yes | yes | yes | yes | -| 3D mouse (3Dconnexion SpaceMouse) | yes | **no** | **no** | **no** | no | +| 3D mouse (3Dconnexion SpaceMouse) | yes | **no** | 2D pan and zoom through raw HID (#650, Tools ▸ 3D Mouse); not checked on a physical device in the PR | same (hidapi, udev) | no | | Pen tablet / digitizer (TABLET command, calibration) | yes (Windows) | **no** | **no** | **no** | no | -| Screen magnifier following the cursor | yes | — | breaks (#39; PR #187 adds a system-cursor option) | — | — | -| Plotters and printers (PC3 devices, system printers) | yes | **no**: PDF/PNG/SVG files only; Print asks where to save the PDF (#26) | same | same | PDF bytes shown instead of a download (#134) | +| Screen magnifier following the cursor | yes | — | breaks (#39 is open; the option to keep the system cursor over the drawing area landed, #187) | — | — | +| Plotters and printers (PC3 devices, system printers) | yes | **no** system printers: PDF, PNG and SVG plotter devices only (#564); the Plot dialog writes the file (#160); CUPS printing is open PR #755 | same | same | PDF bytes shown instead of a download (#134) | ## Performance on hardware (internal numbers only) @@ -48,5 +48,6 @@ next step. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d: SpaceMouse 2D pan/zoom (#650), magnifier option (#187), winit PRs #110–#119 closed in favour of open PR #668, system printers still open (PR #755); percentage and hours not re-measured | | 2026-10-13 | minor | Zoom and pan regenerate in the background: 2–4.5 s stalls down to 26–64 ms on a hatched DWG | | 2026-10-10 | major | First hardware parity doc: GPU backends per platform, input devices, displays, plotters | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 470b6f0d8..7c6e39431 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (Swedish catalog added: complete catalog, menu headings, native-speaker terminology review; previously: complete current Korean catalog with Hangul font coverage) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audit against main e707ab4d: Chinese, Spanish and Arabic catalogs added to the table, row counts re-measured, reference-catalog lag measured, totals recomputed) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How far CADCraft's interface and drawing text are from AutoCAD's languages. Summarised in [ROADMAP.md](../ROADMAP.md#languages); work items in [gaps.md](gaps.md#localization). @@ -23,8 +23,8 @@ shaping and right-to-left text through TrueType, vertical SHX text styles. - **A display-time string catalog** (`crates/ui-egui/src/i18n/`, landed with #36): a TSV per language (context, English source, translation, `@plural` rows), Edit → Interface Language with Auto (system language), live switching, a saved choice, and tests for coverage, placeholders - and plurals ([localization.md](localization.md)). The Ukrainian and German catalogs have - **989 rows** each, + and plurals ([localization.md](localization.md)). The twelve catalogs have between 1,003 + (French) and 1,322 rows (Ukrainian, the reference), counted 2026-10-13, covering menus, command labels, tool groups and tooltips, the Start page, tabs, status controls, object snaps, drafting prompts, property labels and dialogs. Engine diagnostics, CLI/MCP responses and command history stay English, and uncatalogued text falls back to @@ -36,53 +36,60 @@ shaping and right-to-left text through TrueType, vertical SHX text styles. Bidirectional Algorithm and OpenType shaping with `harfrust` (Arabic, Persian and Urdu joining, lam-alef, ZWNJ, marks; Hebrew), in TEXT and MTEXT including wrapping (#287). Left-to-right lines are still placed one glyph per code point: **no shaping** for Devanagari and other Indic - scripts, and **no vertical text**. SHX fonts are not read; our stroke font stands in. -- **Text input:** egui/winit IME. Several upstream IME fixes are queued as PRs (#110–#119: - macOS Korean, emoji picker, Windows caret placement, X11 and Wayland), so CJK input is not yet - reliable on every platform. + scripts, and **no vertical text**. SHX fonts are not read; our stroke font stands in, and wide East Asian characters in it fill the square cells a big font would give them (#861). +- **Text input:** egui/winit IME. The upstream IME fixes (macOS Korean, emoji picker, Windows + caret placement, X11 and Wayland) were proposed as PRs #110–#119, which were closed in favour + of the consolidated, still open PR #668, so CJK input is not yet reliable on every platform. ## Languages Order and columns from craftrules' progress-docs standard. Every UI percentage is **measured** from the catalogs (0 rows for every language without a catalog file). Hours are **estimated**: -about 3–5 h per language for an Opus 5.5 agent to translate the ~990 catalog rows and fix layout, +about 3–5 h per language for an Opus 5.5 agent to translate the ~1,300 catalog rows and fix layout, plus native review by a human; extending the catalog to the remaining English-only strings (engine diagnostics, uncatalogued text) is about 4–6 h, counted once in the first row. | Language | Code | UI strings translated | Dialogs / tooltips / help | Script support | Native review | Status | Estimate to `full` | |---|---|---|---|---|---|---|---| | English | en | source (100%) | 100% (help is a command reference, not AutoCAD-sized help) | Latin: yes | n/a | full | — | -| Simplified Chinese | zh-Hans | 0 (0%) | 0% | CJK glyphs render via fallback; IME fixes pending (#110–#119); no vertical text | no | none | 8–12 h (includes extending the catalog, 4–6 h) | -| Spanish | es | 0 (0%) | 0% | Latin: yes | no | none | 3–5 h | +| Simplified Chinese | zh-Hans | 1,112 catalog rows; 210 reference rows untranslated (English fallback) | partial | CJK glyphs render via the CJK interface fonts loaded in every language (#861); IME fixes pending (#668); no vertical text | contributed by @mayloglog (#684); no native review recorded | partial | 2–4 h + native review | +| Spanish | es | 1,239 catalog rows; 87 reference rows untranslated | dialogs and tooltips yes | Latin: yes | contributed by @PedroGuille (#610) and extended by @diegozpy (#680); no native review recorded | partial | 1–2 h | | Hindi | hi | 0 (0%) | 0% | Devanagari: no shaping | no | none | 3–5 h + 15–25 h shaping (shared with Arabic) | -| Arabic | ar | 0 (0%) | 0% | Drawing text shaped and laid out right to left (#287); the UI is not mirrored | no | none | 3–5 h + 15–25 h RTL UI | -| French | fr | ≈ 900 catalog rows (gaps reported, English fallback) | partial | Latin: yes | contributed by @pechnikov2026-star (#624); no native review yet | partial | 2–4 h | -| Russian | ru | ≈ 900 catalog rows (gaps reported, English fallback) | partial | Cyrillic: yes (bundled egui fonts) | contributed by @pechnikov2026-star (#624); no native review yet | partial | 2–4 h | -| Portuguese | pt | 0 (0%) | 0% | Latin: yes | no | none | 3–5 h | +| Arabic | ar | 1,229 catalog rows; 99 reference rows untranslated | partial | Drawing text shaped and laid out right to left (#287); interface fonts for Arabic on Linux, Windows and macOS; the UI is not mirrored (reading labels right to left is open PR #996) | contributed by @hasan-sdaif (#798); no native review recorded | partial | 1–2 h + 15–25 h RTL UI | +| French | fr | 1,003 catalog rows; 319 reference rows untranslated | partial | Latin: yes | contributed by @pechnikov2026-star (#624); no native review yet | partial | 2–4 h | +| Russian | ru | 1,004 catalog rows; 318 reference rows untranslated | partial | Cyrillic: yes (bundled egui fonts) | contributed by @pechnikov2026-star (#624); no native review yet | partial | 2–4 h | | Indonesian | id | 0 (0%) | 0% | Latin: yes | no | none | 3–5 h | -| Japanese | ja | 0 (0%) | 0% | CJK glyphs render; IME pending; no vertical text | no | none | 4–6 h | -| German | de | 989 catalog rows (≈ 100% of the catalog; ≈ 80% of all UI strings, estimated: engine diagnostics and uncatalogued text stay English) | dialogs and tooltips yes; command reference searchable in German | Latin: yes (bundled egui fonts cover ä ö ü Ä Ö Ü ß; long strings will need layout checks) | no native review | partial | 1–2 h | -| Korean | ko | 1,235 rows (1,229 ordinary, 4 menu, 2 count); full existing catalog union and marked UI coverage | dialogs, tooltips, Options and translated command-reference labels | UI requires catalog-covering installed or optional craft-fonts Hang/Kore face; English fallback without one; IME fixes still pending | original AI-assisted translation; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native review + platform layout/IME validation | +| Japanese | ja | 0 (0%) | 0% | CJK glyphs render; IME pending (#668); no vertical text | no | none | 4–6 h | +| German | de | 1,030 catalog rows; 292 reference rows untranslated (it had 989, the whole catalog, on 2026-10-11) | dialogs and tooltips yes; command reference searchable in German | Latin: yes (bundled egui fonts cover ä ö ü Ä Ö Ü ß; long strings will need layout checks) | no native review | partial | 2–4 h | +| Korean | ko | 1,235 catalog rows (1,229 ordinary, 4 menu, 2 count); 95 reference rows untranslated | dialogs, tooltips, Options and translated command-reference labels | UI requires catalog-covering installed or optional craft-fonts Hang/Kore face; English fallback without one; IME fixes still pending | original AI-assisted translation; independent native proofreading pending | complete when it landed; reference rows added since fall back to English | native review + platform layout/IME validation | | Vietnamese | vi | 0 (0%) | 0% | Latin with stacked diacritics: renders per code point, untested | no | none | 3–5 h | -| Ukrainian | uk | 989 catalog rows (≈ 100% of the catalog; ≈ 80% of all UI strings, estimated: engine diagnostics and uncatalogued text stay English) | dialogs and tooltips yes; command reference searchable in Ukrainian | Cyrillic: yes (bundled egui fonts) | translated by a contributor; no second review | partial | 2–4 h | -| Czech | cs | 1,202 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings; command reference searchable in Czech | Latin: yes (bundled egui proportional and monospace fonts; Czech letters and quotes tested) | AI-assisted by @Losminek; independent review pass; not yet proofread by a native speaker | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | -| Swedish | sv | 1,235 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | -| Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | +| Ukrainian | uk | 1,322 catalog rows (the reference catalog; every new command needs a row here) | dialogs and tooltips yes; command reference searchable in Ukrainian | Cyrillic: yes (bundled egui fonts) | translated by a contributor; no second review | partial (≈ 80% of all UI strings, estimated: engine diagnostics and uncatalogued text stay English) | 2–4 h | +| Portuguese (Brazilian) | pt-BR | 1,240 catalog rows; 86 reference rows untranslated | dialogs and tooltips yes | Latin: yes (bundled egui fonts; accented letters tested) | @WladmirJunior and @RicSchonfelder (AI-assisted); no native proofreading pass | complete when it landed (#791); reference rows added since fall back to English | native review | +| Czech | cs | 1,214 catalog rows; 116 reference rows untranslated | dialogs and tooltips yes; contextual menu headings; command reference searchable in Czech | Latin: yes (bundled egui proportional and monospace fonts; Czech letters and quotes tested) | AI-assisted by @Losminek; independent review pass; not yet proofread by a native speaker | complete when it landed; reference rows added since fall back to English | native review + shared English-only UI work | +| Swedish | sv | 1,235 catalog rows; 95 reference rows untranslated | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete when it landed; reference rows added since fall back to English | line-by-line proofreading + shared English-only UI work | +| Italian | it | 1,231 catalog rows; 93 reference rows untranslated | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete when it landed; reference rows added since fall back to English | native review + shared English-only UI work | -Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean and Swedish. -Czech, Swedish and Brazilian Portuguese cover the reference catalog and every marked UI literal; engine diagnostics and uncatalogued text -remain English. AutoCAD for Mac ships 7 -non-English languages (zh-Hans, es, fr, ja, de, ko, it); of those, CADCraft now ships German and Korean, -and additionally Ukrainian, which AutoCAD for Mac doesn't ship. +"Rows" are the catalog's lines that are neither comments nor blank (ordinary, `menu` and `@plural` rows), +counted on 2026-10-13. "Reference rows untranslated" compares each catalog's (context, English source) +keys with Ukrainian's, the reference that every new command must extend: 75 of those rows (for +example the 3D Mouse dialog, Align Multileaders, the Block Editor prompt) are missing from every other +catalog, so those labels show in English there. The test suite reports such gaps but doesn't fail on them. -**Total to put all twelve at `full`:** about 55–95 Opus 5.5 hours (catalog extension 4–6 h, -ten translations 30–50 h, complex-script shaping and RTL 30–45 h), plus native-speaker review for +Languages shipped (`LANGUAGES` in `crates/ui-egui/src/i18n/mod.rs`): Ukrainian, Brazilian Portuguese, German, Spanish, Czech, +Russian, French, Simplified Chinese, Italian, Korean, Swedish and Arabic, twelve catalogs. Engine diagnostics and uncatalogued text +remain English. AutoCAD for Mac ships 7 non-English languages (zh-Hans, es, fr, ja, de, ko, it); CADCraft ships six of them (all +but Japanese), and additionally Ukrainian, Brazilian Portuguese, Czech, Russian, Swedish and Arabic, which AutoCAD for Mac doesn't ship. + +**Total to put the languages at `full`:** about 62–102 Opus 5.5 hours, summed from the table's estimates (catalog extension 4–6 h, +four languages not started 13–21 h, closing the reference-catalog gaps of the eleven partial or lagging catalogs 15–30 h, +complex-script shaping and RTL 30–45 h), plus native-speaker review for each language, which needs humans. Translations parallelise fully once the catalog exists. ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d: Chinese (#684), Spanish (#610, #680) and Arabic (#798) rows filled in from the catalogs; row counts re-measured for all twelve; each catalog's untranslated reference rows measured; German and the "complete" catalogs no longer called complete; PRs #110–#119 noted as closed in favour of #668; total hours recomputed (55–95 → 62–102) | | 2026-10-13 | minor | Swedish added: 1,235 rows, one/other plurals, menu headings, locale/preferences/menu/font/render tests; no gaps in the marked UI literals; terminology and the running app reviewed by a native speaker | | 2026-10-13 | minor | Korean added: full 1,235-row existing catalog union, single count form, locale/persistence/live-switch tests, and validated Hangul UI fonts; native review and platform verification pending | | 2026-10-12 | minor | Italian added: 1,227 rows, one/other plurals, two `menu` headings, locale/preference/plural/font tests; AI-assisted, native proofreading pending | diff --git a/docs/localization.md b/docs/localization.md index 86bcdc6e2..952276a1f 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -33,8 +33,8 @@ dialogs, and the About window's controls. The command reference can be searched command ID, English label, or translated label. Ukrainian has enforced coverage; missing entries in the other catalogs are reported by tests and fall back to English. -Czech has 1,202 catalog rows, covering the reference catalog and every marked UI -literal, including Options. Four `menu` entries distinguish menu headings from object/command +Czech has 1,214 catalog rows (counted 2026-10-13), covering the reference catalog and every marked UI +literal when it landed, including Options. Four `menu` entries distinguish menu headings from object/command labels: **Zobrazení / Pohled**, **Kreslení / Kreslit**, **Kótování / Kóta**, and **Modifikace / Upravit**. The translation is AI-assisted work by @Losminek, reviewed against Czech desktop and CAD UI conventions and an independent review pass; it has not yet been proofread by a native speaker. @@ -46,13 +46,21 @@ The translations are original, AI-assisted Korean CAD terminology (for example, 치수, 모깎기, 모따기, 간격띄우기 and 객체 스냅). Independent native proofreading and platform-specific layout/IME validation remain follow-up work. -Brazilian Portuguese has 1,231 catalog rows and also covers the reference catalog and every marked UI -literal: commands, menus, tool groups and tooltips, object snaps, drafting prompts, dialogs and -Preferences; its gaps are now zero. Its plural rule is `one|other` (0 and 1 are `one`), as CLDR defines +Brazilian Portuguese has 1,240 catalog rows and also covered the reference catalog and every marked UI +literal when it landed (#791): commands, menus, tool groups and tooltips, object snaps, drafting prompts, dialogs and +Preferences. Its plural rule is `one|other` (0 and 1 are `one`), as CLDR defines for `pt`, and the catalog's accented letters (`Á Â Í Ó Ú à á â ã ç é ê í ó ô õ ú`) render in the bundled fonts. The original catalog was contributed by @WladmirJunior; the remaining rows were completed by @RicSchonfelder with AI assistance and have not yet been proofread by a native speaker. +The other catalogs, with their rows counted on 2026-10-13: Ukrainian 1,322 (the reference), Spanish 1,239, +Italian 1,231, Swedish 1,235, Arabic 1,229, Simplified Chinese 1,112, German 1,030, Russian 1,004 and French 1,003. +Strings added to the Ukrainian catalog since a language's last update (for example the 3D Mouse dialog and the +Block Editor prompt) show in English there; [localization-parity.md](localization-parity.md) lists the count per language. +Arabic uses the six CLDR plural forms and a font chain for Arabic script (Noto Sans Arabic, Segoe UI/Tahoma, Geeza Pro); +the interface is not mirrored. CJK interface fonts load in every language, so Chinese, Japanese and Korean file, layout +and layer names don't show as boxes (#861). + Drawing titles, layer/layout/block/style names, parameter names and expressions, text in a drawing, and command-line input are user data and retain their original spelling. Clickable command keywords retain their English spelling so the text shown matches the input accepted @@ -90,9 +98,10 @@ The implementation follows the display-time catalog pattern used by Optional `menu` entries translate menu headings via `i18n::menu` / `i18n::tr_menu`; without one, the ordinary translation is used. - `@plural` entries hold the language's forms for integer counts: Ukrainian `one|few|many`, - German and Spanish `one|other`, Brazilian Portuguese `one|other` (0 and 1 are `one`), - Czech `one|few|other` (1; 2–4; everything else, including 0, 11, 21 and 22). - Korean has one form (`other`) for all integer counts. + German, Spanish, Italian, Swedish and Simplified Chinese `one|other`, Brazilian Portuguese and French `one|other` (0 and 1 are `one`), + Russian `one|few|many` (as Ukrainian), Czech `one|few|other` (1; 2–4; everything else, including 0, 11, 21 and 22). + Korean has one form (`other`) for all integer counts; Arabic has six (`plural_arabic`). + (The rules are the `plural` and `plural_forms` fields of `LANGUAGES` in `i18n/mod.rs`.) The API takes `u64`, so fractional counts are not accepted. - Register a new catalog in `i18n::LANGUAGES`, add its preference variant and code/name, and set its integer plural rule and form count on the `Language` row. diff --git a/docs/plotters.md b/docs/plotters.md index 7ca7c785d..17afc30b3 100644 --- a/docs/plotters.md +++ b/docs/plotters.md @@ -108,9 +108,8 @@ In the file name, characters other than letters, digits, spaces and `-_()+,` bec an active offset is rejected rather than ignored. Layout plots do not use model offsets. - `exportpdf` takes the same options and always writes PDF. -Model-space PDF plots don't apply the paper's margins yet. They fit the drawing inside the -default margins. PNG plots apply them. SVG plots show a layout's whole sheet, or the -model-space extents. +Model-space PDF plots apply the device paper's margins as the printable area (#633; `io/src/pdf.rs`), +as PNG plots do. SVG plots show a layout's whole sheet, or the model-space extents. ## Plot transparency diff --git a/docs/roadmap.md b/docs/roadmap.md index 3d46be9df..f5147d410 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # CADCraft roadmap detail -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (Block Editor for static blocks: "Use blocks" evidence updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audit against main e707ab4d: alpha-gate evidence, beta checklist states and milestone notes; percentages and hours not re-scored) · **Target:** Autodesk AutoCAD 2027 Forward-looking plan: milestones with status, the current focus, and what comes next with estimates. The summary is [ROADMAP.md](../ROADMAP.md); the work items behind every line are in @@ -10,19 +10,19 @@ Opus 5.5 agent-hours. ## Current focus 1. **Gate and land.** (`cargo fmt` on main is fixed.) Add a PR workflow that runs - `cargo xtask ci`, then review and land the 47 open PRs, most of them community bug fixes + `cargo xtask ci` (open PR #847), then review and land the 89 open PRs (2026-10-13), most of them community bug fixes (S1–S3). ≈ 15–25 h. 2. **Stop losing data on save** (FF1, FF2, FF7) and save DWG/DXF at a chosen version (FF3). ≈ 30–45 h. 3. **A real-file corpus** and a check of our output in AutoCAD (FF5, needs the owner). -4. **Precision input:** object snap tracking, extension/parallel snaps, FROM/M2P/TK, typed snap - overrides, editable dynamic input (U1–U4). ≈ 25–35 h. -5. **Unstub the prompt options** of the most-used commands (F1). ≈ 15–25 h. -6. **Autosave, recovery, AUDIT, RECOVER** (F4). ≈ 10–15 h. -7. **The rest of the alpha gate:** block editor and REFEDIT, xref attach (F2, F3), and plot styles - with a plot dialog and preview (F14). ≈ 50–80 h. +4. ~~**Precision input:** object snap tracking, extension/parallel snaps, FROM/M2P/TK, typed snap + overrides, editable dynamic input (U1–U4).~~ Done (#379, #393, #441, #60, #519); U4 and the grip and selection leftovers (U5, U6) remain. +5. ~~**Unstub the prompt options** of the most-used commands (F1).~~ Done (#397, #408, #547, #558, #559); the stubs left are listed in F1. +6. ~~**Autosave, recovery, AUDIT, RECOVER** (F4).~~ Done on the desktop (#406, #416); F4 lists the web-build leftovers. +7. **The rest of the alpha gate:** ~~block editor and REFEDIT, xref attach (F2, F3), and plot styles + with a plot dialog and preview (F14)~~ landed (#824, #818, #525, #410, #160, #186); left: dynamic-block authoring, XCLIP, editing an xref in place (F2, F3), and printing beyond files (F14, H3). ≈ 50–80 h. -Items 2–5 and 7 are the [alpha gate](#alpha-gate) rows. +Items 2 and 7 are the open [alpha gate](#alpha-gate) rows. ## Alpha gate @@ -32,11 +32,11 @@ the alpha checklist. Main platform: macOS. | Core workflow | Works end to end? | Evidence | Hours to pass | |---|---|---|---| -| Draw and modify precisely with object snaps and tracking | **partial, blocking** | Running snaps, polar, ortho and coordinate entry work; object snap tracking, extension and parallel snaps are toggles with no behaviour; no FROM/M2P/TK or typed snap overrides; TRIM/EXTEND standard mode, OFFSET Erase/Layer/Multiple, ROTATE Reference print "not available yet"; ellipse/spline intersections approximate ([ui-parity.md](ui-parity.md), [gaps.md](gaps.md) U1, U3, U4, F1) | 35–50 | -| Dimension and annotate | partial, not blocking | All core DIM types, associativity, DIMSTYLE variables (43 of ~80), TEXT/MTEXT, MLEADER, tables work; no DIMSTYLE dialog, MTEXT editor not in place, MLEADER thin (F7, F9, F10). A drafter can dimension a sheet end to end | 0 for the gate (beta work) | -| Use blocks (insert library blocks, edit them, attributes, xrefs) | **partial, blocking** | Static BLOCK/INSERT/attributes, ATTSYNC, BATTMAN editing, xrefs (#525) and the Block Editor (BEDIT/BSAVE/BCLOSE: every reference updates) work; no REFEDIT, so a block can't be edited in place in the drawing; no XCLIP; dynamic blocks from other drawings lose their behaviour (F2, F3) | 35–55 | +| Draw and modify precisely with object snaps and tracking | **partial, blocking** | Running snaps, polar, ortho, coordinate entry, object snap tracking, extension, parallel and apparent snaps (#379), FROM/M2P/TK and typed snap overrides, TRIM/EXTEND, OFFSET and ROTATE options (#397) work; ellipse/spline intersections approximate; a few prompt options still print "not available yet" ([ui-parity.md](ui-parity.md), [gaps.md](gaps.md) U4, F1) | 35–50 | +| Dimension and annotate | partial, not blocking | All core DIM types, associativity, DIMSTYLE variables (43 of ~80), TEXT/MTEXT, MLEADER (with MLEADEREDIT/ALIGN/COLLECT, #816), tables and the in-place MTEXT editor (#792) work; no DIMSTYLE dialog, MLEADER styles thin, no fields (F7, F9, F10). A drafter can dimension a sheet end to end | 0 for the gate (beta work) | +| Use blocks (insert library blocks, edit them, attributes, xrefs) | **partial, blocking** | Static BLOCK/INSERT/attributes, ATTSYNC, BATTMAN editing, xrefs (#525), the Block Editor (BEDIT/BSAVE/BCLOSE: every reference updates), REFEDIT (#818: a block reference is edited in place) and dynamic block references (visibility, distances, stretch and move actions, lookups, grips; #838–#883) work; no XCLIP, an xref can't be edited in place, no dynamic-block authoring (F2, F3) | 35–55 | | Layers, layouts and plotting a sheet | **partial, blocking** | Layers, layouts, viewports, page setups, PDF output, plot styles (CTB/STB, #410), the Plot dialog (#160), Plot Preview and PUBLISH (#186) and plotter devices (#564) work; printers only via PDF/PNG/SVG files (F14, H3) | 15–25 | -| Save DWG that AutoCAD opens without loss, and reopen others' DWGs | **no** | DXF keeps what we don't model (#528) and writes native MULTILEADERs (#459, not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects and some foreign data; never checked in AutoCAD; no real-file tests; a 10 MB DWG failed after ~2 min (#57) (FF1–FF6) | 40–60 + owner (real-file corpus, AutoCAD check) | +| Save DWG that AutoCAD opens without loss, and reopen others' DWGs | **no** | DXF keeps what we don't model (#528) and writes native MULTILEADERs (#459, not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects and some foreign data (ACIS data of solids is kept, #781; damaged DWGs open partially, #859); never checked in AutoCAD; no real-file tests; a 10 MB DWG failed after ~2 min (#57) (FF1–FF6) | 40–60 + owner (real-file corpus, AutoCAD check) | | **To alpha** | | | **≈ 125–190** | Ready for real work is ≈ 38%, also under the ~40% alpha bar; closing the gate rows lifts it past @@ -49,16 +49,16 @@ remaining gaps are known bugs and edge features (≈ 75% ready for real work). | Item | State | Est. | |---|---|---| -| DWG/DXF: nothing lost on save; MULTILEADER native; version choice; code pages; real-file corpus green; verified in AutoCAD | not started | 50–75 | +| DWG/DXF: nothing lost on save; MULTILEADER native; version choice; code pages; real-file corpus green; verified in AutoCAD | partial (DXF lossless #528, MULTILEADER #459, version choice #421, code pages #505 landed; corpus and AutoCAD check not started) | 50–75 | | 2D geometry exact for ellipses and splines; polyline offset correct; relative tolerances | not started | 50–80 | | Precision input at AutoCAD level (tracking, dynamic input, overrides, point modifiers, grips, selection keywords, context menus) | partial | 90–140 | | Every Draw/Modify prompt option works; associative arrays | partial | 40–60 | | Annotation depth: DIMSTYLE manager and variables, missing DIM commands, in-place MTEXT, fields, MLEADER editing, annotative scaling, tables | partial | 90–130 | -| Xrefs, block editor, dynamic blocks, groups, attribute tools | not started | 90–135 | +| Xrefs, block editor, dynamic blocks, groups, attribute tools | partial (xrefs, Block Editor, REFEDIT, groups, attribute tools and dynamic block references landed; authoring, XCLIP and in-place xref editing not started) | 90–135 | | Plot styles, plot preview, PUBLISH, non-rectangular viewports | partial | 30–45 | | Autosave, recovery, AUDIT/RECOVER, Options dialog, templates, SHX, user `.lin`/`.pat` | partial | 40–60 | | AutoLISP core subset and SCRIPT | done (AutoLISP #758, SCRIPT #693); Visual LISP, DCL and reactors to come | 30–50 | -| Catalog plus AutoCAD for Mac's languages | not started | 30–45 | +| Catalog plus AutoCAD for Mac's languages | partial (twelve catalogs shipped, six of AutoCAD for Mac's seven other languages; Japanese and the catalog extension not started) | 30–45 | | Stability: CI gate, issue backlog, command smoke sweep, geometry fuzzing | partial | 30–50 | | Platforms: web open/save, Windows/Linux runtime checks; performance at 1M entities and large DWG | partial | 20–35 | | **Total to beta** | | **≈ 600–930** | @@ -74,7 +74,7 @@ agents that built each milestone, are in the progress log of [ROADMAP.md](../ROA | # | Milestone | Status | Remaining (h) | |---|---|---|---| | M0 | Skeleton and vertical slice: workspace, AutoCAD-style UI, command line, draw/modify basics, DXF, CLI, MCP, web | done | — | -| M1 | Drafting core: every 2D Draw command and option, dynamic input, object snap tracking, snap overrides | ≈ 55% (Draw breadth strong; tracking, dynamic input, overrides missing) | 35–55 | +| M1 | Drafting core: every 2D Draw command and option, dynamic input, object snap tracking, snap overrides | ≈ 55% (percentage from 2026-10-10 and not re-scored: tracking, dynamic input and overrides have landed since) | 35–55 | | M2 | Modify: grips, PEDIT, SPLINEDIT, LENGTHEN, BLEND, ALIGN, associative arrays, trim/extend for all curves, MATCHPROP UI | ≈ 50% | 45–70 | | M3 | Layers and properties | ≈ 70% (open layer bugs #71–#75, #87) | 10–15 | | M4 | Annotation: DIM*, DIMSTYLE manager, MLEADER, in-place MTEXT, fields, tables, annotative scaling, SHX | ≈ 40% | 90–130 | @@ -85,8 +85,8 @@ agents that built each milestone, are in the progress log of [ROADMAP.md](../ROA | M9 | Parametric | ≈ 50% | 20–30 | | M10 | Performance: 1M entities at 60 fps, large DWG loads | ≈ 60% (internal numbers only) | 20–40 | | M11 | 3D: UCS, orbit, visual styles, solids, surfaces, meshes, sections, rendering | ≈ 2% | 300–450 | -| M12 | Automation: AutoLISP, SCRIPT, action recorder, sheet sets, Express Tools | ≈ 15% (MCP, CLI, control channel done) | 130–220 | -| M13 | 1.0 polish: preferences, workspaces, localisation, accessibility, signed packages, docs | ≈ 15% (signed packages for every platform exist; themes done; string catalog with Ukrainian and German, live language switching, #36) | 110–170 | +| M12 | Automation: AutoLISP, SCRIPT, action recorder, sheet sets, Express Tools | ≈ 15% (percentage from 2026-10-10 and not re-scored; MCP, CLI, control channel, AutoLISP core #855 and SCRIPT #693 done) | 130–220 | +| M13 | 1.0 polish: preferences, workspaces, localisation, accessibility, signed packages, docs | ≈ 15% (signed packages for every platform exist; themes done; string catalog with twelve languages, live language switching, #36; percentage from 2026-10-10 and not re-scored) | 110–170 | | — | Geometry precision (cross-cutting, see [geometry-parity.md](geometry-parity.md)) | ≈ 40% | 70–110 | | — | AI features | ≈ 0% in-app | 40–80 | | | **Remaining to full parity** | | **≈ 1,300–2,100** | @@ -103,6 +103,7 @@ AutoLISP surface, AI features with openly licensed local models, and every remai | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d: alpha-gate evidence for drafting, annotation, blocks and DWG rows; beta-checklist states for DWG/DXF, blocks and languages; current-focus items 4–7; milestone notes M1, M12, M13; percentages and hours not re-scored | | 2026-10-12 | minor | Block Editor for static blocks landed: "Use blocks" evidence updated; status and hours unchanged (REFEDIT and dynamic blocks remain) | | 2026-10-11 | minor | Alpha-gate evidence refreshed for merged work (#459, #525, #528, #160, #186, #564); statuses and hours unchanged | | 2026-10-10 | minor | Merged main: fmt fixed, Ukrainian catalog noted in M13, ready for real work 38% | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bdf89d03f..a1c7fc9d4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (Block Editor for static blocks; blocks evidence updated, numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (evidence text re-audited against main e707ab4d; percentages, hours and breadth counts not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -148,14 +148,14 @@ presence: an option that prints "not available yet" doesn't count. |---|---:|---:|---|---|---| | Draw (2D) | 13% | 60% | 15–25 | ARC 11/11 methods, CIRCLE 6/6, RECTANG all options, REVCLOUD, WIPEOUT, XLINE; PLINE arc options and SPLINE options done (#397, #408); MLINE, REGION and HELIX are objects (#510); isometric drafting (#556) | [gaps](gaps.md#features) | | Modify | 15% | 50% | 40–60 | TRIM/EXTEND, OFFSET, ROTATE, PEDIT and SPLINEDIT options done (#397, #558, #559); associative arrays with ARRAYEDIT (#448), no array grips; MATCHPROP picker and Settings (#439) | [gaps](gaps.md#features) | -| Geometry precision | 10% | 40% | 70–110 | exact for lines/arcs/circles; ellipse and spline intersections, offsets, closest points tessellated; absolute tolerances; polyline offset doesn't recompute bulges | [geometry-parity](geometry-parity.md) | -| Layers and properties | 7% | 70% | 10–15 | Layer Properties Manager with filters, states, VP overrides; QSELECT; Quick Properties; transparency; linetype manager thin; 19 linetypes of ~45 | [gaps](gaps.md#features) | +| Geometry precision | 10% | 40% | 70–110 | exact for lines/arcs/circles; ellipse and spline intersections, offsets, closest points tessellated; absolute tolerances; polyline offset recomputes arc bulges since #825 but has no loop cleanup | [geometry-parity](geometry-parity.md) | +| Layers and properties | 7% | 70% | 10–15 | Layer Properties Manager with filters, states, VP overrides; QSELECT; Quick Properties; object transparency drawn on screen, in exports and in plots (#764); linetype manager thin; 19 linetypes of ~45 | [gaps](gaps.md#features) | | Dimensions | 9% | 45% | 25–35 | all core DIM types and associativity; style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT, QDIM modes (#507) and TOLERANCE (#420); no DIMSTYLE manager dialog or smart DIM | [gaps](gaps.md#features) | -| Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | -| Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | +| Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); in-place editor with formatting toolbar and ruler for new MTEXT (#792; existing text is edited with TEXTEDIT, in-place editing of it is open PR #1002); no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | +| Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); MLEADEREDIT, MLEADERALIGN and MLEADERCOLLECT (#816); tables with cell styles, formulas, breaking and CSV data links (#534); no FIELD (open PR #551) | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | -| Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT, REFSET and REFCLOSE (#818); dynamic block references read and edited, with grips (#838–#883); no dynamic-block authoring, XCLIP (open PR #728), DesignCenter | [gaps](gaps.md#features) | +| Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468), MVIEW Restore (#633); no system printers (CUPS printing is open PR #755) | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563), MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | | 3D modelling, visualisation, rendering | 5% | 2% | 300–450 | no UCS, 3D views, orbit, solids, surfaces, meshes, sections, visual styles, materials, lights or rendering; 150 of the 491 menu items | [gaps](gaps.md#features) | @@ -169,12 +169,12 @@ presence: an option that prints "not available yet" doesn't count. | Features (table above) | 35% | 41% | 735–1,115 | estimated | this file | | UI/UX fidelity (point entry, snaps, tracking, dynamic input, grips, selection, command line, chrome) | 15% | 43% | 100–160 | estimated, weighted in the doc | [ui-parity](ui-parity.md) | | File formats (DWG/DXF fidelity first) | 20% | 30% | 170–280 | estimated | [file-format-parity](file-format-parity.md) | -| Stability and correctness | 10% | 35% | 30–50 | estimated: about 60 bug fixes merged on 2026-10-10 alone, 30 open issues, `cargo fmt` failing on main (PR #194), no CI runs the Rust tests on pull requests | [gaps](gaps.md#stability) | +| Stability and correctness | 10% | 35% | 30–50 | estimated: about 60 bug fixes merged on 2026-10-10 alone, 150 open issues (`gh issue list`, 2026-10-13), `cargo fmt` fixed on main, no CI runs the Rust tests on pull requests (PR #847 open) | [gaps](gaps.md#stability) | | Performance | 5% | 60% | 20–40 | internal numbers only (200k entities fluent); 1M entities and large DWG loads untested; a 10 MB DWG took ~2 min to fail (#57) | [hardware-parity](hardware-parity.md#performance-on-hardware-internal-numbers-only) | -| Ecosystem and automation (AutoLISP/Visual LISP, .NET/ObjectARX, CUI, APPLOAD, Express Tools, App Store) | 5% | 10% | 120–200 | estimated; MCP, CLI and the control channel are ahead of AutoCAD, but no LISP, CUI or plug-ins | [gaps](gaps.md#ecosystem-and-automation) | +| Ecosystem and automation (AutoLISP/Visual LISP, .NET/ObjectARX, CUI, APPLOAD, Express Tools, App Store) | 5% | 10% | 120–200 | estimated; MCP, CLI and the control channel are ahead of AutoCAD; AutoLISP core (#855) and SCRIPT (#693) landed, but no Visual LISP, CUI or plug-ins | [gaps](gaps.md#ecosystem-and-automation) | | Hardware | 3% | 45% | 15–25 | estimated | [hardware-parity](hardware-parity.md) | -| Platforms | 3% | 75% | 15–25 | macOS, Windows (x64/x86/arm64), Linux, FreeBSD, web: more than AutoCAD; but the web build can't open or save files reliably (#55, #133, #134) and has no DWG, and Windows/Linux get little runtime testing | [gaps](gaps.md#platforms) | -| Localization | 3% | 5% | 60–100 | measured: string catalog with Ukrainian (936 rows, #36); none of AutoCAD for Mac's 7 other languages | [localization-parity](localization-parity.md) | +| Platforms | 3% | 75% | 15–25 | macOS, Windows (x64/x86/arm64), Linux, FreeBSD, web: more than AutoCAD; but the web build's plot shows raw PDF bytes (#134; open and save fixed, #55, #133) and it has no DWG, and Windows/Linux get little runtime testing | [gaps](gaps.md#platforms) | +| Localization | 3% | 5% | 60–100 | string catalog with twelve languages (Ukrainian 1,322 rows, #36; six of AutoCAD for Mac's 7 other languages, all but Japanese); the 5% and the hours are from 2026-10-10 and not re-scored | [localization-parity](localization-parity.md) | | AI features (Autodesk Assistant, Smart Blocks, Markup Assist) | 1% | 20% | 40–80 | none of AutoCAD's in-app AI; agent control over MCP is a different strength | [gaps](gaps.md#ai-features) | | **Ready for real work** | 100% | **≈ 38%** | **≈ 1,300–2,100** | | | @@ -223,6 +223,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Re-audit against main e707ab4d: evidence text of the text, leaders, blocks, layouts, ecosystem, stability, platforms, localization and geometry rows refreshed for #633, #764, #792, #816, #818, #825, #838–#883, #855; percentages, hours and breadth counts (245/491, 233/491) not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | | 2026-10-12 | minor | Blocks row evidence: Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); percentages and hours not re-measured | | 2026-10-11 | minor | Evidence text of the feature-area rows refreshed for merged work (#397, #406, #408, #417, #420, #433, #448, #451, #453, #459, #468, #507, #510, #525, #534, #546, #547, #558, #563, #564, #567, #571); parity percentages and hours not re-measured | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5495d4813..179a696f9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,17 +1,19 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (animation effects follow the operating system's setting) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-13 · **Last updated:** 2026-10-13 · **Change:** minor (re-audit against main e707ab4d: rows that earlier work had already closed corrected; area percentages and the 48% not re-measured) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How CADCraft's interaction compares with AutoCAD's: point entry, object snaps, tracking, dynamic input, grips, selection, the command line, chrome and navigation. A drafter's speed in AutoCAD comes from these, so "the command exists" isn't enough: it has to accept the same input, snap to the same points and respond to the same keys. Work items: [gaps.md](gaps.md#uiux). -**Headline (estimated): UI/UX fidelity ≈ 48%.** The command line, point syntax, the common -running snaps, polar/ortho, object snap tracking and the palettes are real, and so are the -Extension, Parallel and Apparent Intersection snaps (#379); dynamic input is a read-only -tooltip; FROM, M2P, TK and point filters don't exist; hot-grip options are advertised but -ignored; there are no context menus. Remaining: **≈ 110–170 Opus 5.5 hours**. +**Headline (estimated): UI/UX fidelity ≈ 48%.** The command line, point syntax (FROM, M2P, TK, +point filters, typed snap overrides), the common running snaps, polar/ortho, PolarSnap, object snap +tracking, Dynamic Input (pointer boxes, grip dimensional input, DYNPROMPT), hot-grip options with +several hot grips, shortcut menus and the palettes are real, and so are the Extension, Parallel and +Apparent Intersection snaps (#379). Missing: lasso selection, selection cycling, grip hover menus, +multifunctional grips on dimensions and text, workspaces and the navigation bar. The 48% and the area +percentages below are from 2026-10-11 and were not re-measured. Remaining: **≈ 110–170 Opus 5.5 hours**. ## How this was measured @@ -49,7 +51,7 @@ ignored; there are no context menus. Remaining: **≈ 110–170 Opus 5.5 hours** | Architectural/engineering distances `5'6-1/2"` | yes | yes | `units.rs:93-140` | | `FROM` (base point + offset) | yes | yes: "Base point:", ":" with `@` measured from the base; nests with M2P and filters | `pointmod.rs` | | `M2P` / `MTP` (midpoint between two points) | yes | yes | `pointmod.rs` | -| `TK` (tracking) | yes | **no** | | +| `TK` (tracking) | yes | yes (`TK`, or `TRACKING` from three letters; `TT` is the temporary track point) | `pointmod.rs` | | Point filters `.x`, `.y`, `.xy`, `.z` | yes | yes (`.x` … `.yz`, "(need YZ):"); Z is asked for and dropped (no 3D) | `pointmod.rs` | | Angle override `<45` | yes | yes: ` Date: Tue, 13 Oct 2026 21:14:29 +0200 Subject: [PATCH 003/531] fix(dxf): hostile-input hardening in the DXF reader and writer (#1025) Binary reals are finite-filtered like ASCII ones; ASCII reads a UTF-8 BOM and CR-only/mixed line ends (and the tag-count precheck counts the same lines); text is decoded per line/string, valid UTF-8 first, else the code page, in both readers; trailing spaces no longer hide SECTION/ENDSEC/EOF; integer groups reject inf/NaN and clamp to their width; hex groups pad an odd digit and drop non-hex characters in reader and writers; the ASCII writer sanitises hex and splits it at 254 digits; write_binary wraps in-range unsigned 16/32-bit values. Co-Authored-By: Claude Sonnet 5.5 --- crates/dxf/src/codepage.rs | 37 ++++++-- crates/dxf/src/lib.rs | 107 ++++++++++++++++++---- crates/dxf/tests/hardening.rs | 167 ++++++++++++++++++++++++++++++++++ crates/io/tests/codepages.rs | 6 +- 4 files changed, 286 insertions(+), 31 deletions(-) create mode 100644 crates/dxf/tests/hardening.rs diff --git a/crates/dxf/src/codepage.rs b/crates/dxf/src/codepage.rs index 6f27b5be4..ddc4ca24f 100644 --- a/crates/dxf/src/codepage.rs +++ b/crates/dxf/src/codepage.rs @@ -93,7 +93,7 @@ pub(crate) fn decode(bytes: &[u8], d: Decoder) -> Cow<'_, str> { /// line (the group code `3` between them), looked for in the HEADER section only (the scan stops /// at the first `ENDSEC`). Works on the raw bytes, before they are decoded. fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> { - let mut lines = bytes.split(|&b| b == b'\n').map(<[u8]>::trim_ascii); + let mut lines = bytes.split(|&b| b == b'\n' || b == b'\r').map(<[u8]>::trim_ascii).filter(|l| !l.is_empty()); while let Some(line) = lines.next() { if line == b"ENDSEC" { return None; @@ -108,10 +108,21 @@ fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> { None } -/// Decode a whole ASCII DXF file. Valid UTF-8 is read as UTF-8: R2007+ files, pure-ASCII files, -/// and older files from writers that ignored the code page. Anything else is decoded from the -/// file's `$DWGCODEPAGE`, or from Windows-1252 (the usual `ANSI_1252`) when the header has none -/// or names a code page CADCraft doesn't know, which is logged as a warning. +/// Decode one string of a DXF file: valid UTF-8 is read as UTF-8 (R2007+ files, pure-ASCII text, +/// and older files from writers that ignored the code page); anything else comes from the +/// code page `d`. The same policy for ASCII lines and binary strings, so one stray byte spoils +/// one string, not the whole file. +pub(crate) fn decode_text(bytes: &[u8], d: Decoder) -> Cow<'_, str> { + match std::str::from_utf8(bytes) { + Ok(s) => Cow::Borrowed(s), + Err(_) => decode(bytes, d), + } +} + +/// Decode a whole ASCII DXF file, line by line (see [`decode_text`]). Lines that aren't valid +/// UTF-8 are decoded from the file's `$DWGCODEPAGE`, or from Windows-1252 (the usual `ANSI_1252`) +/// when the header has none or names a code page CADCraft doesn't know, which is logged as a +/// warning. pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> { if let Ok(s) = std::str::from_utf8(bytes) { return Cow::Borrowed(s); @@ -126,7 +137,13 @@ pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> { } None => Decoder::Utf8, }; - decode(bytes, d) + // Split after each line terminator (CR, LF or CRLF are all ASCII, so they never occur inside + // a multi-byte character of the supported code pages) and decode each line on its own. + let mut out = String::with_capacity(bytes.len()); + for line in bytes.split_inclusive(|&b| b == b'\n' || b == b'\r') { + out.push_str(&decode_text(line, d)); + } + Cow::Owned(out) } /// The text state of a binary DXF file, learnt from its header as the tags go by: `$ACADVER` @@ -147,12 +164,12 @@ enum HeaderVar { } impl BinaryText { - /// Decode one string value of group `code` and update the state from it. Strings of R2007+ - /// files, and of files without a code page, are UTF-8 when valid (else Windows-1252); older - /// files' strings are in their code page. + /// Decode one string value of group `code` and update the state from it. A string that is + /// valid UTF-8 is read as such; otherwise it is in the file's code page (Windows-1252 for + /// R2007+ files and files without a known code page). pub(crate) fn string(&mut self, code: i32, raw: &[u8]) -> String { let d = if self.utf8 { Decoder::Utf8 } else { self.code_page.unwrap_or(Decoder::Utf8) }; - let s = decode(raw, d).into_owned(); + let s = decode_text(raw, d).into_owned(); match (code, self.var.take()) { (9, _) => { self.var = match s.trim() { diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 82ecf55e8..77b0ad89d 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -61,7 +61,9 @@ impl Value { match self { Value::Int(i) => *i, Value::Real(r) if r.is_finite() => *r as i64, - Value::Str(s) => s.trim().parse::().unwrap_or_else(|_| s.trim().parse::().map(|f| f as i64).unwrap_or(0)), + Value::Str(s) => { + s.trim().parse::().unwrap_or_else(|_| s.trim().parse::().ok().filter(|f| f.is_finite()).map_or(0, |f| f as i64)) + } Value::Bool(b) => i64::from(*b), _ => 0, } @@ -153,15 +155,25 @@ fn typed(code: i32, text: &str) -> Value { match kind_of(code) { Kind::Real => t.parse::().ok().filter(|v| v.is_finite()).map(Value::Real).unwrap_or(Value::Real(0.0)), Kind::Int16 | Kind::Int32 | Kind::Int64 => { - t.parse::().map(Value::Int).unwrap_or_else(|_| Value::Int(t.parse::().map(|f| f as i64).unwrap_or(0))) + // A float spelling ("1e3", "12.0") is accepted when finite, clamped to the group's + // width; NaN, inf and text become 0. + let (lo, hi) = match kind_of(code) { + Kind::Int16 => (i64::from(i16::MIN), i64::from(i16::MAX)), + Kind::Int32 => (i64::from(i32::MIN), i64::from(i32::MAX)), + _ => (i64::MIN, i64::MAX), + }; + t.parse::() + .map(Value::Int) + .unwrap_or_else(|_| Value::Int(t.parse::().ok().filter(|f| f.is_finite()).map_or(0, |f| (f as i64).clamp(lo, hi)))) } Kind::Bool => Value::Bool(t.parse::().unwrap_or(0) != 0), - Kind::Hex => Value::Hex(t.to_string()), + Kind::Hex => Value::Hex(normalize_hex(t)), Kind::Str => Value::Str(text.trim_end_matches(['\r', '\n']).to_string()), } } const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0"; +const UTF8_BOM: &[u8] = b"\xEF\xBB\xBF"; /// Most group codes read from one file. A `Tag` takes 40 bytes plus its text, so this bounds the /// tag list to a few GB; real drawings stay far below (a 10 MB DWG is typically a few million). pub const MAX_TAGS: usize = 50_000_000; @@ -181,8 +193,10 @@ pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result> { if let Some(body) = bytes.strip_prefix(BINARY_SENTINEL) { return parse_binary_with_limit(body, max_tags); } - // Every group code takes two lines (code, value). - let tags = bytes.iter().filter(|&&b| b == b'\n').count().div_ceil(2); + let bytes = bytes.strip_prefix(UTF8_BOM).unwrap_or(bytes); + // Every group code takes two lines (code, value); a line ends at LF, CRLF or a lone CR. + let ends = bytes.iter().enumerate().filter(|&(i, &b)| b == b'\n' || (b == b'\r' && bytes.get(i + 1) != Some(&b'\n'))).count(); + let tags = ends.div_ceil(2); if tags > max_tags { return Err(DxfError::TooLarge { tags, limit: max_tags }); } @@ -257,6 +271,22 @@ fn unescape_unicode(s: &str) -> String { out } +/// The lines of an ASCII DXF text: LF, CRLF and a lone CR (old Mac files) all end a line, like +/// [`str::lines`] otherwise (no empty line after a final terminator). +fn ascii_lines(text: &str) -> impl Iterator { + let mut rest = text; + std::iter::from_fn(move || { + if rest.is_empty() { + return None; + } + let end = rest.find(['\r', '\n']).unwrap_or(rest.len()); + let line = rest.get(..end).unwrap_or_default(); + let after = rest.get(end..).unwrap_or_default(); + rest = after.strip_prefix("\r\n").or_else(|| after.strip_prefix(['\r', '\n'])).unwrap_or(after); + Some(line) + }) +} + pub fn parse_ascii(text: &str) -> Result> { parse_ascii_with_limit(text, MAX_TAGS) } @@ -264,7 +294,7 @@ pub fn parse_ascii(text: &str) -> Result> { #[allow(clippy::while_let_loop)] fn parse_ascii_with_limit(text: &str, max_tags: usize) -> Result> { let mut tags = Vec::new(); - let mut lines = text.lines().enumerate(); + let mut lines = ascii_lines(text.strip_prefix('\u{feff}').unwrap_or(text)).enumerate(); loop { let Some((ln, code_line)) = lines.next() else { break }; let ct = code_line.trim(); @@ -282,7 +312,7 @@ fn parse_ascii_with_limit(text: &str, max_tags: usize) -> Result> { if tags.len() > max_tags { return Err(DxfError::TooLarge { tags: tags.len(), limit: max_tags }); } - if code == 0 && tags.last().is_some_and(|t| t.str() == "EOF") { + if code == 0 && tags.last().is_some_and(|t| t.str().trim_end() == "EOF") { break; } } @@ -358,7 +388,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result> { } let v = match kind_of(code) { Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))), - Kind::Real => Value::Real(c.f64()?), + Kind::Real => Value::Real(Some(c.f64()?).filter(|v| v.is_finite()).unwrap_or(0.0)), Kind::Int16 => Value::Int(i64::from(c.i16()?)), Kind::Int32 => Value::Int(i64::from(c.i32()?)), Kind::Int64 => Value::Int(c.i64()?), @@ -373,7 +403,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result> { Value::Hex(s) } }; - let eof = code == 0 && matches!(&v, Value::Str(s) if s == "EOF"); + let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF"); tags.push(Tag { code, value: v }); if tags.len() > max_tags { return Err(DxfError::TooLarge { tags: tags.len(), limit: max_tags }); @@ -418,7 +448,22 @@ pub fn write_ascii_as(tags: &[Tag], utf8: bool) -> String { Value::Real(r) => out.push_str(&format_real(*r)), Value::Int(i) => out.push_str(&i.to_string()), Value::Bool(b) => out.push_str(&i64::from(*b).to_string()), - Value::Hex(h) => out.push_str(h), + Value::Hex(h) => { + // The DXF Reference limits a binary chunk line to 254 hex digits (127 bytes); + // longer data continues in further groups of the same code. Only hex digits are + // written, so a hostile value can't inject tags. + let digits = normalize_hex(h); + let mut chunks: Vec<&str> = digits.as_bytes().chunks(254).map(|c| std::str::from_utf8(c).unwrap_or_default()).collect(); + if chunks.is_empty() { + chunks.push(""); + } + for (n, chunk) in chunks.into_iter().enumerate() { + if n > 0 { + let _ = write!(out, "\r\n{:>3}\r\n", t.code); + } + out.push_str(chunk); + } + } } out.push_str("\r\n"); } @@ -460,13 +505,11 @@ pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { } Kind::Int16 => { out.extend_from_slice(&code_bytes); - let v = t.value.as_i64().clamp(i64::from(i16::MIN), i64::from(i16::MAX)); - out.extend_from_slice(&i16::try_from(v).unwrap_or_default().to_le_bytes()); + out.extend_from_slice(&wrap_i16(t.value.as_i64())); } Kind::Int32 => { out.extend_from_slice(&code_bytes); - let v = t.value.as_i64().clamp(i64::from(i32::MIN), i64::from(i32::MAX)); - out.extend_from_slice(&i32::try_from(v).unwrap_or_default().to_le_bytes()); + out.extend_from_slice(&wrap_i32(t.value.as_i64())); } Kind::Int64 => { out.extend_from_slice(&code_bytes); @@ -494,12 +537,38 @@ pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { out } -/// The bytes of hex text, two digits each; anything that isn't a pair of hex digits is skipped. +/// Hex text cleaned up: only the hex digits are kept, and an odd trailing digit is padded with +/// `0` (so the bytes before it are never shifted). Used by the reader and both writers. +fn normalize_hex(s: &str) -> String { + let mut out: String = s.chars().filter(char::is_ascii_hexdigit).collect(); + if out.len() % 2 == 1 { + out.push('0'); + } + out +} + +/// The bytes of hex text, two digits each (see [`normalize_hex`]). fn hex_bytes(s: &str) -> Vec { - let digits: Vec = s.bytes().filter_map(|b| char::from(b).to_digit(16).and_then(|d| u8::try_from(d).ok())).collect(); + let digits: Vec = normalize_hex(s).bytes().filter_map(|b| char::from(b).to_digit(16).and_then(|d| u8::try_from(d).ok())).collect(); digits.as_chunks::<2>().0.iter().map(|[hi, lo]| (hi << 4) | lo).collect() } +/// A 16- or 32-bit integer for binary DXF: values that fit the unsigned width wrap into the +/// signed one (65535 is -1, as writers that store unsigned flags expect); anything else clamps. +fn wrap_i16(v: i64) -> [u8; 2] { + match u16::try_from(v) { + Ok(u) => u.to_le_bytes(), + Err(_) => i16::try_from(v.clamp(i64::from(i16::MIN), i64::from(i16::MAX))).unwrap_or_default().to_le_bytes(), + } +} + +fn wrap_i32(v: i64) -> [u8; 4] { + match u32::try_from(v) { + Ok(u) => u.to_le_bytes(), + Err(_) => i32::try_from(v.clamp(i64::from(i32::MIN), i64::from(i32::MAX))).unwrap_or_default().to_le_bytes(), + } +} + /// Whether `bytes` are a binary DXF file (they start with the binary sentinel). pub fn is_binary(bytes: &[u8]) -> bool { bytes.starts_with(BINARY_SENTINEL) @@ -535,12 +604,12 @@ pub fn sections(tags: &[Tag]) -> Vec
{ let mut out = Vec::new(); let mut i = 0; while i < tags.len() { - let is_sec = tags.get(i).is_some_and(|t| t.code == 0 && t.str() == "SECTION"); + let is_sec = tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim_end() == "SECTION"); if is_sec { - let name = tags.get(i + 1).filter(|t| t.code == 2).map(Tag::str).unwrap_or_default(); + let name = tags.get(i + 1).filter(|t| t.code == 2).map(|t| t.str().trim_end().to_string()).unwrap_or_default(); let start = i + 2; let mut j = start; - while j < tags.len() && !(tags.get(j).is_some_and(|t| t.code == 0 && t.str() == "ENDSEC")) { + while j < tags.len() && !(tags.get(j).is_some_and(|t| t.code == 0 && t.str().trim_end() == "ENDSEC")) { j += 1; } out.push(Section { name, tags: tags.get(start..j).unwrap_or(&[]).to_vec() }); diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs new file mode 100644 index 000000000..24bfea082 --- /dev/null +++ b/crates/dxf/tests/hardening.rs @@ -0,0 +1,167 @@ +//! Hostile-input hardening of the DXF reader and writer (#1025): one regression test per finding. + +use cadcraft_dxf::{Tag, Value, parse, parse_with_limit, sections, write_ascii, write_binary}; + +const SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0"; + +fn bin_with(f: impl FnOnce(&mut Vec)) -> Vec { + let mut b = SENTINEL.to_vec(); + f(&mut b); + b.extend_from_slice(&0i16.to_le_bytes()); + b.extend_from_slice(b"EOF\0"); + b +} + +#[test] +fn binary_reals_that_are_not_finite_become_zero() { + for bits in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let b = bin_with(|b| { + b.extend_from_slice(&10i16.to_le_bytes()); + b.extend_from_slice(&bits.to_le_bytes()); + }); + let tags = parse(&b).unwrap(); + assert_eq!(tags[0], Tag::f(10, 0.0), "{bits}"); + } +} + +#[test] +fn ascii_accepts_bom_and_cr_only_line_ends() { + let want = vec![Tag::s(0, "SECTION"), Tag::s(2, "ENTITIES"), Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")]; + let text = "0\rSECTION\r2\rENTITIES\r0\rENDSEC\r0\rEOF\r"; + assert_eq!(parse(text.as_bytes()).unwrap(), want); + let mut bom = b"\xEF\xBB\xBF".to_vec(); + bom.extend_from_slice(text.replace('\r', "\r\n").as_bytes()); + assert_eq!(parse(&bom).unwrap(), want); + // Mixed terminators. + assert_eq!(parse(b"0\r\nSECTION\r2\nENTITIES\n0\rENDSEC\r\n0\nEOF").unwrap(), want); +} + +#[test] +fn cr_only_files_count_against_the_tag_limit() { + let mut text = String::new(); + for _ in 0..50 { + text.push_str("999\rcomment\r"); + } + text.push_str("0\rEOF\r"); + assert!(parse_with_limit(text.as_bytes(), 10).is_err()); + assert_eq!(parse_with_limit(text.as_bytes(), 100).unwrap().len(), 51); +} + +#[test] +fn one_bad_byte_spoils_one_line_not_the_file() { + // Header says ANSI_1251; one line is UTF-8, one is Windows-1251, one has a stray byte. + let mut b = b"9\n$DWGCODEPAGE\n3\nANSI_1251\n1\n".to_vec(); + b.extend_from_slice("Größe".as_bytes()); + b.extend_from_slice(b"\n1\n\xCF\xF0\xE8\xE2\xE5\xF2\n0\nEOF\n"); + let t = parse(&b).unwrap(); + assert_eq!(t[1].str(), "ANSI_1251"); + assert_eq!(t[2].str(), "Größe"); + assert_eq!(t[3].str(), "Привет"); +} + +#[test] +fn ascii_and_binary_decode_alike() { + // ANSI_1252 file with UTF-8 bytes in one string and a Latin-1 byte in another. + let utf8 = "Größe".as_bytes(); + let latin = b"Caf\xE9"; + let mut a = b"9\n$DWGCODEPAGE\n3\nANSI_1252\n1\n".to_vec(); + a.extend_from_slice(utf8); + a.extend_from_slice(b"\n1\n"); + a.extend_from_slice(latin); + a.extend_from_slice(b"\n0\nEOF\n"); + let from_ascii = parse(&a).unwrap(); + let b = bin_with(|b| { + for (code, s) in [(9i16, &b"$DWGCODEPAGE"[..]), (3, b"ANSI_1252"), (1, utf8), (1, latin)] { + b.extend_from_slice(&code.to_le_bytes()); + b.extend_from_slice(s); + b.push(0); + } + }); + let from_binary = parse(&b).unwrap(); + assert_eq!(from_ascii[2].str(), "Größe"); + assert_eq!(from_ascii[3].str(), "Café"); + assert_eq!(from_binary[2].str(), "Größe"); + assert_eq!(from_binary[3].str(), "Café"); +} + +#[test] +fn trailing_spaces_keep_sections_and_eof() { + let t = parse(b"0\nSECTION \n2\nENTITIES \n0\nLINE\n0\nENDSEC \n0\nEOF \n0\nSECTION\n2\nX\n0\nENDSEC\n").unwrap(); + // The EOF with a trailing space still ends the file. + assert_eq!(t.len(), 5); + let s = sections(&t); + assert_eq!(s.len(), 1); + assert_eq!(s[0].name, "ENTITIES"); + assert_eq!(s[0].tags.len(), 1); + // Binary EOF too. + let mut b = SENTINEL.to_vec(); + b.extend_from_slice(&0i16.to_le_bytes()); + b.extend_from_slice(b"EOF \0"); + b.extend_from_slice(&1i16.to_le_bytes()); + b.extend_from_slice(b"after\0"); + assert_eq!(parse(&b).unwrap().len(), 1); +} + +#[test] +fn integer_groups_reject_non_finite_and_clamp() { + let t = parse(b"70\ninf\n70\nNaN\n70\n1e30\n70\n-1e30\n90\n1e30\n160\n1e30\n160\n-inf\n62\n12.0\n0\nEOF\n").unwrap(); + assert_eq!(t[0], Tag::i(70, 0)); + assert_eq!(t[1], Tag::i(70, 0)); + assert_eq!(t[2], Tag::i(70, i64::from(i16::MAX))); + assert_eq!(t[3], Tag::i(70, i64::from(i16::MIN))); + assert_eq!(t[4], Tag::i(90, i64::from(i32::MAX))); + assert_eq!(t[5], Tag::i(160, i64::MAX)); + assert_eq!(t[6], Tag::i(160, 0)); + assert_eq!(t[7], Tag::i(62, 12)); + assert_eq!(Value::Str("inf".into()).as_i64(), 0); +} + +#[test] +fn hex_groups_pad_odd_digits_and_drop_junk() { + let t = parse(b"310\nABC\n310\nA-B zC1\n310\n\n1004\n0aF\n0\nEOF\n").unwrap(); + assert_eq!(t[0].value, Value::Hex("ABC0".into())); + assert_eq!(t[1].value, Value::Hex("ABC1".into())); + assert_eq!(t[2].value, Value::Hex(String::new())); + assert_eq!(t[3].value, Value::Hex("0aF0".into())); + // The binary writer agrees with the reader: the odd digit is padded, nothing shifts. + let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true)).unwrap(); + assert_eq!(back[0].value, Value::Hex("ABC0".into())); +} + +#[test] +fn ascii_hex_cannot_inject_tags_and_is_split_at_254_digits() { + let evil = Tag::new(310, Value::Hex("AB\r\n0\r\nEOF".into())); + let text = write_ascii(&[evil, Tag::s(0, "EOF")]); + let back = parse(text.as_bytes()).unwrap(); + assert_eq!(back.len(), 2, "{text:?}"); + assert_eq!(back[0].value, Value::Hex("AB0EF0".into())); + let long = "AB".repeat(300); + let back = parse(write_ascii(&[Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")]).as_bytes()).unwrap(); + let sizes: Vec = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect(); + assert_eq!(sizes, vec![254, 254, 92]); + // An empty chunk is still one group. + let back = parse(write_ascii(&[Tag::new(310, Value::Hex(String::new())), Tag::s(0, "EOF")]).as_bytes()).unwrap(); + assert_eq!(back[0].code, 310); +} + +#[test] +fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() { + let tags = [ + Tag::i(70, 65535), + Tag::i(70, 40000), + Tag::i(70, 70000), + Tag::i(70, -40000), + Tag::i(90, 0xFFFF_FFFF), + Tag::i(90, 1 << 40), + Tag::i(90, -(1 << 40)), + Tag::s(0, "EOF"), + ]; + let back = parse(&write_binary(&tags, true)).unwrap(); + assert_eq!(back[0], Tag::i(70, -1)); + assert_eq!(back[1], Tag::i(70, 40000 - 65536)); + assert_eq!(back[2], Tag::i(70, i64::from(i16::MAX))); + assert_eq!(back[3], Tag::i(70, i64::from(i16::MIN))); + assert_eq!(back[4], Tag::i(90, -1)); + assert_eq!(back[5], Tag::i(90, i64::from(i32::MAX))); + assert_eq!(back[6], Tag::i(90, i64::from(i32::MIN))); +} diff --git a/crates/io/tests/codepages.rs b/crates/io/tests/codepages.rs index 40d85b3f4..64664f5bc 100644 --- a/crates/io/tests/codepages.rs +++ b/crates/io/tests/codepages.rs @@ -156,8 +156,10 @@ fn binary_dxf_honours_the_code_page() { let read = |b: &[u8]| text_of(&cadcraft_io::read_dxf(b).unwrap()); assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xCF\xF0\xE8\xE2\xE5\xF2")), "Привет"); assert_eq!(read(&bin("AC1018", "ANSI_932", b"\x95\x5C\\U+00E9")), "表é"); - // A short Cyrillic string that is also valid UTF-8 (D1 B2) is still read in the code page. - assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xD1\xB2")), "СІ"); + // A string that is valid UTF-8 (D1 B2) is read as UTF-8 in binary files too, the same policy + // as ASCII files (#1025); a code-page string with a non-UTF-8 byte still uses the code page. + assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xD1\xB2")), "\u{0472}"); + assert_eq!(read(&bin("AC1015", "ANSI_1252", "Größe".as_bytes())), "Größe"); assert_eq!(read(&bin("AC1021", "ANSI_1251", "Привет".as_bytes())), "Привет"); assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Café"); } From 771643094889ef6c468e4e6b6be5f7bddf3394ed Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 21:18:54 +0200 Subject: [PATCH 004/531] DXF: multi-byte East Asian code pages read from the code page unless the whole file is UTF-8 (#1025) Co-Authored-By: Claude Sonnet 5.5 --- crates/dxf/src/codepage.rs | 71 ++++++++++++++++++++++++++++++----- crates/dxf/src/lib.rs | 10 ++++- crates/dxf/tests/hardening.rs | 38 +++++++++++++++++++ 3 files changed, 109 insertions(+), 10 deletions(-) diff --git a/crates/dxf/src/codepage.rs b/crates/dxf/src/codepage.rs index ddc4ca24f..f0d2a985d 100644 --- a/crates/dxf/src/codepage.rs +++ b/crates/dxf/src/codepage.rs @@ -108,10 +108,21 @@ fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> { None } +impl Decoder { + /// True for the multi-byte East Asian code pages (Shift-JIS, GBK, EUC-KR/Wansung, Big5). + /// Their short double-byte strings are often also valid UTF-8, so UTF-8 is only trusted for + /// a whole file there (see [`decode_ascii_file`] and [`BinaryText`]). + fn is_east_asian(self) -> bool { + use encoding_rs as e; + matches!(self, Decoder::Encoding(x) if x == e::SHIFT_JIS || x == e::GBK || x == e::EUC_KR || x == e::BIG5) + } +} + /// Decode one string of a DXF file: valid UTF-8 is read as UTF-8 (R2007+ files, pure-ASCII text, /// and older files from writers that ignored the code page); anything else comes from the /// code page `d`. The same policy for ASCII lines and binary strings, so one stray byte spoils -/// one string, not the whole file. +/// one string, not the whole file. East Asian code pages don't use this rule (see +/// [`Decoder::is_east_asian`]). pub(crate) fn decode_text(bytes: &[u8], d: Decoder) -> Cow<'_, str> { match std::str::from_utf8(bytes) { Ok(s) => Cow::Borrowed(s), @@ -119,10 +130,13 @@ pub(crate) fn decode_text(bytes: &[u8], d: Decoder) -> Cow<'_, str> { } } -/// Decode a whole ASCII DXF file, line by line (see [`decode_text`]). Lines that aren't valid -/// UTF-8 are decoded from the file's `$DWGCODEPAGE`, or from Windows-1252 (the usual `ANSI_1252`) -/// when the header has none or names a code page CADCraft doesn't know, which is logged as a -/// warning. +/// Decode a whole ASCII DXF file. A file that is valid UTF-8 throughout is UTF-8. Otherwise, for +/// a single-byte code page, each line is decoded on its own (see [`decode_text`]): lines that +/// aren't valid UTF-8 come from the file's `$DWGCODEPAGE`, or from Windows-1252 (the usual +/// `ANSI_1252`) when the header has none or names a code page CADCraft doesn't know, which is +/// logged as a warning. For a multi-byte East Asian code page the whole file is decoded from +/// that code page, because a short double-byte string (two half-width katakana, many kanji +/// pairs) can be valid UTF-8 by accident and must not be misread line by line. pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> { if let Ok(s) = std::str::from_utf8(bytes) { return Cow::Borrowed(s); @@ -137,6 +151,9 @@ pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> { } None => Decoder::Utf8, }; + if d.is_east_asian() { + return decode(bytes, d); + } // Split after each line terminator (CR, LF or CRLF are all ASCII, so they never occur inside // a multi-byte character of the supported code pages) and decode each line on its own. let mut out = String::with_capacity(bytes.len()); @@ -155,6 +172,12 @@ pub(crate) struct BinaryText { var: Option, utf8: bool, code_page: Option, + /// Decode every string of an East Asian code page file from the code page, never as UTF-8 + /// (the second pass of [`BinaryText::needs_code_page_pass`]). + code_page_only: bool, + /// Non-ASCII strings seen under an East Asian code page: valid UTF-8 / not valid UTF-8. + ea_utf8: bool, + ea_other: bool, } #[derive(Clone, Copy, PartialEq)] @@ -164,12 +187,42 @@ enum HeaderVar { } impl BinaryText { - /// Decode one string value of group `code` and update the state from it. A string that is - /// valid UTF-8 is read as such; otherwise it is in the file's code page (Windows-1252 for - /// R2007+ files and files without a known code page). + /// The state for the second pass over a file whose strings are a mix of valid UTF-8 and + /// not: every string of an East Asian code page is decoded from that code page. + pub(crate) fn code_page_pass() -> Self { + Self { code_page_only: true, ..Self::default() } + } + + /// True when the file declared a multi-byte East Asian code page and its non-ASCII strings are + /// not all valid UTF-8 although some are: those can be short double-byte strings that look + /// like UTF-8 by accident, so the file must be parsed again with [`Self::code_page_pass`]. (A + /// file whose strings are all valid UTF-8 is UTF-8; one with none is plainly the code page.) + pub(crate) fn needs_code_page_pass(&self) -> bool { + !self.code_page_only && self.ea_utf8 && self.ea_other + } + + /// Decode one string value of group `code` and update the state from it. For single-byte code + /// pages a string that is valid UTF-8 is read as such, otherwise it is in the file's code page + /// (Windows-1252 for R2007+ files and files without a known code page). East Asian code pages + /// see [`Self::needs_code_page_pass`]. pub(crate) fn string(&mut self, code: i32, raw: &[u8]) -> String { let d = if self.utf8 { Decoder::Utf8 } else { self.code_page.unwrap_or(Decoder::Utf8) }; - let s = decode_text(raw, d).into_owned(); + let s = if d.is_east_asian() { + if self.code_page_only { + decode(raw, d).into_owned() + } else { + if !raw.is_ascii() { + if std::str::from_utf8(raw).is_ok() { + self.ea_utf8 = true; + } else { + self.ea_other = true; + } + } + decode_text(raw, d).into_owned() + } + } else { + decode_text(raw, d).into_owned() + }; match (code, self.var.take()) { (9, _) => { self.var = match s.trim() { diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 77b0ad89d..bcb30db05 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -378,8 +378,16 @@ pub fn parse_binary(b: &[u8]) -> Result> { } fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result> { - let mut c = Cur { b, p: 0 }; let mut text = codepage::BinaryText::default(); + let tags = parse_binary_pass(b, max_tags, &mut text)?; + if text.needs_code_page_pass() { + return parse_binary_pass(b, max_tags, &mut codepage::BinaryText::code_page_pass()); + } + Ok(tags) +} + +fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText) -> Result> { + let mut c = Cur { b, p: 0 }; let mut tags = Vec::new(); while c.p < b.len() { let mut code = i32::from(c.i16()?); diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs index 24bfea082..27f494187 100644 --- a/crates/dxf/tests/hardening.rs +++ b/crates/dxf/tests/hardening.rs @@ -165,3 +165,41 @@ fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() { assert_eq!(back[5], Tag::i(90, i64::from(i32::MAX))); assert_eq!(back[6], Tag::i(90, i64::from(i32::MIN))); } + +/// Strings of a `$DWGCODEPAGE`-declared file as ASCII text and as a binary file. +fn both_forms(code_page: &str, strings: &[&[u8]]) -> [Vec; 2] { + let mut a = format!("9\n$DWGCODEPAGE\n3\n{code_page}\n").into_bytes(); + for s in strings { + a.extend_from_slice(b"1\n"); + a.extend_from_slice(s); + a.push(b'\n'); + } + a.extend_from_slice(b"0\nEOF\n"); + let b = bin_with(|b| { + for (code, s) in [(9i16, &b"$DWGCODEPAGE"[..]), (3, code_page.as_bytes())].into_iter().chain(strings.iter().map(|s| (1, *s))) { + b.extend_from_slice(&code.to_le_bytes()); + b.extend_from_slice(s); + b.push(0); + } + }); + [parse(&a).unwrap(), parse(&b).unwrap()] +} + +#[test] +fn east_asian_short_strings_that_look_like_utf8_stay_in_the_code_page() { + // C3 B1 is valid UTF-8 ("ñ") but is also two half-width katakana in Shift-JIS; the second + // string is plainly Shift-JIS, so the file is not UTF-8. + for t in both_forms("ANSI_932", &[b"\xC3\xB1", b"\x90\x7D\x96\xCA"]) { + assert_eq!(t[2].str(), "\u{FF83}\u{FF71}"); + assert_eq!(t[3].str(), "図面"); + } +} + +#[test] +fn east_asian_file_that_is_all_utf8_reads_as_utf8() { + for t in both_forms("ANSI_932", &["図面".as_bytes(), b"\xC3\xB1", b"plain"]) { + assert_eq!(t[2].str(), "図面"); + assert_eq!(t[3].str(), "ñ"); + assert_eq!(t[4].str(), "plain"); + } +} From 0de6ec8706917e218b475545394aa79b48f0fe37 Mon Sep 17 00:00:00 2001 From: Leonardo Pires Batista Date: Tue, 13 Oct 2026 16:41:59 -0300 Subject: [PATCH 005/531] fonts: read user SHX text fonts and keep Latin accents single-stroke Co-Authored-By: Codex --- README.md | 13 +- crates/fonts/src/lib.rs | 29 ++- crates/fonts/src/shx.rs | 385 ++++++++++++++++++++++++++++ crates/fonts/src/shx/program.rs | 242 +++++++++++++++++ crates/fonts/src/shx/tests.rs | 211 +++++++++++++++ crates/fonts/src/stroke.rs | 55 ++++ crates/fonts/src/ttf.rs | 2 +- crates/fonts/tests/latin_accents.rs | 54 ++++ crates/io/tests/shx_text.rs | 35 +++ docs/file-format-parity.md | 5 +- docs/gaps.md | 5 +- docs/shx-fonts.md | 75 ++++++ 12 files changed, 1096 insertions(+), 15 deletions(-) create mode 100644 crates/fonts/src/shx.rs create mode 100644 crates/fonts/src/shx/program.rs create mode 100644 crates/fonts/src/shx/tests.rs create mode 100644 crates/fonts/tests/latin_accents.rs create mode 100644 crates/io/tests/shx_text.rs create mode 100644 docs/shx-fonts.md diff --git a/README.md b/README.md index a259af4f3..978a0ab4d 100644 --- a/README.md +++ b/README.md @@ -144,9 +144,11 @@ input (`CRAFT_FONTS_DIR= cargo build --release`) al fonts: BIZ UDPGothic, BIZ UDMincho and Shippori Mincho (Japanese) and Noto Sans Arabic (the web build, which has no system fonts, only BIZ UDPGothic Regular and Noto Sans Arabic). A text style can use them by family name, and they draw characters a text's font lacks when no installed -wide-coverage CJK font has them. Without `CRAFT_FONTS_DIR` nothing is embedded. SHX -fonts (including big fonts such as `chineset.shx`) aren't read yet: text in an SHX style is drawn -with our own stroke font, and any character a text's font lacks (CJK, for example) is drawn from +wide-coverage CJK font has them. Without `CRAFT_FONTS_DIR` nothing is embedded. User-supplied +SHX text fonts (`shapes 1.0/1.1`, Unicode `unifont 1.0`) load from the directories in +`CADCRAFT_SHXPATH`, with their own strokes and advances. Big fonts aren't read yet. Missing +SHX fonts use FONTALT or our own stroke font (including Latin accents); any character a text's +font lacks (CJK, for example) is drawn from an installed font that has it, preferring wide-coverage fonts such as Noto Sans CJK, Source Han Sans, WenQuanYi, PingFang or Microsoft JhengHei. Two settings, set with `SETVAR` or (for every run) an environment variable, steer this: @@ -165,6 +167,11 @@ Linux and the BSDs `/usr/share/fonts`, `/usr/local/share/fonts`, `~/.local/share by file name (`Vazirmatn-Regular.ttf`) or family name (`Vazirmatn`), or inline in MTEXT with `\fVazirmatn;`. Restart CADCraft after installing a font: the font folders are scanned once. +**Your own SHX fonts.** Set `CADCRAFT_SHXPATH` to the folders containing fonts you are entitled +to use (semicolon-separated on Windows, colon-separated on Unix), then name the file or stem in +STYLE or inline MTEXT. CADCraft does not bundle proprietary fonts or scan CAD installations. +See [SHX fonts](docs/shx-fonts.md) for configuration, supported programs and limits. + **Right-to-left text (Persian, Arabic, Urdu, Hebrew).** TEXT and MTEXT lines are laid out with the Unicode Bidirectional Algorithm (the paragraph direction comes from its first letter, so numbers and Latin words inside Persian text keep their own order), and Arabic-script text is shaped with diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 9ccc69cac..badb2bd9c 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -1,8 +1,8 @@ //! CADCraft text layout. //! //! Turns TEXT and MTEXT into stroke polylines with the built-in single-stroke font -//! ("CADCraft Stroke") or glyph outlines of installed TrueType fonts ([`ttf`]), with a -//! per-character fallback to installed fonts for characters the chosen font lacks. Handles the +//! ("CADCraft Stroke"), user-supplied SHX fonts ([`shx`]) or glyph outlines of installed +//! TrueType fonts ([`ttf`]), with a per-character fallback for characters the chosen font lacks. Handles the //! `%%` control codes, alignment modes, width factor, obliquing, MTEXT inline formatting //! (paragraphs, stacking, height changes), word wrap and attachment points. //! @@ -16,6 +16,7 @@ pub mod bidi; mod complex; mod mtext; +pub mod shx; mod stroke; pub mod subset; pub mod ttf; @@ -263,6 +264,9 @@ pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { /// Width of the gap MTEXT leaves between two words. Words are measured without their trailing /// letter gap, so the stroke font's gap is added on both sides of the space, as TEXT lays it out. pub fn space_width(font: &TextFont, height: f64, width_factor: f64) -> f64 { + if let TextFont::Shx(face) = font { + return face.width(" ", height, width_factor); + } if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, " ", height, width_factor) { @@ -271,28 +275,33 @@ pub fn space_width(font: &TextFont, height: f64, width_factor: f64) -> f64 { stroke_advance(' ', height, width_factor) + stroke::GAP / stroke::CAP * height * width_factor } -/// The font a piece of text is set in: the built-in stroke font or an installed TrueType / -/// OpenType face (outlines). Either way, characters the font lacks come from a fallback font. +/// The font a piece of text is set in: the built-in stroke font, a user SHX font or an installed +/// TrueType / OpenType face (outlines). Characters the font lacks come from a fallback font. #[derive(Clone, Debug, Default)] pub enum TextFont { #[default] Stroke, Outline(ttf::Face), + Shx(std::sync::Arc), } impl TextFont { - /// Resolve a text style font name: an installed TTF/OTF/TTC when found; else, for a font we - /// can't find (an SHX file, a missing TTF), the FONTALT font ([`ttf::font_alt`]) when set; + /// Resolve a text style font name: an installed TTF/OTF/TTC or user SHX when found; else, + /// for a font we can't find, the FONTALT font ([`ttf::font_alt`]) when set; /// else the stroke font. pub fn resolve(name: &str) -> TextFont { if let Some(f) = ttf::find(name) { return TextFont::Outline(f); } + if let Some(f) = shx::find(name) { + return TextFont::Shx(f); + } let n = name.trim(); if n.is_empty() || n.eq_ignore_ascii_case(BUILTIN_FONT) { return TextFont::Stroke; } - ttf::find(&ttf::font_alt()).map(TextFont::Outline).unwrap_or(TextFont::Stroke) + let alt = ttf::font_alt(); + ttf::find(&alt).map(TextFont::Outline).or_else(|| shx::find(&alt).map(TextFont::Shx)).unwrap_or(TextFont::Stroke) } pub fn is_outline(&self) -> bool { matches!(self, TextFont::Outline(_)) @@ -410,6 +419,9 @@ pub(crate) fn decorations(spans: &[(f64, f64, bool, bool)], h: f64) -> Vec Shaped { + if let TextFont::Shx(face) = font { + return face.shape(s, height, width_factor, oblique); + } if let TextFont::Outline(face) = font && let Some(sh) = ttf::shape(face, s, height, width_factor, oblique) { @@ -420,6 +432,9 @@ pub fn shape_line(font: &TextFont, s: &str, height: f64, width_factor: f64, obli /// Width of one line in `font`. pub fn text_width(font: &TextFont, s: &str, height: f64, width_factor: f64) -> f64 { + if let TextFont::Shx(face) = font { + return face.width(s, height, width_factor); + } if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, s, height, width_factor) { diff --git a/crates/fonts/src/shx.rs b/crates/fonts/src/shx.rs new file mode 100644 index 000000000..be9cac18f --- /dev/null +++ b/crates/fonts/src/shx.rs @@ -0,0 +1,385 @@ +//! User-supplied compiled stroke fonts. No font files are bundled or searched in CAD bundles. +//! +//! Shape programs follow Autodesk's public Shape Descriptions / Special Codes Reference. +//! The binary record layouts are documented in `docs/shx-fonts.md`. All fixtures are synthetic. + +mod program; +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::io::Read; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, OnceLock, PoisonError, RwLock}; + +use cadcraft_geom::Vec2; + +use crate::{Shaped, bidi}; + +const MAX_FILE_BYTES: usize = 8 << 20; +const MAX_PROGRAM_BYTES: usize = 8192; +const MAX_FONTS: usize = 32; +const MAX_LOADED_BYTES: usize = 64 << 20; +#[cfg(not(target_arch = "wasm32"))] +const MAX_FILES: usize = 8192; +const MAX_CACHED_GLYPHS: usize = 4096; +const MAX_CACHED_POINTS: usize = 262_144; + +/// Malformed, unsupported or excessively complex font data. Resolution keeps the fallback. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Error { + Invalid, + Unsupported, + Limit, +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Invalid => "invalid SHX font", + Self::Unsupported => "unsupported SHX font format or encoding", + Self::Limit => "SHX font exceeds a complexity or memory limit", + }) + } +} + +impl std::error::Error for Error {} + +#[derive(Debug)] +struct Glyph { + strokes: Vec>, + advance: f64, +} + +#[derive(Debug, Default)] +struct GlyphCache { + glyphs: HashMap>>, + points: usize, +} + +/// Parsed font programs, with bounded, lazy decoding shared by every placement. +#[derive(Debug)] +pub struct Font { + cap: f64, + unicode: bool, + dual: bool, + programs: HashMap>, + cache: RwLock, + bytes: usize, +} + +/// Checked cursor shared by the record reader and program interpreter. +struct Cursor<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Cursor<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, pos: 0 } + } + fn take(&mut self, n: usize) -> Result<&'a [u8], Error> { + let end = self.pos.checked_add(n).ok_or(Error::Limit)?; + let result = self.bytes.get(self.pos..end).ok_or(Error::Invalid)?; + self.pos = end; + Ok(result) + } + fn byte(&mut self) -> Result { + self.take(1)?.first().copied().ok_or(Error::Invalid) + } + fn word(&mut self) -> Result { + Ok(u16::from(self.byte()?) | (u16::from(self.byte()?) << 8)) + } + fn name(&mut self) -> Result<(), Error> { + let n = self.bytes.get(self.pos..).and_then(|s| s.iter().position(|b| *b == 0)).ok_or(Error::Invalid)?; + self.take(n.checked_add(1).ok_or(Error::Limit)?)?; + Ok(()) + } + fn done(&self) -> bool { + self.pos == self.bytes.len() + } +} + +impl Font { + /// Parse shapes 1.0/1.1 and Unicode unifont 1.0. Big fonts and packed encodings are rejected. + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_FILE_BYTES { + return Err(Error::Limit); + } + let mut r = Cursor::new(bytes); + let mut font = Self { cap: 0.0, unicode: false, dual: false, programs: HashMap::new(), cache: RwLock::default(), bytes: bytes.len() }; + if bytes.starts_with(b"AutoCAD-86 unifont 1.0\r\n\x1a") { + r.take(25)?; + let count = r.word()?; + if count == 0 || r.word()? != 0 { + return Err(Error::Invalid); + } + let size = usize::from(r.word()?); + let mut definition = Cursor::new(r.take(size)?); + definition.name()?; + font.metrics(&mut definition)?; + if definition.byte()? != 0 { + return Err(Error::Unsupported); + } + let _embedding_permission = definition.byte()?; + if definition.byte()? != 0 || !definition.done() { + return Err(Error::Invalid); + } + font.unicode = true; + for _ in 1..count { + let id = r.word()?; + let size = usize::from(r.word()?); + font.record(id, r.take(size)?)?; + } + if !r.done() { + return Err(Error::Invalid); + } + } else if bytes.starts_with(b"AutoCAD-86 shapes 1.0\r\n\x1a") || bytes.starts_with(b"AutoCAD-86 shapes 1.1\r\n\x1a") { + r.take(24)?; + let first = r.word()?; + let last = r.word()?; + let count = usize::from(r.word()?); + if count == 0 { + return Err(Error::Invalid); + } + // Check the entire index exists before allocating from its input-derived count. + let mut index = Cursor::new(r.take(count.checked_mul(4).ok_or(Error::Limit)?)?); + let mut entries = Vec::with_capacity(count); + for _ in 0..count { + entries.push((index.word()?, usize::from(index.word()?))); + } + if entries.first().map(|e| e.0) != Some(first) || entries.last().map(|e| e.0) != Some(last) { + return Err(Error::Invalid); + } + for (id, size) in entries { + let record = r.take(size)?; + if id == 0 { + let mut definition = Cursor::new(record); + definition.name()?; + font.metrics(&mut definition)?; + if definition.byte()? != 0 || !definition.done() { + return Err(Error::Invalid); + } + } else { + font.record(id, record)?; + } + } + if r.take(3)? != b"EOF" || !r.done() { + return Err(Error::Invalid); + } + } else { + return Err(Error::Unsupported); + } + if font.cap <= 0.0 || font.programs.is_empty() { + return Err(Error::Invalid); + } + Ok(font) + } + + fn metrics(&mut self, r: &mut Cursor<'_>) -> Result<(), Error> { + self.cap = f64::from(r.byte()?); + let _descent = r.byte()?; + self.dual = match r.byte()? { + 0 => false, + 2 => true, + _ => return Err(Error::Unsupported), + }; + Ok(()) + } + + fn record(&mut self, id: u16, bytes: &[u8]) -> Result<(), Error> { + let mut r = Cursor::new(bytes); + r.name()?; + let data = bytes.get(r.pos..).ok_or(Error::Invalid)?; + if data.is_empty() || data.last() != Some(&0) || data.len() > MAX_PROGRAM_BYTES || self.programs.contains_key(&id) { + return Err(Error::Invalid); + } + self.programs.insert(id, data.to_vec()); + Ok(()) + } + + fn id(&self, c: char) -> Option { + if !self.unicode { + match c { + '°' if self.programs.contains_key(&256) => return Some(256), + '±' if self.programs.contains_key(&257) => return Some(257), + '⌀' | 'Ø' if self.programs.contains_key(&258) => return Some(258), + _ => {} + } + } + u16::try_from(u32::from(c)).ok() + } + + fn glyph(&self, c: char) -> Option> { + let id = self.id(c)?; + if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).glyphs.get(&id) { + return g.clone(); + } + let result = program::decode(self, id).ok().map(Arc::new); + let points = result.as_ref().map_or(0, |g| g.strokes.iter().map(Vec::len).sum()); + let mut cache = self.cache.write().unwrap_or_else(PoisonError::into_inner); + if let Some(g) = cache.glyphs.get(&id) { + return g.clone(); + } + if cache.glyphs.len() < MAX_CACHED_GLYPHS && cache.points.saturating_add(points) <= MAX_CACHED_POINTS { + cache.points += points; + cache.glyphs.insert(id, result.clone()); + } + result + } + + /// Horizontal layout uses the font's cap height and pen-end advances (no added stroke gap). + pub(crate) fn shape(&self, text: &str, height: f64, width_factor: f64, oblique: f64) -> Shaped { + let h = if height.is_finite() && height > 0.0 { height } else { 1.0 }; + let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; + let oblique = if oblique.is_finite() { oblique } else { 0.0 }; + let shear = oblique.tan().clamp(-10.0, 10.0); + let scale = h / self.cap; + let chars = crate::decode_controls(text); + let logical: Vec = chars.iter().map(|v| v.0).collect(); + let mut out = Shaped::default(); + let mut spans = Vec::new(); + let mut x = 0.0; + for (run, rtl) in bidi::visual_runs(&logical, None) { + let indices: Box> = if rtl { Box::new(run.rev()) } else { Box::new(run) }; + for i in indices { + let Some(&(c, under, over)) = chars.get(i) else { continue }; + if bidi::is_format_control(c) { + continue; + } + let c = if rtl { bidi::mirror(c) } else { c }; + let advance = if let Some(g) = self.glyph(c) { + for stroke in &g.strokes { + out.strokes.push(stroke.iter().map(|p| Vec2::new(x + p.x * scale * wf + p.y * scale * shear, p.y * scale)).collect()); + } + g.advance * scale * wf + } else { + let mut fallback = crate::shape_stroke(&c.to_string(), h, wf, oblique); + let advance = fallback.width + crate::stroke::GAP / crate::stroke::CAP * h * wf; + fallback.map(|p| p + Vec2::new(x, 0.0)); + out.extend(fallback); + advance + }; + spans.push((x, x + advance, under, over)); + x += advance; + } + } + out.strokes.extend(crate::decorations(&spans, h)); + out.width = x.max(0.0); + out + } + + pub(crate) fn width(&self, text: &str, height: f64, width_factor: f64) -> f64 { + if bidi::has_rtl(text) { + // Mirrored punctuation can have a different advance in a supplied font. + return self.shape(text, height, width_factor, 0.0).width; + } + let h = if height.is_finite() && height > 0.0 { height } else { 1.0 }; + let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; + crate::decode_controls(text) + .into_iter() + .filter(|(c, _, _)| !bidi::is_format_control(*c)) + .map(|(c, _, _)| { + self.glyph(c).map_or_else( + || crate::line_width(&c.to_string(), h, wf) + crate::stroke::GAP / crate::stroke::CAP * h * wf, + |g| g.advance * h / self.cap * wf, + ) + }) + .sum::() + .max(0.0) + } +} + +#[derive(Default)] +struct Registry { + paths: HashMap, + fonts: HashMap>>, + bytes: usize, +} + +fn key(name: &str) -> Option { + let name = name.trim().rsplit(['/', '\\']).next()?; + if name.is_empty() || name.len() > 255 { + return None; + } + let lower = name.to_ascii_lowercase(); + if let Some(stem) = lower.strip_suffix(".shx") { + (!stem.is_empty() && !stem.contains(':')).then(|| stem.to_owned()) + } else if lower.contains('.') || lower.contains(':') { + None + } else { + Some(lower) + } +} + +fn registry() -> &'static Mutex { + static REGISTRY: OnceLock> = OnceLock::new(); + REGISTRY.get_or_init(|| Mutex::new(scan())) +} + +fn scan() -> Registry { + #[cfg(target_arch = "wasm32")] + return Registry::default(); + #[cfg(not(target_arch = "wasm32"))] + { + let mut registry = Registry::default(); + if let Some(paths) = std::env::var_os("CADCRAFT_SHXPATH") { + let mut files = 0usize; + for dir in std::env::split_paths(&paths).take(32) { + let Ok(entries) = std::fs::read_dir(dir) else { continue }; + for entry in entries.take(MAX_FILES.saturating_sub(files)) { + files += 1; + let Ok(entry) = entry else { continue }; + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("shx")) + && let Some(name) = path.file_name().and_then(|n| n.to_str()).and_then(key) + { + registry.paths.entry(name).or_insert(path); + } + } + } + } + registry + } +} + +/// Register user-provided bytes (also works on WASM); never writes or embeds a font file. +pub fn register(name: &str, bytes: &[u8]) -> Result<(), Error> { + let name = key(name).ok_or(Error::Invalid)?; + let font = Arc::new(Font::parse(bytes)?); + let mut registry = registry().lock().unwrap_or_else(PoisonError::into_inner); + let old = registry.fonts.get(&name).and_then(Option::as_ref).map_or(0, |f| f.bytes); + let total = registry.bytes.saturating_sub(old).saturating_add(font.bytes); + if total > MAX_LOADED_BYTES || (!registry.fonts.contains_key(&name) && registry.fonts.len() >= MAX_FONTS) { + return Err(Error::Limit); + } + registry.bytes = total; + registry.fonts.insert(name, Some(font)); + Ok(()) +} + +/// Resolve by file name or stem from the configured directories or registered font bytes. +pub fn find(name: &str) -> Option> { + let name = key(name)?; + let mut registry = registry().lock().unwrap_or_else(PoisonError::into_inner); + if let Some(font) = registry.fonts.get(&name) { + return font.clone(); + } + let path = registry.paths.get(&name)?; + if registry.fonts.len() >= MAX_FONTS { + return None; + } + let mut bytes = Vec::new(); + let result = std::fs::File::open(path).ok().and_then(|file| { + file.take((MAX_FILE_BYTES + 1) as u64).read_to_end(&mut bytes).ok()?; + if registry.bytes.saturating_add(bytes.len()) > MAX_LOADED_BYTES { + return None; + } + Font::parse(&bytes).ok().map(Arc::new) + }); + if let Some(font) = &result { + registry.bytes += font.bytes; + } + registry.fonts.insert(name, result.clone()); + result +} diff --git a/crates/fonts/src/shx/program.rs b/crates/fonts/src/shx/program.rs new file mode 100644 index 000000000..92ae813cc --- /dev/null +++ b/crates/fonts/src/shx/program.rs @@ -0,0 +1,242 @@ +//! Bounded interpreter of the publicly documented SHP/SHX pen commands. + +use std::f64::consts::{FRAC_PI_4, TAU}; + +use cadcraft_geom::Vec2; + +use super::{Cursor, Error, Font, Glyph}; + +const MAX_DEPTH: usize = 32; +const MAX_STACK: usize = 32; +const MAX_STEPS: usize = 65_536; +const MAX_POINTS: usize = 8192; +const MAX_COORD: f64 = 1.0e6; + +struct Pen<'a> { + font: &'a Font, + pos: Vec2, + down: bool, + scale: f64, + stack: Vec, + strokes: Vec>, + active: Vec, + steps: usize, + points: usize, +} + +pub(super) fn decode(font: &Font, id: u16) -> Result { + let mut pen = + Pen { font, pos: Vec2::ZERO, down: true, scale: 1.0, stack: Vec::new(), strokes: Vec::new(), active: Vec::new(), steps: 0, points: 0 }; + pen.run(id, 0)?; + pen.flush(); + if !pen.stack.is_empty() { + return Err(Error::Invalid); + } + Ok(Glyph { strokes: pen.strokes, advance: pen.pos.x }) +} + +impl Pen<'_> { + fn step(&mut self) -> Result<(), Error> { + self.steps += 1; + if self.steps > MAX_STEPS { Err(Error::Limit) } else { Ok(()) } + } + + fn flush(&mut self) { + if self.active.len() >= 2 { + self.strokes.push(std::mem::take(&mut self.active)); + } else { + self.active.clear(); + } + } + + fn move_to(&mut self, target: Vec2) -> Result<(), Error> { + if !target.is_finite() || target.x.abs().max(target.y.abs()) > MAX_COORD { + return Err(Error::Limit); + } + if self.down { + let added = if self.active.is_empty() { 2 } else { 1 }; + self.points += added; + if self.points > MAX_POINTS { + return Err(Error::Limit); + } + if self.active.is_empty() { + self.active.push(self.pos); + } + self.active.push(target); + } else { + self.flush(); + } + self.pos = target; + Ok(()) + } + + fn displacement(&mut self, dx: f64, dy: f64) -> Result<(), Error> { + self.move_to(self.pos + Vec2::new(dx, dy) * self.scale) + } + + fn arc(&mut self, radius: f64, start: f64, sweep: f64) -> Result<(), Error> { + if !radius.is_finite() || radius <= 0.0 || radius > MAX_COORD || !sweep.is_finite() || sweep.abs() > TAU + 1e-8 { + return Err(Error::Invalid); + } + let center = self.pos - Vec2::new(start.cos(), start.sin()) * radius; + let count = (sweep.abs() / (TAU / 128.0)).ceil().clamp(1.0, 128.0) as usize; + let count = if self.down { count } else { 1 }; + for i in 1..=count { + let angle = start + sweep * i as f64 / count as f64; + self.move_to(center + Vec2::new(angle.cos(), angle.sin()) * radius)?; + } + Ok(()) + } + + fn bulge(&mut self, dx: f64, dy: f64, bulge: f64) -> Result<(), Error> { + let delta = Vec2::new(dx, dy) * self.scale; + if bulge == 0.0 || !self.down { + return self.move_to(self.pos + delta); + } + if bulge.abs() > 127.0 || delta.len2() == 0.0 { + return Err(Error::Invalid); + } + let b = bulge / 127.0; + let center = self.pos + delta * 0.5 + Vec2::new(-delta.y, delta.x) * ((1.0 - b * b) / (4.0 * b)); + let relative = self.pos - center; + self.arc(relative.len(), relative.y.atan2(relative.x), 4.0 * b.atan()) + } + + fn run(&mut self, id: u16, depth: usize) -> Result<(), Error> { + if depth >= MAX_DEPTH { + return Err(Error::Limit); + } + let program = self.font.programs.get(&id).ok_or(Error::Invalid)?; + let mut r = Cursor::new(program); + let mut skip = false; + loop { + self.step()?; + let code = r.byte()?; + let execute = !skip; + skip = false; + match code { + 0 => return if r.done() { Ok(()) } else { Err(Error::Invalid) }, + 1 => { + if execute { + self.down = true; + } + } + 2 => { + if execute { + self.down = false; + self.flush(); + } + } + 3 | 4 => { + let factor = f64::from(r.byte()?); + if factor == 0.0 { + return Err(Error::Invalid); + } + if execute { + self.scale = if code == 3 { self.scale / factor } else { self.scale * factor }; + if !(1e-6..=MAX_COORD).contains(&self.scale) { + return Err(Error::Limit); + } + } + } + 5 => { + if execute { + if self.stack.len() >= MAX_STACK { + return Err(Error::Limit); + } + self.stack.push(self.pos); + } + } + 6 => { + if execute { + self.flush(); + self.pos = self.stack.pop().ok_or(Error::Invalid)?; + } + } + 7 => { + let id = if self.font.unicode { + // Unicode subshape operands are high byte first; record ids are LE. + (u16::from(r.byte()?) << 8) | u16::from(r.byte()?) + } else { + u16::from(r.byte()?) + }; + if execute { + self.run(id, depth + 1)?; + } + } + 8 | 9 | 12 | 13 => loop { + self.step()?; + let dx = f64::from(i8::from_ne_bytes([r.byte()?])); + let dy = f64::from(i8::from_ne_bytes([r.byte()?])); + if matches!(code, 9 | 13) && dx == 0.0 && dy == 0.0 { + break; + } + let bulge = if matches!(code, 12 | 13) { f64::from(i8::from_ne_bytes([r.byte()?])) } else { 0.0 }; + if execute { + self.bulge(dx, dy, bulge)?; + } + if matches!(code, 8 | 12) { + break; + } + }, + 10 | 11 => { + let (offset, end, radius) = if code == 11 { + let offset = f64::from(r.byte()?) / 256.0; + let end = r.byte()?; + let end = if end == 0 { 1.0 } else { f64::from(end) / 256.0 }; + let radius = (u16::from(r.byte()?) << 8) | u16::from(r.byte()?); + (offset, end, f64::from(radius)) + } else { + (0.0, 1.0, f64::from(r.byte()?)) + }; + // The sign is sign-magnitude for arc octants, not two's-complement. + let spec = r.byte()?; + let sign = if spec & 128 == 0 { 1.0 } else { -1.0 }; + let octant = (spec & 127) >> 4; + let span = spec & 15; + if octant > 7 || span > 7 { + return Err(Error::Invalid); + } + let span = if span == 0 { 8.0 } else { f64::from(span) }; + let start = (f64::from(octant) + sign * offset) * FRAC_PI_4; + let sweep = sign * (span - 1.0 + end - offset) * FRAC_PI_4; + if execute { + self.arc(radius * self.scale, start, sweep)?; + } + } + 14 => { + if self.font.dual && execute { + skip = true; + } + } + 15 => return Err(Error::Unsupported), + _ => { + let length = f64::from(code >> 4); + let direction = code & 15; + // Directions at 22.5-degree steps use half-grid intermediate vectors. + let (dx, dy) = match direction { + 0 => (1.0, 0.0), + 1 => (1.0, 0.5), + 2 => (1.0, 1.0), + 3 => (0.5, 1.0), + 4 => (0.0, 1.0), + 5 => (-0.5, 1.0), + 6 => (-1.0, 1.0), + 7 => (-1.0, 0.5), + 8 => (-1.0, 0.0), + 9 => (-1.0, -0.5), + 10 => (-1.0, -1.0), + 11 => (-0.5, -1.0), + 12 => (0.0, -1.0), + 13 => (0.5, -1.0), + 14 => (1.0, -1.0), + _ => (1.0, -0.5), + }; + if execute { + self.displacement(dx * length, dy * length)?; + } + } + } + } + } +} diff --git a/crates/fonts/src/shx/tests.rs b/crates/fonts/src/shx/tests.rs new file mode 100644 index 000000000..fa06f5636 --- /dev/null +++ b/crates/fonts/src/shx/tests.rs @@ -0,0 +1,211 @@ +use super::*; +use crate::{MTextParams, TextFont, layout_mtext_with, shape_line, text_width}; + +// Original synthetic glyph programs. These bytes are assembled here, never compiled in AutoCAD. +fn unifont(rows: &[(u16, &[u8])], mode: u8) -> Vec { + let mut data = b"AutoCAD-86 unifont 1.0\r\n\x1a".to_vec(); + data.extend_from_slice(&(rows.len() as u16 + 1).to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + let definition = [b't', b'e', b's', b't', 0, 6, 2, mode, 0, 0, 0]; + data.extend_from_slice(&(definition.len() as u16).to_le_bytes()); + data.extend_from_slice(&definition); + for (id, program) in rows { + data.extend_from_slice(&id.to_le_bytes()); + data.extend_from_slice(&(program.len() as u16 + 1).to_le_bytes()); + data.push(0); + data.extend_from_slice(program); + } + data +} + +fn legacy(version: &str, rows: &[(u16, &[u8])]) -> Vec { + let mut data = format!("AutoCAD-86 shapes {version}\r\n\x1a").into_bytes(); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&rows.last().unwrap().0.to_le_bytes()); + data.extend_from_slice(&(rows.len() as u16 + 1).to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&5u16.to_le_bytes()); + for (id, program) in rows { + data.extend_from_slice(&id.to_le_bytes()); + data.extend_from_slice(&(program.len() as u16 + 1).to_le_bytes()); + } + data.extend_from_slice(&[0, 6, 2, 2, 0]); + for (_, program) in rows { + data.push(0); + data.extend_from_slice(program); + } + data.extend_from_slice(b"EOF"); + data +} + +const A: &[u8] = &[2, 8, 1, 0, 1, 8, 0, 6, 8, 4, 250, 2, 8, 2, 0, 0]; +const ACUTE: &[u8] = &[7, 0, 65, 5, 2, 8, 251, 7, 1, 8, 2, 1, 6, 0]; +const SPACE: &[u8] = &[2, 8, 3, 0, 0]; + +#[test] +fn unicode_subshapes_use_high_byte_first_and_preserve_advance() { + let font = Font::parse(&unifont(&[(65, A), (193, ACUTE), (32, SPACE)], 2)).unwrap(); + let a = font.glyph('A').unwrap(); + let acute = font.glyph('\u{00C1}').unwrap(); + assert_eq!(a.advance, 7.0); + assert_eq!(acute.advance, a.advance); + assert_eq!(acute.strokes.first(), a.strokes.first()); + assert!(acute.strokes.iter().flatten().any(|p| p.y == 8.0)); + let face = TextFont::Shx(Arc::new(font)); + let shaped = shape_line(&face, "A\u{00C1} A", 3.0, 0.8, 0.2); + assert!(shaped.glyphs.is_empty(), "all glyphs stay single-stroke"); + assert!((shaped.width - 24.0 * 3.0 / 6.0 * 0.8).abs() < 1e-9); + assert!((text_width(&face, "A\u{00C1} A", 3.0, 0.8) - shaped.width).abs() < 1e-9); + assert!((crate::space_width(&face, 3.0, 0.8) - 1.2).abs() < 1e-9); + assert!(shaped.strokes.iter().flatten().all(|p| p.is_finite())); +} + +#[test] +fn legacy_versions_map_dimension_symbols_and_latin_characters() { + for version in ["1.0", "1.1"] { + let bytes = legacy(version, &[(65, A), (193, &[7, 65, 0]), (256, A), (257, A), (258, A)]); + let font = Font::parse(&bytes).unwrap(); + for c in ['A', '\u{00C1}', '°', '±', '⌀'] { + assert_eq!(font.glyph(c).unwrap().advance, 7.0); + } + assert_eq!(font.shape("%%d%%p%%c", 6.0, 1.0, 0.0).width, 21.0); + } +} + +#[test] +fn pen_commands_have_known_geometry() { + let cases: &[(u16, &[u8], Vec2)] = &[ + (65, &[0x24, 0x20, 2, 0x2c, 0], Vec2::new(2.0, 0.0)), + (66, &[4, 2, 8, 3, 2, 3, 2, 8, 1, 0, 0], Vec2::new(7.0, 4.0)), + (67, &[9, 3, 1, 3, 255, 0, 0, 0], Vec2::new(6.0, 0.0)), + (68, &[10, 3, 0x02, 0], Vec2::new(-3.0, 3.0)), + (69, &[10, 3, 0x82, 0], Vec2::new(-3.0, -3.0)), + (70, &[11, 0, 0, 0, 3, 0x02, 0], Vec2::new(-3.0, 3.0)), + (71, &[12, 6, 0, 127, 0], Vec2::new(6.0, 0.0)), + (72, &[13, 6, 0, 127, 6, 0, 129, 0, 0, 0], Vec2::new(12.0, 0.0)), + (73, &[5, 8, 0, 6, 6, 2, 8, 7, 0, 0], Vec2::new(7.0, 0.0)), + (74, &[14, 9, 50, 50, 50, 50, 0, 0, 8, 3, 0, 0], Vec2::new(3.0, 0.0)), + (75, &[14, 7, 0, 65, 8, 3, 0, 0], Vec2::new(3.0, 0.0)), + ]; + let rows: Vec<_> = cases.iter().map(|(id, bytes, _)| (*id, *bytes)).collect(); + let font = Font::parse(&unifont(&rows, 2)).unwrap(); + for (id, _, end) in cases { + let glyph = program::decode(&font, *id).unwrap(); + assert!((glyph.advance - end.x).abs() < 1e-8, "glyph {id}"); + if !matches!(*id, 65 | 73) { + let last = glyph.strokes.last().unwrap().last().unwrap(); + assert!(last.dist(*end) < 1e-8, "glyph {id}: {last:?}"); + } + } + let semicircle = font.glyph('G').unwrap(); + assert!(semicircle.strokes.iter().flatten().any(|p| (p.y + 3.0).abs() < 1e-8)); + let cw = font.glyph('E').unwrap(); + assert!(cw.strokes.iter().flatten().all(|p| p.y <= 1e-8)); +} + +#[test] +fn resolution_mtext_wrapping_and_inline_font_use_shx_metrics() { + register("cadcraft-synthetic-unifont.shx", &unifont(&[(65, A), (193, ACUTE), (32, SPACE)], 2)).unwrap(); + let font = TextFont::resolve("CADCRAFT-SYNTHETIC-UNIFONT.SHX"); + assert!(matches!(font, TextFont::Shx(_))); + assert!(matches!(TextFont::resolve("cadcraft-synthetic-unifont"), TextFont::Shx(_))); + let mut params = MTextParams::new(Vec2::ZERO, 6.0); + params.font = font; + params.width = 18.0; + let layout = layout_mtext_with("A\u{00C1} A\u{00C1}", ¶ms); + assert_eq!(layout.lines, ["A\u{00C1}", "A\u{00C1}"]); + assert!(layout.pieces.iter().all(|p| p.shaped.glyphs.is_empty())); + params.width = 0.0; + params.font = TextFont::Stroke; + let inline = layout_mtext_with("\\Fcadcraft-synthetic-unifont.shx;A\u{00C1}", ¶ms); + assert_eq!(inline.lines, ["A\u{00C1}"]); + assert!(inline.pieces.iter().all(|p| p.shaped.glyphs.is_empty())); + assert!(inline.strokes.iter().flatten().any(|p| (p.x - 12.0).abs() < 1e-9), "native pen-end spacing"); +} + +#[test] +fn configured_directory_loads_only_named_user_fonts() { + // A child process isolates startup environment and the once-scanned registry, without + // unsafe process-wide environment mutation in parallel Rust tests. + if std::env::var_os("CADCRAFT_SHX_TEST_CHILD").is_some() { + let font = find("CADCRAFT-SYNTHETIC-PATH.SHX").unwrap(); + assert_eq!(font.glyph('A').unwrap().advance, 7.0); + assert!(matches!(TextFont::resolve("cadcraft-synthetic-path"), TextFont::Shx(_))); + assert!(find("cadcraft-broken-path.shx").is_none()); + assert!(find("cadcraft-nonexistent-path.shx").is_none()); + assert!(matches!(TextFont::resolve("cadcraft-nonexistent-path.shx"), TextFont::Shx(_)), "SHX FONTALT"); + assert!(matches!(TextFont::resolve(crate::BUILTIN_FONT), TextFont::Stroke)); + assert!(find("../cadcraft-synthetic-path.ttf").is_none()); + return; + } + let dir = std::env::temp_dir().join(format!("cadcraft-shx-path-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("cadcraft-synthetic-path.shx"), unifont(&[(65, A)], 2)).unwrap(); + std::fs::write(dir.join("cadcraft-broken-path.shx"), b"not a font").unwrap(); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "shx::tests::configured_directory_loads_only_named_user_fonts", "--nocapture"]) + .env("CADCRAFT_SHX_TEST_CHILD", "1") + .env("CADCRAFT_SHXPATH", &dir) + .env("CADCRAFT_FONTALT", "cadcraft-synthetic-path.shx") + .output() + .unwrap(); + std::fs::remove_file(dir.join("cadcraft-synthetic-path.shx")).unwrap(); + std::fs::remove_file(dir.join("cadcraft-broken-path.shx")).unwrap(); + std::fs::remove_dir(&dir).unwrap(); + assert!(result.status.success(), "{}\n{}", String::from_utf8_lossy(&result.stdout), String::from_utf8_lossy(&result.stderr)); +} + +#[test] +fn malformed_and_hostile_fonts_never_panic() { + let valid = unifont(&[(65, A), (193, ACUTE)], 2); + for end in 0..valid.len() { + assert!(Font::parse(&valid[..end]).is_err(), "truncated at {end}"); + } + let malformed: &[&[u8]] = &[ + &[7, 0, 65, 0], // cycle + &[6, 0], // stack underflow + &[5, 0], // unbalanced stack + &[3, 0, 0], // division by zero + &[4, 255, 4, 255, 4, 255, 0], // excessive scale + &[9, 1, 1, 0], // missing displacement terminator + &[11, 0], // truncated arc + &[10, 1, 0x79, 0], // invalid octant span + &[15, 0], // unsupported opcode + ]; + for program in malformed { + let font = Font::parse(&unifont(&[(65, program)], 2)).unwrap(); + assert!(program::decode(&font, 65).is_err()); + let fallback = font.shape("A\u{00C1}", 1.0, 1.0, 0.0); + assert!(!fallback.strokes.is_empty() && fallback.glyphs.is_empty()); + } + // Deep acyclic calls, excessive points, random mutation, duplicates and bogus lengths. + let mut chain: Vec> = (65u16..110).map(|id| vec![7, 0, (id + 1) as u8, 0]).collect(); + chain.push(vec![0]); + let rows: Vec<_> = chain.iter().enumerate().map(|(i, p)| (65 + i as u16, p.as_slice())).collect(); + assert!(matches!(program::decode(&Font::parse(&unifont(&rows, 2)).unwrap(), 65), Err(Error::Limit))); + let mut many_points = vec![0x10; 4096]; + many_points.push(0); + let font = Font::parse(&unifont(&[(65, &[7, 0, 66, 7, 0, 66, 0]), (66, &many_points)], 2)).unwrap(); + assert!(matches!(program::decode(&font, 65), Err(Error::Limit))); + let mut state = 0x1234_5678u32; + for _ in 0..500 { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + let mut bytes = valid.clone(); + let i = state as usize % bytes.len(); + bytes[i] ^= (state >> 24) as u8; + if let Ok(font) = Font::parse(&bytes) { + let _ = font.shape("A\u{00C1}", 1.0, 1.0, 0.0); + } + } + assert!(Font::parse(&unifont(&[(65, A), (65, A)], 2)).is_err()); + assert!(matches!(Font::parse(b"AutoCAD-86 bigfont 1.0\r\n\x1a"), Err(Error::Unsupported))); + assert!(matches!(Font::parse(&vec![0; MAX_FILE_BYTES + 1]), Err(Error::Limit))); + let font = Font::parse(&valid).unwrap(); + for n in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 0.0] { + let shaped = font.shape("A\u{00C1}B", n, n, n); + assert!(shaped.width.is_finite()); + assert!(shaped.strokes.iter().flatten().all(|p| p.is_finite())); + } +} diff --git a/crates/fonts/src/stroke.rs b/crates/fonts/src/stroke.rs index e6d38b7db..43aa2dd3f 100644 --- a/crates/fonts/src/stroke.rs +++ b/crates/fonts/src/stroke.rs @@ -110,6 +110,61 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> { 'Ø' | 'ø' | '⌀' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"), // List bullet: a small crossed diamond at mid x-height. '•' => (2.0, "1d0e1f2e1d 0e2e 1d1f"), + // Original Latin diacritics, composed from our own letter bodies and marks. + '\u{00C0}' => (4.0, concat!("0c2i4c 1f3f", " 1k3j")), + '\u{00C1}' => (4.0, concat!("0c2i4c 1f3f", " 1j3k")), + '\u{00C2}' => (4.0, concat!("0c2i4c 1f3f", " 0j2k4j")), + '\u{00C3}' => (4.0, concat!("0c2i4c 1f3f", " 0j1k3j4k")), + '\u{00C4}' => (4.0, concat!("0c2i4c 1f3f", " 1j1k 3j3k")), + '\u{00C5}' => (4.0, concat!("0c2i4c 1f3f", " 2j1k2l3k2j")), + '\u{00C7}' => (4.0, concat!("4h3i1i0h0d1c3c4d", " 2c3b2a1a")), + '\u{00C8}' => (4.0, concat!("4i0i0c4c 0f3f", " 1k3j")), + '\u{00C9}' => (4.0, concat!("4i0i0c4c 0f3f", " 1j3k")), + '\u{00CA}' => (4.0, concat!("4i0i0c4c 0f3f", " 0j2k4j")), + '\u{00CB}' => (4.0, concat!("4i0i0c4c 0f3f", " 1j1k 3j3k")), + '\u{00CC}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0k2j")), + '\u{00CD}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0j2k")), + '\u{00CE}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0j1k2j")), + '\u{00CF}' => (2.0, concat!("0i2i 1i1c 0c2c", " 0j0k 2j2k")), + '\u{00D1}' => (4.0, concat!("0c0i4c4i", " 0j1k3j4k")), + '\u{00D2}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 1k3j")), + '\u{00D3}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 1j3k")), + '\u{00D4}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 0j2k4j")), + '\u{00D5}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 0j1k3j4k")), + '\u{00D6}' => (4.0, concat!("1c0d0h1i3i4h4d3c1c", " 1j1k 3j3k")), + '\u{00D9}' => (4.0, concat!("0i0d1c3c4d4i", " 1k3j")), + '\u{00DA}' => (4.0, concat!("0i0d1c3c4d4i", " 1j3k")), + '\u{00DB}' => (4.0, concat!("0i0d1c3c4d4i", " 0j2k4j")), + '\u{00DC}' => (4.0, concat!("0i0d1c3c4d4i", " 1j1k 3j3k")), + '\u{00DD}' => (4.0, concat!("0i2f4i 2f2c", " 1j3k")), + '\u{00E0}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 1i3h")), + '\u{00E1}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 1h3i")), + '\u{00E2}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 0h2i4h")), + '\u{00E3}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 0h1i3h4i")), + '\u{00E4}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 1h1i 3h3i")), + '\u{00E5}' => (4.0, concat!("4g4c 4f3g1g0f0d1c3c4d", " 2h1i2j3i2h")), + '\u{00E7}' => (4.0, concat!("4f3g1g0f0d1c3c4d", " 2c3b2a1a")), + '\u{00E8}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 1i3h")), + '\u{00E9}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 1h3i")), + '\u{00EA}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 0h2i4h")), + '\u{00EB}' => (4.0, concat!("0e4e4f3g1g0f0d1c3c4d", " 1h1i 3h3i")), + '\u{00EC}' => (1.0, concat!("0c0g", " 0i1h")), + '\u{00ED}' => (1.0, concat!("0c0g", " 0h1i")), + '\u{00EE}' => (1.0, concat!("0c0g", " 0h0i1h")), + '\u{00EF}' => (1.0, concat!("0c0g", " 0h0i 1h1i")), + '\u{00F1}' => (4.0, concat!("0c0g 0f1g3g4f4c", " 0h1i3h4i")), + '\u{00F2}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 1i3h")), + '\u{00F3}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 1h3i")), + '\u{00F4}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 0h2i4h")), + '\u{00F5}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 0h1i3h4i")), + '\u{00F6}' => (4.0, concat!("1c0d0f1g3g4f4d3c1c", " 1h1i 3h3i")), + '\u{00F9}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 1i3h")), + '\u{00FA}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 1h3i")), + '\u{00FB}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 0h2i4h")), + '\u{00FC}' => (4.0, concat!("0g0d1c3c4d 4g4c", " 1h1i 3h3i")), + '\u{00FD}' => (4.0, concat!("0g2c 4g1a0a", " 1h3i")), + '\u{00FF}' => (4.0, concat!("0g2c 4g1a0a", " 1h1i 3h3i")), + '\u{0178}' => (4.0, concat!("0i2f4i 2f2c", " 1j1k 3j3k")), _ => return None, }; Some(g) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 62759c1b0..583746fec 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -7,7 +7,7 @@ //! //! Two process-wide settings (like AutoCAD's profile variables) control substitution: //! - [`font_alt`] (`FONTALT`): the font used for a text style font that can't be found (an SHX -//! file we don't read, a missing TTF). Empty = the built-in stroke font. +//! file that isn't available, a missing TTF). Empty = the built-in stroke font. //! - [`fallback_fonts`] (`FONTFALLBACK`): fonts tried first for characters the text's font //! lacks (CJK in an SHX big font, for example), before the automatic system font search. //! diff --git a/crates/fonts/tests/latin_accents.rs b/crates/fonts/tests/latin_accents.rs new file mode 100644 index 000000000..79d4a37c1 --- /dev/null +++ b/crates/fonts/tests/latin_accents.rs @@ -0,0 +1,54 @@ +use cadcraft_fonts::{MTextParams, TextFont, char_advance, layout_mtext_with, line_width, shape_stroke}; +use cadcraft_geom::Vec2; + +#[test] +fn latin_accents_keep_single_strokes_and_the_base_letter_spacing() { + let groups = [ + ('A', "ÀÁÂÃÄÅ"), + ('C', "Ç"), + ('E', "ÈÉÊË"), + ('I', "ÌÍÎÏ"), + ('N', "Ñ"), + ('O', "ÒÓÔÕÖ"), + ('U', "ÙÚÛÜ"), + ('Y', "ÝŸ"), + ('a', "àáâãäå"), + ('c', "ç"), + ('e', "èéêë"), + ('i', "ìíîï"), + ('n', "ñ"), + ('o', "òóôõö"), + ('u', "ùúûü"), + ('y', "ýÿ"), + ]; + for (base, accents) in groups { + for c in accents.chars() { + let shaped = shape_stroke(&c.to_string(), 6.0, 0.8, 0.2); + assert!(shaped.glyphs.is_empty(), "{c} must not become a filled system-font outline"); + assert!(!shaped.strokes.is_empty()); + assert_eq!(char_advance(c), char_advance(base)); + assert!((line_width(&c.to_string(), 6.0, 0.8) - shaped.width).abs() < 1e-9); + assert!(shaped.strokes.iter().flatten().all(|p| p.is_finite())); + let next = shape_stroke(&format!("{c}B"), 6.0, 0.8, 0.2); + let plain = shape_stroke(&format!("{base}B"), 6.0, 0.8, 0.2); + assert_eq!(next.width, plain.width, "accent does not shift the next letter"); + } + } + for (accent, base) in [('Ç', 'C'), ('Ã', 'A'), ('Á', 'A'), ('Ó', 'O')] { + let plain = shape_stroke(&base.to_string(), 6.0, 1.0, 0.0); + let marked = shape_stroke(&accent.to_string(), 6.0, 1.0, 0.0); + assert!(marked.strokes.starts_with(&plain.strokes), "same letter body for {accent}"); + assert!(marked.strokes.len() > plain.strokes.len()); + } +} + +#[test] +fn portuguese_mtext_wraps_with_consistent_stroke_metrics() { + let text = "A CONCEPÇÃO SERÁ APROVADA APÓS O PROCESSAMENTO DA ESTRUTURA"; + let params = MTextParams { width: 32.0, font: TextFont::Stroke, ..MTextParams::new(Vec2::ZERO, 1.0) }; + let layout = layout_mtext_with(text, ¶ms); + assert!(layout.lines.len() >= 2); + assert_eq!(layout.lines.join(" "), text); + assert!(layout.pieces.iter().all(|p| p.shaped.glyphs.is_empty())); + assert!(layout.strokes.iter().flatten().all(|p| p.is_finite())); +} diff --git a/crates/io/tests/shx_text.rs b/crates/io/tests/shx_text.rs new file mode 100644 index 000000000..bd04a031b --- /dev/null +++ b/crates/io/tests/shx_text.rs @@ -0,0 +1,35 @@ +//! Synthetic DXF STYLE -> TEXT/MTEXT -> display list, without external font fixtures. + +use cadcraft_doc::Space; + +fn font() -> Vec { + let mut bytes = b"AutoCAD-86 unifont 1.0\r\n\x1a".to_vec(); + bytes.extend_from_slice(&[4, 0, 0, 0, 8, 0]); + bytes.extend_from_slice(&[b's', 0, 6, 2, 2, 0, 0, 0]); + for (id, program) in + [(32u16, vec![2, 8, 3, 0, 0]), (65, vec![8, 0, 6, 8, 4, 250, 2, 8, 3, 0, 0]), (193, vec![7, 0, 65, 5, 2, 8, 252, 7, 1, 8, 2, 1, 6, 0])] + { + bytes.extend_from_slice(&id.to_le_bytes()); + bytes.extend_from_slice(&(program.len() as u16 + 1).to_le_bytes()); + bytes.push(0); + bytes.extend(program); + } + bytes +} + +#[test] +fn shx_style_and_unicode_escapes_render_as_native_strokes_and_roundtrip() { + cadcraft_fonts::shx::register("cadcraft-io-synthetic.shx", &font()).unwrap(); + let dxf = "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nSTYLE\n0\nSTYLE\n2\nR80\n3\ncadcraft-io-synthetic.shx\n0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nTEXT\n7\nR80\n10\n0\n20\n0\n40\n6\n1\nA\\U+00C1\n0\nMTEXT\n7\nR80\n10\n0\n20\n-20\n40\n6\n41\n18\n1\nA\\U+00C1 A\\U+00C1\n0\nENDSEC\n0\nEOF\n"; + let drawing = cadcraft_io::read(dxf.as_bytes(), "synthetic.dxf").unwrap(); + let display = cadcraft_render::build(&drawing, &Space::Model, &cadcraft_render::Options::default()); + assert!(display.tris.is_empty(), "SHX letters and accents are strokes, not filled TrueType outlines"); + assert!(display.verts.iter().any(|p| (p.x - 11.0).abs() < 1e-9), "native advance of 7, not the built-in advance"); + assert!(display.verts.iter().any(|p| p.y > 6.0), "accent above the cap height"); + assert!(display.verts.iter().any(|p| p.y < -27.0), "MTEXT wraps its second word"); + let saved = cadcraft_io::write_dxf(&drawing); + let reopened = cadcraft_io::read(saved.as_bytes(), "synthetic.dxf").unwrap(); + let again = cadcraft_render::build(&reopened, &Space::Model, &cadcraft_render::Options::default()); + assert_eq!(display.verts, again.verts); + assert!(again.tris.is_empty()); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5b3a94ce8..f17732ed2 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (multiline attributes read, drawn and written) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (user SHX text fonts read; Latin stroke accents) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -112,7 +112,7 @@ early (#175), but the throughput problem remains. **DWG ≈ 30% read, ≈ 15% wr | DWF/DWFx export, DWF underlay | yes | no | 10–15 | | DGN import/export/underlay | yes | no (needs a public spec; owner decision) | 25–40 | | WMF, EPS, ACIS SAT, STL, FBX, IGES/STEP (Windows), 3DS | various | no; most are 3D and wait for M11 | 20–40 | -| SHX fonts (`.shx`, big fonts) | read | **not parsed**: our stroke font or FONTALT stands in, so text metrics differ from AutoCAD | 8–12 | +| SHX fonts (`.shx`, big fonts) | read | user `shapes 1.0/1.1` and Unicode `unifont 1.0` text fonts read via `CADCRAFT_SHXPATH`, native strokes/cap/advances; original Latin fallback accents. Big fonts, packed encodings and vertical text not read; separate SHX MTEXT attachment rules remain ([details](shx-fonts.md), part of #801) | 8–12 (not re-estimated) | | Linetype (`.lin`) and hatch pattern (`.pat`) files | load user files | user files load (#552); linetype shape (SHX) elements are skipped | 1–2 | | Plot styles (`.ctb`, `.stb`), plotter configs (`.pc3`), `.pmp` | yes | plot style tables in our own JSON format ([plot-styles.md](plot-styles.md)) and kept in the drawing; plotter devices with papers and printable areas in our own JSON format ([plotters.md](plotters.md), #564); binary `.ctb`/`.stb`/`.pc3`/`.pmp` not read (no public spec) | 4–8 | | Scripts (`.scr`) | SCRIPT | script text through the CLI, MCP and control channel; no SCRIPT command reading a `.scr` file | 1–2 | @@ -135,6 +135,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | SHX text fonts: bounded, lazy pen-program reader; style resolution and inline MTEXT use native cap/advance metrics; missing-font Latin accents draw as original single strokes. Big fonts and separate SHX MTEXT attachment rules remain; no proprietary fonts bundled | | 2026-10-12 | minor | PDF output: object transparency plotted as PDF alpha (`/ExtGState` `/ca` `/CA`) when the page setup's or the plot's "Plot transparency" is on; PNG plots blend it, SVG uses `opacity`; plots without it are unchanged byte for byte | | 2026-10-12 | minor | DXF/DWG save: the Model layout's plot settings are written as CADCraft plots model space, drawing extents scaled to fit (PLOTSETTINGS 74 = 1, 75 = 0), instead of plot type 5 "Layout information", which other programs' Plot dialogs can't use for model space | | 2026-10-12 | minor | VIEWPORT frozen layers also written and read as AutoCAD's group 341 layer handles, so third-party viewers honour per-viewport freezing in DXF (DWG converter gap noted) | diff --git a/docs/gaps.md b/docs/gaps.md index 0adb80f12..37bd5d034 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (multiline attributes read, drawn and saved: F17 narrowed) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (FF8 narrowed: user SHX text fonts read; Latin stroke accents) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -75,7 +75,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | FF5 | **[alpha blocker]** Real-file corpus (`storytold/cadcraft-corpus`), open → save → reopen tests, black-box check in AutoCAD | High | 10–15 + human | | FF6 | **[alpha blocker]** DWG throughput: a 10 MB DWG took ~2 min to fail (#57) | High for real projects | 6–10 | | FF7 | Table record and object handles from other programs' files are renumbered on the first save (entity handles are kept; `*D` blocks no longer duplicate and once reopened, CADCraft's own files keep every handle across saves, #495) | Low | 4–6 | -| FF8 | SHX fonts (shape and big fonts) not read | Medium-high (text metrics differ) | 8–12 | +| FF8 | SHX big fonts and packed encodings not read; vertical text and SHX-specific MTEXT attachment offsets remain. User shape fonts 1.0/1.1 and Unicode unifont 1.0 load via `CADCRAFT_SHXPATH`, with native strokes/advances; missing-font Latin accents stay single-stroke ([details](shx-fonts.md), part of #801) | Medium-high (unsupported fonts and some layout metrics differ) | 8–12 (not re-estimated) | | FF9 | `.pc3` plotter configuration files; linetype shape (SHX) elements are skipped (templates and `.dwt`, user `.lin`/`.pat` and `.pgp` alias files landed, #552; `.ctb`/`.stb`, #410) | Low-medium | 5–10 | | FF10 | PDF import and underlays (PDFATTACH); raster image attach (IMAGEATTACH). PDF export has real text in embedded TrueType subsets, PDF layers, several sheets per file and hyperlinks (#567, #571) | Medium | 20–35 | | FF11 | DWF/DWFx, DGN, WMF, EPS, ACIS/STL and other exchange formats | Low-medium | 50–100 | @@ -145,6 +145,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | FF8 narrowed: user SHX text fonts read with bounded pen-program decoding, native cap/advance metrics and original Latin stroke accents; big fonts, alternate encodings and separate SHX MTEXT layout rules remain | | 2026-10-12 | minor | Object transparency (entity, ByLayer, ByBlock) is drawn: on screen (TRANSPARENCYDISPLAY, on by default), in PNG/SVG exports, and in plots when the page setup's "Plot transparency" is on (PDF alpha, PNG blending, SVG opacity; PLOTTRANSPARENCYOVERRIDE): F14 narrowed | | 2026-10-12 | minor | Hatch and Gradient dialog (HATCH, GRADIENT; HPDLGMODE) and Hatch Edit dialog (HATCHEDIT, right-click, double-click a hatch): F13 narrowed to Preview, Inherit Properties and boundary add/remove in edit mode | | 2026-10-12 | minor | A bare system variable name typed at the command line (ORTHOMODE, GRIDMODE…) runs SETVAR on that variable, as in AutoCAD; U10 narrowed | diff --git a/docs/shx-fonts.md b/docs/shx-fonts.md new file mode 100644 index 000000000..b341d6f83 --- /dev/null +++ b/docs/shx-fonts.md @@ -0,0 +1,75 @@ +# SHX text fonts + +CADCraft reads user-supplied compiled stroke fonts in the `AutoCAD-86 shapes 1.0`, +`shapes 1.1` and Unicode `unifont 1.0` formats. It draws their pen programs as strokes, +using their cap height and pen-end advances. TEXT, MTEXT (including inline font switches, +wrapping and paragraph formatting), attributes, dimensions and table text use the same resolver. +Font names in DXF styles are preserved on save. + +## Supplying fonts + +Put fonts you are entitled to use in a separate directory and set `CADCRAFT_SHXPATH` before +starting CADCraft. It is an OS path list: semicolons on Windows, colons on Unix. For example, +in PowerShell: + +```powershell +$env:CADCRAFT_SHXPATH = 'C:\Users\you\CADFonts' +cadcraft drawing.dxf +``` + +The resolver searches those directories once, without recursion, by case-insensitive file name +or stem (`romans.shx` and `romans`). It does not search CAD installation bundles. Font files +are loaded only when used. Restart after changing the directories or installing a font. +Available SHX fonts take precedence over FONTALT. Missing, invalid or unsupported fonts keep +the existing FONTALT / CADCraft Stroke fallback. The original built-in stroke font now covers +the precomposed Latin accents used in Portuguese, instead of mixing thin letters with filled +TrueType accents. Characters absent from an SHX font retain the per-character fallback. + +The Rust `cadcraft_fonts::shx::register(name, bytes)` API accepts user-supplied bytes on native +and WASM builds. There is no web font-upload UI yet; the web build cannot search local folders. +No proprietary font is embedded, redistributed or included as a test fixture. + +## Supported programs and limits + +The interpreter supports pen up/down, the 16 compact vector directions, scaling, location +push/pop, subshapes, displacements, octant arcs, fractional arcs, bulge arcs and skipping +vertical-only commands during horizontal layout. Arcs are tessellated with up to 128 segments +per revolution. Glyphs are decoded lazily and shared across placements. + +Big fonts, packed multibyte encodings, vertical layout, SHP source loading and linetype shape +elements remain unsupported. Legacy shape fonts map Latin character numbers and the three +dimension symbols; alternate legacy character encodings are not inferred from the drawing. +Unicode SHX text uses bidi display order; OpenType joining is available through TrueType fonts, +not SHX programs. MTEXT still uses the existing attachment and line-pitch rules: this change +does not claim to fix the separate SHX layout offsets reported in #801. + +Hostile-input limits: 8 MiB per file; 8 KiB per glyph program; 32 loaded fonts / 64 MiB of +program bytes; 32 subshape levels and location-stack entries; 65,536 interpreter steps and +8,192 points per decoded glyph; finite coordinates within ±1,000,000 font units. Each font +caches at most 4,096 glyphs / 262,144 points. Directory scans stop after 8,192 entries across +at most 32 directories. Unsupported or over-limit programs fall back without panicking. + +## Format references and verification + +The pen language and metrics come from Autodesk's public +[Shape Descriptions](https://help.autodesk.com/cloudhelp/2026/ENU/AutoCAD-MAC-Customization/files/GUID-DE941DB5-7044-433C-AA68-2A9AE98A5713.htm), +[Special Codes Reference](https://help.autodesk.com/cloudhelp/2026/ENU/AutoCAD-MAC-Customization/files/GUID-06832147-16BE-4A66-A6D0-3ADF98DC8228.htm) +and [Text Font Descriptions](https://help.autodesk.com/cloudhelp/2026/ENU/AutoCAD-MAC-Customization/files/GUID-9BBE5B28-DF02-4EC5-863A-BA04AB6F5EF1.htm). +The compiled container layout was checked against the public MIT-licensed +[ezdxf format reader](https://github.com/mozman/ezdxf/blob/master/src/ezdxf/fonts/shapefile.py), +as a format reference; no library code or font definitions are incorporated. + +Binary headers end in CR/LF and `0x1A`. Shapes files have a little-endian first/last/count +header, an `(id, record length)` index, named records and an `EOF` marker. Unifont has a +little-endian record count, definition id/length and named definition with cap/descent/mode/ +encoding/embedding fields, followed by `(id, length, named program)` records. Unicode subshape +operands use high-byte-first ordering (distinct from little-endian record ids), as reported +in [#801](https://github.com/storytold/cadcraft/issues/801). + +Tests assemble original programs directly in Rust and cover both containers, native advances, +accent subshapes, arcs, pen/stack operations, inline MTEXT, wrapping, DXF Unicode escapes and +round trips. Truncation at every byte, deterministic mutations, cycles and invalid operands +exercise fallback and bounds. Implementation uses the public format references above; automated +tests use only original synthetic fixtures. At the reporter's explicit request, a manual local +check also loaded their installed `romans.shx` while rendering their DXF. Neither that font nor +the drawing is included in the repository or automated tests. From c32c0f5e30eecdfe6dce20c5a0948eed4e4293fb Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 21:48:35 +0200 Subject: [PATCH 006/531] fix(fonts): paragraph direction skips bidi isolates; harakat no longer block the Lam-Alef ligature (#1033) base_rtl now ignores strong characters between an isolate initiator and its PDI (or the end, when unmatched), per UBA P2. presentation_forms looks past combining marks for the Alef after a Lam and emits the marks after the ligature. Co-Authored-By: Claude Sonnet 5.5 --- crates/fonts/src/bidi.rs | 76 +++++++++++++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 8 deletions(-) diff --git a/crates/fonts/src/bidi.rs b/crates/fonts/src/bidi.rs index 1ca5a90ae..0cebd6bbc 100644 --- a/crates/fonts/src/bidi.rs +++ b/crates/fonts/src/bidi.rs @@ -33,13 +33,21 @@ pub(crate) fn is_mark(c: char) -> bool { } /// Base direction of a paragraph from its first strong character (rules P2/P3): `Some(true)` -/// right-to-left, `Some(false)` left-to-right, `None` when it has no strong character. +/// right-to-left, `Some(false)` left-to-right, `None` when it has no strong character. As rule +/// P2 requires, characters between an isolate initiator and its matching PDI (or the end of the +/// paragraph, when unmatched) are skipped. pub fn base_rtl(s: &str) -> Option { - s.chars().find_map(|c| match bidi_class(c) { - BidiClass::L => Some(false), - BidiClass::R | BidiClass::AL => Some(true), - _ => None, - }) + let mut isolate_depth: usize = 0; + for c in s.chars() { + match bidi_class(c) { + BidiClass::LRI | BidiClass::RLI | BidiClass::FSI => isolate_depth = isolate_depth.saturating_add(1), + BidiClass::PDI => isolate_depth = isolate_depth.saturating_sub(1), + BidiClass::L if isolate_depth == 0 => return Some(false), + BidiClass::R | BidiClass::AL if isolate_depth == 0 => return Some(true), + _ => {} + } + } + None } fn para_level(base: Option) -> Option { @@ -349,14 +357,24 @@ pub fn presentation_forms(chars: &[char], keep: impl Fn(char) -> bool) -> Vec<(c let mut i = 0; while let Some(&c) = chars.get(i) { let form = forms.get(i).copied().flatten(); + // Combining marks (harakat) between lam and alef are transparent for joining, so they + // don't block the ligature; they stay after it, in logical order. + let alef_at = + if c == '\u{0644}' { chars.get(i + 1..).and_then(|rest| rest.iter().position(|ch| !is_mark(*ch))).map(|p| i + 1 + p) } else { None }; if c == '\u{0644}' && let Some(f) = form - && let Some(&a) = chars.get(i + 1) + && let Some(j) = alef_at + && let Some(&a) = chars.get(j) && let Some(lig) = lam_alef(a, matches!(f, Form::Medial | Form::Final)) && keep(lig) { out.push((lig, i)); - i += 2; + for k in i + 1..j { + if let Some(&m) = chars.get(k) { + out.push((m, k)); + } + } + i = j + 1; continue; } let shaped = form.and_then(|f| presentation_form(c, f)).filter(|p| keep(*p)).unwrap_or(c); @@ -442,6 +460,48 @@ mod tests { assert!(visual_runs(&[], None).is_empty() && char_levels("", None).is_empty()); } + #[test] + fn paragraph_direction_skips_isolate_contents() { + // RLI שלום PDI abc: the Hebrew sits inside the isolate, so the first strong character is "a". + assert_eq!(base_rtl("\u{2067}שלום\u{2069} abc"), Some(false)); + assert_eq!(base_rtl("\u{2066}abc\u{2069} שלום"), Some(true)); + assert_eq!(base_rtl("\u{2068}שלום\u{2069}abc"), Some(false)); + // Nested isolates: only the outermost PDI closes the outer one. + assert_eq!(base_rtl("\u{2066}a\u{2067}ב\u{2069}a\u{2069}ב"), Some(true)); + assert_eq!(base_rtl("\u{2067}\u{2066}a\u{2069}ב\u{2069}a"), Some(false)); + // An unmatched initiator isolates the rest of the paragraph. + assert_eq!(base_rtl("\u{2067}שלום"), None); + assert_eq!(base_rtl("\u{2067}שלום\u{2069}"), None); + // A stray PDI does not close anything and does not underflow. + assert_eq!(base_rtl("\u{2069}\u{2069}שלום"), Some(true)); + // No strong character outside the isolates. + assert_eq!(base_rtl("12 \u{2066}abc\u{2069} 34"), None); + // Without isolates nothing changes. + assert_eq!(base_rtl(" 123 سلام abc"), Some(true)); + } + + #[test] + fn harakat_between_lam_and_alef_keep_the_ligature() { + let run = |s: &str| -> Vec<(char, usize)> { + let chars: Vec = s.chars().collect(); + presentation_forms(&chars, |_| true) + }; + // Lam + fatha + alef: the ligature, then the fatha (logical order kept). + assert_eq!(run("ل\u{064E}ا"), vec![('\u{FEFB}', 0), ('\u{064E}', 1)]); + // Word-medial: س + lam + fatha + shadda + alef gives the final ligature, marks after it. + assert_eq!(run("سل\u{064E}\u{0651}ا"), vec![('\u{FEB3}', 0), ('\u{FEFC}', 1), ('\u{064E}', 2), ('\u{0651}', 3)]); + // Plain lam + alef is unchanged. + assert_eq!(run("لا"), vec![('\u{FEFB}', 0)]); + // Mark after the alef is not between them: unchanged behaviour. + assert_eq!(run("لا\u{064E}"), vec![('\u{FEFB}', 0), ('\u{064E}', 2)]); + // Lam + mark + a non-alef letter: no ligature, the lam joins forward as before. + assert_eq!(run("ل\u{064E}م"), vec![('\u{FEDF}', 0), ('\u{064E}', 1), ('\u{FEE2}', 2)]); + // Lam + mark at the end: no alef, nothing breaks. + assert_eq!(run("ل\u{064E}"), vec![('\u{FEDD}', 0), ('\u{064E}', 1)]); + // A non-mark between lam and alef blocks the ligature. + assert_eq!(run("ل-ا").len(), 3); + } + #[test] fn hostile_input_never_panics() { for s in [ From 101397d9c517fffb4a886ee7c201204b5739f959 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 21:50:47 +0200 Subject: [PATCH 007/531] fix(fonts): MTEXT keeps the text after an unterminated code; bound oblique, line spacing and relative heights (#1035) - \U+hhhh (with surrogate pairs; a lone surrogate gives U+FFFD) and \M+nhhhh are decoded before plain_mtext, the layout parser and Paragraphs::scan read the contents. An unknown code without an argument now drops only the backslash and the code character instead of everything up to the next ';'. - layout_mtext_with: a non-finite oblique is 0; line spacing is 1 when not finite and positive, and clamped to 0.25..=4 (also in the paragraph layout). - Relative \H...x heights stay within 1e-3..1e3 times the MTEXT height. - cadcraft-fonts depends on cadcraft-dxf (L0) for the \M+ code page tables; mif_escape_at is public for that. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/dxf/src/lib.rs | 2 +- crates/fonts/Cargo.toml | 1 + crates/fonts/src/mtext.rs | 184 +++++++++++++++++++++++++++++++-- crates/fonts/src/mtext/para.rs | 7 +- 5 files changed, 186 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d4350e7fc..4955c5363 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -645,6 +645,7 @@ dependencies = [ name = "cadcraft-fonts" version = "0.6.2" dependencies = [ + "cadcraft-dxf", "cadcraft-geom", "harfrust", "skrifa 0.47.0", diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 82ecf55e8..0654ec87d 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -203,7 +203,7 @@ fn escape_at(chars: &[char], i: usize) -> Option { /// The character of a `\M+nXXXX` escape starting at `chars[i]`, if there is one: `n` names a /// double-byte code page and `XXXX` is the character's two bytes in hex. -fn mif_escape_at(chars: &[char], i: usize) -> Option { +pub fn mif_escape_at(chars: &[char], i: usize) -> Option { if chars.get(i) != Some(&'\\') || chars.get(i + 1) != Some(&'M') || chars.get(i + 2) != Some(&'+') { return None; } diff --git a/crates/fonts/Cargo.toml b/crates/fonts/Cargo.toml index d2bdddf88..859d6c1e4 100644 --- a/crates/fonts/Cargo.toml +++ b/crates/fonts/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] cadcraft-geom = { workspace = true } +cadcraft-dxf = { workspace = true } skrifa = { workspace = true } harfrust = { workspace = true } unicode-bidi = { workspace = true } diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 1d53dc915..ab3ec549c 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -9,6 +9,8 @@ pub(crate) mod para; /// Strip MTEXT formatting codes to plain text with `\n` paragraph breaks. /// Stacked fractions `\S1/2;` become `1/2`; `\~` is a space; braces are dropped. pub fn plain_mtext(s: &str) -> String { + let s = unescape_codes(s); + let s = s.as_ref(); let mut out = String::with_capacity(s.len()); let chars: Vec = s.chars().collect(); let mut i = 0; @@ -56,7 +58,7 @@ pub fn plain_mtext(s: &str) -> String { } 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => i += 2, // Codes with an argument terminated by ';' (\f, \F, \H, \W, \Q, \T, \A, \C, \c, \p). - _ => { + _ if takes_arg(code) => { let mut j = i + 2; while let Some(&ch) = chars.get(j) { if ch == ';' { @@ -66,6 +68,8 @@ pub fn plain_mtext(s: &str) -> String { } i = j + 1; } + // An unknown code has no argument: drop the backslash and the code only. + _ => i += 2, } } '{' | '}' => i += 1, @@ -178,6 +182,89 @@ const MAX_ATOMS: usize = 200_000; /// Scale of stacked text relative to the surrounding text. const STACK_SCALE: f64 = 0.7; +/// Codes that take an argument terminated by `;` (besides `\S`, which has its own scan). Any +/// other code stands alone, so a missing `;` must not swallow the text after it. +pub(crate) fn takes_arg(code: char) -> bool { + matches!(code, 'f' | 'F' | 'H' | 'W' | 'Q' | 'T' | 'A' | 'C' | 'c' | 'p') +} + +/// The line-spacing factor to lay out with: AutoCAD's 0.25..=4 range, 1 for a missing or +/// non-finite value. +pub(crate) fn sane_line_spacing(v: f64) -> f64 { + if v.is_finite() && v > 0.0 { v.clamp(0.25, 4.0) } else { 1.0 } +} + +/// Four hex digits at `chars[at..at + 4]`. +fn hex4(chars: &[char], at: usize) -> Option { + let digits = chars.get(at..at.checked_add(4)?)?; + digits.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?)) +} + +/// Push a decoded character so that the tokenizers read it as text, never as markup. +fn push_literal(out: &mut String, c: char) { + if matches!(c, '\\' | '{' | '}') { + out.push('\\'); + } + out.push(c); +} + +/// Decode `\U+hhhh` (one UTF-16 unit; a surrogate pair gives one character, a lone surrogate +/// U+FFFD) and `\M+nhhhh` (double-byte East Asian characters) to the characters they stand +/// for. Malformed escapes are left for the tokenizers, which drop the backslash and the code. +/// An escaped backslash (`\\U+0041`) is not an escape. +pub(crate) fn unescape_codes(s: &str) -> std::borrow::Cow<'_, str> { + if !s.contains("\\U+") && !s.contains("\\M+") { + return std::borrow::Cow::Borrowed(s); + } + let chars: Vec = s.chars().collect(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while let Some(&c) = chars.get(i) { + if c != '\\' { + out.push(c); + i += 1; + continue; + } + let (n, plus) = (chars.get(i + 1).copied(), chars.get(i + 2).copied()); + if n == Some('U') && plus == Some('+') { + if let Some(unit) = hex4(&chars, i + 3) { + i += 7; + let low = |at: usize| { + (chars.get(at) == Some(&'\\') && chars.get(at + 1) == Some(&'U') && chars.get(at + 2) == Some(&'+')) + .then(|| hex4(&chars, at + 3)) + .flatten() + .filter(|u| (0xDC00..0xE000).contains(u)) + }; + let ch = if (0xD800..0xDC00).contains(&unit) { + match low(i) { + Some(lo) => { + i += 7; + char::from_u32(0x10000 + ((unit - 0xD800) << 10) + (lo - 0xDC00)) + } + None => None, + } + } else { + char::from_u32(unit) + }; + push_literal(&mut out, ch.unwrap_or('\u{fffd}')); + continue; + } + } else if n == Some('M') && plus == Some('+') && chars.get(i + 3).is_some_and(char::is_ascii_digit) && hex4(&chars, i + 4).is_some() { + push_literal(&mut out, cadcraft_dxf::mif_escape_at(&chars, i).unwrap_or('\u{fffd}')); + i += 8; + continue; + } + // Any other backslash pair stays as it is (and an escaped backslash stays one). + out.push('\\'); + i += 1; + if let Some(&next) = chars.get(i) { + out.push(next); + i += 1; + } + } + std::borrow::Cow::Owned(out) +} + fn arg(chars: &[char], from: usize) -> (String, usize) { let mut j = from; let mut a = String::new(); @@ -229,6 +316,8 @@ fn font_switch(a: &str) -> Option { /// Parse MTEXT contents into words, spaces and paragraph breaks with their formats. fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { let chars: Vec = contents.chars().collect(); + let h_min = base.height * 1e-3; + let h_max = if (base.height * 1e3).is_finite() { base.height * 1e3 } else { f64::MAX }; let mut fmts = vec![base]; let mut cur = 0usize; let mut stack: Vec = Vec::new(); @@ -328,7 +417,9 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { None => (false, num(&a)), }; if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) { - derive(&mut fmts, &mut cur, &|f| f.height = if rel { f.height * v } else { v }); + // Relative heights compound; keep the result within 1e-3..1e3 times the + // MTEXT's own height, never infinite. + derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v }); } } 'W' => { @@ -367,11 +458,13 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { derive(&mut fmts, &mut cur, &|f| f.valign = v); } } - _ => { - // \T, \p and unknown codes: argument up to ';'. + _ if takes_arg(code) => { + // \T and \p: argument up to ';'. let (_, n) = arg(&chars, i); i = n; } + // An unknown code has no argument: only the backslash and the code are dropped. + _ => {} } } '{' => { @@ -537,11 +630,14 @@ pub fn layout_mtext(contents: &str, insert: Vec2, height: f64, width: f64, attac /// Lay out MTEXT: inline formatting runs, stacked fractions, paragraphs, word wrap to the /// column width and the attachment point. pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout { + let contents = unescape_codes(contents); + let contents = contents.as_ref(); let h = if p.height > 0.0 && p.height.is_finite() { p.height } else { 1.0 }; let wf = if p.width_factor.is_finite() && p.width_factor > 0.0 { p.width_factor } else { 1.0 }; let width = if p.width.is_finite() && p.width > 0.0 { p.width } else { 0.0 }; let rotation = if p.rotation.is_finite() { p.rotation } else { 0.0 }; - let base = Fmt { font: p.font.clone(), height: h, color: None, under: false, over: false, wf, oblique: p.oblique, valign: 1 }; + let oblique = if p.oblique.is_finite() { p.oblique } else { 0.0 }; + let base = Fmt { font: p.font.clone(), height: h, color: None, under: false, over: false, wf, oblique, valign: 1 }; let (atoms, fmts) = parse(contents, base.clone()); if para::needed(contents, p) { return para::layout(contents, p, &base); @@ -616,7 +712,7 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout { for l in &mut lines { l.reorder_bidi(bases.get(l.para).copied().flatten()); } - let ls = if p.line_spacing > 0.0 && p.line_spacing.is_finite() { p.line_spacing } else { 1.0 }; + let ls = sane_line_spacing(p.line_spacing); // Baselines below the top of the first line. let mut baselines = Vec::with_capacity(lines.len()); let mut y = 0.0; @@ -688,6 +784,82 @@ mod tests { assert_eq!(plain_mtext("unterminated \\H2"), "unterminated "); } + #[test] + fn unicode_escapes_are_decoded_in_every_parser() { + // The escape has no `;`, so it must not swallow the rest of the text. + assert_eq!(plain_mtext("A\\U+00B0 B C;D"), "A\u{b0} B C;D"); + assert_eq!(lay("A\\U+00B0 B C;D", 0.0).lines, vec!["A\u{b0} B C;D"]); + // The paragraph path (`\p`) and the plain path agree. + assert_eq!(lay("\\pxql;A\\U+00B0 B C;D", 0.0).lines, vec!["A\u{b0} B C;D"]); + let scanned = para::Paragraphs::scan("\\U+00B0\\pi1;x\\U+0041 y;z"); + assert!(scanned.formatted()); + // A surrogate pair is one character; a lone surrogate is U+FFFD. + assert_eq!(plain_mtext("\\U+D83D\\U+DE00!"), "\u{1f600}!"); + assert_eq!(lay("\\U+D83D\\U+DE00!", 0.0).lines, vec!["\u{1f600}!"]); + assert_eq!(plain_mtext("a\\U+D83Db"), "a\u{fffd}b"); + assert_eq!(plain_mtext("a\\U+DE00b\\U+D83D"), "a\u{fffd}b\u{fffd}"); + // A decoded backslash or brace is text, not markup; an escaped backslash is not an escape. + assert_eq!(plain_mtext("\\U+005CH2;x"), "\\H2;x"); + assert_eq!(plain_mtext("\\\\U+0041"), "\\U+0041"); + // `\M+n` double-byte characters, decoded like the DXF reader does. + assert_eq!(plain_mtext("\\M+5BCFE x;y"), "\u{4ef6} x;y"); + // Malformed escapes lose only the backslash and the code. + assert_eq!(plain_mtext("a\\U+12 b"), "a+12 b"); + assert_eq!(plain_mtext("a\\M+ b"), "a+ b"); + } + + #[test] + fn unknown_code_without_semicolon_keeps_the_text() { + assert_eq!(plain_mtext("A\\Zbc d"), "Abc d"); + assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["Abc d"]); + assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["Abc d"]); + // A trailing lone backslash is dropped. + assert_eq!(plain_mtext("A\\"), "A"); + // Codes with an argument still take it up to the `;`, or to the end. + assert_eq!(plain_mtext("A\\H2;B"), "AB"); + assert_eq!(plain_mtext("A\\H2 B"), "A"); + } + + #[test] + fn non_finite_oblique_and_line_spacing_are_repaired() { + let run = |oblique: f64, spacing: f64| { + let p = MTextParams { oblique, line_spacing: spacing, ..MTextParams::new(Vec2::ZERO, 1.0) }; + layout_mtext_with("AB\\PCD", &p) + }; + let finite = + |l: &MTextLayout| l.bounds.min.x.is_finite() && l.bounds.max.x.is_finite() && l.bounds.min.y.is_finite() && l.bounds.max.y.is_finite(); + let reference = run(0.0, 1.0); + for o in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let l = run(o, 1.0); + assert!(finite(&l), "oblique {o}"); + assert_eq!(l.bounds, reference.bounds, "oblique {o}"); + } + for s in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, -2.0] { + let l = run(0.0, s); + assert!(finite(&l), "spacing {s}"); + assert_eq!(l.bounds, reference.bounds, "spacing {s}"); + } + // Spacing is clamped to AutoCAD's 0.25..=4 range. + assert_eq!(run(0.0, 1e9).bounds, run(0.0, 4.0).bounds); + assert_eq!(run(0.0, 1e-9).bounds, run(0.0, 0.25).bounds); + assert!(run(0.0, 4.0).bounds.height() > reference.bounds.height()); + // The paragraph layout takes the same path. + let p = MTextParams { oblique: f64::NAN, line_spacing: f64::NAN, ..MTextParams::new(Vec2::ZERO, 1.0) }; + assert!(finite(&layout_mtext_with("\\pxql;AB\\PCD", &p))); + } + + #[test] + fn relative_heights_do_not_run_away() { + let src = format!("{}A", "\\H999999x;".repeat(60)); + let l = lay(&src, 0.0); + assert!(l.bounds.height().is_finite() && l.bounds.width().is_finite()); + assert!(l.bounds.height() <= 1e3 * 1.5, "{}", l.bounds.height()); + assert!(l.bounds.height() > 100.0, "the glyph must not vanish: {}", l.bounds.height()); + // Shrinking is bounded too. + let tiny = lay(&format!("{}A", "\\H0.000001x;".repeat(60)), 0.0); + assert!(tiny.bounds.height() > 0.0); + } + #[test] fn wraps_to_width() { let l = layout_mtext("the quick brown fox jumps over the lazy dog", Vec2::ZERO, 1.0, 8.0, 1, 0.0, 1.0); diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index d31f6a79d..760e6807a 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -264,6 +264,7 @@ pub struct Paragraphs { impl Paragraphs { pub fn scan(contents: &str) -> Paragraphs { + let contents = super::unescape_codes(contents); let chars: Vec = contents.chars().collect(); let mut out = Paragraphs { states: vec![ParaProps::default()], ..Default::default() }; let mut cur = 0usize; @@ -303,10 +304,12 @@ impl Paragraphs { cur = out.states.len() - 1; } } - _ => { + _ if super::takes_arg(code) => { let (_, n) = arg(&chars, i); i = n; } + // An unknown code has no argument: only the backslash and the code go. + _ => {} } } '\n' => { @@ -517,7 +520,7 @@ pub(super) fn layout(contents: &str, p: &MTextParams, base: &Fmt) -> MTextLayout finish(&mut lines, &mut line, fmt(last_fmt), k, true, 0.0); // Vertical placement: baselines below the top of each line's column. - let ls = if p.line_spacing > 0.0 && p.line_spacing.is_finite() { p.line_spacing } else { 1.0 }; + let ls = super::sane_line_spacing(p.line_spacing); let cols = p.columns.as_ref().filter(|_| width > 0.0); let max_cols = match cols { Some(c) if c.dynamic => MAX_COLUMNS, From cab962a7cbd870f6ab35e1e54da12c953668b9ef Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Tue, 13 Oct 2026 20:21:59 -0600 Subject: [PATCH 008/531] Let multileader text be edited (double-click, TEXTEDIT, Properties) Double-clicking a multileader's text now opens the in-place editor, the same as MTEXT. TEXTEDIT accepts a multileader and edits its MText contents (newlines round-trip as \P). The Properties palette shows a Contents field and a Text height field for a multileader with text, and properties.set writes them back. Fixes #1081. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify2.rs | 13 ++++++- crates/engine/src/cmd/props.rs | 11 ++++++ crates/engine/tests/mleader_text_edit.rs | 45 +++++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 10 +++-- crates/ui-egui/src/palettes.rs | 11 ++++++ crates/ui-egui/tests/text_double_click.rs | 24 ++++++++++++ 6 files changed, 109 insertions(+), 5 deletions(-) create mode 100644 crates/engine/tests/mleader_text_edit.rs diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index e94d7f124..7e85cfb08 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -2161,6 +2161,8 @@ 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() }), _ => None, } @@ -2175,11 +2177,16 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { EntityKind::Text(t) => t.value = text.to_string(), EntityKind::AttDef(a) => a.text.value = text.to_string(), EntityKind::MText(t) => t.contents = text.replace('\n', "\\P"), + EntityKind::MLeader(m) if m.text.is_some() => { + if let Some(t) = &mut m.text { + t.contents = text.replace('\n', "\\P"); + } + } EntityKind::Dimension(d) => { d.text = if text == "<>" { String::new() } else { text.to_string() }; d.block = None; } - _ => return Err(other("Select a text, mtext, attribute definition or dimension.")), + _ => return Err(other("Select a text, mtext, multileader, attribute definition or dimension.")), } set_kind(s, h, k) } @@ -2240,9 +2247,11 @@ impl Interactive for TextEditM { (None, Input::Point(p)) => { let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; let kind = curves::entity(s, h)?.kind; - let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, attribute definition or dimension."))?; + 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, }; self.h = Some((h, old)); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 6e68a9d8d..12b998202 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -319,6 +319,17 @@ fn run_set(s: &mut Session, p: &Value) -> Result { t.rotation = x.to_radians(); } } + // A multileader's text: its contents (#1081) and height. + EntityKind::MLeader(m) => { + if let Some(t) = &mut m.text { + if let Some(v) = str_param(p, "text") { + t.contents = v.replace('\n', "\\P"); + } + if let Some(x) = num("height").filter(|x| *x > 0.0) { + t.height = x; + } + } + } EntityKind::LwPolyline(pl) => { if let Some(x) = num("width").filter(|x| *x >= 0.0) { pl.const_width = x; diff --git a/crates/engine/tests/mleader_text_edit.rs b/crates/engine/tests/mleader_text_edit.rs new file mode 100644 index 000000000..ba2887419 --- /dev/null +++ b/crates/engine/tests/mleader_text_edit.rs @@ -0,0 +1,45 @@ +//! #1081: a multileader's text can be edited: TEXTEDIT (what a double-click starts) takes it and +//! hands it to the in-place editor, and the Properties palette's Contents field changes it. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +fn text_of(s: &Session) -> String { + s.doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| t.contents.clone()) } else { None }) + .unwrap() +} + +#[test] +fn textedit_and_properties_change_a_multileaders_text() { + let mut s = Session::new(); + s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); + let (h, at) = s + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| (e.handle, t.insert.xy())) } else { None }) + .unwrap(); + + // TEXTEDIT on the text: the current contents are the default, and the in-place editor gets + // the multileader's MTEXT. + s.cmdline("TEXTEDIT").unwrap(); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + let p = s.current_prompt().unwrap(); + assert_eq!(p.message, "Enter new text"); + assert_eq!(p.default.as_deref(), Some("example text")); + assert_eq!(s.editing_mtext().map(|m| m.contents), Some("example text".to_string())); + s.input(Input::Text("edited\nsecond line".into())).unwrap(); + assert_eq!(text_of(&s), "edited\\Psecond line"); + s.cancel(); + + // The Properties palette's Contents field. + s.execute("properties.set", &json!({"handles": [h.hex()], "text": "from properties"})).unwrap(); + assert_eq!(text_of(&s), "from properties"); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e5725e353..ffe153bcf 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1862,12 +1862,16 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } /// The model space tiles on screen (none without tiling): each tile's rectangle in `full`. -/// 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. +/// 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. 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| { - app.session.doc().ok()?.entity(h).map(|e| matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_))) + 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, + }) }); if is_text != Some(true) { return false; diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index c5283e084..99287fac5 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1018,6 +1018,17 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, &ids); num(ui, "Defined width", "width", len(tx.width), &mut set, &mut bad, &ids); } + // A multileader's text (#1081): it had no field, so it couldn't be changed. + EntityKind::MLeader(ml) => { + if let Some(tx) = &ml.text { + prop_row(ui, "Contents", |ui| { + if let Some(s) = edit_field(ui, ui.id().with(("mltxt", &ids)), tx.contents.clone()) { + set = Some(json!({ "handles": ids, "text": s })); + } + }); + num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, &ids); + } + } EntityKind::LwPolyline(pl) => { num(ui, "Global width", "width", len(pl.const_width), &mut set, &mut bad, &ids); let g = cadcraft_geom::Polyline { vertices: pl.vertices.clone(), closed: pl.closed }; diff --git a/crates/ui-egui/tests/text_double_click.rs b/crates/ui-egui/tests/text_double_click.rs index 782234d10..1b0918f01 100644 --- a/crates/ui-egui/tests/text_double_click.rs +++ b/crates/ui-egui/tests/text_double_click.rs @@ -76,3 +76,27 @@ fn double_click_elsewhere_starts_no_command() { assert_eq!(h.state().session.running.as_ref().map(|r| r.id.as_str()), None, "{at:?}"); } } + +/// #1081: double-clicking a multileader's text edits it, as for TEXT and MTEXT. +#[test] +fn double_click_on_a_multileaders_text_starts_textedit() { + let mut h = harness(); + h.state_mut().run("mleader", json!({ "points": [[16, -10], [20, -5]], "text": "example text" })).unwrap(); + h.run_steps(3); + let at = h + .state() + .session + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| t.insert.xy()) } else { None }) + .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")); + let p = s.current_prompt().unwrap(); + assert_eq!(p.message, "Enter new text"); + assert_eq!(p.default.as_deref(), Some("example text")); + assert!(s.editing_mtext().is_some(), "the in-place editor opens on it"); +} From bcac20dd5fffb953638e24e7438d8d47a6265231 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:25:48 +0300 Subject: [PATCH 009/531] io: a handle at the top of the range leaves new objects their own --- crates/doc/src/lib.rs | 11 +++++- crates/io/src/dxf_read.rs | 6 ++- crates/io/tests/handle_exhaustion.rs | 59 ++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 crates/io/tests/handle_exhaustion.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6462d3ac8..be0e8e504 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -35,6 +35,13 @@ pub use refedit::{RefEdit, WorkItem}; pub use store::EntityStore; pub use tables::*; +/// Handles at or above this are not followed or handed out: a hostile or damaged file naming one +/// (an object's handle, or its `$HANDSEED`) would leave nothing above it to allocate, and a new +/// object given that same handle would replace the object that has it (#913). Objects read with +/// such a handle get a fresh one; the four billion handles above the limit stay free for the +/// drawing's own growth. +pub const HANDLE_LIMIT: u64 = u64::MAX - 0xFFFF_FFFF; + /// File data CADCraft doesn't model, kept for saving (#528). pub mod dynblock; pub mod foreign; @@ -194,8 +201,8 @@ impl Drawing { } /// Make sure future handles don't collide with `h` (after loading a file). pub fn bump_handseed(&mut self, h: Handle) { - if h.0 >= self.handseed { - self.handseed = h.0.saturating_add(1); + if h.0 >= self.handseed && h.0 < HANDLE_LIMIT { + self.handseed = h.0 + 1; } } diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 7615bc569..52d1acb56 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -1218,11 +1218,13 @@ fn parse_entities(recs: &[(String, Vec)], d: &mut Drawing, rx: &mut Rx, ski } if let Some((c, mut k)) = kindent { let h = match handle { - Some(h) => { + // A handle at the top of the range (a hostile or damaged file) can't be followed: + // take a fresh one instead, so new objects don't replace this one (#913). + Some(h) if h.0 < cadcraft_doc::HANDLE_LIMIT => { d.bump_handseed(h); h } - None => d.new_handle(), + _ => d.new_handle(), }; entity_extras(kind, tags, h, &mut k, rx); let more: Vec<_> = diff --git a/crates/io/tests/handle_exhaustion.rs b/crates/io/tests/handle_exhaustion.rs new file mode 100644 index 000000000..c0ec951bf --- /dev/null +++ b/crates/io/tests/handle_exhaustion.rs @@ -0,0 +1,59 @@ +//! A hostile or damaged file can carry a handle at the top of the handle range: an object's own +//! handle, or its `$HANDSEED`. Nothing can be allocated above it, so every fresh handle came +//! back as that same top handle — and the store replaces an entity with the same handle, so the +//! next object drawn silently replaced the file's own object (#913). +#![cfg(not(target_arch = "wasm32"))] + +use cadcraft_doc::{Common, Drawing, EntityKind, Handle, Line, Space}; +use cadcraft_geom::Vec3; + +const TOP: &str = "FFFFFFFFFFFFFFFF"; + +fn read(text: &str) -> Drawing { + cadcraft_io::read_dxf(text.as_bytes()).unwrap() +} + +fn line(x: f64, y: f64) -> EntityKind { + EntityKind::Line(Line { a: Vec3::new(x, y, 0.0), b: Vec3::new(x + 1.0, y, 0.0) }) +} + +/// One line, with `entity_handle` when given, under a `$HANDSEED` of `seed`. +fn dxf(entity_handle: Option<&str>, seed: &str) -> String { + let handle = entity_handle.map(|h| format!("5\n{h}\n")).unwrap_or_default(); + format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n{seed}\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n0\nLINE\n{handle}8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n0.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n" + ) +} + +#[test] +fn an_object_at_the_top_of_the_handle_range_is_not_replaced_by_a_new_one() { + let mut d = read(&dxf(Some(TOP), TOP)); + assert_eq!(d.model.len(), 1); + // Draw a line: a fresh handle, then the entity. + d.add(&Space::Model, Common::default(), line(10.0, 10.0)).unwrap(); + assert_eq!(d.model.len(), 2, "the file's line was replaced by the new one"); + let handles: Vec = d.model.iter().map(|e| e.handle).collect(); + let unique: std::collections::HashSet = handles.iter().copied().collect(); + assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}"); + assert!(d.model.iter().any(|e| matches!(e.kind, EntityKind::Line(ref l) if l.a.x == 0.0)), "the file's line is gone"); +} + +#[test] +fn a_seed_at_the_top_of_the_handle_range_cannot_be_followed_twice() { + let mut d = read(&dxf(None, TOP)); + let a = d.add(&Space::Model, Common::default(), line(0.0, 10.0)).unwrap(); + let b = d.add(&Space::Model, Common::default(), line(0.0, 20.0)).unwrap(); + assert_ne!(a, b, "two objects were given the same handle"); + assert_eq!(d.model.len(), 3, "the second line replaced the first"); +} + +#[test] +fn an_ordinary_high_handle_keeps_its_identity() { + // Far below the top of the range a file's handles are its own: they stay as they are. + let h = "FFFFFFFF"; + let mut d = read(&dxf(Some(h), h)); + assert!(d.entity(Handle::parse_hex(h).unwrap()).is_some(), "the file's handle was renumbered"); + let n = d.add(&Space::Model, Common::default(), line(0.0, 5.0)).unwrap(); + assert!(n.0 > Handle::parse_hex(h).unwrap().0, "a new handle below the file's own"); +} From 1d29b626e66cc1a06999ba36dfb40e441929b3f6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 14 Oct 2026 23:49:44 +0200 Subject: [PATCH 010/531] fix(fonts): MTEXT \W...x multiplies the width factor; document the atom cap (#1272) Co-Authored-By: Claude Sonnet 5.5 --- crates/fonts/src/mtext.rs | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 1d53dc915..8ccc21989 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -173,7 +173,9 @@ enum Atom { Para(usize), } -/// Upper bound on parsed atoms (hostile contents). +/// Upper bound on parsed atoms (words, spaces and paragraph breaks) per MTEXT. Hostile contents +/// are cut here: once more than this many atoms are parsed, `parse` stops reading and the rest +/// of the contents is silently dropped from the layout. There is no warning to the caller. const MAX_ATOMS: usize = 200_000; /// Scale of stacked text relative to the surrounding text. const STACK_SCALE: f64 = 0.7; @@ -334,8 +336,14 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { 'W' => { let (a, n) = arg(&chars, i); i = n; - if let Some(v) = num(a.trim_end_matches(['x', 'X'])).filter(|v| *v > 0.01 && *v < 100.0) { - derive(&mut fmts, &mut cur, &|f| f.wf = v); + // `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it. + let (rel, v) = match a.trim().strip_suffix(['x', 'X']) { + Some(r) => (true, num(r)), + None => (false, num(&a)), + }; + if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) { + // Relative factors compound; keep the result within the absolute range. + derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v }); } } 'Q' => { @@ -688,6 +696,29 @@ mod tests { assert_eq!(plain_mtext("unterminated \\H2"), "unterminated "); } + /// The width factor of the last format `parse` derived. + fn last_wf(contents: &str, base_wf: f64) -> f64 { + let base = Fmt { font: TextFont::Stroke, height: 1.0, color: None, under: false, over: false, wf: base_wf, oblique: 0.0, valign: 1 }; + parse(contents, base).1.last().map_or(f64::NAN, |f| f.wf) + } + + #[test] + fn width_factor_x_is_relative() { + assert_eq!(last_wf("\\W2;a", 1.5), 2.0, "absolute sets the factor"); + assert_eq!(last_wf("\\W2x;a", 1.5), 3.0, "x multiplies the current factor"); + assert_eq!(last_wf("\\W2;\\W2x;a", 1.0), 4.0, "relative builds on the last absolute"); + assert_eq!(last_wf("\\W0.5X;a", 1.0), 0.5, "capital X too"); + // Hostile: a long relative chain stays inside the absolute range. + let chain = "\\W99x;".repeat(50); + assert_eq!(last_wf(&chain, 1.0), 100.0); + let down = "\\W0.02x;".repeat(50); + assert_eq!(last_wf(&down, 1.0), 0.01); + // Out of range or not a number: ignored. + assert_eq!(last_wf("\\W1e999x;a", 1.5), 1.5); + assert_eq!(last_wf("\\WNaNx;a", 1.5), 1.5); + assert_eq!(last_wf("\\Wx;a", 1.5), 1.5); + } + #[test] fn wraps_to_width() { let l = layout_mtext("the quick brown fox jumps over the lazy dog", Vec2::ZERO, 1.0, 8.0, 1, 0.0, 1.0); From ad072e6cb027411c99470b272189b42238912974 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Thu, 15 Oct 2026 10:54:43 -0600 Subject: [PATCH 011/531] MENUBAR and TOOLBAR at the command line bring hidden bars back (#1341) On Windows and Linux the in-window menu bar is the only menu, so once it was hidden there was no way back from the keyboard: MENUBAR and TOOLBAR, which AutoCAD users type for this, were unknown commands. MENUBAR asks "Enter new value for MENUBAR <1>:" (1 shows, 0 hides), and TOOLBAR (alias -TOOLBAR) asks for Show or Hide, Show by default. The JSON forms report or set the bars. The engine records the change and the UI applies it, reporting what it shows every frame. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/interface.rs | 123 ++++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/lib.rs | 6 ++ crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/lib.rs | 15 ++- crates/ui-egui/tests/menubar_toolbar.rs | 57 +++++++++++ 7 files changed, 204 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/interface.rs create mode 100644 crates/ui-egui/tests/menubar_toolbar.rs diff --git a/crates/engine/src/cmd/interface.rs b/crates/engine/src/cmd/interface.rs new file mode 100644 index 000000000..88fea379a --- /dev/null +++ b/crates/engine/src/cmd/interface.rs @@ -0,0 +1,123 @@ +//! MENUBAR and TOOLBAR: show or hide the window's menu bar and tool bar from the command line, as +//! in AutoCAD. With the menu bar hidden on Windows and Linux (where it is the only menu), typing +//! these is the way back. +//! +//! The UI owns the bars: it reports what it shows in [`Session::bars_shown`] and applies +//! [`Session::bars_request`], which these commands set. + +use serde_json::{Value, json}; + +use super::*; +use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; + +/// The interface bars MENUBAR and TOOLBAR control. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InterfaceBars { + pub menubar: bool, + pub toolbar: bool, +} + +impl Default for InterfaceBars { + fn default() -> Self { + InterfaceBars { menubar: true, toolbar: true } + } +} + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("menubar", "Menu Bar", run_menubar) + .params("{value?: 0|1} (1 shows the in-window menu bar, 0 hides it; without it, reports it)") + .enabled(always) + .noundo() + .interactive(|s| Ok(Box::new(MenubarM { current: s.bars_shown.menubar }))), + CommandSpec::new("toolbar", "Tool Bar", run_toolbar) + .alias(&["-toolbar"]) + .params("{show?: bool} (without it, reports it)") + .enabled(always) + .noundo() + .interactive(|_| Ok(Box::new(ToolbarM))), + ] +} + +fn set(s: &mut Session, f: impl FnOnce(&mut InterfaceBars)) { + let mut b = s.bars_request.unwrap_or(s.bars_shown); + f(&mut b); + s.bars_shown = b; + s.bars_request = Some(b); +} + +fn run_menubar(s: &mut Session, p: &Value) -> Result { + let v = match p.get("value") { + None | Some(Value::Null) => return Ok(json!({ "value": u8::from(s.bars_shown.menubar) })), + Some(v) => v + .as_u64() + .or_else(|| v.as_str().and_then(|t| t.trim().parse().ok())) + .filter(|v| *v <= 1) + .ok_or_else(|| bad("menubar", "`value` must be 0 or 1"))?, + }; + set(s, |b| b.menubar = v == 1); + Ok(json!({ "value": v })) +} + +fn run_toolbar(s: &mut Session, p: &Value) -> Result { + let Some(show) = p.get("show").filter(|v| !v.is_null()) else { return Ok(json!({ "show": s.bars_shown.toolbar })) }; + let show = show.as_bool().ok_or_else(|| bad("toolbar", "`show` must be true or false"))?; + set(s, |b| b.toolbar = show); + Ok(json!({ "show": show })) +} + +/// Typed MENUBAR: "Enter new value for MENUBAR <1>:". +struct MenubarM { + current: bool, +} + +impl Interactive for MenubarM { + fn name(&self) -> &'static str { + "MENUBAR" + } + fn prompt(&self, _s: &Session) -> Prompt { + Prompt::new("Enter new value for MENUBAR", Accept::NUMBER).default(u8::from(self.current).to_string()) + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match i { + Input::Enter => Ok(Step::Done), + Input::Text(t) => match run_menubar(s, &json!({ "value": t })) { + Ok(_) => Ok(Step::Done), + Err(_) => { + s.echo("Requires 0 or 1."); + Ok(Step::Continue) + } + }, + _ => Ok(Step::Continue), + } + } +} + +/// Typed TOOLBAR: "Enter tool bar option [Show/Hide] :" (CADCraft has one tool bar). +struct ToolbarM; + +impl Interactive for ToolbarM { + fn name(&self) -> &'static str { + "TOOLBAR" + } + fn prompt(&self, _s: &Session) -> Prompt { + Prompt::new("Enter tool bar option", Accept::TEXT).kw(&["Show", "Hide"]).default("Show") + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let word = match &i { + Input::Enter => "show".to_string(), + Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(), + _ => return Ok(Step::Continue), + }; + let show = if !word.is_empty() && "show".starts_with(&word) { + true + } else if !word.is_empty() && "hide".starts_with(&word) { + false + } else { + s.echo("Invalid option keyword."); + return Ok(Step::Continue); + }; + run_toolbar(s, &json!({ "show": show }))?; + Ok(Step::Done) + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index f7307f26b..7e268c48f 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -19,6 +19,7 @@ mod griphot; pub(crate) mod groups; pub(crate) mod hatch; mod inquiry; +pub mod interface; mod layer; mod layout; mod lisp; @@ -197,6 +198,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(inquiry::specs()); v.extend(settings::specs()); v.extend(options::specs()); + v.extend(interface::specs()); v.extend(utility::specs()); v.extend(table::specs()); v.extend(tolerance::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 97f4b969b..d40f33379 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -671,6 +671,10 @@ pub struct Session { lisp_last: Option>, /// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks). pub hatch_picks: Option, + /// The window's menu bar and tool bar as the UI shows them (it reports them every frame). + pub bars_shown: cmd::interface::InterfaceBars, + /// A change MENUBAR or TOOLBAR asked for, for the UI to apply. + pub bars_request: Option, } impl Default for Session { @@ -719,6 +723,8 @@ impl Session { lisp: lisp::LispState::default(), lisp_last: None, hatch_picks: None, + bars_shown: Default::default(), + bars_request: None, } } pub fn new_drawing(&mut self, metric: bool) -> usize { diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f4ad00852..0386146db 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -535,6 +535,7 @@ Measure Medir Measure Distance Medir distancia Measure Geometry Medir geometría + Menu Bar Barra de menús Merge Cells Combinar celdas Merged PRs PR integradas Mid Between 2 Points Punto medio entre 2 puntos diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index adce43ae7..f75eca1b3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -521,6 +521,7 @@ Measure Розмітити Measure Distance Виміряти відстань Measure Geometry Виміряти геометрію + Menu Bar Рядок меню Merge Cells Об'єднати комірки Merged PRs Об'єднані PR Mid Between 2 Points Середина між 2 точками diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 91c48e5f8..a6b9ca138 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -337,6 +337,7 @@ impl CadApp { /// Submit a line of command-line text. A refused line is echoed to the history; the error is /// also returned. pub fn cmdline(&mut self, text: &str) -> Option { + self.sync_bars(); if !self.session.prompting() { let first = text.split_whitespace().next().unwrap_or(""); // `cmd {json}` is a programmatic call: the engine runs it with those parameters. @@ -345,11 +346,22 @@ impl CadApp { return None; } } - let e = self.session.cmdline(text).err()?.to_string(); + let r = self.session.cmdline(text); + self.sync_bars(); + let e = r.err()?.to_string(); self.session.echo(e.clone()); Some(e) } + /// Apply a menu bar / tool bar change MENUBAR or TOOLBAR asked for, and report the bars shown. + fn sync_bars(&mut self) { + if let Some(b) = self.session.bars_request.take() { + self.ui.in_window_menu = b.menubar; + self.ui.show_toolbar = b.toolbar; + } + self.session.bars_shown = cadcraft_engine::cmd::interface::InterfaceBars { menubar: self.ui.in_window_menu, toolbar: self.ui.show_toolbar }; + } + /// The theme the interface shows now (the choice resolved against the OS appearance). pub fn shown_theme(&self) -> egui::Theme { self.shown_theme.unwrap_or_else(|| self.ui.theme.resolve(None)) @@ -616,6 +628,7 @@ impl CadApp { fn draw(&mut self, ui: &mut egui::Ui) { let t0 = now_ms(); + self.sync_bars(); control::begin_frame(ui.ctx()); let t = theme::Tokens::get(); chrome::title_and_toolbar(self, ui); diff --git a/crates/ui-egui/tests/menubar_toolbar.rs b/crates/ui-egui/tests/menubar_toolbar.rs new file mode 100644 index 000000000..74ca46566 --- /dev/null +++ b/crates/ui-egui/tests/menubar_toolbar.rs @@ -0,0 +1,57 @@ +//! MENUBAR and TOOLBAR at the command line bring a hidden menu bar and tool bar back (#1341): +//! on Windows and Linux the in-window menu bar is the only menu, so with it hidden typing these +//! is the way back, as in AutoCAD. + +use cadcraft_engine::Session; +use cadcraft_ui_egui::{CadApp, Services}; +use serde_json::json; + +fn app() -> CadApp { + CadApp::new(Session::new(), Services::default()) +} + +#[test] +fn typed_menubar_shows_and_hides_the_menu_bar() { + let mut app = app(); + app.ui.in_window_menu = false; + app.cmdline("MENUBAR"); + assert_eq!(app.session.prompt_text(), "MENUBAR Enter new value for MENUBAR <0>:"); + app.cmdline("1"); + assert!(app.session.running.is_none()); + assert!(app.ui.in_window_menu); + // 0 hides it again; anything else is refused and asked again. + app.cmdline("MENUBAR"); + app.cmdline("2"); + assert!(app.session.running.is_some(), "still asking"); + app.cmdline("0"); + assert!(!app.ui.in_window_menu); +} + +#[test] +fn typed_toolbar_shows_the_tool_bar_by_default() { + let mut app = app(); + app.ui.show_toolbar = false; + app.cmdline("TOOLBAR"); + assert_eq!(app.session.prompt_text(), "TOOLBAR Enter tool bar option or [Show/Hide] :"); + app.cmdline(""); + assert!(app.ui.show_toolbar); + app.cmdline("TOOLBAR"); + app.cmdline("H"); + assert!(!app.ui.show_toolbar); +} + +#[test] +fn the_json_forms_report_and_set_the_bars() { + let mut app = app(); + app.ui.in_window_menu = true; + app.ui.show_toolbar = false; + app.cmdline("MENUBAR"); + app.cmdline(""); + assert_eq!(app.session.execute("menubar", &json!({})).unwrap(), json!({ "value": 1 })); + assert_eq!(app.session.execute("toolbar", &json!({})).unwrap(), json!({ "show": false })); + app.session.execute("toolbar", &json!({ "show": true })).unwrap(); + app.cmdline("MENUBAR"); + app.cmdline(""); + assert!(app.ui.show_toolbar && app.ui.in_window_menu); + assert!(app.session.execute("menubar", &json!({ "value": 3 })).is_err()); +} From bc7357ffb86cdcc727c439f166daa78138824492 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 17 Oct 2026 20:06:36 +1100 Subject: [PATCH 012/531] UCS: the UCS command, and points, angles and coordinates in the current UCS (part of #1106) A current user coordinate system, per space: model space's in the header (UCSORG, UCSXDIR, UCSYDIR, UCSNAME), each layout's on the layout. The drawing stays in world coordinates; a UCS changes how points are read and shown, so drawing and regenerating cost nothing more. - UCS: origin, then points on the X axis and the XY plane (the default), World, Previous (ten per space), NAmed (Restore, Save, Delete, ?), OBject (lines, arcs, circles, polylines, points, text, blocks, 2D solids, 3D faces, dimensions), View and Z (UCSAXISANG). X, Y, ZAxis and Face tilt the UCS out of the XY plane and say they are not available yet. Tools > New UCS > World / Origin / 3 Point / View / Z. A UCS change is undone as an edit is. - Typed points are read in the UCS: x,y from its origin along its axes, @dx,dy along its axes, polar angles from its X axis, # absolute in the UCS, * and @* world. Every direction prompt (and ANGBASE) is measured from the UCS X axis; sizes of angles aren't affected. JSON parameters stay in world coordinates. - Dynamic Input reads and shows its values in the UCS; the status bar, ID and DIST show coordinates in it (their JSON results keep world values). - UCSNAME, UCSORG, UCSXDIR, UCSYDIR, WORLDUCS (read-only), UCSAXISANG and UCSICON. UCSICON ON/OFF/Noorigin/ORigin; the icon turns with the UCS, sits at its origin when that fits on screen, and has the square only in the World UCS. View > UCS Icon > Origin. The ViewCube pill shows the UCS name and its menu restores World or a named UCS. The icon takes clicks only at the Command prompt, so snaps at the origin reach the drawing. - AutoLISP: getpoint, getcorner, entsel and getangle answer in the UCS, command takes UCS points, trans converts between the WCS, the UCS, display coordinates and an object's OCS; entity lists stay in WCS. - Files: model space's UCS in the header and the shown VPORT (110-112), each layout's in its LAYOUT object (13, 16, 17, 345 for a named UCS), through DXF and DWG. The DWG bridge drops $UCSNAME: a CADCraft XRECORD keeps it, used only while the UCS still is that named one. Broken values aren't written back. - A UCS tilted out of the XY plane read from a file is kept and saved as it is; points are read in the World UCS meanwhile, and the user is told once. Tests: engine (command, every option, previous, named, object rules, undo, paper space, typed input, directions, displays, variables, UCSICON, tilted, hostile), LISP (trans, getpoint, command, getangle), files (DXF, DWG twice, named layout UCS, stale name copy, tilted, broken, hostile), Dynamic Input and the icon. --- apps/cadcraft/src/workspace.rs | 1 - crates/doc/src/tables.rs | 6 +- crates/engine/src/cmd/inquiry.rs | 14 +- crates/engine/src/cmd/layout.rs | 2 +- crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/ucs.rs | 642 ++++++++++++++++++++++++++ crates/engine/src/lib.rs | 14 +- crates/engine/src/lisp/drawing.rs | 61 ++- crates/engine/src/lisp/input.rs | 27 +- crates/engine/src/lisp/mod.rs | 4 +- crates/engine/src/lisp/ucs_tests.rs | 147 ++++++ crates/engine/src/pointmod.rs | 4 +- crates/engine/src/prompt.rs | 38 +- crates/engine/src/sysvars.rs | 34 +- crates/engine/src/sysvars/table.rs | 3 + crates/engine/src/ucs.rs | 374 +++++++++++++++ crates/engine/src/units.rs | 28 +- crates/engine/tests/angle_settings.rs | 2 +- crates/engine/tests/ucs.rs | 494 ++++++++++++++++++++ crates/io/src/dxf_ext.rs | 3 + crates/io/src/dxf_read.rs | 44 +- crates/io/src/dxf_write.rs | 212 +++++---- crates/io/tests/ucs_roundtrip.rs | 255 ++++++++++ crates/ui-egui/src/canvas.rs | 50 +- crates/ui-egui/src/chrome.rs | 3 +- crates/ui-egui/src/cmdline.rs | 3 +- crates/ui-egui/src/dyninput.rs | 73 ++- crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/lib.rs | 2 - crates/ui-egui/src/menus.rs | 10 +- crates/ui-egui/src/viewcube.rs | 162 ++++++- docs/autolisp.md | 2 +- docs/file-format-parity.md | 3 +- docs/gaps.md | 4 +- docs/parity-checklist.md | 19 +- docs/ui-parity.md | 4 +- 36 files changed, 2547 insertions(+), 207 deletions(-) create mode 100644 crates/engine/src/cmd/ucs.rs create mode 100644 crates/engine/src/lisp/ucs_tests.rs create mode 100644 crates/engine/src/ucs.rs create mode 100644 crates/engine/tests/ucs.rs create mode 100644 crates/io/tests/ucs_roundtrip.rs diff --git a/apps/cadcraft/src/workspace.rs b/apps/cadcraft/src/workspace.rs index e2a429d94..b91f2701a 100644 --- a/apps/cadcraft/src/workspace.rs +++ b/apps/cadcraft/src/workspace.rs @@ -51,7 +51,6 @@ fn snapshot(ui: &UiState) -> Result { "showStatusBar": ui.show_status_bar, "showCommandLine": ui.show_command_line, "showViewcube": ui.show_viewcube, - "showUcsIcon": ui.show_ucs_icon, "showLayerList": ui.show_layer_list, "toolsetTab": ui.toolset_tab, "collapsedGroups": ui.collapsed_groups, diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index f9824ec6d..522b3e96a 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -784,11 +784,15 @@ pub struct Layout { /// Saved paper-space view (centre, height). #[serde(default)] pub view: Option<(Vec2, f64)>, + /// The layout's current paper-space UCS (the LAYOUT object's groups 13, 16, 17 and 345); + /// `None`: the World UCS. Its name is empty when it isn't a named UCS. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ucs: Option, } impl Layout { pub fn new(name: &str, tab_order: u32) -> Self { - Layout { name: name.into(), tab_order, page: PageSetup::default(), entities: EntityStore::new(), view: None } + Layout { name: name.into(), tab_order, page: PageSetup::default(), entities: EntityStore::new(), view: None, ucs: None } } } diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index f16ad6447..e343c616a 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -71,8 +71,9 @@ fn fmt_a(s: &Session, v: f64) -> String { format_angle(v, h.0, h.1) } +/// DIST's report: the angle and deltas measured in the current UCS. fn dist_text(s: &Session, a: Vec2, b: Vec2) -> String { - let d = b - a; + let d = s.input_ucs().vec_to_ucs(b - a); format!( "Distance = {}, Angle in XY Plane = {}, Angle from XY Plane = 0\nDelta X = {}, Delta Y = {}, Delta Z = {}", fmt_d(s, a.dist(b)), @@ -89,10 +90,17 @@ fn run_dist(s: &mut Session, p: &Value) -> Result { Ok(json!({ "distance": a.dist(b), "angle": (b - a).angle().to_degrees(), "dx": b.x - a.x, "dy": b.y - a.y, "message": dist_text(s, a, b) })) } +/// ID's report: the point in the current UCS (on its XY plane). +fn id_text(s: &Session, p: Vec2) -> String { + let u = s.ucs_point(p); + format!("X = {} Y = {} Z = {}", fmt_d(s, u.x), fmt_d(s, u.y), fmt_d(s, 0.0)) +} + fn run_id(s: &mut Session, p: &Value) -> Result { let a = point_req("id", p, "at")?; s.last_point = a; - Ok(json!({ "x": a.x, "y": a.y, "message": format!("X = {} Y = {} Z = {}", fmt_d(s, a.x), fmt_d(s, a.y), fmt_d(s, 0.0)) })) + let u = s.ucs_point(a); + Ok(json!({ "x": a.x, "y": a.y, "ucs": [u.x, u.y, 0.0], "message": id_text(s, a) })) } fn list_text(s: &Session, h: Handle) -> String { @@ -600,7 +608,7 @@ impl Interactive for IdM { } fn input(&mut self, s: &mut Session, i: Input) -> Result { if let Input::Point(p) = i { - let m = format!("X = {} Y = {} Z = {}", fmt_d(s, p.x), fmt_d(s, p.y), fmt_d(s, 0.0)); + let m = id_text(s, p); s.echo(m); } Ok(Step::Done) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index cac585209..9c9d6f935 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -305,7 +305,7 @@ fn run_copy(s: &mut Session, p: &Value) -> Result { let h = d.new_handle(); store.push(Entity { handle: h, ..Entity::clone(e) }); } - d.layouts.push(Layout { name: to.clone(), tab_order: order, page: src.page, entities: store, view: src.view }); + d.layouts.push(Layout { name: to.clone(), tab_order: order, page: src.page, entities: store, view: src.view, ucs: src.ucs }); Ok(json!({ "name": to })) } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index f7307f26b..00f1f21cd 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -39,6 +39,7 @@ mod spline_opts; mod table; mod tolerance; mod trimextend; +mod ucs; mod utility; mod view; @@ -175,6 +176,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(qselect::specs()); v.extend(selecttools::specs()); v.extend(view::specs()); + v.extend(ucs::specs()); v.extend(draw::specs()); v.extend(draw2::specs()); v.extend(annotate::specs()); diff --git a/crates/engine/src/cmd/ucs.rs b/crates/engine/src/cmd/ucs.rs new file mode 100644 index 000000000..75a477817 --- /dev/null +++ b/crates/engine/src/cmd/ucs.rs @@ -0,0 +1,642 @@ +//! UCS an UCSICON: the current user coordinate system ([`crate::ucs`]) and its icon. +//! +//! UCS sets the current UCS of the space commands act on: by an origin and points on the new X +//! axis and XY plane (the default option), World, Previous, NAmed (Restore, Save, Delete, `?`), +//! OBject (lined up with an object), View and Z (a turn about Z). X, Y, ZAxis and Face tilt the +//! UCS out of the XY plane, which CADCraft doesn't draw in yet; they say so. A UCS change is part +//! of the command's undo step, as an edit is. + +use cadcraft_doc::{Drawing, EntityKind}; +use cadcraft_geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +use super::{CommandSpec, bad, str_param}; +use crate::prompt::{Accept, Input, Interactive, Prompt, Step}; +use crate::ucs::{UcsFrame, named}; +use crate::{EngineError, Result, Session}; + +/// The UCS command's options, as typed. +const OPTIONS: &[&str] = &["Face", "NAmed", "OBject", "Previous", "View", "World", "X", "Y", "Z", "ZAxis"]; + +/// Characters a UCS name can't hold. +const BAD_NAME_CHARS: &[char] = &['<', '>', '/', '\\', '"', ':', ';', '?', '*', '|', ',', '=', '`']; + +/// Longest UCS name. +const MAX_NAME: usize = 255; + +/// Most UCS table records a drawing keeps (a hostile script can't grow it without bound). +const MAX_NAMED: usize = 10_000; + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("ucs", "UCS", run_ucs) + .params( + "{option?: origin|world|previous|named|object|view|z|x|y|zaxis|face (default origin), origin?: [x,y(,z)], xPoint?, xyPoint? \ + (origin: the new origin, and points on its positive X axis and on the positive-Y side of its XY plane; without them \ + the axes stay), angle? (z: degrees counterclockwise about Z, default UCSAXISANG), action?: restore|save|delete|list \ + (named), name? (named; delete and list take wildcards and commas), replace?: bool (save over an existing name), \ + handle?, at? (object: the object and the point it is picked at)} → {ucs: {name, origin, xAxis, yAxis}}. Points \ + are world coordinates. x, y, zaxis and face tilt the UCS out of the XY plane and are not available yet.", + ) + .interactive(|_| Ok(Box::new(UcsM::default()))), + CommandSpec::new("ucs.world", "World", |s, p| run_ucs(s, &with_option(p, "world"))) + .menu(&["Tools", "New UCS", "World"]) + .params("{} (the World UCS)"), + CommandSpec::new("ucs.origin", "Origin", |s, p| run_ucs(s, &with_option(p, "origin"))) + .menu(&["Tools", "New UCS", "Origin"]) + .params("{origin: [x,y(,z)]} (moves the UCS, keeping its axes)") + .interactive(|_| Ok(Box::new(UcsM::starting(Stage::OriginOnly)))), + CommandSpec::new("ucs.3point", "3 Point", |s, p| run_ucs(s, &with_option(p, "origin"))) + .menu(&["Tools", "New UCS", "3 Point"]) + .params("{origin, xPoint?, xyPoint?} (as `ucs` origin)") + .interactive(|_| Ok(Box::new(UcsM::starting(Stage::ThreePoint)))), + CommandSpec::new("ucs.view", "View", |s, p| run_ucs(s, &with_option(p, "view"))) + .menu(&["Tools", "New UCS", "View"]) + .params("{} (XY plane square to the view, origin kept)"), + CommandSpec::new("ucs.z", "Z", |s, p| run_ucs(s, &with_option(p, "z"))) + .menu(&["Tools", "New UCS", "Z"]) + .params("{angle?} (degrees counterclockwise about Z, default UCSAXISANG)") + .interactive(|_| Ok(Box::new(UcsM::starting(Stage::ZAngle)))), + CommandSpec::new("ucsicon", "UCS Icon", run_ucsicon) + .params("{on?: bool, origin?: bool} (UCSICON: the icon shown, and at the UCS origin when that is on screen) → {on, origin}") + .noundo() + .interactive(|_| Ok(Box::new(UcsIconM))), + ] +} + +fn with_option(p: &Value, option: &str) -> Value { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + if let Some(o) = p.as_object_mut() { + o.insert("option".into(), json!(option)); + } + p +} + +/// A JSON point with an optional Z: `[x, y]`, `[x, y, z]` or `{x, y, z?}`. +fn point3(v: &Value) -> Option { + let p = if let Some(a) = v.as_array() { + Vec3::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2).and_then(Value::as_f64).unwrap_or(0.0)) + } else { + Vec3::new(v.get("x")?.as_f64()?, v.get("y")?.as_f64()?, v.get("z").and_then(Value::as_f64).unwrap_or(0.0)) + }; + p.is_finite().then_some(p) +} + +fn point3_param(cmd: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => point3(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite point [x, y] or [x, y, z]"))), + } +} + +/// `UCS` as JSON: the result is the new current UCS. +fn run_ucs(s: &mut Session, p: &Value) -> Result { + let option = str_param(p, "option").unwrap_or("origin").trim().to_ascii_lowercase(); + match option.as_str() { + "origin" | "3point" => { + let origin = point3_param("ucs", p, "origin")?.ok_or_else(|| bad("ucs", "`origin` ([x, y] or [x, y, z]) is required"))?; + let x = point3_param("ucs", p, "xPoint")?; + let xy = point3_param("ucs", p, "xyPoint")?; + if xy.is_some() && x.is_none() { + return Err(bad("ucs", "`xyPoint` needs `xPoint`")); + } + set_by_points(s, origin, x, xy)?; + } + "world" | "w" => s.set_ucs(UcsFrame::WORLD, "")?, + "previous" | "p" => { + if !s.ucs_previous()? { + return Err(bad("ucs", "there is no previous UCS")); + } + } + "view" | "v" => s.set_ucs(view_ucs(s), "")?, + "z" => { + let deg = match p.get("angle") { + None | Some(Value::Null) => axis_angle(s), + Some(v) => v.as_f64().filter(|a| a.is_finite()).ok_or_else(|| bad("ucs", "`angle` must be a finite number of degrees"))?, + }; + rotate_z(s, deg.to_radians())?; + } + "object" | "ob" => { + let h = super::targets(s, p)?.first().copied().ok_or_else(|| bad("ucs", "`handle` (the object) is required"))?; + let at = p.get("at").and_then(super::point_value); + set_by_object(s, h, at)?; + } + "named" | "na" => { + let action = str_param(p, "action").unwrap_or("restore").trim().to_ascii_lowercase(); + let name = str_param(p, "name").map(str::trim).unwrap_or_default().to_string(); + match action.as_str() { + "restore" | "r" => restore(s, &name).map_err(|e| bad("ucs", e))?, + "save" | "s" => save(s, &name, p.get("replace").and_then(Value::as_bool).unwrap_or(false)).map_err(|e| bad("ucs", e))?, + "delete" | "d" => { + let n = delete(s, if name.is_empty() { "" } else { &name })?; + return Ok(json!({ "deleted": n, "ucs": ucs_json(s) })); + } + "list" | "?" => return Ok(json!({ "list": list(s, if name.is_empty() { "*" } else { &name }), "ucs": ucs_json(s) })), + other => return Err(bad("ucs", format!("unknown named action `{other}` (restore, save, delete or list)"))), + } + } + "x" | "y" | "zaxis" | "za" | "face" | "f" => return Err(bad("ucs", tilted_message(&option))), + other => return Err(bad("ucs", format!("unknown option `{other}`"))), + } + Ok(json!({ "ucs": ucs_json(s) })) +} + +fn ucs_json(s: &Session) -> Value { + let (u, name) = s.ucs_named(); + let p = |v: Vec3| json!([v.x, v.y, v.z]); + json!({ "name": name, "origin": p(u.origin), "xAxis": p(u.x), "yAxis": p(u.y), "world": u.is_world() }) +} + +fn tilted_message(option: &str) -> String { + let label = match option { + "x" => "UCS X", + "y" => "UCS Y", + "zaxis" | "za" => "UCS ZAxis", + _ => "UCS Face", + }; + format!("{label} tilts the UCS out of the XY plane, which is not available yet.") +} + +/// The UCSAXISANG default for Z, in degrees. +fn axis_angle(s: &Session) -> f64 { + s.doc().map(|d| d.header.i64("UCSAXISANG", 90)).unwrap_or(90) as f64 +} + +/// A 2D point of the current UCS's XY plane as a 3D world point. +fn on_plane(s: &Session, p: Vec2) -> Vec3 { + p.to3(s.ucs().origin.z) +} + +/// The UCS through `origin`, with points on its X axis and in its XY plane (world points). +fn set_by_points(s: &mut Session, origin: Vec3, x: Option, xy: Option) -> Result<()> { + let f = s.ucs().from_points(origin, x, xy).ok_or_else(|| EngineError::Other("Those points don't define a UCS: they lie on one line.".into()))?; + if !f.is_planar() { + return Err(EngineError::Other("That UCS is tilted out of the XY plane (or turned over), which is not available yet.".into())); + } + s.set_ucs(f, "") +} + +/// UCS View: the XY plane square to the view (a plan view, so the World UCS's axes), at the +/// current origin. +fn view_ucs(s: &Session) -> UcsFrame { + UcsFrame::WORLD.with_origin(s.ucs().origin) +} + +fn rotate_z(s: &mut Session, angle: f64) -> Result<()> { + let f = s.ucs().rotated_z(angle); + s.set_ucs(f, "") +} + +/// UCS OBject: the UCS lined up with object `h`, picked at `at` (world) when known. +fn set_by_object(s: &mut Session, h: cadcraft_doc::Handle, at: Option) -> Result<()> { + let d = s.doc()?; + let e = d.entity(h).ok_or_else(|| EngineError::Other("No such object.".into()))?; + let ext = e.common.extrusion; + if ext.is_finite() && (ext.x.abs() > 1e-9 || ext.y.abs() > 1e-9 || ext.z < 0.0) { + return Err(EngineError::Other("That object lies in a tilted plane; a UCS out of the XY plane is not available yet.".into())); + } + let f = object_frame(&s.ucs(), &e.kind, at)?; + s.set_ucs(f, "") +} + +/// A frame at `o` whose X axis points along `dir` in the XY plane. +fn along(o: Vec3, dir: Vec2) -> Result { + UcsFrame::new(o, dir.to3(0.0), dir.perp().to3(0.0)) + .ok_or_else(|| EngineError::Other("That object has no direction to line the UCS up with.".into())) +} + +/// The UCS OBject rules: where each kind of object puts the origin and the X axis. +fn object_frame(cur: &UcsFrame, kind: &EntityKind, at: Option) -> Result { + let near = |a: Vec2, b: Vec2| at.is_none_or(|p| p.dist(a) <= p.dist(b)); + match kind { + // The endpoint nearer the pick; X along the line. + EntityKind::Line(l) => { + let (o, other) = if near(l.a.xy(), l.b.xy()) { (l.a, l.b) } else { (l.b, l.a) }; + along(o, other.xy() - o.xy()) + } + // The centre; X through the endpoint nearer the pick. + EntityKind::Arc(a) => { + let (e0, e1) = (Vec2::polar(a.center.xy(), a.radius, a.start), Vec2::polar(a.center.xy(), a.radius, a.end)); + let e = if near(e0, e1) { e0 } else { e1 }; + along(a.center, e - a.center.xy()) + } + // The centre; X through the pick. + EntityKind::Circle(c) => { + let d = at.map(|p| p - c.center.xy()).filter(|d| d.len() > 1e-12).unwrap_or(cur.x.xy()); + along(c.center, d) + } + // The first vertex; X toward the next one. + EntityKind::LwPolyline(p) => { + let first = p.vertices.first().map(|v| v.p).ok_or_else(|| EngineError::Other("That polyline has no vertices.".into()))?; + let next = p.vertices.iter().map(|v| v.p).find(|q| q.dist(first) > 1e-12).ok_or_else(|| EngineError::Other("That polyline has no length.".into()))?; + along(first.to3(p.elevation), next - first) + } + // The point; the X axis stays as it is. + EntityKind::Point(p) => along(p.p, cur.x.xy()), + // The insertion point; X along the object's rotation. + EntityKind::Text(t) => along(t.insert, Vec2::from_angle(t.rotation)), + EntityKind::AttDef(a) => along(a.text.insert, Vec2::from_angle(a.text.rotation)), + EntityKind::Insert(i) => along(i.insert, Vec2::from_angle(i.rotation)), + // The first corner; X toward the second. + EntityKind::Solid(so) | EntityKind::Trace(so) => { + let [a, b, ..] = so.corners; + along(a, b.xy() - a.xy()) + } + // The first corner; X toward the second, Y toward the fourth. + EntityKind::Face3d(f) => { + let [a, b, _, d] = f.corners; + let frame = UcsFrame::new(a, b - a, d - a).ok_or_else(|| EngineError::Other("That face has no area to line the UCS up with.".into()))?; + if frame.is_planar() { + Ok(frame) + } else { + Err(EngineError::Other("That face lies out of the XY plane; a UCS out of it is not available yet.".into())) + } + } + // The middle of the text; the X axis stays as it is. + EntityKind::Dimension(dm) => along(dm.text_mid, cur.x.xy()), + _ => Err(EngineError::Other("The UCS can't be lined up with that kind of object (lines, arcs, circles, polylines, points, text, blocks, 2D solids, 3D faces and dimensions can).".into())), + } +} + +/// A usable UCS name, or why not. +fn check_name(name: &str) -> std::result::Result { + let n = name.trim(); + if n.is_empty() { + return Err("A UCS name is required.".into()); + } + if n.chars().count() > MAX_NAME { + return Err(format!("A UCS name has at most {MAX_NAME} characters.")); + } + if n.contains(BAD_NAME_CHARS) || n.chars().any(char::is_control) { + return Err(format!("\"{n}\" is not a valid UCS name.")); + } + if n.eq_ignore_ascii_case("*WORLD*") || n.eq_ignore_ascii_case("WORLD") { + return Err("\"World\" is the World UCS; save under another name.".into()); + } + Ok(n.to_string()) +} + +fn restore(s: &mut Session, name: &str) -> std::result::Result<(), String> { + let d = s.doc().map_err(|e| e.to_string())?; + let (f, n) = named(d, name).ok_or_else(|| format!("Cannot find UCS \"{}\".", name.trim()))?; + if !f.is_planar() { + // Kept and saved as read, but not current until tilted UCSs are available. + return Err(format!("UCS \"{n}\" is tilted out of the XY plane, which is not available yet.")); + } + s.set_ucs(f, &n).map_err(|e| e.to_string()) +} + +fn exists(d: &Drawing, name: &str) -> bool { + d.ucss.iter().any(|u| u.name.eq_ignore_ascii_case(name)) +} + +/// Save the current UCS as `name` (replacing a UCS of that name only with `replace`); it is then +/// the current UCS's name. +fn save(s: &mut Session, name: &str, replace: bool) -> std::result::Result<(), String> { + let n = check_name(name)?; + let frame = s.ucs(); + let d = s.doc_mut().map_err(|e| e.to_string())?; + match d.ucss.iter_mut().find(|u| u.name.eq_ignore_ascii_case(&n)) { + Some(_) if !replace => return Err(format!("UCS \"{n}\" already exists.")), + Some(u) => *u = frame.record(&u.name.clone()), + None => { + if d.ucss.len() >= MAX_NAMED { + return Err(format!("A drawing keeps at most {MAX_NAMED} named UCSs.")); + } + d.ucss.push(frame.record(&n)); + } + } + let kept = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(&n)).map(|u| u.name.clone()).unwrap_or(n); + s.set_ucs(frame, &kept).map_err(|e| e.to_string()) +} + +/// Whether `name` matches one of the comma-separated wildcard patterns. +fn matches(patterns: &str, name: &str) -> bool { + patterns + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .any(|p| super::qselect::wildcard(&p.to_ascii_uppercase(), &name.to_ascii_uppercase())) +} + +/// Delete the named UCSs matching `patterns`; the current UCS keeps its axes but loses a deleted +/// name. Returns how many went. +fn delete(s: &mut Session, patterns: &str) -> Result { + let gone: Vec = s.doc()?.ucss.iter().filter(|u| matches(patterns, &u.name)).map(|u| u.name.clone()).collect(); + if gone.is_empty() { + return Ok(0); + } + let (frame, current) = s.ucs_named(); + s.doc_mut()?.ucss.retain(|u| !gone.iter().any(|g| g == &u.name)); + if gone.iter().any(|g| g.eq_ignore_ascii_case(¤t)) { + s.set_ucs(frame, "")?; + } + Ok(gone.len()) +} + +/// How the current UCS is named in messages. +fn shown_name(s: &Session) -> String { + let (u, name) = s.ucs_named(); + if !name.is_empty() { + name + } else if u.is_world() { + "*WORLD*".into() + } else { + "*NO NAME*".into() + } +} + +/// `?`: the named UCSs matching `patterns`, their origins and axes relative to the current UCS. +fn list(s: &Session, patterns: &str) -> String { + let Ok(d) = s.doc() else { return String::new() }; + let cur = s.input_ucs(); + let (lu, lp) = (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4)); + let f = |v: f64| crate::units::format_distance(v, lu, lp); + let pt = |v: Vec3| format!("<{},{},{}>", f(v.x), f(v.y), f(v.z)); + let axis = |o: Vec3, a: Vec3| cur.to_ucs3(o + a) - cur.to_ucs3(o); + let mut out = format!("Current ucs name: {}\nSaved coordinate systems:", shown_name(s)); + let mut any = false; + for u in d.ucss.iter().filter(|u| matches(patterns, &u.name)) { + any = true; + let Some(fr) = UcsFrame::of(u) else { continue }; + out.push_str(&format!( + "\n\n{}\n Origin = {}, X Axis = {}\n Y Axis = {}, Z Axis = {}", + u.name, + pt(cur.to_ucs3(fr.origin)), + pt(axis(fr.origin, fr.x)), + pt(axis(fr.origin, fr.y)), + pt(axis(fr.origin, fr.z())) + )); + } + if !any { + out.push_str("\n\n(none)"); + } + out +} + +/// Where the interactive UCS is. +#[derive(Clone, Debug, Default, PartialEq)] +enum Stage { + #[default] + Main, + /// Tools > New UCS > Origin: only the origin. + OriginOnly, + /// Tools > New UCS > 3 Point: the origin first, then the axes. + ThreePoint, + XPoint(Vec3), + XyPoint(Vec3, Vec3), + Named, + Restore, + Save, + Replace(String), + Delete, + List, + Object, + ZAngle, +} + +#[derive(Default)] +struct UcsM { + stage: Stage, +} + +impl UcsM { + fn starting(stage: Stage) -> Self { + UcsM { stage } + } +} + +fn other(msg: impl Into) -> EngineError { + EngineError::Other(msg.into()) +} + +impl Interactive for UcsM { + fn name(&self) -> &'static str { + "UCS" + } + fn begin(&mut self, s: &mut Session) -> Result { + s.echo(format!("Current ucs name: {}", shown_name(s))); + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + match &self.stage { + Stage::Main => Prompt::new("Specify origin of UCS", Accept::POINT).kw(OPTIONS).default("World"), + Stage::OriginOnly | Stage::ThreePoint => { + let o = s.ucs().origin; + Prompt::new("Specify new origin point", Accept::POINT).default(format!("{},{},{}", o.x, o.y, o.z)) + } + Stage::XPoint(o) => Prompt::new("Specify point on X-axis", Accept::POINT).default("Accept").base(o.xy()), + Stage::XyPoint(o, _) => Prompt::new("Specify point on the XY plane", Accept::POINT).default("Accept").base(o.xy()), + Stage::Named => Prompt::new("Enter an option", Accept::TEXT).kw(&["Restore", "Save", "Delete", "?"]), + Stage::Restore => Prompt::new("Enter name of UCS to restore", Accept::TEXT).kw(&["?"]), + Stage::Save => Prompt::new("Enter name to save current UCS", Accept::TEXT).kw(&["?"]), + Stage::Replace(n) => Prompt::new(format!("UCS \"{n}\" already exists. Replace it?"), Accept::TEXT).kw(&["Yes", "No"]).default("No"), + Stage::Delete => Prompt::new("Enter UCS name(s) to delete", Accept::TEXT).default("none"), + Stage::List => Prompt::new("Enter UCS name(s) to list", Accept::TEXT).default("*"), + Stage::Object => Prompt::new("Select object to align UCS", Accept::POINT), + Stage::ZAngle => Prompt::new("Specify rotation angle about Z axis", Accept::NUMBER).default(format!("{}", axis_angle(s))), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if i == Input::Cancel { + return Ok(Step::Cancel); + } + match (self.stage.clone(), i) { + (Stage::Main, Input::Enter) => { + s.set_ucs(UcsFrame::WORLD, "")?; + Ok(Step::Done) + } + (Stage::Main, Input::Keyword(k)) => match k.as_str() { + "World" => { + s.set_ucs(UcsFrame::WORLD, "")?; + Ok(Step::Done) + } + "Previous" => { + if !s.ucs_previous()? { + s.echo("There is no previous UCS."); + } + Ok(Step::Done) + } + "View" => { + let f = view_ucs(s); + s.set_ucs(f, "")?; + Ok(Step::Done) + } + "NAmed" => { + self.stage = Stage::Named; + Ok(Step::Continue) + } + "OBject" => { + self.stage = Stage::Object; + Ok(Step::Continue) + } + "Z" => { + self.stage = Stage::ZAngle; + Ok(Step::Continue) + } + "X" | "Y" | "ZAxis" | "Face" => { + s.echo(tilted_message(&k.to_ascii_lowercase())); + Ok(Step::Continue) + } + _ => Ok(Step::Continue), + }, + (Stage::Main | Stage::ThreePoint, Input::Point(p)) => { + self.stage = Stage::XPoint(on_plane(s, p)); + Ok(Step::Continue) + } + (Stage::OriginOnly, Input::Point(p)) => { + let f = s.ucs().with_origin(on_plane(s, p)); + s.set_ucs(f, "")?; + Ok(Step::Done) + } + (Stage::OriginOnly | Stage::ThreePoint, Input::Enter) => Ok(Step::Done), + (Stage::XPoint(o), Input::Enter) => { + set_by_points(s, o, None, None)?; + Ok(Step::Done) + } + (Stage::XPoint(o), Input::Point(p)) => { + let x = on_plane(s, p); + if x.xy().dist(o.xy()) <= 1e-12 { + return Err(other("The point on the X axis must differ from the origin.")); + } + self.stage = Stage::XyPoint(o, x); + Ok(Step::Continue) + } + (Stage::XyPoint(o, x), Input::Enter) => { + set_by_points(s, o, Some(x), None)?; + Ok(Step::Done) + } + (Stage::XyPoint(o, x), Input::Point(p)) => { + set_by_points(s, o, Some(x), Some(on_plane(s, p)))?; + Ok(Step::Done) + } + (Stage::Named, Input::Keyword(k)) => { + self.stage = match k.as_str() { + "Restore" => Stage::Restore, + "Save" => Stage::Save, + "Delete" => Stage::Delete, + _ => Stage::List, + }; + Ok(Step::Continue) + } + (Stage::Named, Input::Enter) => Ok(Step::Done), + (Stage::Restore | Stage::Save, Input::Keyword(_)) => { + let l = list(s, "*"); + s.echo(l); + Ok(Step::Continue) + } + (Stage::Restore, Input::Text(t)) => { + restore(s, &t).map_err(other)?; + Ok(Step::Done) + } + (Stage::Save, Input::Text(t)) => { + let n = check_name(&t).map_err(other)?; + if s.doc().is_ok_and(|d| exists(d, &n)) { + self.stage = Stage::Replace(n); + return Ok(Step::Continue); + } + save(s, &n, false).map_err(other)?; + Ok(Step::Done) + } + (Stage::Replace(n), Input::Keyword(k)) => { + if k == "Yes" { + save(s, &n, true).map_err(other)?; + } + Ok(Step::Done) + } + (Stage::Replace(_), Input::Enter) | (Stage::Restore | Stage::Save | Stage::Delete, Input::Enter) => Ok(Step::Done), + (Stage::Delete, Input::Text(t)) => { + let n = delete(s, &t)?; + s.echo(format!("{n} UCS name(s) deleted.")); + Ok(Step::Done) + } + (Stage::List, Input::Enter) => { + let l = list(s, "*"); + s.echo(l); + Ok(Step::Done) + } + (Stage::List, Input::Text(t)) => { + let l = list(s, &t); + s.echo(l); + Ok(Step::Done) + } + (Stage::Object, Input::Point(p)) => { + let h = super::curves::pick_at(s, p).ok_or_else(|| other("No object found there; select an object."))?; + set_by_object(s, h, Some(p))?; + Ok(Step::Done) + } + (Stage::Object, Input::Enter) => Ok(Step::Done), + (Stage::ZAngle, Input::Enter) => { + let a = axis_angle(s).to_radians(); + rotate_z(s, a)?; + Ok(Step::Done) + } + (Stage::ZAngle, Input::Text(t)) => { + let a = s.angle_settings().amount(&t).filter(|a| a.is_finite()).ok_or_else(|| other("Requires a valid angle."))?; + rotate_z(s, a)?; + Ok(Step::Done) + } + (Stage::Main, Input::Text(_)) => Err(other("Requires a point or an option keyword.")), + _ => Err(other("Invalid input.")), + } + } +} + +fn set_ucsicon(s: &mut Session, on: Option, origin: Option) -> Result { + let mut bits = s.ucsicon_bits(); + if let Some(on) = on { + bits = if on { bits | 1 } else { bits & !1 }; + } + if let Some(o) = origin { + bits = if o { bits | 2 } else { bits & !2 }; + } + s.doc_mut()?.header.set_i64("UCSICON", bits); + Ok(json!({ "on": bits & 1 != 0, "origin": bits & 2 != 0 })) +} + +fn run_ucsicon(s: &mut Session, p: &Value) -> Result { + let flag = |k: &str| -> Result> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(v) => Err(bad("ucsicon", format!("`{k}` must be true or false, got {v}"))), + } + }; + let (on, origin) = (flag("on")?, flag("origin")?); + set_ucsicon(s, on, origin) +} + +struct UcsIconM; + +impl Interactive for UcsIconM { + fn name(&self) -> &'static str { + "UCSICON" + } + fn prompt(&self, s: &Session) -> Prompt { + let on = s.ucsicon_bits() & 1 != 0; + Prompt::new("Enter an option", Accept::TEXT).kw(&["ON", "OFF", "All", "Noorigin", "ORigin", "Selectable", "Properties"]).default(if on { + "ON" + } else { + "OFF" + }) + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match i { + Input::Keyword(k) => { + match k.as_str() { + "ON" => set_ucsicon(s, Some(true), None).map(|_| ())?, + "OFF" => set_ucsicon(s, Some(false), None).map(|_| ())?, + "Noorigin" => set_ucsicon(s, None, Some(false)).map(|_| ())?, + "ORigin" => set_ucsicon(s, None, Some(true)).map(|_| ())?, + other => { + s.echo(format!("UCSICON {other} is not available yet.")); + return Ok(Step::Continue); + } + } + Ok(Step::Done) + } + Input::Enter | Input::Cancel => Ok(Step::Done), + _ => Err(other("Requires an option keyword.")), + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 97f4b969b..7ec0ef1d9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,6 +27,7 @@ pub mod select; pub mod snap; pub mod spatial; pub mod sysvars; +pub mod ucs; pub mod undoctl; pub mod units; @@ -142,6 +143,11 @@ pub struct DocState { /// The Block Editor (BEDIT), when it is open: `doc` is then the editor's drawing, and the /// drawing itself waits in it ([`DocState::drawing`]). pub block_edit: Option, + /// Earlier UCSs for UCS Previous, oldest first, with the space each was current in (at most + /// [`ucs::MAX_PREVIOUS`] per space; not saved with the drawing). + pub ucs_previous: Vec<(Space, ucs::UcsFrame, String)>, + /// The user was told that the current UCS is tilted ([`Session::note_tilted_ucs`]). + pub ucs_tilted_noted: bool, } static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -168,6 +174,8 @@ impl DocState { uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), binary_dxf: false, block_edit: None, + ucs_previous: Vec::new(), + ucs_tilted_noted: false, } } /// The drawing has changes not saved to its file, or the Block Editor has changes not yet @@ -1516,7 +1524,8 @@ impl Session { lisp::value::Value::Real(r) => self.typed(&format!("{r}")), lisp::value::Value::Str(s) => self.typed(&s), other => match other.as_point() { - Some(p) => self.input(Input::Point(Vec2::new(p[0], p[1]))), + // A point from LISP is in the current UCS, as typed coordinates are. + Some(p) => self.input(Input::Point(self.input_ucs().to_wcs(Vec2::new(p[0], p[1])))), None => { self.echo(format!("Invalid input: {}", lisp::value::to_text(&other, true))); Ok(()) @@ -1537,7 +1546,8 @@ impl Session { return self.input(Input::Keyword(k)); } if prompt.accept.point { - if let Some(p) = prompt::parse_point_with(tt, self.last_point, &self.angle_settings()) { + self.note_tilted_ucs(); + if let Some(p) = self.parse_typed_point(tt, self.last_point) { self.last_polar = prompt::parse_polar_text(tt, &self.angle_settings()); return self.input(Input::Point(p)); } diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 689221810..af793b029 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -111,7 +111,9 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec) -> Result { Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))), Value::Cons(_) => { if let Some(p) = arg.as_point() { - feed(ctx.s, Input::Point(Vec2::new(p[0], p[1]))); + // A routine's points are in the current UCS, as typed ones are. + let w = ctx.s.input_ucs().to_wcs(Vec2::new(p[0], p[1])); + feed(ctx.s, Input::Point(w)); } else if let Value::Ename(h) = arg.car() { // An `entsel` result: (ename point). feed(ctx.s, Input::Pick(vec![h])); @@ -940,11 +942,62 @@ pub fn angtof(ctx: &mut Ctx<'_>, a: Vec) -> Result { Ok(Flow::Value(ctx.s.angle_settings().direction(&s).map(Value::Real).unwrap_or_default())) } -/// `(trans pt from to [disp])`: points are in the world system throughout (no UCS yet). -pub fn trans(_ctx: &mut Ctx<'_>, a: Vec) -> Result { +/// A coordinate system `trans` converts from or to: its origin and axes in world coordinates. +fn trans_system(ctx: &Ctx<'_>, v: &Value) -> Result { + use crate::ucs::UcsFrame; + match v { + // 0 the WCS; 1 the current UCS; 2 the display system and 3 paper space's, which in a plan + // view without a twist line up with the WCS. + Value::Int(0 | 2 | 3) => Ok(UcsFrame::WORLD), + Value::Int(1) => Ok(ctx.s.input_ucs()), + // An object: its OCS. + Value::Ename(h) => { + let d = ctx.s.doc().map_err(|e| LispError::new(e.to_string()))?; + let e = d.entity(*h).ok_or_else(|| LispError::bad_arg("lentityp", v))?; + ocs(e.common.extrusion).ok_or_else(|| LispError::bad_arg("lentityp", v)) + } + // An extrusion direction: the OCS of objects with it. + Value::Cons(_) => { + let n = v.as_point().ok_or_else(|| LispError::bad_arg("coordinate system", v))?; + ocs(cadcraft_geom::Vec3::new(n[0], n[1], n[2])).ok_or_else(|| LispError::bad_arg("coordinate system", v)) + } + other => Err(LispError::bad_arg("coordinate system", other)), + } +} + +/// The object coordinate system of extrusion direction `n` (the arbitrary axis algorithm of the +/// DXF Reference): `None` for a direction with no length. +fn ocs(n: cadcraft_geom::Vec3) -> Option { + use cadcraft_geom::Vec3; + let l = n.len(); + if !(l > 1e-12 && l.is_finite()) { + return None; + } + let n = n * (1.0 / l); + let w = if n.x.abs() < 1.0 / 64.0 && n.y.abs() < 1.0 / 64.0 { Vec3::new(0.0, 1.0, 0.0) } else { Vec3::Z }; + let ax = w.cross(n); + crate::ucs::UcsFrame::new(Vec3::ZERO, ax, n.cross(ax)) +} + +/// `(trans pt from to [disp])`: `pt` from coordinate system `from` to `to` (0 WCS, 1 UCS, 2 and 3 +/// display, an entity name for its OCS, or an extrusion direction); with `disp` non-nil `pt` is a +/// displacement, which the systems' origins don't move. +pub fn trans(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 3, 4)?; let p = a[0].as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &a[0]))?; - Ok(Flow::Value(Value::point(&p))) + let (from, to) = (trans_system(ctx, &a[1])?, trans_system(ctx, &a[2])?); + let disp = a.get(3).is_some_and(|v| !v.is_nil()); + let p = cadcraft_geom::Vec3::new(p[0], p[1], p[2]); + let q = if disp { + let w = from.x * p.x + from.y * p.y + from.z() * p.z; + cadcraft_geom::Vec3::new(w.dot(to.x), w.dot(to.y), w.dot(to.z())) + } else { + to.to_ucs3(from.to_wcs3(p)) + }; + if !q.is_finite() { + return Err(LispError::bad_arg("2D/3D point", &a[0])); + } + Ok(Flow::Value(Value::point(&[q.x, q.y, q.z]))) } /// What `(load name)` reads: a file loaded through APPLOAD (the web), or one on disk, with diff --git a/crates/engine/src/lisp/input.rs b/crates/engine/src/lisp/input.rs index fca32e5b8..330c9be90 100644 --- a/crates/engine/src/lisp/input.rs +++ b/crates/engine/src/lisp/input.rs @@ -49,8 +49,8 @@ pub struct GetRequest { } impl GetRequest { - /// The prompt the command line shows. - pub fn prompt(&self) -> Prompt { + /// The prompt the command line shows (`ucs`: the UCS the routine's points are in). + pub fn prompt(&self, ucs: &crate::ucs::UcsFrame) -> Prompt { let any = self.initget.bits & 128 != 0 || !self.initget.keywords.is_empty(); let accept = match self.kind { GetKind::Point | GetKind::Corner | GetKind::EntSel => Accept { text: any, ..Accept::POINT }, @@ -63,7 +63,7 @@ impl GetRequest { (None, true) => default_message(self.kind).to_string(), (None, false) => self.message.clone(), }; - let base = self.first.or(self.base).map(|p| Vec2::new(p[0], p[1])); + let base = self.first.or(self.base).map(|p| ucs.to_wcs(Vec2::new(p[0], p[1]))); let mut p = Prompt::new(message, accept).base_opt(base); p.keywords = self.initget.keywords.clone(); p.raw = true; @@ -100,11 +100,21 @@ impl GetRequest { Ok(Value::Nil) } Input::Keyword(k) => Ok(Value::str(&k)), - Input::Point(p) => self.point(s, [p.x, p.y, 0.0]), + // Points come back in the current UCS, on its XY plane. + Input::Point(p) => { + let u = s.ucs_point(p); + self.point(s, [u.x, u.y, 0.0]) + } // A deferred tangent/perpendicular snap is the point it was picked at here. - Input::Deferred(d) => self.point(s, [d.at.x, d.at.y, 0.0]), + Input::Deferred(d) => { + let u = s.ucs_point(d.at); + self.point(s, [u.x, u.y, 0.0]) + } Input::Pick(hs) => match (self.kind, hs.first()) { - (GetKind::EntSel, Some(h)) => Ok(Value::list(vec![Value::Ename(*h), Value::point(&[s.last_point.x, s.last_point.y, 0.0])])), + (GetKind::EntSel, Some(h)) => { + let u = s.ucs_point(s.last_point); + Ok(Value::list(vec![Value::Ename(*h), Value::point(&[u.x, u.y, 0.0])])) + } _ => Err("Invalid point.".into()), }, Input::Text(t) => self.text(s, &t), @@ -135,7 +145,8 @@ impl GetRequest { let ap = s.settings.pickbox.max(1.0) * s.pixel_size(); let space = s.state().map(|st| st.edit_space()).map_err(|e| Again::Msg(e.to_string()))?; let d = s.doc().map_err(|e| Again::Msg(e.to_string()))?; - match crate::select::pick(d, &space, Vec2::new(p[0], p[1]), ap) { + // `p` is in the UCS; objects are picked at the world point. + match crate::select::pick(d, &space, s.input_ucs().to_wcs(Vec2::new(p[0], p[1])), ap) { Some(h) => Ok(Value::list(vec![Value::Ename(h), Value::point(&p)])), None => Err("Missed, try again.".into()), } @@ -180,6 +191,8 @@ impl GetRequest { }, GetKind::Angle { orient } => match s.angle_settings().direction(t) { Some(a) => { + // Measured in the UCS, as an angle from two points is. + let a = a - s.angle_settings().ucs; let a = if orient { a } else { a - s.lisp_angbase() }; self.check_number(a.rem_euclid(std::f64::consts::TAU), false) } diff --git a/crates/engine/src/lisp/mod.rs b/crates/engine/src/lisp/mod.rs index d9fdc9a10..ac42d53cd 100644 --- a/crates/engine/src/lisp/mod.rs +++ b/crates/engine/src/lisp/mod.rs @@ -493,7 +493,7 @@ impl Session { /// A routine waits for the user's answer to a `get…` function: its prompt. pub(crate) fn lisp_prompt(&self) -> Option { match self.lisp.run.as_ref()?.waiting.as_ref()? { - Need::Get(req) => Some(req.prompt()), + Need::Get(req) => Some(req.prompt(&self.input_ucs())), _ => None, } } @@ -611,3 +611,5 @@ fn file_key(name: &str) -> String { #[cfg(test)] mod tests; +#[cfg(test)] +mod ucs_tests; diff --git a/crates/engine/src/lisp/ucs_tests.rs b/crates/engine/src/lisp/ucs_tests.rs new file mode 100644 index 000000000..f03b27a42 --- /dev/null +++ b/crates/engine/src/lisp/ucs_tests.rs @@ -0,0 +1,147 @@ +//! AutoLISP in a UCS (#1106): `getpoint` and friends answer in the current UCS, `command` takes +//! UCS points, `trans` converts between the WCS, the UCS, display coordinates and an object's +//! OCS, and entity lists stay in world coordinates. + +#![allow(clippy::unwrap_used)] + +use cadcraft_geom::Vec2; +use serde_json::json; + +use super::value::to_text; +use crate::Session; +use crate::cmd::file::{EntityCodec, set_entity_codec}; + +fn session() -> Session { + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + let mut s = Session::new(); + s.new_drawing(false); + s +} + +fn ok(s: &mut Session, code: &str) -> String { + match s.lisp_eval(code, false, true, Vec::new()) { + Ok(Some(Ok(v))) => to_text(&v, true), + other => panic!("{code}: {other:?}"), + } +} + +fn err(s: &mut Session, code: &str) -> bool { + matches!(s.lisp_eval(code, false, true, Vec::new()), Ok(Some(Err(_))) | Err(_)) +} + +/// The three numbers of a printed point. +fn pt(text: &str) -> [f64; 3] { + let v: Vec = text.trim_matches(['(', ')']).split_whitespace().map(|x| x.parse().unwrap()).collect(); + [v[0], v[1], v.get(2).copied().unwrap_or(0.0)] +} + +fn close(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +/// The UCS at (100, 50) turned 90° (UCS X is world +Y). +fn turned(s: &mut Session) { + s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap(); + s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap(); +} + +#[test] +fn trans_between_world_ucs_and_display() { + let mut s = session(); + turned(&mut s); + // UCS (10, 0) is world (100, 60). + assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 0)")), [100.0, 60.0, 0.0])); + assert!(close(pt(&ok(&mut s, "(trans '(100 60 0) 0 1)")), [10.0, 0.0, 0.0])); + // A 2D point is at Z 0. + assert!(close(pt(&ok(&mut s, "(trans '(10 0) 1 0)")), [100.0, 60.0, 0.0])); + // Displacements turn but don't move. + assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 0 T)")), [0.0, 10.0, 0.0])); + // The display system lines up with the world one in a plan view. + assert!(close(pt(&ok(&mut s, "(trans '(10 0 0) 1 2)")), [100.0, 60.0, 0.0])); + assert!(close(pt(&ok(&mut s, "(trans '(3 4 5) 2 0)")), [3.0, 4.0, 5.0])); + // UCS → UCS and back is the identity. + assert!(close(pt(&ok(&mut s, "(trans (trans '(7 -3 2) 1 0) 0 1)")), [7.0, -3.0, 2.0])); +} + +#[test] +fn trans_to_and_from_an_objects_ocs() { + let mut s = session(); + // A circle in the world XY plane: its OCS is the WCS. + ok(&mut s, "(command \"_.CIRCLE\" '(5 5) 2)"); + assert!(close(pt(&ok(&mut s, "(trans '(5 5 0) 0 (entlast))")), [5.0, 5.0, 0.0])); + // An extrusion direction straight up is the WCS too; one along +X follows the arbitrary + // axis algorithm (OCS X = world Y × N = (0, 0, -1)... the DXF Reference's rule). + assert!(close(pt(&ok(&mut s, "(trans '(1 2 3) '(0 0 1) 0)")), [1.0, 2.0, 3.0])); + let w = pt(&ok(&mut s, "(trans '(1 0 0) '(1 0 0) 0)")); + assert!(close(w, [0.0, 1.0, 0.0]), "{w:?}"); + let back = pt(&ok(&mut s, "(trans (trans '(1 2 3) '(1 0 0) 0) 0 '(1 0 0))")); + assert!(close(back, [1.0, 2.0, 3.0]), "{back:?}"); + // Bad systems and points are errors, not crashes. + for bad in [ + "(trans '(1 2) 7 0)", + "(trans '(1 2) \"x\" 0)", + "(trans '(1 2) '(0 0 0) 0)", + "(trans \"p\" 0 1)", + "(trans '(1 2) 0)", + "(trans '(1e308 1e308) '(1e-320 0 0) 0)", + ] { + assert!(err(&mut s, bad), "{bad}"); + } +} + +#[test] +fn getpoint_answers_in_the_ucs_and_command_reads_ucs_points() { + let mut s = session(); + turned(&mut s); + s.cmdline("(setq p (getpoint))").unwrap(); + // The user clicks world (100, 60): the routine gets UCS (10, 0). + s.input(crate::Input::Point(Vec2::new(100.0, 60.0))).unwrap(); + assert!(close(pt(&to_text(&s.lisp_var("P"), true)), [10.0, 0.0, 0.0]), "{}", to_text(&s.lisp_var("P"), true)); + // Typed at getpoint: read in the UCS, given back in it. + s.cmdline("(setq q (getpoint))").unwrap(); + s.cmdline("3,4").unwrap(); + assert!(close(pt(&to_text(&s.lisp_var("Q"), true)), [3.0, 4.0, 0.0])); + // `command` takes those points as UCS points: the line lands at the world places clicked. + ok(&mut s, "(command \"_.LINE\" p q \"\")"); + let d = s.doc().unwrap(); + let l = d.model.iter().find_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap(); + assert!(l.a.xy().dist(Vec2::new(100.0, 60.0)) < 1e-9 && l.b.xy().dist(Vec2::new(96.0, 53.0)) < 1e-9, "{l:?}"); + // Entity lists stay in world coordinates. + let g = ok(&mut s, "(cdr (assoc 10 (entget (entlast))))"); + assert!(close(pt(&g), [100.0, 60.0, 0.0]), "{g}"); + // `!expr` at the command line is a UCS point too. + s.cmdline("line").unwrap(); + s.cmdline("!p").unwrap(); + s.cmdline("!q").unwrap(); + s.cmdline("").unwrap(); + let n = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Line(_))).count(); + assert_eq!(n, 2); + let d = s.doc().unwrap(); + let last = d.model.iter().filter_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).last().unwrap(); + assert!(last.a.xy().dist(Vec2::new(100.0, 60.0)) < 1e-9 && last.b.xy().dist(Vec2::new(96.0, 53.0)) < 1e-9, "{last:?}"); +} + +#[test] +fn getangle_and_getdist_measure_in_the_ucs() { + let mut s = session(); + turned(&mut s); + // Two clicks one above the other in the world: along the UCS X axis, angle 0. + s.cmdline("(setq a (getangle))").unwrap(); + s.input(crate::Input::Point(Vec2::new(100.0, 50.0))).unwrap(); + s.input(crate::Input::Point(Vec2::new(100.0, 70.0))).unwrap(); + let a: f64 = to_text(&s.lisp_var("A"), true).parse().unwrap(); + assert!(a.abs() < 1e-6 || (a - std::f64::consts::TAU).abs() < 1e-6, "{a}"); + // A typed angle is measured in the UCS as well. + s.cmdline("(setq b (getangle))").unwrap(); + s.cmdline("45").unwrap(); + let b: f64 = to_text(&s.lisp_var("B"), true).parse().unwrap(); + assert!((b - std::f64::consts::FRAC_PI_4).abs() < 1e-6, "{b} (printed to 6 places)"); + // Distances don't depend on the UCS. + s.cmdline("(setq d (getdist '(0 0)))").unwrap(); + s.cmdline("3,4").unwrap(); + assert_eq!(to_text(&s.lisp_var("D"), true), "5.0"); + // The UCS variables read from LISP. + assert!(close(pt(&ok(&mut s, "(getvar \"UCSORG\")")), [100.0, 50.0, 0.0])); + assert!(close(pt(&ok(&mut s, "(getvar \"UCSXDIR\")")), [0.0, 1.0, 0.0])); + assert_eq!(ok(&mut s, "(getvar \"WORLDUCS\")"), "0"); +} diff --git a/crates/engine/src/pointmod.rs b/crates/engine/src/pointmod.rs index 74c1ab083..d773baf47 100644 --- a/crates/engine/src/pointmod.rs +++ b/crates/engine/src/pointmod.rs @@ -236,7 +236,7 @@ impl Session { // A distance at "Next point" of TK: straight across or up from the last tracking point, // the way the cursor lies from it. if let Some(Frame::Track { last: Some(l) }) = self.point_mods.last().copied() - && crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_none() + && self.parse_typed_point(t, self.last_point).is_none() && let Some(d) = crate::units::parse_distance(t) { let dir = (crate::snap::ortho(l, self.cursor) - l).normalized(); @@ -245,7 +245,7 @@ impl Session { } if let Some(Frame::Angle { base, dir }) = self.point_mods.last().copied() { // Typed coordinates are explicit: they win over the override. - if crate::prompt::parse_point_with(t, self.last_point, &self.angle_settings()).is_some() { + if self.parse_typed_point(t, self.last_point).is_some() { self.point_mods.pop(); return None; } diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index b5de83286..755cc5841 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -235,10 +235,9 @@ pub struct Drag { } /// Parse a typed point: `x,y[,z]`, `@dx,dy`, `@dist Option { parse_point_with(text, last, &crate::units::AngleSettings::default()) } @@ -246,14 +245,31 @@ pub fn parse_point(text: &str, last: Vec2) -> Option { /// `parse_point` with polar angles read per `angles` (AUNITS, ANGBASE, ANGDIR); `d< Option { + parse_point_in(text, last, angles, &crate::ucs::UcsFrame::WORLD) +} + +/// `parse_point_with` in a UCS: coordinates are UCS coordinates (`x,y` from its origin along its +/// axes, `@dx,dy` along its axes), and polar angles are measured as `angles` says (which carries +/// the UCS rotation, [`crate::units::AngleSettings::ucs`]). A `*` prefix reads the point in +/// world coordinates instead. `last` and the result are world points. +pub fn parse_point_in(text: &str, last: Vec2, angles: &crate::units::AngleSettings, ucs: &crate::ucs::UcsFrame) -> Option { let t = text.trim(); if t.is_empty() { return None; } - let t = t.strip_prefix('*').map_or(t, str::trim_start); + let (mut world, t) = match t.strip_prefix('*') { + Some(r) => (true, r.trim_start()), + None => (false, t), + }; let (rel, body) = if let Some(b) = t.strip_prefix('@') { let b = b.trim(); - (true, b.strip_prefix('*').map_or(b, str::trim_start)) + match b.strip_prefix('*') { + Some(r) => { + world = true; + (true, r.trim_start()) + } + None => (true, b), + } } else if let Some(b) = t.strip_prefix('#') { (false, b.trim()) } else { @@ -262,11 +278,15 @@ pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSett if rel && body.is_empty() { return Some(last); } + let (frame, angles) = if world { (crate::ucs::UcsFrame::WORLD, angles.world()) } else { (*ucs, *angles) }; + // `p`: a world displacement (polar, whose angle already says the UCS's direction), or UCS + // coordinates (`x,y`). let p = if let Some((d, a)) = body.split_once('<') { let dist = crate::units::parse_distance(d)?; // `d< = body.split(',').collect(); if parts.len() < 2 || parts.len() > 3 { @@ -277,10 +297,10 @@ pub fn parse_point_with(text: &str, last: Vec2, angles: &crate::units::AngleSett if let Some(z) = parts.get(2) { crate::units::parse_distance(z)?; } - Vec2::new(x, y) + let v = Vec2::new(x, y); + if rel { last + frame.vec_to_wcs(v) } else { frame.to_wcs(v) } }; - let r = if rel { last + p } else { p }; - r.is_finite().then_some(r) + p.is_finite().then_some(p) } #[cfg(test)] diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 31451b6bc..35ac77268 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -152,6 +152,19 @@ pub fn get(s: &Session, name: &str) -> Option { json!([v.center.x, v.center.y, 0.0]) } "VIEWSIZE" => json!(s.state().ok()?.view().height), + // The current UCS of the space commands act on (paper space has its own per layout), + // set by the UCS command. + "UCSNAME" | "UCSORG" | "UCSXDIR" | "UCSYDIR" | "WORLDUCS" => { + let (u, name) = s.ucs_named(); + let p = |v: cadcraft_geom::Vec3| json!([v.x, v.y, v.z]); + match n.as_str() { + "UCSNAME" => json!(name), + "UCSORG" => p(u.origin), + "UCSXDIR" => p(u.x), + "UCSYDIR" => p(u.y), + _ => json!(i32::from(u.is_world())), + } + } "EXTMIN" | "EXTMAX" => { let d = s.doc().ok()?; let e = d.extents(&s.space()); @@ -196,8 +209,25 @@ fn as_pt(v: &Value) -> Option { } /// Variables `get` reports from session or drawing state that `set` can't change. -const READ_ONLY: &[&str] = - &["CMDNAMES", "DWGNAME", "DBMOD", "BLOCKEDITOR", "CTAB", "LASTPOINT", "VIEWCTR", "VIEWSIZE", "EXTMIN", "EXTMAX", "UNDOCTL", "UNDOMARKS"]; +const READ_ONLY: &[&str] = &[ + "CMDNAMES", + "DWGNAME", + "DBMOD", + "BLOCKEDITOR", + "CTAB", + "LASTPOINT", + "VIEWCTR", + "VIEWSIZE", + "EXTMIN", + "EXTMAX", + "UNDOCTL", + "UNDOMARKS", + "UCSNAME", + "UCSORG", + "UCSXDIR", + "UCSYDIR", + "WORLDUCS", +]; pub fn is_read_only(name: &str) -> bool { READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase()) diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index b1a91b8e1..df668c1a2 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -73,6 +73,9 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("TEXTFILL", Kind::Choice(&[0, 1]), Def::Int(1)), ("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)), + ("UCSAXISANG", Kind::Choice(&[5, 10, 15, 18, 22, 45, 90, 180]), Def::Int(90)), + // 1: the UCS icon is shown; 2: at the UCS origin when that is on screen. + ("UCSICON", Kind::Int(0, 3), Def::Int(3)), ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), ]; diff --git a/crates/engine/src/ucs.rs b/crates/engine/src/ucs.rs new file mode 100644 index 000000000..c23190bed --- /dev/null +++ b/crates/engine/src/ucs.rs @@ -0,0 +1,374 @@ +//! The user coordinate system (UCS): the coordinate system points are typed in, coordinates are +//! shown in and directions are measured in. +//! +//! Model space keeps its current UCS in the drawing header (UCSORG, UCSXDIR, UCSYDIR, UCSNAME, +//! as a DXF file does), each layout its paper-space UCS ([`cadcraft_doc::Layout::ucs`]). The +//! drawing itself stays in world coordinates: a UCS changes how points are read and shown, +//! never the stored geometry, so it costs nothing while drawing or regenerating. +//! +//! CADCraft draws in the world XY plane. A UCS whose XY plane is that plane (any origin, any +//! rotation about Z) is used in full; one tilted out of it is kept and saved as it is, while +//! points are read in the World UCS ([`Session::input_ucs`]). + +use cadcraft_doc::{Drawing, HVal, Space, Ucs}; +use cadcraft_geom::{Vec2, Vec3}; + +use crate::{Result, Session}; + +/// How many earlier UCSs UCS Previous goes back through, in each space. +pub const MAX_PREVIOUS: usize = 10; + +/// How close to the World UCS, or to the world XY plane, counts as on it. +const TOL: f64 = 1e-9; + +/// A coordinate system: its origin and unit X and Y axes, in world coordinates. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UcsFrame { + pub origin: Vec3, + pub x: Vec3, + pub y: Vec3, +} + +impl Default for UcsFrame { + fn default() -> Self { + Self::WORLD + } +} + +impl UcsFrame { + pub const WORLD: UcsFrame = UcsFrame { origin: Vec3::ZERO, x: Vec3::new(1.0, 0.0, 0.0), y: Vec3::new(0.0, 1.0, 0.0) }; + + /// A frame from an origin and X and Y directions: X is normalised and Y made square to it in + /// their plane. `None` for non-finite values or directions with no length or along each other. + pub fn new(origin: Vec3, x: Vec3, y: Vec3) -> Option { + if !(origin.is_finite() && x.is_finite() && y.is_finite()) { + return None; + } + let xl = x.len(); + if !(xl > TOL && xl.is_finite()) { + return None; + } + let x = x * (1.0 / xl); + let yo = y.len(); + if !(yo > TOL && yo.is_finite()) { + return None; + } + // What is left of Y square to X: next to nothing means the two lie along each other. + let y = y - x * x.dot(y); + let yl = y.len(); + if !yl.is_finite() || yl <= 1e-9 * yo { + return None; + } + Some(UcsFrame { origin, x, y: y * (1.0 / yl) }) + } + + /// A UCS table record's frame (`None`: unusable axes). + pub fn of(u: &Ucs) -> Option { + UcsFrame::new(u.origin, u.x_axis, u.y_axis) + } + + /// This frame as a UCS table record named `name`. + pub fn record(&self, name: &str) -> Ucs { + Ucs { name: name.to_string(), origin: self.origin, x_axis: self.x, y_axis: self.y } + } + + pub fn z(&self) -> Vec3 { + self.x.cross(self.y) + } + + /// The World UCS (to within rounding). + pub fn is_world(&self) -> bool { + self.origin.len() <= TOL * (1.0 + self.origin.len()) && self.is_planar() && (self.x - Vec3::new(1.0, 0.0, 0.0)).len() <= TOL + } + + /// Its XY plane is the world XY plane with Z up (any origin height, any rotation about Z). + pub fn is_planar(&self) -> bool { + self.x.z.abs() <= TOL && self.y.z.abs() <= TOL && self.z().z > 0.0 + } + + /// The direction of its X axis in the world XY plane, radians counterclockwise from +X. + pub fn rotation(&self) -> f64 { + self.x.xy().angle() + } + + /// A point of the UCS XY plane, in world coordinates (planar frames; a tilted frame's XY + /// plane seen from above). + pub fn to_wcs(&self, p: Vec2) -> Vec2 { + self.origin.xy() + self.vec_to_wcs(p) + } + + /// A world point in UCS coordinates (planar frames). + pub fn to_ucs(&self, p: Vec2) -> Vec2 { + self.vec_to_ucs(p - self.origin.xy()) + } + + /// A displacement in the UCS XY plane, in world coordinates. + pub fn vec_to_wcs(&self, v: Vec2) -> Vec2 { + self.x.xy() * v.x + self.y.xy() * v.y + } + + /// A world displacement in UCS coordinates. + pub fn vec_to_ucs(&self, v: Vec2) -> Vec2 { + Vec2::new(v.dot(self.x.xy()), v.dot(self.y.xy())) + } + + /// A UCS point in world coordinates, in 3D. + pub fn to_wcs3(&self, p: Vec3) -> Vec3 { + self.origin + self.x * p.x + self.y * p.y + self.z() * p.z + } + + /// A world point in UCS coordinates, in 3D. + pub fn to_ucs3(&self, p: Vec3) -> Vec3 { + let d = p - self.origin; + Vec3::new(d.dot(self.x), d.dot(self.y), d.dot(self.z())) + } + + /// The same axes at another origin. + pub fn with_origin(&self, origin: Vec3) -> UcsFrame { + UcsFrame { origin, ..*self } + } + + /// Turned by `angle` radians about its own Z axis (counterclockwise looking down Z). + pub fn rotated_z(&self, angle: f64) -> UcsFrame { + let (s, c) = angle.sin_cos(); + UcsFrame { origin: self.origin, x: self.x * c + self.y * s, y: self.y * c - self.x * s } + } + + /// UCS from points (world coordinates): a new origin; with a point on the positive X axis, + /// X points at it; with a point on the positive-Y half of the XY plane too, that fixes Y. + /// Without the third point Y stays square to X and to this frame's Z. `None` when the + /// points don't fix an axis (on top of each other, or all three on a line). + pub fn from_points(&self, origin: Vec3, x_point: Option, xy_point: Option) -> Option { + let Some(xp) = x_point else { return origin.is_finite().then(|| self.with_origin(origin)) }; + let x = xp - origin; + match xy_point { + Some(yp) => UcsFrame::new(origin, x, yp - origin), + None => { + let xl = x.len(); + if !(xl > TOL && xl.is_finite()) { + return None; + } + let y = self.z().cross(x * (1.0 / xl)); + UcsFrame::new(origin, x, y) + } + } + } +} + +/// The current UCS of `space` in `d` and its name (empty when it isn't a named UCS). A missing +/// or unusable one is the World UCS. +pub fn current(d: &Drawing, space: &Space) -> (UcsFrame, String) { + match space { + Space::Model => { + let h = &d.header; + let frame = match (h.point("UCSORG"), h.point("UCSXDIR"), h.point("UCSYDIR")) { + (Some(o), Some(x), Some(y)) => UcsFrame::new(o, x, y), + (o, None, None) => o.filter(|o| o.is_finite()).map(|o| UcsFrame::WORLD.with_origin(o)), + _ => None, + }; + match frame { + Some(f) => (f, h.str("UCSNAME", "").trim().to_string()), + None => (UcsFrame::WORLD, String::new()), + } + } + Space::Paper(name) => match d.layout(name).and_then(|l| l.ucs.as_ref()).and_then(|u| Some((UcsFrame::of(u)?, u.name.trim().to_string()))) { + Some(x) => x, + None => (UcsFrame::WORLD, String::new()), + }, + } +} + +/// Make `frame` (named `name`, empty for an unnamed one) the current UCS of `space`. +pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str) { + match space { + Space::Model => { + let h = &mut d.header; + h.set("UCSORG", HVal::Point(frame.origin)); + h.set("UCSXDIR", HVal::Point(frame.x)); + h.set("UCSYDIR", HVal::Point(frame.y)); + h.set_str("UCSNAME", name); + } + Space::Paper(layout) => { + if let Some(l) = d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)) { + l.ucs = (!(frame.is_world() && name.is_empty())).then(|| frame.record(name)); + } + } + } +} + +/// The named UCS `name` of the drawing's UCS table, if it has one with usable axes. +pub fn named(d: &Drawing, name: &str) -> Option<(UcsFrame, String)> { + let u = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name.trim()))?; + Some((UcsFrame::of(u)?, u.name.clone())) +} + +impl Session { + /// The current UCS of the space commands act on, and its name. + pub fn ucs_named(&self) -> (UcsFrame, String) { + self.doc().map(|d| current(d, &self.space())).unwrap_or_default() + } + + /// The current UCS of the space commands act on. + pub fn ucs(&self) -> UcsFrame { + self.ucs_named().0 + } + + /// The UCS points are typed in and shown in: the current one, or the World UCS while the + /// current one is tilted out of the XY plane (CADCraft draws in that plane). + pub fn input_ucs(&self) -> UcsFrame { + let u = self.ucs(); + if u.is_planar() { u } else { UcsFrame::WORLD } + } + + /// A typed point as the user means it: in the current UCS (`*` for world coordinates), with + /// the drawing's angle settings; relative forms from `last`. A world point. + pub fn parse_typed_point(&self, text: &str, last: Vec2) -> Option { + crate::prompt::parse_point_in(text, last, &self.angle_settings(), &self.input_ucs()) + } + + /// A world point in the coordinates shown to the user (the current UCS). + pub fn ucs_point(&self, p: Vec2) -> Vec2 { + self.input_ucs().to_ucs(p) + } + + /// A world direction (radians from world +X) measured from the current UCS X axis. + pub fn ucs_angle(&self, a: f64) -> f64 { + cadcraft_geom::norm_angle(a - self.input_ucs().rotation()) + } + + /// Make `frame` the current UCS (named `name`; empty for an unnamed one), remembering the one + /// it replaces for UCS Previous. Part of the running command's undo step. + pub fn set_ucs(&mut self, frame: UcsFrame, name: &str) -> Result<()> { + let space = self.space(); + let (old, old_name) = self.ucs_named(); + if old == frame && old_name.eq_ignore_ascii_case(name) { + return Ok(()); + } + set_current(self.doc_mut()?, &space, &frame, name); + let st = self.state_mut()?; + st.ucs_previous.push((space.clone(), old, old_name)); + // At most MAX_PREVIOUS per space: drop that space's oldest. + if st.ucs_previous.iter().filter(|(s, _, _)| *s == space).count() > MAX_PREVIOUS + && let Some(i) = st.ucs_previous.iter().position(|(s, _, _)| *s == space) + { + st.ucs_previous.remove(i); + } + Ok(()) + } + + /// Go back to the UCS before the current one in this space; `false` when there is none. + pub fn ucs_previous(&mut self) -> Result { + let space = self.space(); + let st = self.state_mut()?; + let Some(i) = st.ucs_previous.iter().rposition(|(s, _, _)| *s == space) else { return Ok(false) }; + let (_, frame, name) = st.ucs_previous.remove(i); + set_current(self.doc_mut()?, &space, &frame, &name); + Ok(true) + } + + /// UCSICON: 1 the icon is shown, 2 at the UCS origin (when that is on screen). + pub fn ucsicon_bits(&self) -> i64 { + self.doc().map(|d| d.header.i64("UCSICON", 3)).unwrap_or(3).clamp(0, 3) + } + + /// Tell the user once per drawing that its current UCS is tilted and points are read in the + /// World UCS for now. + pub(crate) fn note_tilted_ucs(&mut self) { + if self.ucs().is_planar() { + return; + } + let Ok(st) = self.state_mut() else { return }; + if std::mem::replace(&mut st.ucs_tilted_noted, true) { + return; + } + self.echo("The current UCS is tilted out of the XY plane; points are read and shown in the World UCS for now."); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn near(a: Vec2, b: Vec2) -> bool { + a.dist(b) < 1e-9 + } + + #[test] + fn world_is_the_identity() { + let w = UcsFrame::WORLD; + assert!(w.is_world() && w.is_planar()); + assert_eq!(w.rotation(), 0.0); + let p = Vec2::new(3.5, -2.25); + assert_eq!(w.to_wcs(p), p); + assert_eq!(w.to_ucs(p), p); + } + + #[test] + fn a_rotated_moved_frame_maps_both_ways() { + let f = UcsFrame::WORLD.with_origin(Vec3::new(100.0, 50.0, 0.0)).rotated_z(30f64.to_radians()); + assert!(f.is_planar() && !f.is_world()); + assert!((f.rotation() - 30f64.to_radians()).abs() < 1e-12); + // The UCS X axis one unit out is 30° from world +X. + assert!(near(f.to_wcs(Vec2::new(1.0, 0.0)), Vec2::new(100.0 + 30f64.to_radians().cos(), 50.0 + 30f64.to_radians().sin()))); + for p in [Vec2::new(0.0, 0.0), Vec2::new(12.0, -7.0), Vec2::new(-1e6, 3e5)] { + assert!(near(f.to_ucs(f.to_wcs(p)), p), "{p:?}"); + let q = Vec3::new(p.x, p.y, 4.0); + assert!((f.to_ucs3(f.to_wcs3(q)) - q).len() < 1e-9); + } + assert!(near(f.vec_to_ucs(f.vec_to_wcs(Vec2::new(2.0, 3.0))), Vec2::new(2.0, 3.0))); + } + + #[test] + fn new_squares_and_rejects() { + let f = UcsFrame::new(Vec3::ZERO, Vec3::new(2.0, 0.0, 0.0), Vec3::new(1.0, 5.0, 0.0)).unwrap(); + assert_eq!((f.x, f.y), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0))); + assert!(UcsFrame::new(Vec3::ZERO, Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0)).is_none()); + assert!(UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 0.0)).is_none()); + assert!(UcsFrame::new(Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)).is_none()); + assert!(UcsFrame::new(Vec3::ZERO, Vec3::new(f64::INFINITY, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)).is_none()); + } + + #[test] + fn tilted_and_flipped_frames_are_not_planar() { + let front = UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0)).unwrap(); + assert!(!front.is_planar()); + let bottom = UcsFrame::new(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, -1.0, 0.0)).unwrap(); + assert!(!bottom.is_planar(), "Z down"); + let raised = UcsFrame::WORLD.with_origin(Vec3::new(0.0, 0.0, 25.0)); + assert!(raised.is_planar() && !raised.is_world()); + } + + #[test] + fn from_points() { + let w = UcsFrame::WORLD; + let o = Vec3::new(10.0, 10.0, 0.0); + assert_eq!(w.from_points(o, None, None), Some(w.with_origin(o))); + let f = w.from_points(o, Some(Vec3::new(10.0, 20.0, 0.0)), None).unwrap(); + assert!((f.rotation() - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && f.is_planar()); + // A third point on the negative-Y side of the X axis turns the UCS over. + let g = w.from_points(o, Some(Vec3::new(20.0, 10.0, 0.0)), Some(Vec3::new(15.0, 0.0, 0.0))).unwrap(); + assert!(!g.is_planar()); + assert!(w.from_points(o, Some(o), None).is_none()); + assert!(w.from_points(o, Some(Vec3::new(20.0, 10.0, 0.0)), Some(Vec3::new(30.0, 10.0, 0.0))).is_none()); + } + + #[test] + fn stored_per_space() { + let mut d = Drawing::default(); + let paper = Space::Paper(d.layouts[0].name.clone()); + let f = UcsFrame::WORLD.with_origin(Vec3::new(5.0, 5.0, 0.0)).rotated_z(0.5); + set_current(&mut d, &Space::Model, &f, "SITE"); + let (m, n) = current(&d, &Space::Model); + assert!((m.origin - f.origin).len() < 1e-12 && (m.x - f.x).len() < 1e-12 && n == "SITE"); + assert_eq!(current(&d, &paper).0, UcsFrame::WORLD, "paper space has its own"); + set_current(&mut d, &paper, &f, ""); + assert!(d.layouts[0].ucs.is_some()); + set_current(&mut d, &paper, &UcsFrame::WORLD, ""); + assert!(d.layouts[0].ucs.is_none()); + // Broken header values are the World UCS. + d.header.set("UCSXDIR", HVal::Point(Vec3::ZERO)); + assert_eq!(current(&d, &Space::Model).0, UcsFrame::WORLD); + d.header.set("UCSXDIR", HVal::Point(Vec3::new(f64::NAN, 0.0, 0.0))); + assert_eq!(current(&d, &Space::Model).0, UcsFrame::WORLD); + } +} diff --git a/crates/engine/src/units.rs b/crates/engine/src/units.rs index dd15111c3..74a5649fa 100644 --- a/crates/engine/src/units.rs +++ b/crates/engine/src/units.rs @@ -161,11 +161,20 @@ pub struct AngleSettings { pub angbase: f64, /// ANGDIR 1: positive angles turn clockwise. pub clockwise: bool, + /// The current UCS's X axis, radians counterclockwise from world +X: directions are measured + /// in the UCS (ANGBASE from its X axis, the overrides and bearings too). Sizes of angles + /// ([`AngleSettings::amount`], [`AngleSettings::rotation`]) don't depend on it. + pub ucs: f64, } impl AngleSettings { pub fn from_header(h: &cadcraft_doc::Header) -> Self { - AngleSettings { aunits: h.i64("AUNITS", 0), angbase: h.f64("ANGBASE", 0.0), clockwise: h.i64("ANGDIR", 0) != 0 } + AngleSettings { aunits: h.i64("AUNITS", 0), angbase: h.f64("ANGBASE", 0.0), clockwise: h.i64("ANGDIR", 0) != 0, ucs: 0.0 } + } + + /// The same settings with directions measured in the World UCS (`*` coordinates). + pub fn world(&self) -> Self { + AngleSettings { ucs: 0.0, ..*self } } /// A typed angle size in radians (included angles, sweeps, angles from an axis): a bare @@ -184,18 +193,18 @@ impl AngleSettings { /// +X counterclockwise whatever ANGBASE and ANGDIR say: `< Option { let t = s.trim(); + let ucs = |a: f64| Some(a + self.ucs).filter(|v| v.is_finite()); if let Some(r) = t.strip_prefix("<<<") { - return parse_units(r, self.aunits).map(|(a, _)| a); + return parse_units(r, self.aunits).and_then(|(a, _)| ucs(a)); } if let Some(r) = t.strip_prefix("<<") { - return parse_units(r, 0).map(|(a, _)| a); + return parse_units(r, 0).and_then(|(a, _)| ucs(a)); } let (a, absolute) = parse_units(t, self.aunits)?; if absolute { - return Some(a); + return ucs(a); } - let v = self.angbase + if self.clockwise { -a } else { a }; - v.is_finite().then_some(v) + ucs(self.angbase + if self.clockwise { -a } else { a }) } } @@ -274,9 +283,12 @@ fn parse_dms(t: &str) -> Option { } impl crate::Session { - /// How typed angles are read in the current drawing (the defaults without one). + /// How typed angles are read in the current drawing (the defaults without one): directions + /// are measured in the current UCS. pub fn angle_settings(&self) -> AngleSettings { - self.doc().map(|d| AngleSettings::from_header(&d.header)).unwrap_or_default() + let a = self.doc().map(|d| AngleSettings::from_header(&d.header)).unwrap_or_default(); + let ucs = self.input_ucs().rotation(); + AngleSettings { ucs: if ucs.is_finite() { ucs } else { 0.0 }, ..a } } } diff --git a/crates/engine/tests/angle_settings.rs b/crates/engine/tests/angle_settings.rs index 59591df86..0bb7ac142 100644 --- a/crates/engine/tests/angle_settings.rs +++ b/crates/engine/tests/angle_settings.rs @@ -91,7 +91,7 @@ fn json_and_default_parsing_keep_degrees_from_east() { // SETVAR reports ANGBASE in degrees. let v = cadcraft_engine::sysvars::get(&s, "ANGBASE").unwrap(); assert!((v.as_f64().unwrap() - 90.0).abs() < 1e-9, "{v}"); - let a = AngleSettings { aunits: 0, angbase: 0.0, clockwise: false }; + let a = AngleSettings { aunits: 0, angbase: 0.0, clockwise: false, ucs: 0.0 }; assert_eq!(a.direction(""), None); assert_eq!(a.direction("nan"), None); assert_eq!(a.direction("1e400"), None); diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs new file mode 100644 index 000000000..37baaa9ec --- /dev/null +++ b/crates/engine/tests/ucs.rs @@ -0,0 +1,494 @@ +//! The user coordinate system (#1106): the UCS command and its options, typed coordinates and +//! directions read in the current UCS, coordinates shown in it, the UCS system variables, +//! UCSICON, paper space's own UCS, undo, and hostile input. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, HVal, Space}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::ucs::UcsFrame; +use serde_json::{Value, json}; + +const TAU: f64 = std::f64::consts::TAU; + +fn session() -> Session { + let mut s = Session::new(); + s.new_drawing(false); + s +} + +fn typed(s: &mut Session, lines: &[&str]) { + for l in lines { + s.cmdline(l).unwrap(); + } +} + +fn near(a: Vec2, x: f64, y: f64) -> bool { + a.dist(Vec2::new(x, y)) < 1e-9 +} + +fn near3(a: Vec3, b: Vec3) -> bool { + (a - b).len() < 1e-9 +} + +fn ang_eq(a: f64, b: f64) -> bool { + let d = (a - b).rem_euclid(TAU); + d < 1e-9 || TAU - d < 1e-9 +} + +fn lines(s: &Session) -> Vec<(Vec2, Vec2)> { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }).collect() +} + +fn last_line(s: &Session) -> (Vec2, Vec2) { + *lines(s).last().expect("a line") +} + +fn logged(s: &Session, text: &str) -> bool { + s.log.iter().any(|l| l.contains(text)) +} + +fn var(s: &Session, name: &str) -> Value { + cadcraft_engine::sysvars::get(s, name).unwrap_or(Value::Null) +} + +fn vec3(v: &Value) -> Vec3 { + Vec3::new(v[0].as_f64().unwrap(), v[1].as_f64().unwrap(), v[2].as_f64().unwrap()) +} + +/// A UCS at (100, 50) turned 90°: UCS X is world +Y, UCS Y is world -X. +fn turned(s: &mut Session) { + s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap(); + s.execute("ucs", &json!({"option": "z", "angle": 90})).unwrap(); + let u = s.ucs(); + assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}"); +} + +// ---------------- the UCS command ---------------- + +#[test] +fn a_new_drawing_is_in_the_world_ucs() { + let s = session(); + assert!(s.ucs().is_world()); + assert_eq!(var(&s, "WORLDUCS"), json!(1)); + assert_eq!(var(&s, "UCSNAME"), json!("")); + assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::ZERO)); + assert!(near3(vec3(&var(&s, "UCSXDIR")), Vec3::new(1.0, 0.0, 0.0))); + assert!(near3(vec3(&var(&s, "UCSYDIR")), Vec3::new(0.0, 1.0, 0.0))); +} + +#[test] +fn ucs_origin_then_enter_moves_the_origin_and_keeps_the_axes() { + let mut s = session(); + typed(&mut s, &["ucs 100,50 "]); + assert!(logged(&s, "Current ucs name: *WORLD*")); + let u = s.ucs(); + assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0))); + assert_eq!(var(&s, "WORLDUCS"), json!(0)); + assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::new(100.0, 50.0, 0.0))); + typed(&mut s, &["ucs "]); + assert!(logged(&s, "Current ucs name: *NO NAME*"), "{:?}", s.log); + assert!(s.ucs().is_world(), "Enter at the first prompt is World"); +} + +#[test] +fn ucs_by_three_points() { + let mut s = session(); + // Origin, a point on the new X axis (straight up), Enter: Y square to it. + typed(&mut s, &["ucs 10,10 10,30 "]); + let u = s.ucs(); + assert!(near3(u.origin, Vec3::new(10.0, 10.0, 0.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)) && near3(u.y, Vec3::new(-1.0, 0.0, 0.0)), "{u:?}"); + // All three points; typed points are read in the UCS current while UCS runs. + typed(&mut s, &["ucs w", "ucs 0,0 1,1 -1,1"]); + let u = s.ucs(); + let r = std::f64::consts::FRAC_1_SQRT_2; + assert!(near3(u.x, Vec3::new(r, r, 0.0)) && near3(u.y, Vec3::new(-r, r, 0.0)) && u.is_planar(), "{u:?}"); + // A third point below the X axis would turn the UCS over: refused, and the UCS is kept. + let before = s.ucs(); + let _ = s.cmdline("ucs 0,0 10,0 5,-5"); + assert!(near3(s.ucs().x, before.x), "a turned-over UCS is not taken"); + s.cancel(); + // Points on one line define nothing. + assert!(s.execute("ucs", &json!({"origin": [0, 0], "xPoint": [10, 0], "xyPoint": [20, 0]})).is_err()); + assert!(s.execute("ucs", &json!({"origin": [0, 0], "xPoint": [0, 0]})).is_err()); +} + +#[test] +fn ucs_z_turns_about_z_and_defaults_to_ucsaxisang() { + let mut s = session(); + typed(&mut s, &["ucs z 30"]); + assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians())); + typed(&mut s, &["ucs z "]); + assert!(ang_eq(s.ucs().rotation(), 120f64.to_radians()), "Enter takes UCSAXISANG (90)"); + cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(45)).unwrap(); + typed(&mut s, &["ucs z "]); + assert!(ang_eq(s.ucs().rotation(), 165f64.to_radians())); + assert!(cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(33)).is_err(), "only the listed angles"); + typed(&mut s, &["ucs z -165"]); + assert!(ang_eq(s.ucs().rotation(), 0.0)); +} + +#[test] +fn ucs_previous_walks_back_ten_steps_per_space() { + let mut s = session(); + for i in 1..=12 { + s.execute("ucs", &json!({"option": "origin", "origin": [i, 0]})).unwrap(); + } + for i in (2..=11).rev() { + typed(&mut s, &["ucs p"]); + assert!(near3(s.ucs().origin, Vec3::new(f64::from(i), 0.0, 0.0)), "back to {i}: {:?}", s.ucs()); + } + let at = s.ucs(); + typed(&mut s, &["ucs p"]); + assert!(logged(&s, "There is no previous UCS.")); + assert_eq!(s.ucs(), at, "only ten are kept"); + assert!(s.execute("ucs", &json!({"option": "previous"})).is_err()); +} + +#[test] +fn named_ucs_save_restore_list_delete() { + let mut s = session(); + turned(&mut s); + typed(&mut s, &["ucs na s SITE"]); + assert_eq!(var(&s, "UCSNAME"), json!("SITE")); + assert_eq!(s.doc().unwrap().ucss.len(), 1); + typed(&mut s, &["ucs w"]); + assert!(s.ucs().is_world()); + typed(&mut s, &["ucs na r site"]); + assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)) && var(&s, "UCSNAME") == json!("SITE"), "restored by any case"); + // Saving over a name asks first. + typed(&mut s, &["ucs z 10", "ucs na s SITE", "n"]); + let saved = s.doc().unwrap().ucss[0].clone(); + assert!(near3(saved.x_axis, Vec3::new(0.0, 1.0, 0.0)), "No keeps the saved one"); + typed(&mut s, &["ucs na s SITE", "y"]); + assert!(!near3(s.doc().unwrap().ucss[0].x_axis, Vec3::new(0.0, 1.0, 0.0)), "Yes replaces it"); + // Listing. + s.execute("ucs", &json!({"option": "named", "action": "save", "name": "Base 2"})).unwrap(); + let list = s.execute("ucs", &json!({"option": "named", "action": "list"})).unwrap()["list"].as_str().unwrap().to_string(); + assert!(list.contains("SITE") && list.contains("Base 2") && list.contains("Origin = <") && list.contains("Z Axis = <"), "{list}"); + typed(&mut s, &["ucs na ? *"]); + assert!(logged(&s, "Saved coordinate systems:")); + // Deleting by wildcard, and the current UCS loses a deleted name. + let r = s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "BASE*"})).unwrap(); + assert_eq!(r["deleted"], json!(1)); + assert_eq!(var(&s, "UCSNAME"), json!(""), "the current one was Base 2"); + typed(&mut s, &["ucs na d SITE"]); + assert!(s.doc().unwrap().ucss.is_empty()); + // Unknown and invalid names. + assert!(s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "NOPE"})).is_err()); + for bad in ["", " ", "a Result { + let h = s.add_entity(kind).unwrap(); + s.execute("ucs", &json!({"option": "world"})).unwrap(); + s.execute("ucs", &json!({"option": "object", "handle": h.hex(), "at": pick})).map_err(|e| e.to_string())?; + Ok(s.ucs()) + }; + use cadcraft_engine::doc::{Arc, Circle, Face3d, Line, LwPolyline, Point}; + // A line: the nearer end; X along the line. + let u = at(&mut s, EntityKind::Line(Line { a: Vec3::new(10.0, 10.0, 0.0), b: Vec3::new(10.0, 30.0, 0.0) }), [10.0, 29.0]).unwrap(); + assert!(near3(u.origin, Vec3::new(10.0, 30.0, 0.0)) && near3(u.x, Vec3::new(0.0, -1.0, 0.0)), "{u:?}"); + // A circle: the centre; X through the pick. + let u = at(&mut s, EntityKind::Circle(Circle { center: Vec3::new(5.0, 5.0, 2.0), radius: 3.0 }), [5.0, 8.0]).unwrap(); + assert!(near3(u.origin, Vec3::new(5.0, 5.0, 2.0)) && near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}"); + // An arc: the centre; X through the nearer end. + let u = at(&mut s, EntityKind::Arc(Arc { center: Vec3::ZERO, radius: 2.0, start: 0.0, end: std::f64::consts::FRAC_PI_2 }), [0.1, 2.0]).unwrap(); + assert!(near3(u.x, Vec3::new(0.0, 1.0, 0.0)), "{u:?}"); + // A polyline: its first vertex; X toward the next. + let pl = LwPolyline { + vertices: vec![ + cadcraft_engine::geom::PolyVertex::new(Vec2::new(1.0, 1.0)), + cadcraft_engine::geom::PolyVertex::new(Vec2::new(1.0, 1.0)), + cadcraft_engine::geom::PolyVertex::new(Vec2::new(-4.0, 1.0)), + ], + closed: false, + const_width: 0.0, + elevation: 3.0, + plinegen: false, + }; + let u = at(&mut s, EntityKind::LwPolyline(pl), [0.0, 0.0]).unwrap(); + assert!(near3(u.origin, Vec3::new(1.0, 1.0, 3.0)) && near3(u.x, Vec3::new(-1.0, 0.0, 0.0)), "{u:?}"); + // Text (and blocks, by the same rule): the insertion point; X along its rotation. + s.execute("ucs", &json!({"option": "world"})).unwrap(); + typed(&mut s, &["text 2,3 1 28.64788975654116 A", ""]); + let th = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).map(|e| e.handle).last().unwrap(); + s.execute("ucs", &json!({"option": "object", "handle": th.hex()})).unwrap(); + let u = s.ucs(); + assert!(near3(u.origin, Vec3::new(2.0, 3.0, 0.0)) && ang_eq(u.rotation(), 0.5), "{u:?}"); + // A point: there, the X axis kept. + let u = at(&mut s, EntityKind::Point(Point { p: Vec3::new(4.0, 4.0, 0.0), angle: 0.0 }), [0.0, 0.0]).unwrap(); + assert!(near3(u.origin, Vec3::new(4.0, 4.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0))); + // A flat 3D face works; a tilted one, an ellipse and a zero-length line don't. + let flat = Face3d { corners: [Vec3::ZERO, Vec3::new(0.0, 5.0, 0.0), Vec3::new(-5.0, 5.0, 0.0), Vec3::new(-5.0, 0.0, 0.0)], hidden_edges: 0 }; + let u = at(&mut s, EntityKind::Face3d(flat), [0.0, 0.0]).unwrap(); + assert!(near3(u.x, Vec3::new(0.0, 1.0, 0.0)) && u.is_planar()); + let tilted = Face3d { corners: [Vec3::ZERO, Vec3::new(5.0, 0.0, 0.0), Vec3::new(5.0, 0.0, 5.0), Vec3::new(0.0, 0.0, 5.0)], hidden_edges: 0 }; + assert!(at(&mut s, EntityKind::Face3d(tilted), [0.0, 0.0]).unwrap_err().contains("not available yet")); + let ell = cadcraft_engine::doc::Ellipse { center: Vec3::ZERO, major: Vec3::new(2.0, 0.0, 0.0), ratio: 0.5, start: 0.0, end: TAU }; + assert!(at(&mut s, EntityKind::Ellipse(ell), [0.0, 0.0]).is_err()); + assert!(at(&mut s, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(0.0, 0.0, 9.0) }), [0.0, 0.0]).is_err()); + assert!(s.ucs().is_world(), "a refused object leaves the UCS"); + // Interactively: a pick on the object. + s.execute("line", &json!({"points": [[50, 50], [50, 80]]})).unwrap(); + typed(&mut s, &["ucs ob 50,79"]); + assert!(near3(s.ucs().origin, Vec3::new(50.0, 80.0, 0.0)), "{:?}", s.ucs()); + let _ = s.cmdline("ucs ob 900,900"); + assert!(s.running.is_some() || logged(&s, "No object found"), "a miss asks again"); + s.cancel(); +} + +#[test] +fn ucs_view_and_the_tilted_options() { + let mut s = session(); + turned(&mut s); + typed(&mut s, &["ucs v"]); + let u = s.ucs(); + assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)), "square to the plan view, origin kept"); + for k in ["x", "y", "za", "f"] { + s.cmdline(&format!("ucs {k}")).unwrap(); + assert!(logged(&s, "not available yet"), "{k}"); + assert!(s.running.is_some(), "{k}: still at the prompt"); + s.cancel(); + assert!(s.execute("ucs", &json!({"option": k})).unwrap_err().to_string().contains("not available yet"), "{k}"); + } +} + +#[test] +fn a_ucs_change_is_undone_like_an_edit() { + let mut s = session(); + typed(&mut s, &["ucs 100,50 "]); + typed(&mut s, &["ucs z 45"]); + s.undo().unwrap(); + let u = s.ucs(); + assert!(near3(u.origin, Vec3::new(100.0, 50.0, 0.0)) && near3(u.x, Vec3::new(1.0, 0.0, 0.0)), "{u:?}"); + s.undo().unwrap(); + assert!(s.ucs().is_world()); + s.redo().unwrap(); + assert!(near3(s.ucs().origin, Vec3::new(100.0, 50.0, 0.0))); +} + +#[test] +fn paper_space_has_its_own_ucs() { + let mut s = session(); + turned(&mut s); + let layout = s.doc().unwrap().layouts[0].name.clone(); + s.execute("layout.set", &json!({"name": layout})).unwrap(); + assert!(s.ucs().is_world(), "a layout starts in the World UCS"); + typed(&mut s, &["ucs z 30"]); + assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians())); + assert!(s.doc().unwrap().layouts[0].ucs.is_some()); + // UCS Previous stays in its space. + typed(&mut s, &["ucs p"]); + assert!(s.ucs().is_world()); + typed(&mut s, &["ucs p"]); + assert!(logged(&s, "There is no previous UCS."), "model space's history isn't paper space's"); + s.execute("layout.set", &json!({"name": "Model"})).unwrap(); + assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)), "model space kept its own"); + let (m, _) = cadcraft_engine::ucs::current(s.doc().unwrap(), &Space::Model); + assert!(near3(m.origin, Vec3::new(100.0, 50.0, 0.0))); +} + +// ---------------- typed input in the UCS ---------------- + +#[test] +fn typed_points_are_read_in_the_ucs() { + let mut s = session(); + turned(&mut s); + // Absolute: from the UCS origin along its axes. + typed(&mut s, &["line 10,0 20,0 "]); + let (a, b) = last_line(&s); + assert!(near(a, 100.0, 60.0) && near(b, 100.0, 70.0), "{a:?} {b:?}"); + // Relative Cartesian along the UCS axes; polar angles from the UCS X axis. + typed(&mut s, &["line 0,0 @5,0 @0,5 @10<90 "]); + let ls = lines(&s); + let n = ls.len(); + assert!(near(ls[n - 3].1, 100.0, 55.0) && near(ls[n - 2].1, 95.0, 55.0) && near(ls[n - 1].1, 85.0, 55.0), "{ls:?}"); + // Absolute polar: from the UCS origin. + typed(&mut s, &["line 0,0 10<0 "]); + assert!(near(last_line(&s).1, 100.0, 60.0), "{:?}", last_line(&s)); + // `#` is absolute in the UCS; `*` and `@*` are world coordinates. + typed(&mut s, &["line #1,2 *1,2 @*3,0 @*5<0 "]); + let ls = lines(&s); + let n = ls.len(); + assert!(near(ls[n - 3].0, 98.0, 51.0) && near(ls[n - 3].1, 1.0, 2.0) && near(ls[n - 2].1, 4.0, 2.0) && near(ls[n - 1].1, 9.0, 2.0), "{ls:?}"); + // A 3D point keeps working (Z is ignored as before). + typed(&mut s, &["line 1,1,5 2,1,5 "]); + let (a, _) = last_line(&s); + assert!(near(a, 99.0, 51.0), "{a:?}"); +} + +#[test] +fn the_world_ucs_reads_points_as_before() { + let script = ["line 1,2 @3,4 @5<30 #7,8 *9,10 @*1,1 "]; + let mut a = session(); + typed(&mut a, &script); + let mut b = session(); + typed(&mut b, &["ucs 100,50 ", "ucs z 33", "ucs w"]); + typed(&mut b, &script); + let (la, lb) = (lines(&a), lines(&b)); + assert_eq!(la.len(), lb.len()); + for (x, y) in la.iter().zip(&lb) { + assert!(x.0.dist(y.0) < 1e-12 && x.1.dist(y.1) < 1e-12, "{x:?} vs {y:?}"); + } +} + +#[test] +fn directions_are_measured_from_the_ucs_x_axis() { + let mut s = session(); + typed(&mut s, &["ucs z 30"]); + // TEXT's rotation 0 lies along the UCS X axis. + typed(&mut s, &["text 0,0 2 0 Hello", ""]); + let rot = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.rotation) } else { None }).unwrap(); + assert!(ang_eq(rot, 30f64.to_radians()), "{rot}"); + // ANGBASE is measured from the UCS X axis too. + cadcraft_engine::sysvars::set(&mut s, "ANGBASE", &json!(90)).unwrap(); + typed(&mut s, &["line 0,0 @10<0 "]); + let (a, b) = last_line(&s); + assert!(ang_eq((b - a).angle(), 120f64.to_radians()), "{:?}", (b - a).angle().to_degrees()); + // `<<` overrides ANGBASE but stays in the UCS. + typed(&mut s, &["line 0,0 @10<<0 "]); + let (a, b) = last_line(&s); + assert!(ang_eq((b - a).angle(), 30f64.to_radians())); + cadcraft_engine::sysvars::set(&mut s, "ANGBASE", &json!(0)).unwrap(); + // A rotation by an angle is a size, the same in any UCS. + let h = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()["handles"][0].as_str().unwrap().to_string(); + typed(&mut s, &["rotate l 0,0 90"]); + let l = s.doc().unwrap().model.iter().find(|e| e.handle.hex() == h).map(|e| e.kind.clone()).unwrap(); + let EntityKind::Line(l) = l else { panic!() }; + assert!(near(l.b.xy(), 0.0, 10.0), "{:?}", l.b); + // JSON parameters stay in world coordinates. + s.execute("line", &json!({"points": [[0, 0], [3, 0]]})).unwrap(); + assert!(near(last_line(&s).1, 3.0, 0.0)); +} + +#[test] +fn coordinates_are_shown_in_the_ucs() { + let mut s = session(); + turned(&mut s); + // ID: the message in the UCS; the JSON result keeps world values beside it. + let r = s.execute("id", &json!({"at": [100, 60]})).unwrap(); + assert!(r["message"].as_str().unwrap().starts_with("X = 10.0000 Y = 0.0000"), "{r}"); + assert_eq!((r["x"].as_f64(), r["y"].as_f64()), (Some(100.0), Some(60.0))); + assert!((r["ucs"][0].as_f64().unwrap() - 10.0).abs() < 1e-9); + typed(&mut s, &["id 3,4"]); + assert!(logged(&s, "X = 3.0000 Y = 4.0000"), "{:?}", s.log.last()); + // DIST: the deltas and the angle in the UCS. + let r = s.execute("dist", &json!({"p1": [100, 50], "p2": [100, 60]})).unwrap(); + let m = r["message"].as_str().unwrap(); + assert!(m.contains("Angle in XY Plane = 0") && m.contains("Delta X = 10.0000") && m.contains("Delta Y = 0.0000"), "{m}"); + // The helpers the status bar and dynamic input use. + assert!(near(s.ucs_point(Vec2::new(100.0, 60.0)), 10.0, 0.0)); + assert!(ang_eq(s.ucs_angle(std::f64::consts::FRAC_PI_2), 0.0)); +} + +// ---------------- variables, UCSICON, tilted UCSs ---------------- + +#[test] +fn ucs_variables_are_read_only() { + let mut s = session(); + for v in ["UCSNAME", "UCSORG", "UCSXDIR", "UCSYDIR", "WORLDUCS"] { + assert!(cadcraft_engine::sysvars::set(&mut s, v, &json!(1)).is_err(), "{v}"); + } + typed(&mut s, &["ucs 5,6 ", "ucs na s A"]); + assert_eq!(var(&s, "UCSNAME"), json!("A")); + assert!(near3(vec3(&var(&s, "UCSORG")), Vec3::new(5.0, 6.0, 0.0))); +} + +#[test] +fn ucsicon_options() { + let mut s = session(); + assert_eq!(s.ucsicon_bits(), 3, "shown, at the origin"); + typed(&mut s, &["ucsicon off"]); + assert_eq!(s.ucsicon_bits(), 2); + typed(&mut s, &["ucsicon on", "ucsicon n"]); + assert_eq!(s.ucsicon_bits(), 1); + typed(&mut s, &["ucsicon or"]); + assert_eq!(s.ucsicon_bits(), 3); + s.cmdline("ucsicon s").unwrap(); + assert!(logged(&s, "not available yet")); + s.cancel(); + let r = s.execute("ucsicon", &json!({"on": false, "origin": false})).unwrap(); + assert_eq!(r, json!({"on": false, "origin": false})); + assert_eq!(var(&s, "UCSICON"), json!(0)); + assert!(s.execute("ucsicon", &json!({"on": "yes"})).is_err()); + assert!(cadcraft_engine::sysvars::set(&mut s, "UCSICON", &json!(9)).is_err()); +} + +#[test] +fn a_tilted_ucs_from_a_file_is_kept_and_input_stays_in_the_world_ucs() { + let mut s = session(); + { + let h = &mut s.doc_mut().unwrap().header; + h.set("UCSORG", HVal::Point(Vec3::new(10.0, 0.0, 0.0))); + h.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0))); + h.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0))); + } + assert!(!s.ucs().is_planar()); + assert_eq!(s.input_ucs(), UcsFrame::WORLD); + typed(&mut s, &["line 1,1 2,2 "]); + assert!(near(last_line(&s).0, 1.0, 1.0), "read in the World UCS"); + assert!(logged(&s, "tilted out of the XY plane")); + let n = s.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count(); + typed(&mut s, &["line 3,3 4,4 "]); + assert_eq!(s.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count(), n, "told once"); + // The UCS itself is untouched until the user sets another. + assert!(near3(vec3(&var(&s, "UCSYDIR")), Vec3::new(0.0, 0.0, 1.0))); + // A tilted named UCS isn't restored. + s.doc_mut().unwrap().ucss.push(cadcraft_engine::doc::Ucs { + name: "FRONT".into(), + origin: Vec3::ZERO, + x_axis: Vec3::new(1.0, 0.0, 0.0), + y_axis: Vec3::new(0.0, 0.0, 1.0), + }); + s.execute("ucs", &json!({"option": "world"})).unwrap(); + assert!(s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "FRONT"})).unwrap_err().to_string().contains("tilted")); + assert!(s.ucs().is_world()); +} + +#[test] +fn hostile_ucs_input_never_panics() { + let mut s = session(); + let bad: Vec = vec![ + json!({"option": "origin", "origin": [f64::MAX, -f64::MAX, f64::MAX]}), + json!({"option": "origin", "origin": ["a", 1]}), + json!({"option": "origin", "origin": [1]}), + json!({"option": "origin", "origin": [0, 0], "xPoint": [1e308, 1e308], "xyPoint": [-1e308, 1e308]}), + json!({"option": "origin", "origin": [0, 0], "xyPoint": [0, 1]}), + json!({"option": "z", "angle": 1e308}), + json!({"option": "z", "angle": "ninety"}), + json!({"option": "object"}), + json!({"option": "object", "handle": "ZZZZ"}), + json!({"option": "object", "handle": "FFFFFF"}), + json!({"option": "named", "action": "explode", "name": "A"}), + json!({"option": "named", "action": "delete", "name": "*,?,[,]"}), + json!({"option": "warp"}), + json!({"option": 7}), + json!(null), + json!([1, 2, 3]), + ]; + for p in &bad { + let _ = s.execute("ucs", p); + let u = s.ucs(); + assert!(u.origin.is_finite() && u.x.is_finite() && u.y.is_finite(), "{p}: {u:?}"); + } + for t in ["ucs 1e400,0", "ucs nan,nan", "ucs 0,0 0,0", "ucs z 1e999", "ucs na s \u{0}", "ucs na r ", "ucs ob", "ucs na ? [", "ucsicon blah"] { + let _ = s.cmdline(t); + s.cancel(); + } + // Broken header values read as the World UCS. + for v in [HVal::Point(Vec3::new(f64::NAN, 0.0, 0.0)), HVal::Point(Vec3::ZERO), HVal::Str("x".into()), HVal::Int(3)] { + s.doc_mut().unwrap().header.set("UCSXDIR", v); + let u = s.ucs(); + assert!(u.origin.is_finite() && u.x.is_finite()); + typed(&mut s, &["line 0,0 1,0 "]); + } +} diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index cb9153456..781019fae 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -35,6 +35,9 @@ pub(crate) const PLOT_STYLE_NAMES_KEY: &str = "ACAD_PLOTSTYLENAME"; pub(crate) const HANDSEED_KEY: &str = "CADCRAFT_HANDSEED"; /// Named-object-dictionary key of the XRECORD holding the current multileader style. pub(crate) const MLEADER_STYLE_KEY: &str = "CADCRAFT_MLEADERSTYLE"; +/// Named-object-dictionary key of the XRECORD holding model space's current UCS name ($UCSNAME, +/// which the DWG bridge drops). +pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME"; /// Most plot style tables and plot style names read from a file. pub(crate) const MAX_PLOT_STYLE_TABLES: usize = 1000; pub(crate) const MAX_PLOT_STYLE_NAMES: usize = 100_000; diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 7615bc569..404c4d797 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -985,6 +985,8 @@ struct Rx { block_arrays: HashMap, /// LAYER record handle (upper case) → layer name (VIEWPORT group 341 frozen layers). layers: HashMap, + /// UCS record handle (upper case) → UCS name (a layout's named UCS, group 345). + ucss: HashMap, } /// The plot style names of a file: the entries of the `ACAD_PLOTSTYLENAME` dictionary of the @@ -1413,6 +1415,9 @@ fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { "LAYER" => { rx.layers.insert(h.trim().to_ascii_uppercase(), n); } + "UCS" => { + rx.ucss.insert(h.trim().to_ascii_uppercase(), n); + } _ => {} } } @@ -1928,6 +1933,8 @@ struct Objects { groups: Vec<(String, Vec)>, /// Saved paper-space views of layouts: (layout name, view). layout_views: Vec<(String, (Vec2, f64))>, + /// Layouts' current UCSs: (layout name, origin, X axis, Y axis, named UCS record handle). + layout_ucss: Vec<(String, Vec3, Vec3, Vec3, Option)>, /// SORTENTSTABLE objects: (owning block record handle, entity handle → sort handle). sortents: Vec<(String, HashMap)>, } @@ -1973,11 +1980,18 @@ impl Objects { self.sortents.push(t); } } - "LAYOUT" if self.layout_views.len() < MAX_OBJECTS => { + "LAYOUT" if self.layout_views.len() < MAX_OBJECTS && self.layout_ucss.len() < MAX_OBJECTS => { let start = tags.iter().position(|x| x.code == 100 && x.str() == "AcDbLayout").unwrap_or(0); - if let (Some(name), Some(view)) = (T(tags.get(start..).unwrap_or(&[])).s(1), layout_view(tags)) { + let own = T(tags.get(start..).unwrap_or(&[])); + if let (Some(name), Some(view)) = (own.s(1), layout_view(tags)) { self.layout_views.push((name, view)); } + // Its current UCS (groups 13, 16, 17; 345 when it is a named UCS). + if let Some(name) = own.s(1) + && [13, 16, 17].iter().all(|c| own.f(*c).is_some()) + { + self.layout_ucss.push((name, own.p(13), own.p(16), own.p(17), own.s(345))); + } } _ => {} } @@ -2001,6 +2015,19 @@ impl Objects { if let Some(style) = self.xrecord_text(crate::dxf_ext::MLEADER_STYLE_KEY).filter(|s| !s.trim().is_empty()) { d.header.set_str("CMLEADERSTYLE", &style); } + // Model space's UCS name when the file lost it ($UCSNAME empty, as through DWG): only + // while the current UCS is still exactly that named UCS. + if d.header.str("UCSNAME", "").trim().is_empty() + && let Some(name) = self.xrecord_text(crate::dxf_ext::UCS_NAME_KEY).map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) + && let Some(u) = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(&name)) + && let (Some(o), Some(x), Some(y)) = (d.header.point("UCSORG"), d.header.point("UCSXDIR"), d.header.point("UCSYDIR")) + && (o - u.origin).len() <= 1e-9 * (1.0 + o.len()) + && (x - u.x_axis).len() <= 1e-9 + && (y - u.y_axis).len() <= 1e-9 + { + let n = u.name.clone(); + d.header.set_str("UCSNAME", &n); + } // Table styles (named by their ACAD_TABLESTYLE dictionary entries). for (h, tags) in &self.table_styles { let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue }; @@ -2080,6 +2107,19 @@ impl Objects { l.view = Some(*view); } } + // Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset. + for (name, origin, x, y, named) in &self.layout_ucss { + let usable = + [*origin, *x, *y].iter().all(|v| v.is_finite()) && x.len() > 1e-12 && y.len() > 1e-12 && x.cross(*y).len() > 1e-9 * x.len() * y.len(); + let ucs_name = named.as_ref().and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase())).cloned().unwrap_or_default(); + let world = origin.len() <= 1e-12 && (*x - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 && (*y - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12; + if !usable || (world && ucs_name.is_empty()) { + continue; + } + if let Some(l) = d.layouts.iter_mut().find(|l| l.name == *name) { + l.ucs = Some(Ucs { name: ucs_name, origin: *origin, x_axis: *x, y_axis: *y }); + } + } // Groups (named by their ACAD_GROUP dictionary entries); members that exist. for (h, tags) in &self.groups { let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue }; diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index cd4d2c17c..c979f313d 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -19,6 +19,8 @@ struct W { pstyles: HashMap, /// Upper-case layer name → its LAYER table record handle (group 341 of viewports). layers: HashMap, + /// Upper-case UCS name → its UCS table record handle (group 345 of layouts and viewports). + ucss: HashMap, /// Persistent reactors of boundary objects: each source object of an associative hatch → /// the hatches (groups `{ACAD_REACTORS 330 …}`), from [`hatch_reactors`]. reactors: HashMap>, @@ -201,7 +203,7 @@ fn annotative_xdata(w: &mut W) { /// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension. fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) { - let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() }; + let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), ucss: HashMap::new(), reactors: HashMap::new() }; let mut sah = false; for (k, v) in &dm.overrides { let Some(field) = DimStyle::field_name(k) else { continue }; @@ -281,6 +283,11 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("CHAMFERB", 40), ("ANGBASE", 50), ("ANGDIR", 70), + // Model space's current UCS (each layout's is in its LAYOUT object). + ("UCSNAME", 2), + ("UCSORG", -3), + ("UCSXDIR", -3), + ("UCSYDIR", -3), ("PDMODE", 70), ("PDSIZE", 40), ("PLINEWID", 40), @@ -291,6 +298,19 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("PSLTSCALE", 70), ]; +/// Model space's current UCS from the header (UCSORG, UCSXDIR, UCSYDIR, UCSNAME): unusable +/// values are the World UCS's, so a broken one read from a file isn't written back. +fn model_ucs(d: &Drawing) -> Ucs { + let h = &d.header; + let p = |name: &str| h.point(name).filter(|v| v.is_finite()); + let axis = |name: &str| p(name).filter(|v| v.len() > 1e-12); + let (x, y) = match (axis("UCSXDIR"), axis("UCSYDIR")) { + (Some(x), Some(y)) if x.cross(y).len() > 1e-9 * x.len() * y.len() => (x, y), + _ => (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)), + }; + Ucs { name: h.str("UCSNAME", ""), origin: p("UCSORG").unwrap_or(Vec3::ZERO), x_axis: x, y_axis: y } +} + fn header_vars(w: &mut W, d: &Drawing) { for (name, code) in HEADER_VARS { let Some(v) = d.header.get(name) else { continue }; @@ -299,6 +319,9 @@ fn header_vars(w: &mut W, d: &Drawing) { let p = match *name { "SNAPUNIT" => d.header.snap_unit().to3(0.0), "GRIDUNIT" => d.header.grid_unit().to3(0.0), + "UCSORG" => model_ucs(d).origin, + "UCSXDIR" => model_ucs(d).x_axis, + "UCSYDIR" => model_ucs(d).y_axis, _ => *p, }; w.s(9, format!("${name}")); @@ -1518,6 +1541,16 @@ fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { w.f(41, if t.aspect.is_finite() && t.aspect > 0.0 { t.aspect } else { 1.0 }); w.f(42, 50.0); w.f(50, d.header.f64("SNAPANG", 0.0)); + // The shown configuration's tiles keep model space's current UCS (UCSVP 1). + if name == VportConfig::ACTIVE { + let ucs = model_ucs(d); + w.i(65, 1); + w.p(110, ucs.origin); + w.p(111, ucs.x_axis); + w.p(112, ucs.y_axis); + w.i(79, 0); + w.f(146, 0.0); + } } w.s(0, "ENDTAB"); } @@ -1586,6 +1619,7 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { next: d.handseed.max(0x100).saturating_add(0x1000), pstyles: HashMap::new(), layers: HashMap::new(), + ucss: HashMap::new(), reactors: hatch_reactors(d), }; // Pre-allocate handles for block records. @@ -1749,6 +1783,9 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { if let Some(name) = d.header.get("CMLEADERSTYLE").and_then(HVal::as_str) { xrecords.push((dxf_ext::MLEADER_STYLE_KEY, w.h(), vec![name.to_string()])); } + if let Some(name) = d.header.get("UCSNAME").and_then(HVal::as_str).map(str::trim).filter(|n| !n.is_empty()) { + xrecords.push((dxf_ext::UCS_NAME_KEY, w.h(), vec![name.to_string()])); + } if let Some(chunks) = dxf_ext::constraint_chunks(&d.constraints, &d.parametric) { xrecords.push((dxf_ext::CONSTRAINTS_KEY, w.h(), chunks)); } @@ -2017,7 +2054,8 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { // UCS: named user coordinate systems (DXF Reference, UCS). let th = table_head(&mut w, "UCS", d.ucss.len()); for u in &d.ucss { - record_head(&mut w, "UCS", &th, "AcDbUCSTableRecord"); + let h = record_head(&mut w, "UCS", &th, "AcDbUCSTableRecord"); + w.ucss.insert(u.name.to_ascii_uppercase(), h); w.s(2, &u.name); w.i(70, 0); w.p(10, u.origin); @@ -2054,7 +2092,7 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.i(70, 0); let v = serde_json::to_value(s).unwrap_or_default(); let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default(); - let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), reactors: HashMap::new() }; + let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), ucss: HashMap::new(), reactors: HashMap::new() }; for (field, code, kind) in dxf_ext::DIM_CODES { let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue }; if !dxf_ext::NEWER_CODES.contains(code) { @@ -2359,94 +2397,101 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.s(3, &l.name); w.s(350, layout_handles.get(i).cloned().unwrap_or_default()); } - let layout_obj = |w: &mut W, h: &str, name: &str, tab: i64, brh: &str, flags: i64, page: &PageSetup, view: Option<(Vec2, f64)>| { - // Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units - // per 143 drawing units). - let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 }; - let standard = page.scale_to_fit || scale == 1.0; - let plot_flags = 512 - | 32 - | if standard { 16 } else { 0 } - | if page.lineweights { 128 } else { 0 } - | if page.center { 4 } else { 0 } - | if page.show_plot_styles { 2 } else { 0 }; - let plot_type = match page.plot_area.as_str() { - "display" => 0, - "extents" => 1, - "limits" => 2, - "window" => 4, - _ => 5, + let layout_obj = + |w: &mut W, h: &str, name: &str, tab: i64, brh: &str, flags: i64, page: &PageSetup, view: Option<(Vec2, f64)>, ucs: Option<&Ucs>| { + // Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units + // per 143 drawing units). + let scale = if page.scale.is_finite() && page.scale > 0.0 { page.scale } else { 1.0 }; + let standard = page.scale_to_fit || scale == 1.0; + let plot_flags = 512 + | 32 + | if standard { 16 } else { 0 } + | if page.lineweights { 128 } else { 0 } + | if page.center { 4 } else { 0 } + | if page.show_plot_styles { 2 } else { 0 }; + let plot_type = match page.plot_area.as_str() { + "display" => 0, + "extents" => 1, + "limits" => 2, + "window" => 4, + _ => 5, + }; + w.s(0, "LAYOUT"); + w.s(5, h); + w.s(330, layout_dict.clone()); + w.s(100, "AcDbPlotSettings"); + w.s(1, ""); + let device = page.device.trim(); + w.s(2, if device.is_empty() || device.eq_ignore_ascii_case("None") { "none_device" } else { device }); + w.s(4, page.paper.replace(' ', "_")); + w.s(6, ""); + for (c, v) in [ + (40, page.margins_mm[0]), + (41, page.margins_mm[1]), + (42, page.margins_mm[2]), + (43, page.margins_mm[3]), + (44, page.width_mm), + (45, page.height_mm), + (46, 0.0), + (47, 0.0), + (48, 0.0), + (49, 0.0), + (140, 0.0), + (141, 0.0), + (142, scale), + (143, 1.0), + ] { + w.f(c, v); + } + w.i(70, plot_flags); + w.i(72, 0); + w.i(73, i64::from(page.landscape)); + w.i(74, plot_type); + w.s(7, &page.plot_style_table); + w.i(75, if page.scale_to_fit { 0 } else { 16 }); + w.f(147, scale); + w.f(148, 0.0); + w.f(149, 0.0); + w.s(100, "AcDbLayout"); + w.s(1, name); + w.i(70, flags); + w.i(71, tab); + w.p2(10, Vec2::ZERO); + w.p2(11, Vec2::new(12.0, 9.0)); + w.p(12, Vec3::ZERO); + w.p(14, Vec3::ZERO); + w.p(15, Vec3::ZERO); + // The layout's current UCS: origin, X and Y axes, orthographic type, then (after the + // block record) the named UCS it is. + let u = ucs.filter(|u| [u.origin, u.x_axis, u.y_axis].iter().all(|v| v.is_finite()) && u.x_axis.cross(u.y_axis).len() > 1e-12); + w.f(146, 0.0); + w.p(13, u.map_or(Vec3::ZERO, |u| u.origin)); + w.p(16, u.map_or(Vec3::new(1.0, 0.0, 0.0), |u| u.x_axis)); + w.p(17, u.map_or(Vec3::new(0.0, 1.0, 0.0), |u| u.y_axis)); + w.i(76, 0); + w.s(330, brh); + if let Some(h) = u.filter(|u| !u.name.trim().is_empty()).and_then(|u| w.ucss.get(&u.name.trim().to_ascii_uppercase())).cloned() { + w.s(345, h); + } + // The saved paper-space view (centre, height) as CADCraft xdata. + if let Some((c, height)) = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite()) { + w.s(1001, dxf_ext::APP); + w.s(1000, "PSVIEW"); + w.s(1002, "{"); + w.p(1010, c.to3(0.0)); + w.f(1040, height); + w.s(1002, "}"); + } }; - w.s(0, "LAYOUT"); - w.s(5, h); - w.s(330, layout_dict.clone()); - w.s(100, "AcDbPlotSettings"); - w.s(1, ""); - let device = page.device.trim(); - w.s(2, if device.is_empty() || device.eq_ignore_ascii_case("None") { "none_device" } else { device }); - w.s(4, page.paper.replace(' ', "_")); - w.s(6, ""); - for (c, v) in [ - (40, page.margins_mm[0]), - (41, page.margins_mm[1]), - (42, page.margins_mm[2]), - (43, page.margins_mm[3]), - (44, page.width_mm), - (45, page.height_mm), - (46, 0.0), - (47, 0.0), - (48, 0.0), - (49, 0.0), - (140, 0.0), - (141, 0.0), - (142, scale), - (143, 1.0), - ] { - w.f(c, v); - } - w.i(70, plot_flags); - w.i(72, 0); - w.i(73, i64::from(page.landscape)); - w.i(74, plot_type); - w.s(7, &page.plot_style_table); - w.i(75, if page.scale_to_fit { 0 } else { 16 }); - w.f(147, scale); - w.f(148, 0.0); - w.f(149, 0.0); - w.s(100, "AcDbLayout"); - w.s(1, name); - w.i(70, flags); - w.i(71, tab); - w.p2(10, Vec2::ZERO); - w.p2(11, Vec2::new(12.0, 9.0)); - w.p(12, Vec3::ZERO); - w.p(14, Vec3::ZERO); - w.p(15, Vec3::ZERO); - w.f(146, 0.0); - w.p(13, Vec3::ZERO); - w.p(16, Vec3::new(1.0, 0.0, 0.0)); - w.p(17, Vec3::new(0.0, 1.0, 0.0)); - w.i(76, 0); - w.s(330, brh); - // The saved paper-space view (centre, height) as CADCraft xdata. - if let Some((c, height)) = view.filter(|(c, v)| c.x.is_finite() && c.y.is_finite() && v.is_finite()) { - w.s(1001, dxf_ext::APP); - w.s(1000, "PSVIEW"); - w.s(1002, "{"); - w.p(1010, c.to3(0.0)); - w.f(1040, height); - w.s(1002, "}"); - } - }; // Model space has no page setup of its own: write what PLOT does for it, the drawing extents // fitted to the paper (plot type 1, scaled to fit). The default page's "layout" area is // plot type 5, "Layout information" (DXF Reference, PLOTSETTINGS group 74), which means // nothing for model space: another program's Plot dialog then shows no plot area or scale. let model_page = PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..PageSetup::default() }; - layout_obj(&mut w, &model_layout, "Model", 0, &ms_br, 1, &model_page, None); + layout_obj(&mut w, &model_layout, "Model", 0, &ms_br, 1, &model_page, None, None); for (i, (_, brh, l)) in ps_brs.iter().enumerate() { let h = layout_handles.get(i).cloned().unwrap_or_default(); - layout_obj(&mut w, &h, &l.name, i64::from(l.tab_order.max(1)), brh, 1, &l.page, l.view); + layout_obj(&mut w, &h, &l.name, i64::from(l.tab_order.max(1)), brh, 1, &l.page, l.view, l.ucs.as_ref()); } // Raster image definitions. w.t.extend(crate::dxf_image::objects(&cx.images, &root_dict)); @@ -2669,6 +2714,7 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec) { next: d.handseed.max(0x100).saturating_add(0x1000), pstyles: HashMap::new(), layers: HashMap::new(), + ucss: HashMap::new(), reactors: HashMap::new(), }; let cx = Ctx { target: Version::R2018, ..Ctx::default() }; diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs new file mode 100644 index 000000000..b79ee3b00 --- /dev/null +++ b/crates/io/tests/ucs_roundtrip.rs @@ -0,0 +1,255 @@ +//! The current UCS survives saving and reopening (#1106): model space's in the header +//! ($UCSORG, $UCSXDIR, $UCSYDIR, $UCSNAME) and the shown VPORT, each layout's in its LAYOUT +//! object (groups 13, 16, 17 and 345 for a named UCS), through DXF and DWG. + +use cadcraft_doc::*; +use cadcraft_geom::Vec3; + +fn near3(a: Vec3, b: Vec3) -> bool { + (a - b).len() < 1e-9 +} + +/// The (code, value) pairs of every `kind` record in DXF text. +fn records(text: &str, kind: &str) -> Vec> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out: Vec> = Vec::new(); + let mut inside = false; + for pair in lines.chunks(2) { + let [code, value] = pair else { break }; + if *code == "0" { + inside = *value == kind; + if inside { + out.push(Vec::new()); + } + } else if inside && let Some(rec) = out.last_mut() { + rec.push((code.to_string(), value.to_string())); + } + } + out +} + +fn group<'a>(rec: &'a [(String, String)], code: &str) -> Option<&'a str> { + rec.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str()) +} + +/// The LAYOUT object of layout `name` (its group 1 after `100 AcDbLayout`; the first group 1 is +/// the page setup's). +fn layout_record(text: &str, name: &str) -> Vec<(String, String)> { + records(text, "LAYOUT") + .into_iter() + .find(|r| r.iter().skip_while(|(c, v)| !(c == "100" && v == "AcDbLayout")).any(|(c, v)| c == "1" && v == name)) + .unwrap_or_else(|| panic!("no LAYOUT {name}")) +} + +fn num(rec: &[(String, String)], code: &str) -> f64 { + group(rec, code).and_then(|v| v.trim().parse().ok()).unwrap_or(f64::NAN) +} + +/// The header variable `$name`'s groups in DXF text. +fn header_var(text: &str, name: &str) -> Vec<(String, String)> { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let mut out = Vec::new(); + let mut on = false; + for pair in lines.chunks(2) { + let [code, value] = pair else { break }; + if *code == "9" { + on = *value == format!("${name}"); + continue; + } + if *code == "0" { + on = false; + } + if on { + out.push((code.to_string(), value.to_string())); + } + } + out +} + +const C30: f64 = 0.866_025_403_784_438_6; + +/// A drawing whose model space is in a named UCS turned 30° at (100, 50, 0), and whose first +/// layout is in an unnamed one at (5, 5) turned 90°. +fn drawing() -> Drawing { + let mut d = Drawing::default(); + let site = Ucs { name: "SITE".into(), origin: Vec3::new(100.0, 50.0, 0.0), x_axis: Vec3::new(C30, 0.5, 0.0), y_axis: Vec3::new(-0.5, C30, 0.0) }; + d.ucss.push(site.clone()); + d.header.set("UCSORG", HVal::Point(site.origin)); + d.header.set("UCSXDIR", HVal::Point(site.x_axis)); + d.header.set("UCSYDIR", HVal::Point(site.y_axis)); + d.header.set_str("UCSNAME", "SITE"); + d.layouts[0].ucs = + Some(Ucs { name: String::new(), origin: Vec3::new(5.0, 5.0, 0.0), x_axis: Vec3::new(0.0, 1.0, 0.0), y_axis: Vec3::new(-1.0, 0.0, 0.0) }); + d +} + +fn check(back: &Drawing) { + let h = &back.header; + assert!(near3(h.point("UCSORG").unwrap(), Vec3::new(100.0, 50.0, 0.0))); + assert!(near3(h.point("UCSXDIR").unwrap(), Vec3::new(C30, 0.5, 0.0))); + assert!(near3(h.point("UCSYDIR").unwrap(), Vec3::new(-0.5, C30, 0.0))); + assert_eq!(h.str("UCSNAME", ""), "SITE"); + let l = back.layouts[0].ucs.clone().expect("the layout keeps its UCS"); + assert!(near3(l.origin, Vec3::new(5.0, 5.0, 0.0)) && near3(l.x_axis, Vec3::new(0.0, 1.0, 0.0)) && l.name.is_empty(), "{l:?}"); + assert!(back.layouts.iter().skip(1).all(|l| l.ucs.is_none()), "the other layouts stay in the World UCS"); +} + +#[test] +fn model_and_layout_ucs_survive_a_dxf_save() { + let d = drawing(); + let text = cadcraft_io::write_dxf(&d); + // The header and the shown viewport both carry model space's UCS. + let org = header_var(&text, "UCSORG"); + assert_eq!((num(&org, "10"), num(&org, "20"), num(&org, "30")), (100.0, 50.0, 0.0)); + assert_eq!(group(&header_var(&text, "UCSNAME"), "2"), Some("SITE")); + let active = records(&text, "VPORT").into_iter().find(|r| group(r, "2").is_some_and(|n| n.eq_ignore_ascii_case("*ACTIVE"))).unwrap(); + assert_eq!((num(&active, "110"), num(&active, "120")), (100.0, 50.0)); + assert!((num(&active, "111") - C30).abs() < 1e-12 && group(&active, "65") == Some("1")); + // The layout object carries the layout's. + let lay = layout_record(&text, &d.layouts[0].name); + assert_eq!((num(&lay, "13"), num(&lay, "23"), num(&lay, "16"), num(&lay, "26")), (5.0, 5.0, 0.0, 1.0)); + assert!(group(&lay, "345").is_none(), "unnamed: no UCS record"); + check(&cadcraft_io::read_dxf(text.as_bytes()).unwrap()); +} + +#[test] +fn a_layouts_named_ucs_points_at_its_record() { + let mut d = drawing(); + d.layouts[0].ucs.as_mut().unwrap().name = "SITE".into(); + let text = cadcraft_io::write_dxf(&d); + let site = records(&text, "UCS").into_iter().find(|r| group(r, "2") == Some("SITE")).and_then(|r| group(&r, "5").map(str::to_string)).unwrap(); + let lay = layout_record(&text, &d.layouts[0].name); + assert_eq!(group(&lay, "345"), Some(site.as_str())); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + assert_eq!(back.layouts[0].ucs.as_ref().unwrap().name, "SITE"); + // A deleted named UCS isn't pointed at, and the layout keeps the axes unnamed. + let mut gone = back.clone(); + gone.ucss.clear(); + let text = cadcraft_io::write_dxf(&gone); + let lay = layout_record(&text, &d.layouts[0].name); + assert!(group(&lay, "345").is_none()); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let u = back.layouts[0].ucs.clone().unwrap(); + assert!(u.name.is_empty() && near3(u.x_axis, Vec3::new(0.0, 1.0, 0.0))); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn model_and_layout_ucs_survive_a_dwg_save() { + let d = drawing(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + check(&back); + // And a second trip. + let again = cadcraft_io::read(&cadcraft_io::write(&back, "x.dwg").unwrap(), "x.dwg").unwrap(); + check(&again); +} + +#[test] +fn a_drawing_in_the_world_ucs_is_written_as_before() { + let d = Drawing::default(); + let text = cadcraft_io::write_dxf(&d); + assert!(header_var(&text, "UCSORG").is_empty(), "nothing set, nothing written"); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + assert!(back.layouts.iter().all(|l| l.ucs.is_none())); + assert!(back.header.point("UCSXDIR").is_none_or(|x| near3(x, Vec3::new(1.0, 0.0, 0.0)))); +} + +#[test] +fn a_tilted_ucs_is_kept_as_it_is() { + let mut d = Drawing::default(); + d.header.set("UCSORG", HVal::Point(Vec3::new(0.0, 0.0, 10.0))); + d.header.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0))); + d.header.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0))); + d.ucss.push(Ucs { name: "FRONT".into(), origin: Vec3::ZERO, x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 0.0, 1.0) }); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + assert!(near3(back.header.point("UCSYDIR").unwrap(), Vec3::new(0.0, 0.0, 1.0))); + assert!(near3(back.header.point("UCSORG").unwrap(), Vec3::new(0.0, 0.0, 10.0))); + assert!(near3(back.ucss[0].y_axis, Vec3::new(0.0, 0.0, 1.0))); +} + +#[test] +fn broken_ucs_values_are_not_written_back() { + let mut d = Drawing::default(); + d.header.set("UCSORG", HVal::Point(Vec3::new(f64::NAN, 1.0, 0.0))); + d.header.set("UCSXDIR", HVal::Point(Vec3::ZERO)); + d.header.set("UCSYDIR", HVal::Point(Vec3::new(f64::INFINITY, 0.0, 0.0))); + d.layouts[0].ucs = Some(Ucs { name: "X".into(), origin: Vec3::new(f64::NAN, 0.0, 0.0), x_axis: Vec3::ZERO, y_axis: Vec3::ZERO }); + let text = cadcraft_io::write_dxf(&d); + assert!(!text.to_ascii_lowercase().contains("nan") && !text.to_ascii_lowercase().contains("inf"), "no non-finite numbers written"); + let x = header_var(&text, "UCSXDIR"); + assert_eq!((num(&x, "10"), num(&x, "20")), (1.0, 0.0), "the World UCS's axes instead"); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + assert!(back.layouts[0].ucs.is_none()); +} + +#[test] +fn hostile_layout_ucs_groups_are_ignored() { + let d = Drawing::default(); + let text = cadcraft_io::write_dxf(&d); + let name = d.layouts[0].name.clone(); + // Rewrite the layout's UCS groups as nonsense: no length, along each other, a dangling 345. + for (x, y, h) in [("0.0", "0.0", "FFFF"), ("1.0", "1.0", "0"), ("nan", "1.0", "ZZ")] { + let mut out = String::new(); + let mut in_layout = false; + let mut lines = text.lines(); + while let (Some(c), Some(v)) = (lines.next(), lines.next()) { + let (ct, vt) = (c.trim(), v.trim()); + if ct == "0" { + in_layout = vt == "LAYOUT"; + } + let v = match (in_layout, ct) { + (true, "16") => x.to_string(), + (true, "27") => y.to_string(), + (true, "17") => y.to_string(), + _ => v.to_string(), + }; + out.push_str(&format!("{c}\n{v}\n")); + if in_layout && ct == "76" { + out.push_str(&format!("345\n{h}\n")); + } + } + let back = cadcraft_io::read_dxf(out.as_bytes()).unwrap(); + let l = back.layout(&name).unwrap(); + assert!(l.ucs.as_ref().is_none_or(|u| u.name.is_empty() && u.x_axis.cross(u.y_axis).len() > 1e-9), "{x},{y},{h}: {:?}", l.ucs); + } +} + +#[test] +fn a_stale_ucs_name_copy_is_not_brought_back() { + let text = cadcraft_io::write_dxf(&drawing()); + // As another program would save it after changing the UCS: $UCSNAME cleared, the axes moved, + // CADCraft's copy of the old name still there. + let mut out = String::new(); + let mut lines = text.lines().peekable(); + let mut var = String::new(); + while let (Some(c), Some(v)) = (lines.next(), lines.next()) { + if c.trim() == "9" { + var = v.trim().to_string(); + } + let v = match (var.as_str(), c.trim()) { + ("$UCSNAME", "2") => String::new(), + ("$UCSXDIR", "10") => "0.0".into(), + ("$UCSXDIR", "20") => "1.0".into(), + ("$UCSYDIR", "10") => "-1.0".into(), + ("$UCSYDIR", "20") => "0.0".into(), + _ => v.to_string(), + }; + out.push_str(&format!("{c}\n{v}\n")); + } + let back = cadcraft_io::read_dxf(out.as_bytes()).unwrap(); + assert_eq!(back.header.str("UCSNAME", ""), "", "the UCS is no longer SITE"); + assert!(near3(back.header.point("UCSXDIR").unwrap(), Vec3::new(0.0, 1.0, 0.0))); + // While it still matches, the copy names it (what a DWG round trip relies on). + let mut same = String::new(); + let mut lines = text.lines(); + let mut var = String::new(); + while let (Some(c), Some(v)) = (lines.next(), lines.next()) { + if c.trim() == "9" { + var = v.trim().to_string(); + } + let v = if var == "$UCSNAME" && c.trim() == "2" { String::new() } else { v.to_string() }; + same.push_str(&format!("{c}\n{v}\n")); + } + assert_eq!(cadcraft_io::read_dxf(same.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE"); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e5725e353..4bf102510 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1826,9 +1826,14 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } draw_tiles(app, ui, &tiles); // UCS icon, ViewCube and viewport label. - if app.ui.show_ucs_icon { - draw_ucs_icon(&painter, rect); - crate::viewcube::ucs_icon(app, ui, rect); + if app.session.ucsicon_bits() & 1 != 0 { + let place = crate::viewcube::IconPlace::of(app, rect, |p| xf.to_screen(p)); + draw_ucs_icon(&painter, &place); + // Clickable only at the Command prompt: while a command runs, a pick or a snap at the UCS + // origin (where the icon may sit) reaches the drawing. + if app.session.running.is_none() && app.session.pending_window.is_none() { + crate::viewcube::ucs_icon(app, ui, rect, &place); + } } if app.ui.show_viewcube && sheet.is_none() { draw_viewcube(app, ui, rect); @@ -2243,16 +2248,23 @@ fn draw_lock(p: &egui::Painter, c: Pos2, color: Color32) { )); } -fn draw_ucs_icon(p: &egui::Painter, rect: Rect) { +/// The UCS icon: its X and Y arms along the current UCS's axes, with a square at the corner for +/// the World UCS. +fn draw_ucs_icon(p: &egui::Painter, at: &crate::viewcube::IconPlace) { let t = Tokens::get(); - let o = pos2(rect.left() + 36.0, rect.bottom() - 34.0); + let (o, x, y) = (at.origin, at.x, at.y); + let arm = crate::viewcube::ARM; let st = Stroke::new(1.0, t.canvas_ink); - p.line_segment([o, o + vec2(60.0, 0.0)], st); - p.line_segment([o, o + vec2(0.0, -60.0)], st); - p.rect_stroke(Rect::from_center_size(o, vec2(9.0, 9.0)), 0.0, st, egui::StrokeKind::Middle); + p.line_segment([o, o + x * arm], st); + p.line_segment([o, o + y * arm], st); + if at.world { + let h = 4.5; + let square = vec![o + (x + y) * h, o + (x - y) * h, o - (x + y) * h, o - (x - y) * h]; + p.add(Shape::closed_line(square, st)); + } let f = egui::FontId::proportional(13.0); - p.text(o + vec2(70.0, 0.0), egui::Align2::LEFT_CENTER, crate::tl!("X"), f.clone(), t.canvas_ink); - p.text(o + vec2(0.0, -70.0), egui::Align2::CENTER_BOTTOM, crate::tl!("Y"), f, t.canvas_ink); + p.text(o + x * (arm + 10.0), egui::Align2::CENTER_CENTER, crate::tl!("X"), f.clone(), t.canvas_ink); + p.text(o + y * (arm + 10.0), egui::Align2::CENTER_CENTER, crate::tl!("Y"), f, t.canvas_ink); } fn viewport_label(p: &egui::Painter, rect: Rect) { @@ -2263,13 +2275,12 @@ fn viewport_label(p: &egui::Painter, rect: Rect) { fn draw_viewcube(app: &mut CadApp, ui: &mut egui::Ui, rect: Rect) { let l = crate::viewcube::Layout::new(rect); - let (c, ring) = (l.center, l.ring); let p = ui.painter_at(rect); crate::viewcube::show(app, ui, &l); - // WCS pill. - let pill = Rect::from_center_size(c + vec2(0.0, ring + 26.0), vec2(56.0, 16.0)); + // UCS pill: the current UCS's name. + let pill = l.pill; p.rect_filled(pill, 8.0, Color32::from_rgb(0x48, 0x50, 0x5c)); - p.text(pill.center(), egui::Align2::CENTER_CENTER, crate::tl!("WCS ⌄"), crate::theme::small(), Tokens::DARK.canvas_ink); + p.text(pill.center(), egui::Align2::CENTER_CENTER, ucs_pill_text(app), crate::theme::small(), Tokens::DARK.canvas_ink); } /// A click on grip `g` (idle): Shift+click makes it hot or cold again; a plain click starts @@ -2655,3 +2666,14 @@ mod hatch_pick_tests { assert!(app.session.running.is_none(), "{:?}", app.session.running.as_ref().map(|r| r.machine.name())); } } + +/// The ViewCube pill's text: WCS, or the current UCS's name (cut short), and the menu arrow. +fn ucs_pill_text(app: &CadApp) -> String { + let (u, name) = app.session.ucs_named(); + if u.is_world() && name.is_empty() { + return crate::tl!("WCS ⌄").to_string(); + } + let n = if name.is_empty() { crate::tl!("Unnamed").to_string() } else { name }; + let short: String = if n.chars().count() > 8 { n.chars().take(7).chain(std::iter::once('…')).collect() } else { n }; + format!("{short} ⌄") +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 3e0860e31..82c9de845 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -347,8 +347,9 @@ pub fn status_bar(app: &mut CadApp, ui: &mut egui::Ui) { ]; let size = 20.0; let mut rx = r.right() - 8.0 - toggles.len() as f32 * (size + 4.0); - // Coordinates. + // Coordinates, in the current UCS. let coord = app.canvas.cursor.map(|c| { + let c = app.session.ucs_point(c); let (lu, lp) = app.session.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4)); format!( "{}, {}, {}", diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index c136b7032..5f945d0a6 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -47,7 +47,8 @@ pub fn dyn_frame(app: &CadApp) -> Option { return None; } let p = app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts)?; - Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute }) + let ucs = app.session.input_ucs(); + Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, ucs }) } /// Take Tab away from egui before it moves keyboard focus to the next widget (which would leave diff --git a/crates/ui-egui/src/dyninput.rs b/crates/ui-egui/src/dyninput.rs index 229ba1739..efe6fefec 100644 --- a/crates/ui-egui/src/dyninput.rs +++ b/crates/ui-egui/src/dyninput.rs @@ -48,6 +48,8 @@ pub struct Frame { pub cartesian: bool, /// DYNPICOORDS = 1: second and next points are absolute instead of relative. pub absolute: bool, + /// The UCS the boxes read and show values in (the engine reads the sent text in it too). + pub ucs: cadcraft_engine::ucs::UcsFrame, } impl Frame { @@ -55,10 +57,11 @@ impl Frame { pub fn default_format(&self) -> Format { if self.base.is_some() && !self.cartesian { Format::Polar } else { Format::Cartesian } } - /// Where the typed values are measured from. + /// Where the typed values are measured from, in UCS coordinates: the last point, or the UCS + /// origin. pub fn origin(&self) -> Vec2 { match self.base { - Some(b) if !self.absolute => b, + Some(b) if !self.absolute => self.ucs.to_ucs(b), _ => Vec2::ZERO, } } @@ -67,9 +70,9 @@ impl Frame { self.base.is_some() && !self.absolute } - /// The live (X, Y) or (distance, angle in radians) of `cursor`. + /// The live (X, Y) or (distance, angle in radians) of `cursor` (a world point), in the UCS. pub fn live(&self, format: Format, cursor: Vec2) -> (f64, f64) { - let d = cursor - self.origin(); + let d = self.ucs.to_ucs(cursor) - self.origin(); match format { Format::Cartesian => (d.x, d.y), Format::Polar => (d.len(), d.y.atan2(d.x)), @@ -145,32 +148,35 @@ pub fn can_lock_second(text: &str, frame: &Frame) -> bool { /// when Tab has locked the second one too (`second_locked`), which pins the cursor to the point. pub fn constrain(entry: &Entry<'_>, frame: &Frame, p: Vec2, second_locked: bool) -> Vec2 { let Some(v) = entry.first_locked() else { return p }; - let o = frame.origin(); + // In UCS coordinates; `p` and the result are world points. + let (o, u) = (frame.origin(), frame.ucs.to_ucs(p)); if second_locked && let Some(w) = entry.second_value() { let q = match entry.format { Format::Cartesian => o + Vec2::new(v, w), Format::Polar => o + Vec2::from_angle(w) * v, }; if q.is_finite() { - return q; + return frame.ucs.to_wcs(q); } } - match entry.format { - Format::Cartesian => Vec2::new(o.x + v, p.y), + let q = match entry.format { + Format::Cartesian => Vec2::new(o.x + v, u.y), Format::Polar => { - let d = p - o; + let d = u - o; let l = d.len(); let dir = if l > 1e-12 { d * (1.0 / l) } else { Vec2::X }; o + dir * v } - } + }; + frame.ucs.to_wcs(q) } /// The command-line text to send for a finished entry, or `None` to send the text as typed /// (nothing split yet: a plain number stays direct distance entry). Empty boxes take the cursor's /// value. Entries measured from the last point are sent with `@` when the prompt's base is the /// session's last point (`last`, what `@` resolves against); otherwise, and for absolute entries, -/// the finished point is sent as `#x,y`, so what was previewed is exactly what is placed. +/// the finished point is sent as `#x,y` (UCS coordinates), so what was previewed is exactly what +/// is placed. pub fn complete(entry: &Entry<'_>, frame: &Frame, cursor: Vec2, last: Vec2) -> Option { if !entry.split { return None; @@ -181,7 +187,8 @@ pub fn complete(entry: &Entry<'_>, frame: &Frame, cursor: Vec2, last: Vec2) -> O if frame.relative() && frame.base == Some(last) { return Some(match entry.format { Format::Cartesian => format!("@{first},{second}"), - // `<<`: degrees from +X counterclockwise, as previewed, whatever ANGBASE/ANGDIR say. + // `<<`: degrees from the UCS X axis counterclockwise, as previewed, whatever + // ANGBASE/ANGDIR say. Format::Polar => format!("@{first}<<{}", second.to_degrees()), }); } @@ -230,7 +237,7 @@ mod tests { use super::*; fn second_point(base: Vec2) -> Frame { - Frame { base: Some(base), cartesian: false, absolute: false } + Frame { base: Some(base), cartesian: false, absolute: false, ..Frame::default() } } fn sent(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option { @@ -268,6 +275,44 @@ mod tests { assert_eq!(tab_separator("rec", &polar), None); } + /// `sent` with the engine reading the text in the frame's UCS, as the command line does. + fn sent_in(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option { + let e = parse(text, frame)?; + let t = complete(&e, frame, cursor, last)?; + let angles = cadcraft_engine::units::AngleSettings { ucs: frame.ucs.rotation(), ..Default::default() }; + cadcraft_engine::prompt::parse_point_in(&t, last, &angles, &frame.ucs) + } + + #[test] + fn the_boxes_read_and_show_values_in_the_ucs() { + // The UCS at (100, 50) turned 90°: UCS X is world +Y. + let ucs = + cadcraft_engine::ucs::UcsFrame::WORLD.with_origin(cadcraft_geom::Vec3::new(100.0, 50.0, 0.0)).rotated_z(std::f64::consts::FRAC_PI_2); + let first = Frame { ucs, ..Frame::default() }; + assert!(close(sent_in("10,0", &first, Vec2::ZERO, Vec2::ZERO), Vec2::new(100.0, 60.0)), "absolute: from the UCS origin"); + let base = Vec2::new(100.0, 60.0); + let f = Frame { base: Some(base), ucs, ..Frame::default() }; + assert!(close(sent_in("5,0", &f, Vec2::ZERO, base), Vec2::new(100.0, 65.0)), "relative along the UCS axes"); + assert!(close(sent_in("10<0", &f, Vec2::ZERO, base), Vec2::new(100.0, 70.0)), "angles from the UCS X axis"); + assert!(close(sent_in("10<90", &f, Vec2::ZERO, base), Vec2::new(90.0, 60.0))); + // Not relative to the last point: sent as `#x,y` in the UCS, placed where it was previewed. + assert!(close(sent_in("5,0", &f, Vec2::ZERO, Vec2::new(-1.0, -1.0)), Vec2::new(100.0, 65.0))); + let abs = Frame { absolute: true, cartesian: true, ..f }; + assert!(close(sent_in("10,5", &abs, Vec2::ZERO, base), Vec2::new(95.0, 60.0))); + // The live values are the cursor's, measured in the UCS. + let (x, y) = f.live(Format::Cartesian, Vec2::new(97.0, 70.0)); + assert!((x - 10.0).abs() < 1e-9 && (y - 3.0).abs() < 1e-9, "{x} {y}"); + let (d, a) = f.live(Format::Polar, Vec2::new(100.0, 70.0)); + assert!((d - 10.0).abs() < 1e-9 && a.abs() < 1e-9, "{d} {a}"); + // A locked value holds the cursor along the UCS axes, and Enter sends that point. + let e = parse("3,", &f).unwrap(); + let held = constrain(&e, &f, Vec2::new(80.0, 99.0), false); + assert!(close(Some(held), Vec2::new(80.0, 63.0)), "{held:?}"); + assert!(close(sent_in("3,", &f, Vec2::new(80.0, 99.0), base), Vec2::new(80.0, 63.0))); + let e = parse("4<", &f).unwrap(); + assert!(close(Some(constrain(&e, &f, Vec2::new(100.0, 90.0), false)), Vec2::new(100.0, 64.0))); + } + #[test] fn first_point_is_absolute() { let f = Frame::default(); @@ -276,7 +321,7 @@ mod tests { #[test] fn absolute_setting_measures_from_the_origin() { - let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true }; + let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true, ..Frame::default() }; assert!(close(sent("40,100", &f, Vec2::ZERO, Vec2::new(5.0, 5.0)), Vec2::new(40.0, 100.0))); } diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index adce43ae7..bd68113e3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1330,3 +1330,11 @@ Justify За шириною Text color Колір тексту Click the ruler to add a tab stop, right-click to remove one Натисніть на лінійку, щоб додати табуляцію; права кнопка видаляє її + 3 Point 3 точки + New UCS Нова СКК + Origin Початок координат + UCS СКК + UCS Icon at Origin Піктограма СКК на початку координат + World Світова + Z Z + Unnamed Без назви diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 91c48e5f8..e9fc41f97 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -77,7 +77,6 @@ pub struct UiState { pub show_status_bar: bool, pub show_command_line: bool, pub show_viewcube: bool, - pub show_ucs_icon: bool, pub show_layer_list: bool, /// Keep the system cursor visible over the drawing area (a small crosshair at the centre of the /// drawn one) instead of hiding it. Screen magnifiers (Windows Magnifier "follow the mouse @@ -163,7 +162,6 @@ impl Default for UiState { show_status_bar: true, show_command_line: true, show_viewcube: true, - show_ucs_icon: true, show_layer_list: false, system_cursor: std::env::var("CADCRAFT_SYSTEM_CURSOR").is_ok_and(|v| !matches!(v.trim(), "" | "0" | "false" | "off")), toolset_tab: "Drafting".into(), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9672270f7..67103acdc 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -39,6 +39,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.toggle.cmdline", "Command Line", &["Window", "Command Line"], Some("Cmd+9")), ("ui.toggle.viewcube", "ViewCube", &["View", "ViewCube", "On"], None), ("ui.toggle.ucsicon", "UCS Icon", &["View", "UCS Icon", "On"], None), + ("ui.toggle.ucsicon.origin", "UCS Icon at Origin", &["View", "UCS Icon", "Origin"], None), ("ui.theme.system", "Use System Setting", &["View", "Interface Theme", "Use System Setting"], None), ("ui.theme.light", "Light", &["View", "Interface Theme", "Light"], None), ("ui.theme.dark", "Dark", &["View", "Interface Theme", "Dark"], None), @@ -238,9 +239,12 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { - toggle(&mut app.ui.show_ucs_icon, params); - Ok(Value::Null) + // UCSICON's bits, through its command: 1 shown, 2 at the UCS origin. + "ui.toggle.ucsicon" | "ui.toggle.ucsicon.origin" => { + let (key, bit) = if id == "ui.toggle.ucsicon" { ("on", 1) } else { ("origin", 2) }; + let mut on = app.session.ucsicon_bits() & bit != 0; + toggle(&mut on, params); + app.run("ucsicon", json!({ key: on })) } "ui.toggle.menubar" => { toggle(&mut app.ui.in_window_menu, params); diff --git a/crates/ui-egui/src/viewcube.rs b/crates/ui-egui/src/viewcube.rs index 6f3ec0a3d..e871ec069 100644 --- a/crates/ui-egui/src/viewcube.rs +++ b/crates/ui-egui/src/viewcube.rs @@ -1,14 +1,14 @@ //! The navigation overlays on the drawing area: the ViewCube (Top face, Home, compass ring and -//! the WCS menu) and the UCS icon. +//! the UCS menu) and the UCS icon. //! //! Every overlay registers a widget that senses clicks *and* drags, so egui hands the pointer to //! the overlay instead of the canvas underneath (a click on the ViewCube must never also pick or //! start a selection window in the drawing). What the overlays do goes through commands: -//! `zoom.extents` (Top face, Home), `ui.toggle.viewcube`, `ui.toggle.ucsicon`. +//! `zoom.extents` (Top face, Home), `ui.toggle.viewcube`, `ui.toggle.ucsicon`, `ucs`. //! -//! CADCraft's model view is a 2D plan view of the World Coordinate System: there is no view -//! twist, no 3D view direction and no user coordinate system yet, so the compass ring explains -//! that instead of rotating, and the WCS menu lists the only coordinate system there is. +//! CADCraft's model view is a 2D plan view: there is no view twist and no 3D view direction yet, +//! so the compass ring explains that instead of rotating. The UCS menu lists World and the +//! drawing's named UCSs. use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, pos2, vec2}; use serde_json::json; @@ -42,7 +42,7 @@ impl Layout { ring, face: Rect::from_center_size(center, vec2(44.0, 44.0)), home: Rect::from_center_size(center + vec2(-ring + 2.0, -ring + 2.0), vec2(20.0, 20.0)), - pill: Rect::from_center_size(center + vec2(0.0, ring + 26.0), vec2(56.0, 16.0)), + pill: Rect::from_center_size(center + vec2(0.0, ring + 26.0), vec2(84.0, 16.0)), bounds: Rect::from_center_size(center, vec2(2.0 * (ring + 10.0), 2.0 * (ring + 10.0))), } } @@ -131,7 +131,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, l: &Layout) { if let Some((id, params)) = action { let _ = app.run(id, params); } - // The WCS pill (painted by the canvas) opens the coordinate-system menu. + // The UCS pill (painted by the canvas, wide enough for a cut-short UCS name) opens the + // coordinate-system menu. let pill = ui.interact(l.pill, ui.id().with("viewcube_wcs"), Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand); let pill = pill.on_hover_text("Coordinate system"); ucs_menu(app, egui::Popup::menu(&pill)); @@ -153,45 +154,119 @@ fn paint_home(p: &egui::Painter, r: Rect, hot: bool) { p.line_segment([c + vec2(-1.2, 2.5), c + vec2(1.2, 2.5)], st); } -/// The UCS icon's arms (as drawn by the canvas at the lower-left corner): the X arm and the Y arm. -pub fn ucs_arms(canvas: Rect) -> [Rect; 2] { - let o = pos2(canvas.left() + 36.0, canvas.bottom() - 34.0); - [Rect::from_min_max(o + vec2(-8.0, -8.0), o + vec2(80.0, 8.0)), Rect::from_min_max(o + vec2(-8.0, -82.0), o + vec2(8.0, 8.0))] +/// How long the UCS icon's arms are, in points. +pub const ARM: f32 = 60.0; + +/// Where the UCS icon is drawn: the point its arms start from, the screen directions of its X +/// and Y arms (unit vectors: the current UCS's axes seen in the plan view) and whether the UCS is +/// the World UCS (the icon then has a square at its corner). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct IconPlace { + pub origin: Pos2, + pub x: egui::Vec2, + pub y: egui::Vec2, + pub world: bool, +} + +impl IconPlace { + /// The World UCS's icon at the lower-left corner of the drawing area. + pub fn corner(canvas: Rect) -> IconPlace { + IconPlace { origin: pos2(canvas.left() + 36.0, canvas.bottom() - 34.0), x: vec2(1.0, 0.0), y: vec2(0.0, -1.0), world: true } + } + + /// The icon for the current UCS: at its origin when UCSICON asks for that (ORigin) and the + /// whole icon fits there, else at the corner. `to_screen` maps a point of the space shown. + pub fn of(app: &CadApp, canvas: Rect, to_screen: impl Fn(cadcraft_geom::Vec2) -> Pos2) -> IconPlace { + let u = app.session.input_ucs(); + let dir = |v: cadcraft_geom::Vec3, or: egui::Vec2| { + let d = vec2(v.x as f32, -(v.y as f32)); + let l = d.length(); + if l.is_finite() && l > 1e-6 { d / l } else { or } + }; + let mut place = IconPlace { x: dir(u.x, vec2(1.0, 0.0)), y: dir(u.y, vec2(0.0, -1.0)), world: u.is_world(), ..IconPlace::corner(canvas) }; + // At the origin only where the screen shows the space the UCS belongs to (not from paper + // space into an active viewport). + let same_space = app.session.space() == app.session.layout_space(); + if app.session.ucsicon_bits() & 2 != 0 && same_space { + let at = to_screen(u.origin.xy()); + let reach = ARM + 16.0; + let inner = canvas.shrink(12.0); + if [at, at + place.x * reach, at + place.y * reach].iter().all(|p| p.x.is_finite() && p.y.is_finite() && inner.contains(*p)) { + place.origin = at; + } + } + place + } + + /// The icon's arms with room around them: the X arm and the Y arm. + pub fn arms(&self) -> [Rect; 2] { + let o = self.origin; + [Rect::from_two_pos(o, o + self.x * (ARM + 20.0)).expand(8.0), Rect::from_two_pos(o, o + self.y * (ARM + 22.0)).expand(8.0)] + } +} + +/// How the current UCS is named on screen. +fn ucs_label(app: &CadApp) -> String { + let (u, name) = app.session.ucs_named(); + if u.is_world() && name.is_empty() { + "World Coordinate System".into() + } else if name.is_empty() { + "Unnamed UCS".into() + } else { + name + } } /// Make the UCS icon clickable: hovering highlights it, a click (either button) opens the /// coordinate-system menu. -pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { +pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect, place: &IconPlace) { let t = Tokens::get(); - let [x, y] = ucs_arms(canvas); + let [x, y] = place.arms(); let rx = ui.interact(x, ui.id().with("ucs_x"), Sense::click_and_drag()); let ry = ui.interact(y, ui.id().with("ucs_y"), Sense::click_and_drag()); - let resp = (rx | ry).on_hover_cursor(CursorIcon::PointingHand).on_hover_text("UCS icon: World Coordinate System"); + let resp = (rx | ry).on_hover_cursor(CursorIcon::PointingHand).on_hover_text(format!("UCS icon: {}", ucs_label(app))); if resp.hovered() { - let o = pos2(x.left() + 8.0, x.center().y); + let o = place.origin; let st = Stroke::new(2.0, t.hover); let p = ui.painter_at(canvas); - p.line_segment([o, o + vec2(60.0, 0.0)], st); - p.line_segment([o, o + vec2(0.0, -60.0)], st); + p.line_segment([o, o + place.x * ARM], st); + p.line_segment([o, o + place.y * ARM], st); } // Opened with `Bool(true)`: a pointer-anchored popup records its position only then. let open = (resp.clicked() || resp.secondary_clicked()).then_some(egui::SetOpenCommand::Bool(true)); ucs_menu(app, egui::Popup::menu(&resp).open_memory(open).at_pointer_fixed()); } -/// The coordinate-system menu: the WCS (the only coordinate system so far) and the icon switch. +/// The coordinate-system menu: World, the drawing's named UCSs (picking one makes it current, +/// through the UCS command) and the icon switch. fn ucs_menu(app: &mut CadApp, popup: egui::Popup<'_>) { - let mut hide = false; + let (u, current) = app.session.ucs_named(); + let names: Vec = app.session.doc().map(|d| d.ucss.iter().map(|u| u.name.clone()).collect()).unwrap_or_default(); + let mut action: Option<(&str, serde_json::Value)> = None; popup.show(|ui| { - ui.radio(true, "World (WCS)").on_hover_text("CADCraft draws in the World Coordinate System; user coordinate systems aren't available yet."); + if ui.radio(u.is_world() && current.is_empty(), "World (WCS)").clicked() { + action = Some(("ucs.world", json!({}))); + ui.close(); + } + for n in &names { + if ui.radio(current.eq_ignore_ascii_case(n), n.as_str()).clicked() { + action = Some(("ucs", json!({"option": "named", "action": "restore", "name": n}))); + ui.close(); + } + } + if !u.is_world() && current.is_empty() { + let _ = ui.radio(true, "Unnamed"); + } ui.separator(); if ui.button("Hide UCS Icon").clicked() { - hide = true; + action = Some(("ui.toggle.ucsicon", json!({"on": false}))); ui.close(); } }); - if hide { - let _ = app.run("ui.toggle.ucsicon", json!({"on": false})); + if let Some((id, params)) = action + && let Err(e) = app.run(id, params) + { + app.session.echo(e); } } @@ -281,11 +356,48 @@ mod tests { assert!(app.session.pending_window.is_some(), "an empty-space click starts a selection window"); } + #[test] + fn the_ucs_icon_follows_the_ucs() { + let (mut app, _ctx) = app_and_ctx(); + let c = canvas(&app); + // A plain mapping: the canvas centre is world (0, 0), one point per unit. + let to_screen = |p: cadcraft_geom::Vec2| pos2(c.center().x + p.x as f32, c.center().y - p.y as f32); + let world = IconPlace::of(&app, c, to_screen); + assert!(world.world && (world.x - vec2(1.0, 0.0)).length() < 1e-6 && (world.y - vec2(0.0, -1.0)).length() < 1e-6); + // At the World origin (on screen, with ORigin on by default). + assert!((world.origin - c.center()).length() < 1e-3, "{:?} vs {:?}", world.origin, c.center()); + // A UCS turned 90° at (20, 10): the X arm points up the screen, the Y arm left. + app.run("ucs", json!({"option": "origin", "origin": [20, 10]})).unwrap(); + app.run("ucs", json!({"option": "z", "angle": 90})).unwrap(); + let p = IconPlace::of(&app, c, to_screen); + assert!(!p.world); + assert!((p.x - vec2(0.0, -1.0)).length() < 1e-6 && (p.y - vec2(-1.0, 0.0)).length() < 1e-6, "{p:?}"); + assert!((p.origin - pos2(c.center().x + 20.0, c.center().y - 10.0)).length() < 1e-3); + // Its click areas lie along the turned arms. + let [ax, ay] = p.arms(); + assert!(ax.contains(p.origin + p.x * 40.0) && ay.contains(p.origin + p.y * 40.0)); + // Noorigin, or an origin off screen: the corner. + app.run("ucsicon", json!({"origin": false})).unwrap(); + assert_eq!(IconPlace::of(&app, c, to_screen).origin, IconPlace::corner(c).origin); + app.run("ucsicon", json!({"origin": true})).unwrap(); + app.run("ucs", json!({"option": "origin", "origin": [1e6, 0]})).unwrap(); + assert_eq!(IconPlace::of(&app, c, to_screen).origin, IconPlace::corner(c).origin); + // The menu switch turns UCSICON off through its command. + app.run("ui.toggle.ucsicon", json!({"on": false})).unwrap(); + assert_eq!(app.session.ucsicon_bits() & 1, 0); + app.run("ui.toggle.ucsicon", json!({})).unwrap(); + assert_eq!(app.session.ucsicon_bits() & 1, 1, "a toggle without `on` flips it"); + app.run("ui.toggle.ucsicon.origin", json!({"on": false})).unwrap(); + assert_eq!(app.session.ucsicon_bits(), 1); + } + #[test] fn ucs_icon_and_wcs_pill_open_the_coordinate_system_menu() { let (mut app, ctx) = app_and_ctx(); - let [x, _] = ucs_arms(canvas(&app)); - click(&mut app, &ctx, x.center(), egui::PointerButton::Primary); + // Where the canvas drew it: at the World origin when that is on screen (UCSICON 3). + let xf = app.canvas.xf.expect("laid out"); + let place = IconPlace::of(&app, canvas(&app), |p| xf.to_screen(p)); + click(&mut app, &ctx, place.origin + place.x * 40.0, egui::PointerButton::Primary); assert!(menu_shown(&ctx), "UCS icon menu"); assert!(app.session.pending_window.is_none(), "the click stayed on the icon"); let l = Layout::new(canvas(&app)); diff --git a/docs/autolisp.md b/docs/autolisp.md index b75ad7ed1..1fce7588f 100644 --- a/docs/autolisp.md +++ b/docs/autolisp.md @@ -63,7 +63,7 @@ reached", malformed source is a reader error, and every built-in checks its argu `vl-string-search vl-string-subst vl-string-trim vl-string-left-trim vl-string-right-trim vl-string-translate vl-string->list vl-list->string vl-prin1-to-string vl-princ-to-string vl-symbol-name vl-symbol-value vl-filename-base vl-filename-extension vl-filename-directory` -- **Geometry:** `polar distance angle inters trans` (`trans` returns the point: no UCS yet) +- **Geometry:** `polar distance angle inters trans` (`trans` between the WCS (0), the current UCS (1), display coordinates (2, 3: the WCS in a plan view) and an object's OCS (an entity name or an extrusion direction); `getpoint` and friends answer in the current UCS and `command` takes UCS points, while entity lists stay in world coordinates) - **Output and files:** `princ prin1 print prompt terpri alert open close read-line write-line findfile` - **Errors:** `*error*`, `vl-catch-all-apply vl-catch-all-error-p vl-catch-all-error-message` diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5b3a94ce8..c9942e0b6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -88,7 +88,7 @@ early (#175), but the throughput problem remains. **DWG ≈ 30% read, ≈ 15% wr | 3DSOLID, BODY, SURFACE, MESH, SHAPE, UNDERLAY, OLE2FRAME, LIGHT, CAMERA, SECTION, POINTCLOUD, proxy entities | kept as Unknown (raw tags) | written back as read, with their CLASS records (#528); **dropped by DWG save** (acadrust) | only their layer follows edits | | Header variables | all read | 36 written | AutoCAD writes about 280 | | Tables: LAYER (+ transparency, description), LTYPE, STYLE, DIMSTYLE, BLOCK_RECORD | yes | yes | | -| Tables: VPORT, VIEW, UCS, APPID | yes | yes: saved viewport configurations (#504), named views, UCSs | UCS elevation lost | +| Tables: VPORT, VIEW, UCS, APPID | yes | yes: saved viewport configurations (#504), named views, UCSs; the current UCS of model space ($UCSORG, $UCSXDIR, $UCSYDIR, $UCSNAME, and the shown VPORT's 110–112) and of each layout (LAYOUT 13, 16, 17, 345) (#1106) | UCS elevation lost; DWG: the bridge drops $UCSNAME (it survives a CADCraft round trip in an XRECORD) | | Objects: LAYOUT, DICTIONARY, XRECORD, TABLESTYLE, DIMASSOC | yes | yes | | | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read | not editable | @@ -135,6 +135,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-17 | minor | The current UCS of model space (header and the shown VPORT) and of each layout (LAYOUT object) is read and written, through DXF and DWG (#1106) | | 2026-10-12 | minor | PDF output: object transparency plotted as PDF alpha (`/ExtGState` `/ca` `/CA`) when the page setup's or the plot's "Plot transparency" is on; PNG plots blend it, SVG uses `opacity`; plots without it are unchanged byte for byte | | 2026-10-12 | minor | DXF/DWG save: the Model layout's plot settings are written as CADCraft plots model space, drawing extents scaled to fit (PLOTSETTINGS 74 = 1, 75 = 0), instead of plot type 5 "Layout information", which other programs' Plot dialogs can't use for model space | | 2026-10-12 | minor | VIEWPORT frozen layers also written and read as AutoCAD's group 341 layer handles, so third-party viewers honour per-viewport freezing in DXF (DWG converter gap noted) | diff --git a/docs/gaps.md b/docs/gaps.md index 0adb80f12..9ec5c6e26 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -45,7 +45,7 @@ do them first. | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT has no Merged Tee and tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data); PURGE skips multiline styles | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | | F22 | Inquiry leftovers (COUNT across spaces and nested blocks, the QuickCalc palette and COMPARE landed, #563; MASSPROP on regions, #510): COMPARE compares the tab shown, not every layout at once, and has no COMPAREEXPORT report; QuickCalc keeps its history and variables for the session only | `file/compare.rs`, `palettes/quickcalc.rs` | Low | 3–5 | | F23 | No Sheet Set Manager, eTransmit, Share, Traces, Markup Import, Activity Insights | menu items uncovered | Low-medium (team workflows) | 40–70 | -| F24 | No 3D: UCS, 3D views, orbit, solids, surfaces, meshes, sections, visual styles, materials, lights, rendering (150 menu items) | [parity-checklist](parity-checklist.md) | Medium (3D users) | 300–450 | +| F24 | No 3D: UCSs tilted out of the XY plane (UCS X, Y, ZAxis and Face say "not available yet"; the UCS command, UCSICON and UCSs in the XY plane landed with #1106), 3D views, orbit, solids, surfaces, meshes, sections, visual styles, materials, lights, rendering (150 menu items) | [parity-checklist](parity-checklist.md) | Medium (3D users) | 300–450 | ## UI/UX @@ -128,7 +128,7 @@ Detail: [localization-parity.md](localization-parity.md). | # | Gap | Est. | |---|---|---| -| E1 | AutoLISP beyond the core (#758 landed the language, `command`, entity lists, selection sets, `get…` input, APPLOAD, `(load)`, `c:` commands and `acad.lsp`/`acaddoc.lsp` at startup): Visual LISP ActiveX (`vlax-`, `vla-`), DCL dialogs, reactors, an APPLOAD dialog with a Startup Suite, UCS-aware `trans` | 30–50 | +| E1 | AutoLISP beyond the core (#758 landed the language, `command`, entity lists, selection sets, `get…` input, APPLOAD, `(load)`, `c:` commands and `acad.lsp`/`acaddoc.lsp` at startup): Visual LISP ActiveX (`vlax-`, `vla-`), DCL dialogs, reactors, an APPLOAD dialog with a Startup Suite (`trans` and `get…` work in the current UCS, #1106) | 30–50 | | E3 | Express Tools equivalents (TXT2MTXT, BREAKLINE, BURST, NCOPY exists, SUPERHATCH, Move/Copy/Rotate) | 30–50 | | E4 | Plug-in API (owner decision: Rust/WASM plug-ins rather than ObjectARX/.NET) | 30–50 | | E5 | CUI customisation and alias (`.pgp`) editor | 15–25 | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9d76332c7..1d8d9302d 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-12 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-17 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 280 / 491 items (57%)** · 409 registered commands. +**Menu breadth: 289 / 491 items (59%)** · 433 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 11 | 85% | -| View | 75 | 31 | 41% | +| View | 75 | 32 | 43% | | Insert | 11 | 5 | 45% | | Format | 27 | 25 | 93% | -| Tools | 85 | 57 | 67% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 64 | 75% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 52 | 46% | | Window | 22 | 3 | 14% | @@ -68,7 +68,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > Light Glyphs - View > Render > Materials Browser - View > UCS Icon > On -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > On - View > ViewCube > Settings @@ -88,18 +87,11 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Inquiry > Volume - Tools > Update Fields -- Tools > Block Editor - Tools > Edit Xref in Place -- Tools > Load Application... -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Customize > Edit Command Aliases (PGP)... @@ -143,7 +135,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5495d4813..4d31efc47 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -42,8 +42,8 @@ ignored; there are no context menus. Remaining: **≈ 110–170 Opus 5.5 hours** | Input | AutoCAD | CADCraft | Evidence | |---|---|---|---| -| `x,y[,z]`, `@dx,dy`, `@d Date: Sun, 18 Oct 2026 12:46:06 +1100 Subject: [PATCH 013/531] UCS: ortho, snap, grid, polar and object snap tracking, and DIMLINEAR follow the current UCS (part of #1106) The drafting aids worked along the world axes whatever the UCS; now they work along the current UCS's. - Ortho (and direct distance entry with it, and TK tracking) along the UCS axes; the isometric axes turn with the UCS. Settings::ucs_angle, filled in by drafting_settings(), carries the UCS rotation. - Grid and grid snap in the UCS: SNAPBASE is a UCS point and SNAPANG an angle from its X axis (snap::grid_frame_in). The rectangular grid is drawn in that frame, so it also honours SNAPANG and SNAPBASE now (its snap already did); the red and green axes are the UCS's. - Polar tracking measured from ANGBASE off the UCS X axis; object snap tracking's orthogonal paths along the UCS axes; the tracking tooltip reads the angle in the UCS. - DIMLINEAR horizontal and vertical (automatic and the keywords) along the UCS axes at the command line; JSON stays in world coordinates. - Ortho at the cursor keeps the full drafting settings (isometric snap steps), not the copy grid snap hands back. Tests: ortho through the cursor and direct distance entry, grid snap and the grid frame with SNAPBASE/SNAPANG, polar tracking and the tracking configuration, isometric axes, DIMLINEAR, and the World UCS unchanged. --- crates/engine/src/cmd/annotate.rs | 39 +++++- crates/engine/src/lib.rs | 7 + crates/engine/src/lisp/ucs_tests.rs | 27 ++++ crates/engine/src/pointmod.rs | 4 +- crates/engine/src/snap.rs | 27 +++- crates/engine/src/snap/iso.rs | 10 +- crates/engine/src/snap/tracking.rs | 20 +-- crates/engine/tests/ucs_drafting.rs | 206 ++++++++++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 71 ++++++---- docs/ui-parity.md | 6 +- 10 files changed, 362 insertions(+), 55 deletions(-) create mode 100644 crates/engine/tests/ucs_drafting.rs diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index 48254955a..97717d854 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -149,8 +149,15 @@ fn auto_rotation(p1: Vec2, p2: Vec2, at: Vec2) -> f64 { if outside_x && !outside_y { std::f64::consts::FRAC_PI_2 } else { 0.0 } } -fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option, aligned: bool) -> DimKind { - if aligned { DimKind::Aligned } else { DimKind::Linear { rotation: rotation.unwrap_or_else(|| auto_rotation(p1, p2, at)) } } +/// A linear or aligned dimension's kind; without a rotation, horizontal or vertical along axes turned +/// `ucs` radians (the current UCS's at the command line; the world's for JSON). +fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option, aligned: bool, ucs: f64) -> DimKind { + if aligned { + return DimKind::Aligned; + } + let ucs = if ucs.is_finite() { ucs } else { 0.0 }; + let auto = || auto_rotation(p1.rotate(-ucs), p2.rotate(-ucs), at.rotate(-ucs)) + ucs; + DimKind::Linear { rotation: rotation.unwrap_or_else(auto) } } /// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints, @@ -219,7 +226,7 @@ fn run_linear(s: &mut Session, p: &Value) -> Result { }; let at = point_req("dimlinear", p, "at")?; let rot = p.get("rotation").and_then(Value::as_f64).map(f64::to_radians); - let k = dim(s, linear_kind(a, b, at, rot, false), at, a, b, Vec2::ZERO, Vec2::ZERO, str_param(p, "text").unwrap_or("")); + let k = dim(s, linear_kind(a, b, at, rot, false, 0.0), at, a, b, Vec2::ZERO, Vec2::ZERO, str_param(p, "text").unwrap_or("")); Ok(json!({ "handle": add_dim(s, k)?.hex() })) } @@ -1056,7 +1063,16 @@ impl Interactive for LinearM { } (_, Input::Point(at)) => { let (Some(&a), Some(&b)) = (self.pts.first(), self.pts.get(1)) else { return Ok(Step::Continue) }; - let k = self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned), at, a, b, Vec2::ZERO, Vec2::ZERO, "")); + let k = self.text.apply(dim( + s, + linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), + at, + a, + b, + Vec2::ZERO, + Vec2::ZERO, + "", + )); add_dim(s, k)?; if let Some(EntityKind::Dimension(d)) = s.last_dim.and_then(|h| s.doc().ok()?.entity(h).map(|e| e.kind.clone())) { let st = s.doc()?.dim_style(&d.style).cloned().unwrap_or_default(); @@ -1067,8 +1083,8 @@ impl Interactive for LinearM { } (_, Input::Keyword(k)) => { match k.as_str() { - "Horizontal" => self.rotation = Some(0.0), - "Vertical" => self.rotation = Some(std::f64::consts::FRAC_PI_2), + "Horizontal" => self.rotation = Some(s.input_ucs().rotation()), + "Vertical" => self.rotation = Some(s.input_ucs().rotation() + std::f64::consts::FRAC_PI_2), "Rotated" => self.rotating = true, other => { self.text.keyword(other); @@ -1083,7 +1099,16 @@ impl Interactive for LinearM { fn preview(&self, s: &Session, c: Vec2) -> Vec { match self.pts.as_slice() { [a] => vec![super::helpers::line(*a, c)], - [a, b] => vec![self.text.apply(dim(s, linear_kind(*a, *b, c, self.rotation, self.aligned), c, *a, *b, Vec2::ZERO, Vec2::ZERO, ""))], + [a, b] => vec![self.text.apply(dim( + s, + linear_kind(*a, *b, c, self.rotation, self.aligned, s.input_ucs().rotation()), + c, + *a, + *b, + Vec2::ZERO, + Vec2::ZERO, + "", + ))], _ => Vec::new(), } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2c927ba6f..7e89db59c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -452,6 +452,10 @@ pub struct Settings { pub polarsnap: bool, /// POLARDIST: the PolarSnap step; 0 uses the snap X spacing. pub polardist: f64, + /// The current UCS's X axis, radians from world +X: ortho, polar and object snap tracking + /// work along the UCS axes. Filled in by [`Session::drafting_settings`]; not a setting. + #[serde(skip)] + pub ucs_angle: f64, } impl Default for Settings { @@ -510,6 +514,7 @@ impl Default for Settings { polaraddang: Vec::new(), polarsnap: false, polardist: 0.0, + ucs_angle: 0.0, } } } @@ -796,6 +801,8 @@ impl Session { settings.snapunit = d.header.snap_unit(); settings.gridunit = d.header.grid_unit(); } + let a = self.input_ucs().rotation(); + settings.ucs_angle = if a.is_finite() { a } else { 0.0 }; settings } /// The space commands act on (model space while working inside a layout viewport). diff --git a/crates/engine/src/lisp/ucs_tests.rs b/crates/engine/src/lisp/ucs_tests.rs index f03b27a42..8bb71103f 100644 --- a/crates/engine/src/lisp/ucs_tests.rs +++ b/crates/engine/src/lisp/ucs_tests.rs @@ -145,3 +145,30 @@ fn getangle_and_getdist_measure_in_the_ucs() { assert!(close(pt(&ok(&mut s, "(getvar \"UCSXDIR\")")), [0.0, 1.0, 0.0])); assert_eq!(ok(&mut s, "(getvar \"WORLDUCS\")"), "0"); } + +#[test] +fn entsel_and_getcorner_answer_in_the_ucs() { + let mut s = session(); + s.execute("line", &json!({"points": [[100, 60], [100, 80]]})).unwrap(); + turned(&mut s); + // entsel: the object, and the pick point in the UCS. + s.cmdline("(setq e (entsel))").unwrap(); + s.input(crate::Input::Point(Vec2::new(100.0, 70.0))).unwrap(); + let v = to_text(&s.lisp_var("E"), true); + assert!(v.contains(" { // Each point after the first goes straight across or up from the last one. - let q = last.map_or(p, |l| crate::snap::ortho(l, p)); + let q = last.map_or(p, |l| crate::snap::ortho_at(l, p, self.drafting_settings().ucs_angle)); self.point_mods.push(Frame::Track { last: Some(q) }); self.last_point = q; return Ok(()); diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 3b38b976f..3a17982a5 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -974,6 +974,17 @@ pub fn ortho(base: Vec2, p: Vec2) -> Vec2 { if d.x.abs() >= d.y.abs() { Vec2::new(p.x, base.y) } else { Vec2::new(base.x, p.y) } } +/// [`ortho`] along axes turned by `angle` radians (the current UCS's). +pub fn ortho_at(base: Vec2, p: Vec2, angle: f64) -> Vec2 { + if !angle.is_finite() || angle == 0.0 { + return ortho(base, p); + } + let d = (p - base).rotate(-angle); + let along = if d.x.abs() >= d.y.abs() { Vec2::new(d.x, 0.0) } else { Vec2::new(0.0, d.y) }; + let r = base + along.rotate(angle); + if r.is_finite() { r } else { p } +} + /// Polar tracking: if the direction base→p is within `tol` radians of a multiple of `inc`, /// return the point projected onto that ray and the angle. pub fn polar(base: Vec2, p: Vec2, inc: f64, tol: f64) -> Option<(Vec2, f64)> { @@ -1007,12 +1018,26 @@ pub fn grid_snap(p: Vec2, unit: Vec2, origin: Vec2, angle: f64) -> Vec2 { if s.is_finite() { s } else { p } } -/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing. +/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing, +/// as stored: in the UCS ([`grid_frame_in`] places them in the world). pub fn grid_frame(d: &Drawing) -> (Vec2, f64) { let base = d.header.point("SNAPBASE").map(|p| p.xy()).filter(|p| p.is_finite()).unwrap_or(Vec2::ZERO); (base, d.header.f64("SNAPANG", 0.0).to_radians()) } +/// The snap grid's origin and rotation in world coordinates, for `space`: SNAPBASE is a point of +/// the current UCS and SNAPANG is measured from its X axis, so the grid and grid snap lie in the +/// UCS (in the World UCS while it is tilted out of the XY plane). +pub fn grid_frame_in(d: &Drawing, space: &Space) -> (Vec2, f64) { + let (base, angle) = grid_frame(d); + let (ucs, _) = crate::ucs::current(d, space); + if !ucs.is_planar() { + return (base, angle); + } + let (o, a) = (ucs.to_wcs(base), ucs.rotation() + angle); + if o.is_finite() && a.is_finite() { (o, a) } else { (base, angle) } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/snap/iso.rs b/crates/engine/src/snap/iso.rs index 9f1688b93..a4469a925 100644 --- a/crates/engine/src/snap/iso.rs +++ b/crates/engine/src/snap/iso.rs @@ -118,11 +118,11 @@ pub fn lattice_snap(p: Vec2, d: f64, origin: Vec2, angle: f64) -> Vec2 { /// isometric lattice, and the settings with grid snap off so the rectangular grid leaves it be. /// Otherwise both unchanged, also when PolarSnap (SNAPTYPE 1) is the snap type: snap mode then /// steps along the tracking paths instead. -pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, mut s: Settings, p: Vec2) -> (Vec2, Settings) { +pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, space: &cadcraft_doc::Space, mut s: Settings, p: Vec2) -> (Vec2, Settings) { if !(s.snapmode && s.isodraft) || s.polarsnap { return (p, s); } - let (origin, angle) = super::grid_frame(doc); + let (origin, angle) = super::grid_frame_in(doc, space); s.snapmode = false; (lattice_snap(p, s.snapunit.y, origin, angle), s) } @@ -144,10 +144,12 @@ fn nearest_axis(plane: IsoPlane, d: Vec2) -> Vec2 { /// Ortho without snapping: `p` constrained relative to `base` to the nearest axis of the current /// isometric plane (or to horizontal/vertical when isometric drafting is off). pub fn constrain(s: &Settings, base: Vec2, p: Vec2) -> Vec2 { + // Along the current UCS's axes (`s.ucs_angle`), the isometric ones turned with it. if !s.isodraft { - return super::ortho(base, p); + return super::ortho_at(base, p, s.ucs_angle); } - let dir = nearest_axis(s.isoplane, p - base); + let a = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 }; + let dir = nearest_axis(s.isoplane, (p - base).rotate(-a)).rotate(a); let r = base + dir * (p - base).dot(dir); if r.is_finite() { r } else { p } } diff --git a/crates/engine/src/snap/tracking.rs b/crates/engine/src/snap/tracking.rs index e0740d7be..4fb9113bb 100644 --- a/crates/engine/src/snap/tracking.rs +++ b/crates/engine/src/snap/tracking.rs @@ -259,12 +259,14 @@ impl TrackConfig { /// direction (radians) of the last segment when the base point ends it. pub fn relative_to(s: &crate::Settings, angbase: f64, last: Option) -> Self { let additional: &[f64] = if s.polar_flags & polarmode::ADDITIONAL != 0 { &s.polaraddang } else { &[] }; - let absolute = polar_angles(s.polarang, additional, angbase); + // Measured in the current UCS: from ANGBASE off its X axis. + let ucs = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 }; + let absolute = polar_angles(s.polarang, additional, angbase + ucs); let polar = match last.filter(|a| a.is_finite() && s.polar_flags & polarmode::RELATIVE != 0) { Some(a) => polar_angles(s.polarang, additional, a), None => absolute.clone(), }; - let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal() }; + let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal(ucs) }; TrackConfig { otrack: s.otrack, osmode: s.osmode, @@ -279,9 +281,9 @@ impl TrackConfig { } } -/// Horizontal and vertical, both ways. -fn orthogonal() -> Vec { - vec![0.0, PI / 2.0, PI, 1.5 * PI] +/// Along the UCS axes (turned `ucs` radians from the world's), both ways. +fn orthogonal(ucs: f64) -> Vec { + [0.0, PI / 2.0, PI, 1.5 * PI].iter().map(|a| norm_angle(a + ucs)).collect() } /// Every multiple of the increment `inc` (POLARANG) around the circle, plus the `additional` @@ -803,10 +805,10 @@ impl crate::Session { return CursorSnap { point: h.point, snap: Some(h), track: None, wait }; } // Isometric snap (SNAPSTYL 1): its lattice in place of the rectangular grid. - let (raw, s) = super::iso::grid_snap(&doc, s, raw); + let (raw, s) = super::iso::grid_snap(&doc, &space, s, raw); let mut p = raw; if s.snapmode && !s.polarsnap { - let (origin, angle) = super::grid_frame(&doc); + let (origin, angle) = super::grid_frame_in(&doc, &space); p = super::grid_snap(p, doc.header.snap_unit(), origin, angle); } if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) { @@ -825,7 +827,9 @@ impl crate::Session { && s.orthomode && !q.corner { - p = super::iso::ortho(&self.settings, b, p); + // The drafting settings as they are (`s` has grid snap turned off once the isometric + // lattice took it), with the UCS axes. + p = super::iso::ortho(&self.drafting_settings(), b, p); } CursorSnap { point: p, snap: None, track: None, wait } } diff --git a/crates/engine/tests/ucs_drafting.rs b/crates/engine/tests/ucs_drafting.rs new file mode 100644 index 000000000..036d97775 --- /dev/null +++ b/crates/engine/tests/ucs_drafting.rs @@ -0,0 +1,206 @@ +//! The drafting aids follow the current UCS (#1106): ortho and direct distance entry along its +//! axes, grid snap in its XY plane (SNAPBASE from its origin, SNAPANG from its X axis), polar and +//! object snap tracking measured from its X axis, isometric axes turned with it, and DIMLINEAR's +//! horizontal and vertical along its axes. In the World UCS everything is as before. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{DimKind, EntityKind}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::snap::tracking::{CursorQuery, TrackConfig}; +use cadcraft_engine::snap::{self, iso}; +use serde_json::json; + +const DEG: f64 = std::f64::consts::PI / 180.0; + +fn session() -> Session { + let mut s = Session::new(); + s.new_drawing(false); + // Nothing running that would snap the cursor elsewhere. + s.settings.osmode = 0; + s.settings.otrack = false; + s.settings.polarmode = false; + s.settings.orthomode = false; + s.settings.snapmode = false; + s +} + +/// The UCS at (5, 5) turned `deg` degrees. +fn turned(s: &mut Session, deg: f64) { + s.execute("ucs", &json!({"option": "origin", "origin": [5, 5]})).unwrap(); + s.execute("ucs", &json!({"option": "z", "angle": deg})).unwrap(); +} + +fn query(base: Option) -> CursorQuery { + CursorQuery { base, deferred: false, corner: false, aperture: 0.01, tol: 1.0, now: 0.0, shift: false } +} + +fn near(a: Vec2, x: f64, y: f64) -> bool { + a.dist(Vec2::new(x, y)) < 1e-9 +} + +fn ang_eq(a: f64, b: f64) -> bool { + let d = (a - b).rem_euclid(std::f64::consts::TAU); + d < 1e-9 || std::f64::consts::TAU - d < 1e-9 +} + +#[test] +fn ortho_follows_the_ucs_axes() { + let mut s = session(); + s.settings.orthomode = true; + // World UCS: horizontal. + let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point; + assert!(near(p, 10.0, 0.0), "{p:?}"); + // Turned 30°: along the UCS X axis, as far as the cursor reaches along it. + turned(&mut s, 30.0); + let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point; + let along = 10.0 * (30.0 * DEG).cos() + 4.0 * (30.0 * DEG).sin(); + assert!(near(p, along * (30.0 * DEG).cos(), along * (30.0 * DEG).sin()), "{p:?}"); + // And along its Y axis when the cursor is nearer that. + let p = s.snap_cursor(Vec2::new(-4.0, 9.0), &query(Some(Vec2::ZERO))).point; + let d = p - Vec2::ZERO; + assert!(ang_eq(d.angle(), 120.0 * DEG) || ang_eq(d.angle(), 300.0 * DEG), "{:?}", d.angle() / DEG); +} + +#[test] +fn direct_distance_with_ortho_goes_along_the_ucs_axis() { + let mut s = session(); + turned(&mut s, 30.0); + s.settings.orthomode = true; + s.cmdline("line 0,0").unwrap(); + // The cursor a little off the UCS X axis: 10 along it. + s.cursor = s.input_ucs().to_wcs(Vec2::new(8.0, 1.0)); + s.cmdline("10").unwrap(); + s.cmdline("").unwrap(); + let l = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap(); + let u = s.input_ucs(); + assert!(l.a.xy().dist(u.to_wcs(Vec2::ZERO)) < 1e-9 && l.b.xy().dist(u.to_wcs(Vec2::new(10.0, 0.0))) < 1e-9, "{l:?}"); +} + +#[test] +fn grid_snap_lies_in_the_ucs() { + let mut s = session(); + cadcraft_engine::sysvars::set(&mut s, "SNAPUNIT", &json!([1, 1])).unwrap(); + s.settings.snapmode = true; + let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point; + assert!(near(p, 5.0, 7.0), "World: {p:?}"); + // Turned 90° at (5, 5): the lattice through (5, 5) along the turned axes; with SNAPBASE and + // SNAPANG measured in the UCS. + turned(&mut s, 90.0); + let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point; + assert!(near(p, 5.0, 7.0), "{p:?}"); + s.execute("ucs", &json!({"option": "z", "angle": -45})).unwrap(); + let u = s.input_ucs(); + let p = s.snap_cursor(u.to_wcs(Vec2::new(2.2, -0.9)), &query(None)).point; + assert!(u.to_ucs(p).dist(Vec2::new(2.0, -1.0)) < 1e-9, "UCS {:?}", u.to_ucs(p)); + let d = s.doc().unwrap(); + let (o, a) = snap::grid_frame_in(d, &s.space()); + assert!(near(o, 5.0, 5.0) && ang_eq(a, 45.0 * DEG), "{o:?} {}", a / DEG); + // SNAPBASE is a UCS point, SNAPANG an angle from its X axis. + cadcraft_engine::sysvars::set(&mut s, "SNAPBASE", &json!([1, 0])).unwrap_or(()); + s.doc_mut().unwrap().header.set("SNAPBASE", cadcraft_engine::doc::HVal::Point(Vec3::new(1.0, 0.0, 0.0))); + s.doc_mut().unwrap().header.set_f64("SNAPANG", 10.0); + let (o, a) = snap::grid_frame_in(s.doc().unwrap(), &s.space()); + assert!(o.dist(u.to_wcs(Vec2::new(1.0, 0.0))) < 1e-9 && ang_eq(a, 55.0 * DEG), "{o:?} {}", a / DEG); + // The stored values are unchanged (they are UCS values). + assert_eq!(snap::grid_frame(s.doc().unwrap()), (Vec2::new(1.0, 0.0), 10.0 * DEG)); +} + +#[test] +fn polar_tracking_is_measured_from_the_ucs_x_axis() { + let mut s = session(); + s.settings.polarmode = true; + s.settings.polarang = 90.0 * DEG; + let base = Vec2::ZERO; + let at32 = Vec2::from_angle(32.0 * DEG) * 10.0; + // World UCS, 90° steps: 32° is on no path. + assert!(s.snap_cursor(at32, &query(Some(base))).track.is_none()); + // Turned 30°: the path at 30° catches it. + turned(&mut s, 30.0); + let snapped = s.snap_cursor(at32, &query(Some(base))); + let t = snapped.track.expect("on the 30° path"); + let d = t.point - base; + assert!(ang_eq(d.angle(), 30.0 * DEG), "{}", d.angle() / DEG); + // The configuration itself: polar angles and the orthogonal tracking paths turn with the UCS. + let st = s.drafting_settings(); + let cfg = TrackConfig::new(&st, 0.0); + for want in [30.0, 120.0, 210.0, 300.0] { + assert!( + cfg.polar_angles.iter().any(|a| ang_eq(*a, want * DEG)), + "{want}: {:?}", + cfg.polar_angles.iter().map(|a| a / DEG).collect::>() + ); + assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG)), "{want}"); + } + // ANGBASE adds to it. + let cfg = TrackConfig::new(&st, 15.0 * DEG); + assert!(cfg.polar_angles.iter().any(|a| ang_eq(*a, 45.0 * DEG))); +} + +#[test] +fn the_world_ucs_drafts_as_before() { + let s = session(); + let st = s.drafting_settings(); + assert_eq!(st.ucs_angle, 0.0); + for (b, p) in [(Vec2::ZERO, Vec2::new(10.0, 4.0)), (Vec2::new(3.0, 3.0), Vec2::new(1.0, 20.0)), (Vec2::ZERO, Vec2::new(-5.0, 5.0))] { + assert_eq!(snap::ortho_at(b, p, 0.0), snap::ortho(b, p)); + assert_eq!(iso::constrain(&st, b, p), snap::ortho(b, p)); + } + let cfg = TrackConfig::new(&st, 0.0); + for want in [0.0, 90.0, 180.0, 270.0] { + assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG))); + } + assert_eq!(snap::grid_frame_in(s.doc().unwrap(), &s.space()), snap::grid_frame(s.doc().unwrap())); + // Hostile angles fall back to the world axes. + assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::NAN), Vec2::new(3.0, 0.0)); + assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::INFINITY), Vec2::new(3.0, 0.0)); +} + +#[test] +fn isometric_axes_turn_with_the_ucs() { + let mut s = session(); + s.settings.isodraft = true; + let st0 = s.drafting_settings(); + turned(&mut s, 40.0); + let st = s.drafting_settings(); + for v in [Vec2::new(10.0, 3.0), Vec2::new(-2.0, 9.0), Vec2::new(4.0, -7.0)] { + let base = Vec2::new(1.0, 2.0); + let r = iso::constrain(&st, base, base + v.rotate(40.0 * DEG)) - base; + let want = iso::constrain(&st0, Vec2::ZERO, v).rotate(40.0 * DEG); + assert!(r.dist(want) < 1e-9, "{v:?}: {r:?} vs {want:?}"); + } +} + +fn last_dim_rotation(s: &Session) -> f64 { + let d = s.doc().unwrap(); + let r = d.model.iter().filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm.kind) } else { None }).last(); + match r { + Some(DimKind::Linear { rotation }) => rotation, + other => panic!("not a linear dimension: {other:?}"), + } +} + +#[test] +fn dimlinear_horizontal_and_vertical_follow_the_ucs() { + let mut s = session(); + turned(&mut s, 30.0); + // Placed above the points (in the UCS): horizontal along the UCS X axis. + s.cmdline("dimlinear 0,0 10,0 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG), "{}", last_dim_rotation(&s) / DEG); + // Beside them: vertical along its Y axis. + s.cmdline("dimlinear 0,0 0,10 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG), "{}", last_dim_rotation(&s) / DEG); + // The keywords. + s.cmdline("dimlinear 0,0 10,10 h 5,20").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG)); + s.cmdline("dimlinear 0,0 10,10 v 20,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG)); + // JSON stays in world coordinates: horizontal is world horizontal. + s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 5]})).unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 0.0)); + // World UCS: as before. + s.execute("ucs", &json!({"option": "world"})).unwrap(); + s.cmdline("dimlinear 0,0 10,0 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 0.0)); + s.cmdline("dimlinear 0,0 0,10 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 90.0 * DEG)); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4bf102510..e85493b0c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -668,40 +668,41 @@ fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) { let unit = if s.gridunit.x == 0.0 { s.snapunit.x } else { s.gridunit.x }; let minor = adaptive(unit, xf.scale, 8.0); let major = minor * major_n; + // The grid lies in the snap frame: SNAPBASE and SNAPANG in the current UCS. + let space = app.session.space(); + let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0)); + let to_world = |q: Vec2| origin + q.rotate(angle); + // The view's corners in grid coordinates bound the lines needed. + let corners = [wb.min, Vec2::new(wb.max.x, wb.min.y), wb.max, Vec2::new(wb.min.x, wb.max.y)].map(|c| (c - origin).rotate(-angle)); + let lo = Vec2::new(corners.iter().map(|c| c.x).fold(f64::INFINITY, f64::min), corners.iter().map(|c| c.y).fold(f64::INFINITY, f64::min)); + let hi = + Vec2::new(corners.iter().map(|c| c.x).fold(f64::NEG_INFINITY, f64::max), corners.iter().map(|c| c.y).fold(f64::NEG_INFINITY, f64::max)); + let (x0, x1) = ((lo.x / minor).floor(), (hi.x / minor).ceil()); + let (y0, y1) = ((lo.y / minor).floor(), (hi.y / minor).ceil()); let mut lines = Vec::new(); - let x0 = (wb.min.x / minor).floor() as i64; - let x1 = (wb.max.x / minor).ceil() as i64; - let y0 = (wb.min.y / minor).floor() as i64; - let y1 = (wb.max.y / minor).ceil() as i64; - if (x1 - x0) < 2000 && (y1 - y0) < 2000 { - for i in x0..=x1 { + if [x0, x1, y0, y1].iter().all(|v| v.is_finite()) && (x1 - x0) < 2000.0 && (y1 - y0) < 2000.0 { + let is_major = |v: f64| ((v / major) - (v / major).round()).abs() < 1e-6; + let stroke = |m: bool| Stroke::new(1.0, if m { t.grid_major } else { t.grid_minor }); + for i in (x0 as i64)..=(x1 as i64) { let x = i as f64 * minor; - let is_major = (x / major).round() * major - x == 0.0 || ((x / major) - (x / major).round()).abs() < 1e-6; - let sx = xf.to_screen(Vec2::new(x, 0.0)).x; - lines.push(Shape::line_segment( - [pos2(sx, xf.rect.top()), pos2(sx, xf.rect.bottom())], - Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }), - )); + let (a, b) = (to_world(Vec2::new(x, lo.y)), to_world(Vec2::new(x, hi.y))); + lines.push(Shape::line_segment([xf.to_screen(a), xf.to_screen(b)], stroke(is_major(x)))); } - for j in y0..=y1 { + for j in (y0 as i64)..=(y1 as i64) { let y = j as f64 * minor; - let is_major = ((y / major) - (y / major).round()).abs() < 1e-6; - let sy = xf.to_screen(Vec2::new(0.0, y)).y; - lines.push(Shape::line_segment( - [pos2(xf.rect.left(), sy), pos2(xf.rect.right(), sy)], - Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }), - )); + let (a, b) = (to_world(Vec2::new(lo.x, y)), to_world(Vec2::new(hi.x, y))); + lines.push(Shape::line_segment([xf.to_screen(a), xf.to_screen(b)], stroke(is_major(y)))); } } p.extend(lines); } - // Axes through the origin. - let o = xf.to_screen(Vec2::ZERO); - if xf.rect.y_range().contains(o.y) { - p.line_segment([pos2(xf.rect.left(), o.y), pos2(xf.rect.right(), o.y)], Stroke::new(1.0, t.axis_x)); - } - if xf.rect.x_range().contains(o.x) { - p.line_segment([pos2(o.x, xf.rect.top()), pos2(o.x, xf.rect.bottom())], Stroke::new(1.0, t.axis_y)); + // The current UCS's X and Y axes through its origin. + let u = app.session.input_ucs(); + let o = u.origin.xy(); + for (dir, color) in [(u.x.xy(), t.axis_x), (u.y.xy(), t.axis_y)] { + if let Some(seg) = clip_infinite(xf, o, dir, false) { + p.line_segment(seg, Stroke::new(1.0, color)); + } } } @@ -718,7 +719,9 @@ fn draw_iso_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) { } d *= 5.0; } - let (origin, angle) = app.session.doc().map(cadcraft_engine::snap::grid_frame).unwrap_or((Vec2::ZERO, 0.0)); + // In the current UCS (SNAPBASE from its origin, SNAPANG from its X axis). + let space = app.session.space(); + let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0)); let lines = iso::grid_lines(xf.world_bounds(), d, origin, angle, s.gridmajor); p.extend( lines.into_iter().map(|l| { @@ -1114,7 +1117,8 @@ fn draw_snap_marker(p: &egui::Painter, at: Pos2, hit: &SnapHit) { /// Acquired tracking points (small `+`, `//` for a Parallel line), the dotted paths the cursor /// is on and the tooltip naming them ("Endpoint: 5.0000 < 90°"). -fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64) { +/// `ucs`: the current UCS's X axis (radians), which the tooltips measure angles from. +fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64, ucs: f64) { use snap::tracking::{Acquired, PathShape}; let t = Tokens::get(); let st = Stroke::new(1.0, t.snap); @@ -1151,7 +1155,7 @@ fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquire p.extend(Shape::dotted_line(&pts, t.snap, 6.0, 1.0)); let (distance, angle) = ( cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4), - (path.from.angle_to(tr.point).to_degrees().round() as i64).rem_euclid(360), + ((path.from.angle_to(tr.point) - ucs).to_degrees().round() as i64).rem_euclid(360), ); tips.push(if path.name == "Polar" { crate::tf!("Polar: {distance} < {angle}°", distance = distance, angle = angle) @@ -1819,7 +1823,14 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } // Acquired tracking points and the polar / tracking paths under the cursor. if app.canvas.cursor.is_some() { - draw_tracking(&painter, &xf, &app.session.tracking.acquired, app.canvas.track.as_ref(), view.height * 4.0); + draw_tracking( + &painter, + &xf, + &app.session.tracking.acquired, + app.canvas.track.as_ref(), + view.height * 4.0, + app.session.input_ucs().rotation(), + ); } if let (Some(hit), Some(_)) = (app.canvas.snap, app.canvas.cursor) { draw_snap_marker(&painter, xf.to_screen(hit.point), &hit); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4d31efc47..fcd57cd92 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -83,12 +83,12 @@ ignored; there are no context menus. Remaining: **≈ 110–170 Opus 5.5 hours** | Feature | AutoCAD | CADCraft | |---|---|---| -| Ortho (F8) | yes | yes (`snap.rs:503`) | -| Polar tracking increment | yes | yes, measured from ANGBASE; dotted path and "Polar: d < a°" tooltip (`snap/tracking.rs`, `canvas.rs` `draw_tracking`) | +| Ortho (F8) | yes | yes, along the current UCS's axes (`snap::ortho_at`) | +| Polar tracking increment | yes | yes, measured from ANGBASE off the current UCS's X axis; dotted path and "Polar: d < a°" tooltip (`snap/tracking.rs`, `canvas.rs` `draw_tracking`) | | Additional polar angles, relative to last segment | yes | additional angles yes (POLARADDANG with POLARMODE 4); **relative to the last segment no** | | Polar distance snap (PolarSnap) | yes | **no** | | **Object snap tracking** (acquire points, alignment paths, intersections of paths) | yes, F11 | yes (#379): resting on a snap point acquires it (`+`), resting again releases it, seven at most; horizontal/vertical paths, or every polar angle with POLARMODE 2; Shift to acquire with POLARMODE 8; crossings of two paths, a path and an object, and a path and a polar path snap; tooltip names each path; a typed distance (direct distance entry) runs along the path the cursor is on, measured from the point the path comes from. Engine: `Session::snap_cursor`, `snap/tracking.rs`; AUTOSNAP bits 8 and 16 | -| Grid (rectangular, major lines, adaptive, limits) | yes | rectangular and isometric (30°, 90° and 150° lines), major lines, adaptive display | +| Grid (rectangular, major lines, adaptive, limits) | yes | rectangular and isometric (30°, 90° and 150° lines), major lines, adaptive display; grid and grid snap in the current UCS (SNAPBASE from its origin, SNAPANG from its X axis), the red and green axes along its X and Y | | Snap (rectangular, isometric, polar snap) | yes | rectangular and isometric (SNAPSTYL 1: the snap Y spacing along the isometric axes), from SNAPBASE turned by SNAPANG | | Isometric drafting (ISODRAFT, isoplanes F5) | yes | yes (#556): ISODRAFT and the status-bar toggle set SNAPSTYL and the plane; ISOPLANE / F5 / Ctrl+E cycle Left, Top, Right (SNAPISOPAIR); ortho, direct distance entry and the crosshair follow the plane's axes; ELLIPSE Isocircle (radius or Diameter, also for elliptical arcs); Drafting Settings snap style radio. Engine: `snap/iso.rs`, `cmd/settings/iso.rs` | | Drafting Settings dialog | yes | yes (`dialogs.rs:36-80`) | From 06e53f3ee7aa8bda86a265ae229f2b083220b6cf Mon Sep 17 00:00:00 2001 From: filforce95 <49290121+filforce95@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:55:23 +0200 Subject: [PATCH 014/531] fix(canvas): clicks count when the button goes down, even while the mouse moves (fixes #1001, #1546) Every click on the drawing used to be decided when the button came up: egui calls a press that travels more than a few points a drag, so a click made while the hand was still moving was lost (object picks, the second corner of a click-click window) or taken where the hand had got to (points, #835). Following the model agreed in #1001, a press now acts at once, where the button went down: it places the point (snapped as the cursor would be there), picks the object or sets a selection window's corner. Each press among a frame's events counts, so a slow frame keeps all its clicks (#815). What the pointer does while the button is held only decides whether the press becomes a drag: once it leaves a 6-point tolerance a 0.25 s timer starts; a button still down then is a drag and closes the window its press opened where it comes up, while a button that comes up sooner was a click and the window waits for the next press. Holding still never makes a drag. The detector lives in canvas/press.rs. Grips with no command running, ZOOM Realtime, the Dynamic Input options menu, model tiles and double-clicks keep their release-based clicks. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 239 +++++++++++++-------- crates/ui-egui/src/canvas/press.rs | 131 +++++++++++ crates/ui-egui/tests/press_first_clicks.rs | 189 ++++++++++++++++ crates/ui-egui/tests/rapid_clicks.rs | 5 +- docs/ui-parity.md | 5 +- 5 files changed, 470 insertions(+), 99 deletions(-) create mode 100644 crates/ui-egui/src/canvas/press.rs create mode 100644 crates/ui-egui/tests/press_first_clicks.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e5725e353..c876c4411 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -119,8 +119,8 @@ pub struct CanvasState { hover_at: Option, /// Constraint glyphs for the parametric overlay (cached per drawing revision). pub param: crate::parametric::Cache, - /// A selection window opened by a press-and-drag, to close where the button is let go. - drag_window: bool, + /// The primary-button press being held, when it was acted on (see [`press`]). + press: Option, /// The right-click that opened the shortcut menu held Shift or Ctrl: it is the object snap /// menu ([`crate::context_menu`]). pub snap_menu: bool, @@ -1369,12 +1369,12 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { if !in_active { app.canvas.hot_grips.clear(); app.session.pending_window = None; - app.canvas.drag_window = false; + app.canvas.press = None; if app.run("mspace", serde_json::json!({"at": [pp.x, pp.y]})).is_err() && active_vp.is_some() { let _ = app.run("pspace", serde_json::json!({})); } app.session.pending_window = None; - app.canvas.drag_window = false; + app.canvas.press = None; app.canvas.list = None; return; } @@ -1403,77 +1403,60 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { hatch_dialog = true; } - // While a command asks for a point, every click places one, however fast the drafting (#815). - // egui drops a click whose button comes up a few pixels from where it went down (a drag to it), - // and eframe hands a slow frame's clicks over together, which egui reports as one. - let point_prompt = app.session.current_prompt().is_some_and(|p| cadcraft_engine::pointmod::accepts(&p)) - && app.session.pending_window.is_none() - && !app.session.realtime_zoom_active(); - let pressed_primary = pressed_primary || (point_prompt && resp.drag_stopped_by(egui::PointerButton::Primary)); - if point_prompt && inside && pressed_primary && !middle_down && app.cmd.options.is_none() && app.cmd.buffer.is_empty() { - let releases: Vec = ui.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos), - _ => None, - }) - .collect() - }); - // The last one is placed below, at the cursor, like any click. - if let Some((_, earlier)) = releases.split_last() { - for pos in earlier.iter().filter(|p| rect.contains(**p)) { - let w = effective_point(app, xf.to_world(*pos), &xf, ui.ctx()); - let result = match app.canvas.snap { - Some(hit) => app.session.input_snapped(hit), - None => app.session.input(Input::Point(w)), - }; - if let Err(e) = result { - app.session.echo(e.to_string()); + // Clicks count when the button goes down, where it went down, however fast the mouse moves + // (#1001, #815): each press among this frame's events places its point, picks its object or + // sets a selection window's corner at once. What the pointer does while the button is held + // only decides whether the press becomes a drag ([`press`]): a drag closes the window its + // press opened where the button comes up; after a click the window waits for the next press. + // Presses on grips (idle) and while ZOOM Realtime runs are left to the clicks further down. + let (steps, now, primary_down) = ui.input(|i| (press::steps(&i.events), i.time, i.pointer.primary_down())); + let mut click_used = false; + for step in steps { + match step { + press::Step::Down(pos, m) => { + app.canvas.press = None; + if !inside || !rect.contains(pos) || middle_down { + continue; + } + // A press on the Dynamic Input options menu is the menu's (picked on release); + // elsewhere it closes the menu and counts as usual. + if app.cmd.options.is_some() { + if app.cmd.option_at(pos).is_some() { + continue; + } + app.cmd.options = None; + } + if press_takes(app, &xf, pos) { + let opened = press_at(app, &xf, ui.ctx(), pos, m); + app.canvas.press = Some(press::Press::new(pos, opened)); + } + } + press::Step::Move(pos) => { + if let Some(p) = &mut app.canvas.press { + p.moved(pos, now); + } + } + press::Step::Up(pos) => { + let Some(mut p) = app.canvas.press.take() else { continue }; + click_used = true; + if p.released_as_drag(pos, now) && p.opened_window && app.session.pending_window.is_some() { + let end = xf.to_world(pos); + let done = if app.session.prompting() { app.session.input(Input::Point(end)) } else { app.session.idle_click(end, mods.shift) }; + if let Err(e) = done { + app.session.echo(e.to_string()); + } } } } } + if !primary_down { + // The button came up where we didn't see it (outside the window, say). + app.canvas.press = None; + } let raw_world = hover_pos.filter(|_| inside).map(|p| xf.to_world(p)); let dyn_frame = crate::cmdline::dyn_frame(app); - if let Some(w) = raw_world { - let mut eff = effective_point(app, w, &xf, ui.ctx()); - // A locked Dynamic Input value (`40,` or `40<` typed) holds the cursor and overrides snaps. - if let Some(f) = dyn_frame - && let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f) - && e.first_locked().is_some() - { - eff = crate::dyninput::constrain(&e, &f, eff, app.cmd.second_locked()); - app.canvas.snap = None; - app.canvas.track = None; - } - // Grip dimensional input: typed lengths and angles hold the grip and override snaps. - let grip_held = crate::grip_dyn::constrain(app, eff); - if let Some(q) = grip_held { - eff = q; - app.canvas.snap = None; - app.canvas.track = None; - } - app.canvas.cursor = Some(eff); - app.session.cursor = eff; - app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred); - // Typed or menu snap overrides (END, NON…) and Tab cycling; a locked Dynamic Input value wins. - if dyn_frame.and_then(|f| crate::dyninput::parse(&app.cmd.buffer, &f)).is_none_or(|e| e.first_locked().is_none()) { - override_cursor(app, w, &xf); - } - // Typed grip dimensions win over snap overrides too. - if let Some(q) = grip_held { - app.canvas.cursor = Some(q); - app.session.cursor = q; - app.canvas.snap = None; - app.session.cursor_deferred = None; - } - } else { - app.canvas.cursor = None; - app.canvas.snap = None; - app.session.cursor_deferred = None; - } + track_cursor(app, raw_world, &xf, ui.ctx(), dyn_frame); // A click on the Dynamic Input options menu picks the keyword; elsewhere it closes the menu. let mut picked = false; @@ -1491,12 +1474,13 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let idle_dbl = dbl_primary && app.session.running.is_none(); if idle_dbl { app.session.pending_window = None; - app.canvas.drag_window = false; + app.canvas.press = None; } let pressed_primary = pressed_primary && !picked && !hatch_dialog && !idle_dbl; - // Clicks. + // Clicks the presses above left alone: on grips, and during ZOOM Realtime. if inside && pressed_primary + && !click_used && !middle_down && let Some(p) = app.canvas.cursor { @@ -1527,31 +1511,6 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.session.echo(e.to_string()); } } - // Press-and-drag selection window (AutoCAD's PICKDRAG = 2; click-click still works): a drag - // that starts while objects are being selected opens a window where the button went down, - // and letting go closes it. Drags on grips and drags while drawing are left alone. - if resp.drag_started_by(egui::PointerButton::Primary) - && !middle_down - && app.session.pending_window.is_none() - && let Some(origin) = ui.input(|i| i.pointer.press_origin()) - && rect.contains(origin) - && grip_at(app, &xf, Some(origin)).is_none() - && crate::dyngrips::at(app, &xf, Some(origin)).is_none() - { - app.canvas.drag_window = app.session.begin_window(xf.to_world(origin)); - } - if app.canvas.drag_window && resp.drag_stopped_by(egui::PointerButton::Primary) { - app.canvas.drag_window = false; - if app.session.pending_window.is_some() - && let Some(end) = ui.input(|i| i.pointer.interact_pos()) - { - let end = xf.to_world(end); - let done = if app.session.prompting() { app.session.input(Input::Point(end)) } else { app.session.idle_click(end, mods.shift) }; - if let Err(e) = done { - app.session.echo(e.to_string()); - } - } - } // Right-click acts as Enter while a command runs (the classic CAD default; held, it opens the // command menu); otherwise it opens the shortcut menu (Repeat, Clipboard, …). // Shift/Ctrl+right-click opens the object snap menu. @@ -1861,6 +1820,95 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { // spin the CPU with the low-latency present mode (`gpu::surface_config`). } +/// Put the cursor at `raw` (world, `None` off the canvas): snaps, ortho and polar, a locked +/// Dynamic Input value and typed grip dimensions applied (`app.canvas.cursor`, `.snap`, `.track`). +fn track_cursor(app: &mut CadApp, raw: Option, xf: &Xf, ctx: &egui::Context, dyn_frame: Option) { + if let Some(w) = raw { + let mut eff = effective_point(app, w, xf, ctx); + // A locked Dynamic Input value (`40,` or `40<` typed) holds the cursor and overrides snaps. + if let Some(f) = dyn_frame + && let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f) + && e.first_locked().is_some() + { + eff = crate::dyninput::constrain(&e, &f, eff, app.cmd.second_locked()); + app.canvas.snap = None; + app.canvas.track = None; + } + // Grip dimensional input: typed lengths and angles hold the grip and override snaps. + let grip_held = crate::grip_dyn::constrain(app, eff); + if let Some(q) = grip_held { + eff = q; + app.canvas.snap = None; + app.canvas.track = None; + } + app.canvas.cursor = Some(eff); + app.session.cursor = eff; + app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred); + // Typed or menu snap overrides (END, NON…) and Tab cycling; a locked Dynamic Input value wins. + if dyn_frame.and_then(|f| crate::dyninput::parse(&app.cmd.buffer, &f)).is_none_or(|e| e.first_locked().is_none()) { + override_cursor(app, w, xf); + } + // Typed grip dimensions win over snap overrides too. + if let Some(q) = grip_held { + app.canvas.cursor = Some(q); + app.session.cursor = q; + app.canvas.snap = None; + app.session.cursor_deferred = None; + } + } else { + app.canvas.cursor = None; + app.canvas.snap = None; + app.session.cursor_deferred = None; + } +} + +/// Whether the press at `pos` is acted on when the button goes down ([`press_at`]): at any prompt +/// and on the drawing with no command running. Grips (with no command running) and ZOOM Realtime +/// keep their clicks. +fn press_takes(app: &mut CadApp, xf: &Xf, pos: Pos2) -> bool { + if app.session.realtime_zoom_active() { + return false; + } + if app.session.prompting() { + return true; + } + crate::dyngrips::at(app, xf, Some(pos)).is_none() && grip_at(app, xf, Some(pos)).is_none() +} + +/// Act on a press at `pos`: at a prompt the point goes in (snapped as the cursor would be there); +/// with no command running it picks the object there or sets a selection window's corner. +/// Returns whether the press opened a selection window. +fn press_at(app: &mut CadApp, xf: &Xf, ctx: &egui::Context, pos: Pos2, mods: egui::Modifiers) -> bool { + let had_window = app.session.pending_window.is_some(); + let raw = xf.to_world(pos); + let dyn_frame = crate::cmdline::dyn_frame(app); + track_cursor(app, Some(raw), xf, ctx, dyn_frame); + let Some(p) = app.canvas.cursor else { return false }; + if app.session.prompting() { + // Ctrl held while picking the point of a grip edit makes copies (the Copy option). + if mods.ctrl && app.session.running.as_ref().is_some_and(|r| r.id == "grip") { + let _ = app.session.input(Input::Keyword("Copy".into())); + } + // Clicking places the point; a value typed into the Dynamic Input boxes is used up. + if let Some(f) = dyn_frame + && crate::dyninput::parse(&app.cmd.buffer, &f).is_some() + { + app.cmd.buffer.clear(); + } + // Preserve a snap's viewport origin for DIST, and its deferred curve where needed. + let result = match app.canvas.snap { + Some(hit) => app.session.input_snapped(hit), + None => app.session.input(Input::Point(p)), + }; + if let Err(e) = result { + app.session.echo(e.to_string()); + } + } else if let Err(e) = app.session.idle_click(raw, mods.shift) { + app.session.echo(e.to_string()); + } + !had_window && app.session.pending_window.is_some() +} + /// The model space tiles on screen (none without tiling): each tile's rectangle in `full`. /// 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. @@ -2606,6 +2654,7 @@ mod blockedit; mod compare; /// Background rebuilds of the display list for a new view. +mod press; mod rebuild; #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/press.rs b/crates/ui-egui/src/canvas/press.rs new file mode 100644 index 000000000..bb890f690 --- /dev/null +++ b/crates/ui-egui/src/canvas/press.rs @@ -0,0 +1,131 @@ +//! Press-first clicks (#1001): a click on the canvas counts when the primary button goes down, at +//! the spot where it went down, however fast the mouse is moving. Where the pointer goes while the +//! button is held only decides whether the press also becomes a drag: +//! +//! - holding still, or staying within [`TOLERANCE`] of the press, never makes a drag; +//! - once the pointer leaves the tolerance a timer starts; a button still down [`DRAG_DELAY`] +//! later is a drag (a selection window the press opened closes where the button comes up); +//! - a button that comes up sooner was a click (the window waits for the next press). +//! +//! The timer starts on leaving the tolerance, not on the press: pressing, holding still and then +//! moving and letting go quickly is still a click, as in AutoCAD. + +use egui::{Modifiers, Pos2}; + +/// How far (points) the pointer may wander from the press before the timer starts. +pub(crate) const TOLERANCE: f32 = 6.0; +/// How long (seconds) the button must stay down after the pointer left [`TOLERANCE`] for the +/// press to be a drag. +pub(crate) const DRAG_DELAY: f64 = 0.25; + +/// A primary-button press being held. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Press { + origin: Pos2, + /// When the pointer first went further than [`TOLERANCE`] from `origin` (seconds). + left_at: Option, + /// The press opened a selection window (set its first corner). + pub(crate) opened_window: bool, +} + +impl Press { + pub(crate) fn new(origin: Pos2, opened_window: bool) -> Self { + Self { origin, left_at: None, opened_window } + } + + /// The pointer is at `pos` at time `now`. + pub(crate) fn moved(&mut self, pos: Pos2, now: f64) { + if self.left_at.is_none() && pos.distance(self.origin) > TOLERANCE { + self.left_at = Some(now); + } + } + + /// Whether the button coming up at `pos` at time `now` ends a drag rather than a click. + pub(crate) fn released_as_drag(&mut self, pos: Pos2, now: f64) -> bool { + self.moved(pos, now); + self.left_at.is_some_and(|t| now - t >= DRAG_DELAY) + } +} + +/// A primary-button event of the frame, in order. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Step { + Down(Pos2, Modifiers), + Move(Pos2), + Up(Pos2), +} + +/// The primary-button presses, pointer moves and releases among a frame's events, in order. A slow +/// frame can hold several clicks; each press is its own step (#815). +pub(crate) fn steps(events: &[egui::Event]) -> Vec { + events + .iter() + .filter_map(|e| match *e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers } => Some(Step::Down(pos, modifiers)), + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(Step::Up(pos)), + egui::Event::PointerMoved(pos) => Some(Step::Move(pos)), + _ => None, + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::pos2; + + #[test] + fn staying_within_the_tolerance_is_a_click_however_long_the_button_is_held() { + let mut p = Press::new(pos2(100.0, 100.0), true); + p.moved(pos2(104.0, 103.0), 0.5); + assert!(!p.released_as_drag(pos2(105.0, 100.0), 5.0)); + } + + #[test] + fn letting_go_soon_after_leaving_the_tolerance_is_a_click() { + let mut p = Press::new(pos2(100.0, 100.0), true); + p.moved(pos2(112.0, 100.0), 1.0); + assert!(!p.released_as_drag(pos2(130.0, 100.0), 1.0 + DRAG_DELAY / 2.0)); + } + + #[test] + fn holding_still_then_moving_and_letting_go_quickly_is_a_click() { + // The timer starts when the pointer leaves the tolerance, not when the button goes down. + let mut p = Press::new(pos2(100.0, 100.0), true); + p.moved(pos2(101.0, 100.0), 2.0); + assert!(!p.released_as_drag(pos2(140.0, 100.0), 2.05)); + } + + #[test] + fn a_button_still_down_after_the_delay_is_a_drag() { + let mut p = Press::new(pos2(100.0, 100.0), true); + p.moved(pos2(110.0, 100.0), 1.0); + p.moved(pos2(200.0, 150.0), 1.1); + assert!(p.released_as_drag(pos2(250.0, 160.0), 1.0 + DRAG_DELAY)); + } + + #[test] + fn steps_keep_every_press_of_a_slow_frame_in_order() { + let at = |x| pos2(x, 10.0); + let button = + |x, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let events = vec![ + egui::Event::PointerMoved(at(1.0)), + button(1.0, true), + button(1.0, false), + egui::Event::PointerButton { pos: at(2.0), button: egui::PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }, + button(3.0, true), + button(3.0, false), + ]; + assert_eq!( + steps(&events), + vec![ + Step::Move(at(1.0)), + Step::Down(at(1.0), Modifiers::NONE), + Step::Up(at(1.0)), + Step::Down(at(3.0), Modifiers::NONE), + Step::Up(at(3.0)) + ] + ); + } +} diff --git a/crates/ui-egui/tests/press_first_clicks.rs b/crates/ui-egui/tests/press_first_clicks.rs new file mode 100644 index 000000000..27dc27072 --- /dev/null +++ b/crates/ui-egui/tests/press_first_clicks.rs @@ -0,0 +1,189 @@ +//! Press-first clicks (#1001): a click counts when the button goes down, where it went down, even +//! while the mouse is moving; holding the button after the pointer left a small tolerance makes a +//! drag. The harness runs at 60 frames a second and each queued event is one frame, so the number +//! of moves between press and release is how long the button was held. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Drawing, EntityKind, Space}; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::prompt::Input; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +fn harness() -> Harness<'static, CadApp> { + let mut session = Session::empty(); + session.open_drawing(Drawing::new_imperial(), "Press first", None); + session.execute("view.set", &json!({"center":[50,50],"height":100})).unwrap(); + session.settings.osmode = 0; + session.settings.snapmode = false; + session.settings.orthomode = false; + session.execute("line", &json!({"points": [[20, 20], [60, 20]]})).unwrap(); + let mut app = CadApp::new(session, Services::default()); + app.canvas.zoom_pending = false; + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(5); + h +} + +fn screen(h: &Harness<'_, CadApp>, p: Vec2) -> Pos2 { + h.state().canvas.xf.unwrap().to_screen(p) +} + +fn button(h: &mut Harness<'_, CadApp>, pos: Pos2, pressed: bool) { + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); +} + +/// Press at `at`, then move `dx` points to the right over `frames` frames and let go there. +fn moving_click(h: &mut Harness<'_, CadApp>, at: Pos2, dx: f32, frames: usize) { + h.event(Event::PointerMoved(at)); + button(h, at, true); + for i in 1..=frames { + h.event(Event::PointerMoved(at + vec2(dx * i as f32 / frames as f32, 0.0))); + } + button(h, at + vec2(dx, 0.0), false); + h.run_steps(2); +} + +/// A click that moves 15 points while the button is down, let go within two frames. +fn quick_moving_click(h: &mut Harness<'_, CadApp>, at: Vec2) { + let pos = screen(h, at); + moving_click(h, pos, 15.0, 2); +} + +fn start(h: &mut Harness<'_, CadApp>, id: &str) { + h.state_mut().start(id); + h.run_steps(2); + assert_eq!(h.state().session.running.as_ref().map(|r| r.id.as_str()), Some(id)); +} + +fn enter(h: &mut Harness<'_, CadApp>) { + h.state_mut().session.input(Input::Enter).unwrap(); + h.run_steps(2); +} + +fn lines(h: &Harness<'_, CadApp>) -> Vec<(Vec2, Vec2)> { + let st = h.state().session.state().unwrap(); + st.doc + .space(&Space::Model) + .unwrap() + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) => Some((l.a.xy(), l.b.xy())), + _ => None, + }) + .collect() +} + +#[test] +fn move_takes_the_base_and_second_point_where_the_button_went_down() { + let mut h = harness(); + start(&mut h, "move"); + quick_moving_click(&mut h, Vec2::new(40.0, 20.0)); + enter(&mut h); + // Base point and second point, both clicked on the move: 15 points is 1.5 drawing units here. + quick_moving_click(&mut h, Vec2::new(30.0, 40.0)); + quick_moving_click(&mut h, Vec2::new(50.0, 40.0)); + let got = lines(&h); + assert_eq!(got.len(), 1, "{got:?}"); + assert!(got[0].0.near(Vec2::new(40.0, 20.0), 1e-3) && got[0].1.near(Vec2::new(80.0, 20.0), 1e-3), "moved by (20, 0): {got:?}"); +} + +#[test] +fn an_object_clicked_on_the_move_is_picked_with_no_command_running() { + let mut h = harness(); + quick_moving_click(&mut h, Vec2::new(40.0, 20.0)); + assert_eq!(h.state().session.selection().len(), 1); + assert!(h.state().session.pending_window.is_none()); +} + +#[test] +fn an_object_clicked_on_the_move_is_picked_at_select_objects() { + let mut h = harness(); + start(&mut h, "erase"); + quick_moving_click(&mut h, Vec2::new(40.0, 20.0)); + enter(&mut h); + assert!(lines(&h).is_empty(), "the line was picked and erased"); +} + +#[test] +fn both_corners_of_a_click_click_window_count_while_the_mouse_moves() { + let mut h = harness(); + // Lower left, then upper right: a window around the whole line. + quick_moving_click(&mut h, Vec2::new(10.0, 10.0)); + assert!(h.state().session.pending_window.is_some(), "a quick click leaves the window open for the second corner"); + quick_moving_click(&mut h, Vec2::new(70.0, 30.0)); + assert!(h.state().session.pending_window.is_none()); + assert_eq!(h.state().session.selection().len(), 1); +} + +#[test] +fn holding_the_button_while_moving_drags_a_window() { + let mut h = harness(); + // Half a second of dragging from lower left to upper right of the line. + let from = screen(&h, Vec2::new(10.0, 10.0)); + let to = screen(&h, Vec2::new(70.0, 30.0)); + h.event(Event::PointerMoved(from)); + button(&mut h, from, true); + for i in 1..=30 { + h.event(Event::PointerMoved(from + (to - from) * (i as f32 / 30.0))); + } + button(&mut h, to, false); + h.run_steps(2); + assert!(h.state().session.pending_window.is_none(), "letting go closes the dragged window"); + assert_eq!(h.state().session.selection().len(), 1); +} + +#[test] +fn holding_still_then_moving_and_letting_go_quickly_is_a_click() { + let mut h = harness(); + let at = screen(&h, Vec2::new(10.0, 10.0)); + h.event(Event::PointerMoved(at)); + button(&mut h, at, true); + // Held in place for half a second: no drag yet. + h.run_steps(30); + h.event(Event::PointerMoved(at + vec2(40.0, 0.0))); + button(&mut h, at + vec2(40.0, 0.0), false); + h.run_steps(2); + assert!(h.state().session.pending_window.is_some(), "still waiting for the second corner"); +} + +#[test] +fn two_window_corners_clicked_within_one_frame_both_count() { + let mut h = harness(); + let (a, b) = (screen(&h, Vec2::new(10.0, 10.0)), screen(&h, Vec2::new(70.0, 30.0))); + // A slow frame: both clicks arrive before the next one is drawn. + for pos in [a, b] { + h.input_mut().events.push(Event::PointerMoved(pos)); + for pressed in [true, false] { + h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + } + h.run_steps(2); + assert!(h.state().session.pending_window.is_none()); + assert_eq!(h.state().session.selection().len(), 1); +} + +#[test] +fn cpolygon_points_clicked_on_the_move_all_count() { + // #1546: a narrow crossing polygon over the line's right end (x 58.6–59.9, the line ends at + // 60), each point clicked while moving. Taken where the buttons came up (1.5 units further + // right) it would miss the line. + let mut h = harness(); + start(&mut h, "erase"); + h.state_mut().session.input(Input::Keyword("CP".into())).unwrap(); + h.run_steps(2); + for p in [Vec2::new(58.6, 15.0), Vec2::new(59.9, 15.0), Vec2::new(59.9, 25.0), Vec2::new(58.6, 25.0)] { + quick_moving_click(&mut h, p); + } + enter(&mut h); + enter(&mut h); + assert!(lines(&h).is_empty(), "the polygon crossed the line and ERASE removed it"); +} diff --git a/crates/ui-egui/tests/rapid_clicks.rs b/crates/ui-egui/tests/rapid_clicks.rs index 1a750630d..2116f9e1d 100644 --- a/crates/ui-egui/tests/rapid_clicks.rs +++ b/crates/ui-egui/tests/rapid_clicks.rs @@ -88,11 +88,12 @@ fn a_click_made_while_the_mouse_moves_still_places_the_point() { let down = screen(&h, Vec2::new(40.0, 10.0)); button(&mut h, down, true); h.run_steps(1); - // The hand is already on its way to the next point when the button comes up. + // The hand is already on its way to the next point when the button comes up; the point is + // where the button went down (#1001), not where the hand got to. let up = down + vec2(12.0, 0.0); button(&mut h, up, false); h.run_steps(2); let got = lines(&h); assert_eq!(got.len(), 1, "{got:?}"); - assert!(got[0].1.near(h.state().canvas.xf.unwrap().to_world(up), 1e-4), "{got:?}"); + assert!(got[0].1.near(h.state().canvas.xf.unwrap().to_world(down), 1e-4), "{got:?}"); } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5495d4813..2833eba5f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (animation effects follow the operating system's setting) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (clicks count on press, even while the mouse moves) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How CADCraft's interaction compares with AutoCAD's: point entry, object snaps, tracking, dynamic input, grips, selection, the command line, chrome and navigation. A drafter's speed in AutoCAD @@ -127,7 +127,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. |---|---|---| | Pick, implied window (left→right) and crossing (right→left) | yes | yes, coloured and dashed rectangles (`lib.rs:576-589`, `canvas.rs:823-836`), filled as SELECTIONAREA, WINDOWAREACOLOR, CROSSINGAREACOLOR and SELECTIONAREAOPACITY say (Visual Effect Settings) | | Keywords W, C, WP, CP, F, BOX, AU, SI, M, G (group), CL (class) | yes | yes except CLass: W, C, F, WP, CP (#226); BOX, AUto, SIngle, Multiple, Group, Add, Remove, Undo (#428); ALL, Last, Previous | -| Press-drag selection windows (PICKDRAG) | yes | yes (#63, PICKDRAG = 2) | +| Press-drag selection windows (PICKDRAG) | yes | yes (#63, PICKDRAG = 2); clicks count when the button goes down, even while the mouse moves, and a press held after the pointer leaves a 6-point tolerance for 0.25 s is a drag (#1001) | | Lasso | yes | **no** | | Selection cycling (SELECTIONCYCLING) | yes | toggle nothing reads | | Selection preview, hover highlight | yes | selected and hovered objects redrawn in the selection colour, fills half see-through (SELECTIONEFFECT 1; 0 dashed), selection effect color; HIGHLIGHT (not saved), SELECTIONPREVIEW, PREVIEWEFFECT, PREVIEWFILTER (Visual Effect Settings) | @@ -202,6 +202,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | Clicks on the drawing count when the button goes down, at that spot, even while the mouse moves: points (base points too), object picks, both corners of a click-click window and polygon points; holding the button after the pointer leaves a 6-point tolerance for 0.25 s drags a window (#1001) | | 2026-10-12 | minor | Selected and hovered objects redrawn in the selection colour (text and arrowheads included); Options ▸ Selection laid out as AutoCAD's: Object grouping, Show grips, grip object limit, selection preview, Visual Effect Settings (selection area, preview filter) | | 2026-10-12 | minor | Animation effects (dialog and menu fades, smoothed wheel scrolling and ⌘/Ctrl+wheel zoom) follow the operating system's setting; View ▸ Accessibility ▸ Animation Effects chooses System, On or Off | | 2026-10-12 | minor | Hatch and Gradient / Hatch Edit dialogs (HATCH, GRADIENT, HATCHEDIT, double-click a hatch; HPDLGMODE) | From 023b833fd4ad20f540d45fa124b6501f3c03fc26 Mon Sep 17 00:00:00 2001 From: filforce95 <49290121+filforce95@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:08:56 +0200 Subject: [PATCH 015/531] docs(ui-parity): a press on an object picks it; a drag from it opens no window (#1001) Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2833eba5f..ecdb42731 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -127,7 +127,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. |---|---|---| | Pick, implied window (left→right) and crossing (right→left) | yes | yes, coloured and dashed rectangles (`lib.rs:576-589`, `canvas.rs:823-836`), filled as SELECTIONAREA, WINDOWAREACOLOR, CROSSINGAREACOLOR and SELECTIONAREAOPACITY say (Visual Effect Settings) | | Keywords W, C, WP, CP, F, BOX, AU, SI, M, G (group), CL (class) | yes | yes except CLass: W, C, F, WP, CP (#226); BOX, AUto, SIngle, Multiple, Group, Add, Remove, Undo (#428); ALL, Last, Previous | -| Press-drag selection windows (PICKDRAG) | yes | yes (#63, PICKDRAG = 2); clicks count when the button goes down, even while the mouse moves, and a press held after the pointer leaves a 6-point tolerance for 0.25 s is a drag (#1001) | +| Press-drag selection windows (PICKDRAG) | yes | yes (#63, PICKDRAG = 2); clicks count when the button goes down, even while the mouse moves, and a press held after the pointer leaves a 6-point tolerance for 0.25 s is a drag; a press on an object picks it, and a drag from it does not open a window (#1001) | | Lasso | yes | **no** | | Selection cycling (SELECTIONCYCLING) | yes | toggle nothing reads | | Selection preview, hover highlight | yes | selected and hovered objects redrawn in the selection colour, fills half see-through (SELECTIONEFFECT 1; 0 dashed), selection effect color; HIGHLIGHT (not saved), SELECTIONPREVIEW, PREVIEWEFFECT, PREVIEWFILTER (Visual Effect Settings) | @@ -202,7 +202,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Date | Change | Summary | |---|---|---| -| 2026-10-18 | minor | Clicks on the drawing count when the button goes down, at that spot, even while the mouse moves: points (base points too), object picks, both corners of a click-click window and polygon points; holding the button after the pointer leaves a 6-point tolerance for 0.25 s drags a window (#1001) | +| 2026-10-18 | minor | Clicks on the drawing count when the button goes down, at that spot, even while the mouse moves: points (base points too), object picks, both corners of a click-click window and polygon points; holding the button after the pointer leaves a 6-point tolerance for 0.25 s drags a window; a press on an object picks it, and a drag from it no longer opens a window (#1001) | | 2026-10-12 | minor | Selected and hovered objects redrawn in the selection colour (text and arrowheads included); Options ▸ Selection laid out as AutoCAD's: Object grouping, Show grips, grip object limit, selection preview, Visual Effect Settings (selection area, preview filter) | | 2026-10-12 | minor | Animation effects (dialog and menu fades, smoothed wheel scrolling and ⌘/Ctrl+wheel zoom) follow the operating system's setting; View ▸ Accessibility ▸ Animation Effects chooses System, On or Off | | 2026-10-12 | minor | Hatch and Gradient / Hatch Edit dialogs (HATCH, GRADIENT, HATCHEDIT, double-click a hatch; HPDLGMODE) | From 3f14431a33f814da3f0766b5fabbc6b9bae3dff1 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 19 Oct 2026 02:08:10 +1100 Subject: [PATCH 016/531] UCS drafting: grid lines and tracking tooltip angle as tested helpers The drawn rectangular grid comes from snap::iso::rect_grid_lines, which shares the isometric grid's line families (clipped to the view, capped at MAX_GRID_LINES), and the tracking tooltip angle from tooltip_angle; both now have tests. Ortho with isometric snap reuses the cursor's settings instead of cloning all of Settings again on every mouse move. --- crates/engine/src/snap/iso.rs | 53 +++++++++++++++++++++++++-- crates/engine/src/snap/tracking.rs | 10 +++--- crates/ui-egui/src/canvas.rs | 58 ++++++++++++++---------------- 3 files changed, 83 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/snap/iso.rs b/crates/engine/src/snap/iso.rs index a4469a925..1123eb4a7 100644 --- a/crates/engine/src/snap/iso.rs +++ b/crates/engine/src/snap/iso.rs @@ -216,16 +216,29 @@ pub struct GridLine { /// major line. Empty when a family would need more than [`MAX_GRID_LINES`] lines. pub fn grid_lines(view: Bounds2, d: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec { let Some(d) = spacing(d) else { return Vec::new() }; + // Neighbouring lines of a family are d·cos 30° apart. + families(view, &[30.0, 90.0, 150.0], d * COS30, origin, angle, major_every) +} + +/// The rectangular grid lines (lines along X and along Y, `d` apart, through `origin`, turned by +/// `angle`) that cross `view`; every `major_every`th line of a family is a major line. Empty when +/// a family would need more than [`MAX_GRID_LINES`] lines. +pub fn rect_grid_lines(view: Bounds2, d: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec { + let Some(d) = spacing(d) else { return Vec::new() }; + families(view, &[0.0, 90.0], d, origin, angle, major_every) +} + +/// Lines along each of `degs` (turned by `angle`), `gap` apart, one through `origin`, clipped to +/// `view`. +fn families(view: Bounds2, degs: &[f64], gap: f64, origin: Vec2, angle: f64, major_every: u32) -> Vec { let angle = if angle.is_finite() { angle } else { 0.0 }; if !(view.min.is_finite() && view.max.is_finite() && origin.is_finite()) { return Vec::new(); } let corners = [view.min, Vec2::new(view.max.x, view.min.y), view.max, Vec2::new(view.min.x, view.max.y)]; - // Neighbouring lines of a family are d·cos 30° apart. - let gap = d * COS30; let major_every = i64::from(major_every.max(1)); let mut out = Vec::new(); - for deg in [30.0f64, 90.0, 150.0] { + for ° in degs { let dir = Vec2::from_angle(deg.to_radians() + angle); let n = dir.perp(); let off = origin.dot(n); @@ -291,4 +304,38 @@ mod tests { assert!(grid_lines(v, 1e-9, Vec2::ZERO, 0.0, 5).is_empty()); assert!(grid_lines(v, f64::NAN, Vec2::ZERO, 0.0, 5).is_empty()); } + + /// The rectangular grid: lines along X and Y through the snap base, `d` apart, every + /// `major_every`th major, all turned by SNAPANG (in the World UCS too) and clipped to the view. + #[test] + fn rect_grid_lines_lie_in_the_snap_frame() { + let v = Bounds2 { min: Vec2::new(0.0, 0.0), max: Vec2::new(10.0, 10.0) }; + let lines = rect_grid_lines(v, 1.0, Vec2::ZERO, 0.0, 5); + // 0..=10 along each axis. + assert_eq!(lines.len(), 22); + let inside = |p: Vec2| p.x >= -1e-9 && p.x <= 10.0 + 1e-9 && p.y >= -1e-9 && p.y <= 10.0 + 1e-9; + assert!(lines.iter().all(|l| inside(l.a) && inside(l.b))); + let vertical_major: Vec = lines.iter().filter(|l| (l.a.x - l.b.x).abs() < 1e-9 && l.major).map(|l| l.a.x).collect(); + assert_eq!(vertical_major.len(), 3, "x = 0, 5 and 10"); + assert!(vertical_major.iter().all(|x| (x / 5.0 - (x / 5.0).round()).abs() < 1e-9)); + // Turned 30° about a base at (0.5, 0.25): every line runs at 30° or 120°, and one of each + // passes through the base. + let (base, a) = (Vec2::new(0.5, 0.25), 30f64.to_radians()); + let turned = rect_grid_lines(v, 1.0, base, a, 5); + assert!(!turned.is_empty()); + let (ux, uy) = (Vec2::from_angle(a), Vec2::from_angle(a).perp()); + for l in &turned { + let d = (l.b - l.a).normalized(); + assert!(d.cross(ux).abs() < 1e-9 || d.cross(uy).abs() < 1e-9, "{l:?}"); + // Each line is a whole number of steps from the base across its direction. + let k = (l.a - base).cross(d); + assert!((k - k.round()).abs() < 1e-9, "{l:?}"); + } + let through = |dir: Vec2| turned.iter().any(|l| (l.b - l.a).normalized().cross(dir).abs() < 1e-9 && (base - l.a).cross(dir).abs() < 1e-9); + assert!(through(ux) && through(uy)); + // Too many lines, or no spacing: nothing drawn. + assert!(rect_grid_lines(v, 1e-6, Vec2::ZERO, 0.0, 5).is_empty()); + assert!(rect_grid_lines(v, f64::NAN, Vec2::ZERO, 0.0, 5).is_empty()); + assert!(rect_grid_lines(v, 1.0, Vec2::new(f64::INFINITY, 0.0), 0.0, 5).is_empty()); + } } diff --git a/crates/engine/src/snap/tracking.rs b/crates/engine/src/snap/tracking.rs index 4fb9113bb..0e7f15fad 100644 --- a/crates/engine/src/snap/tracking.rs +++ b/crates/engine/src/snap/tracking.rs @@ -805,7 +805,8 @@ impl crate::Session { return CursorSnap { point: h.point, snap: Some(h), track: None, wait }; } // Isometric snap (SNAPSTYL 1): its lattice in place of the rectangular grid. - let (raw, s) = super::iso::grid_snap(&doc, &space, s, raw); + let snapmode = s.snapmode; + let (raw, mut s) = super::iso::grid_snap(&doc, &space, s, raw); let mut p = raw; if s.snapmode && !s.polarsnap { let (origin, angle) = super::grid_frame_in(&doc, &space); @@ -827,9 +828,10 @@ impl crate::Session { && s.orthomode && !q.corner { - // The drafting settings as they are (`s` has grid snap turned off once the isometric - // lattice took it), with the UCS axes. - p = super::iso::ortho(&self.drafting_settings(), b, p); + // Grid snap as it was before the isometric lattice took it (`grid_snap` turns it off), + // so ortho keeps whole snap steps along the isometric axes. + s.snapmode = snapmode; + p = super::iso::ortho(&s, b, p); } CursorSnap { point: p, snap: None, track: None, wait } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e85493b0c..e6226e79e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -660,41 +660,18 @@ fn adaptive(unit: f64, scale: f64, min_px: f64) -> f64 { fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) { let t = Tokens::get(); let s = app.session.drafting_settings(); - let wb = xf.world_bounds(); if s.gridmode && s.isodraft { draw_iso_grid(app, p, xf); } else if s.gridmode { - let major_n = f64::from(s.gridmajor.max(1)); let unit = if s.gridunit.x == 0.0 { s.snapunit.x } else { s.gridunit.x }; let minor = adaptive(unit, xf.scale, 8.0); - let major = minor * major_n; // The grid lies in the snap frame: SNAPBASE and SNAPANG in the current UCS. let space = app.session.space(); let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0)); - let to_world = |q: Vec2| origin + q.rotate(angle); - // The view's corners in grid coordinates bound the lines needed. - let corners = [wb.min, Vec2::new(wb.max.x, wb.min.y), wb.max, Vec2::new(wb.min.x, wb.max.y)].map(|c| (c - origin).rotate(-angle)); - let lo = Vec2::new(corners.iter().map(|c| c.x).fold(f64::INFINITY, f64::min), corners.iter().map(|c| c.y).fold(f64::INFINITY, f64::min)); - let hi = - Vec2::new(corners.iter().map(|c| c.x).fold(f64::NEG_INFINITY, f64::max), corners.iter().map(|c| c.y).fold(f64::NEG_INFINITY, f64::max)); - let (x0, x1) = ((lo.x / minor).floor(), (hi.x / minor).ceil()); - let (y0, y1) = ((lo.y / minor).floor(), (hi.y / minor).ceil()); - let mut lines = Vec::new(); - if [x0, x1, y0, y1].iter().all(|v| v.is_finite()) && (x1 - x0) < 2000.0 && (y1 - y0) < 2000.0 { - let is_major = |v: f64| ((v / major) - (v / major).round()).abs() < 1e-6; - let stroke = |m: bool| Stroke::new(1.0, if m { t.grid_major } else { t.grid_minor }); - for i in (x0 as i64)..=(x1 as i64) { - let x = i as f64 * minor; - let (a, b) = (to_world(Vec2::new(x, lo.y)), to_world(Vec2::new(x, hi.y))); - lines.push(Shape::line_segment([xf.to_screen(a), xf.to_screen(b)], stroke(is_major(x)))); - } - for j in (y0 as i64)..=(y1 as i64) { - let y = j as f64 * minor; - let (a, b) = (to_world(Vec2::new(lo.x, y)), to_world(Vec2::new(hi.x, y))); - lines.push(Shape::line_segment([xf.to_screen(a), xf.to_screen(b)], stroke(is_major(y)))); - } - } - p.extend(lines); + let lines = cadcraft_engine::snap::iso::rect_grid_lines(xf.world_bounds(), minor, origin, angle, s.gridmajor); + p.extend(lines.into_iter().map(|l| { + Shape::line_segment([xf.to_screen(l.a), xf.to_screen(l.b)], Stroke::new(1.0, if l.major { t.grid_major } else { t.grid_minor })) + })); } // The current UCS's X and Y axes through its origin. let u = app.session.input_ucs(); @@ -1115,6 +1092,12 @@ fn draw_snap_marker(p: &egui::Painter, at: Pos2, hit: &SnapHit) { p.galley(r.min + vec2(3.0, 1.0), galley, Color32::BLACK); } +/// The whole degrees (0–359) a tracking tooltip shows for the path `from` → `to`, measured from +/// the current UCS's X axis at `ucs` radians. +fn tooltip_angle(from: Vec2, to: Vec2, ucs: f64) -> i64 { + ((from.angle_to(to) - ucs).to_degrees().round() as i64).rem_euclid(360) +} + /// Acquired tracking points (small `+`, `//` for a Parallel line), the dotted paths the cursor /// is on and the tooltip naming them ("Endpoint: 5.0000 < 90°"). /// `ucs`: the current UCS's X axis (radians), which the tooltips measure angles from. @@ -1153,10 +1136,7 @@ fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquire } }; p.extend(Shape::dotted_line(&pts, t.snap, 6.0, 1.0)); - let (distance, angle) = ( - cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4), - ((path.from.angle_to(tr.point) - ucs).to_degrees().round() as i64).rem_euclid(360), - ); + let (distance, angle) = (cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4), tooltip_angle(path.from, tr.point, ucs)); tips.push(if path.name == "Polar" { crate::tf!("Polar: {distance} < {angle}°", distance = distance, angle = angle) } else { @@ -2391,6 +2371,22 @@ pub(crate) mod tests { use super::*; use cadcraft_render::DPrim; + /// Tracking tooltips give angles in the current UCS: a path along a UCS turned 30° reads 0°, + /// one along World X reads 330°, and the World UCS reads world angles. + #[test] + fn tooltip_angles_are_measured_from_the_ucs_x_axis() { + let o = Vec2::new(2.0, 1.0); + let at = |deg: f64| o + Vec2::from_angle(deg.to_radians()) * 5.0; + assert_eq!(tooltip_angle(o, at(90.0), 0.0), 90); + assert_eq!(tooltip_angle(o, at(-45.0), 0.0), 315); + let ucs = 30f64.to_radians(); + assert_eq!(tooltip_angle(o, at(30.0), ucs), 0); + assert_eq!(tooltip_angle(o, at(0.0), ucs), 330); + assert_eq!(tooltip_angle(o, at(120.0), ucs), 90); + // A non-finite angle shows a number, not a panic. + assert!((0..360).contains(&tooltip_angle(o, o, f64::NAN))); + } + fn list(handles: &[u64]) -> DisplayList { let prim = |h| DPrim { handle: Handle(h), color: Rgb(255, 255, 255), aci7: true, lw: 0.0, transparency: 0, kind: Kind::Polyline, start: 0, len: 0 }; From e3aeff2a9bc5379e934d633ac709400adf95229f Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 19 Oct 2026 12:07:55 +1100 Subject: [PATCH 017/531] UCS: review fixes (UCSAXISANG 30, icon placement and hits, LISP preview, Previous history) - UCSAXISANG accepts 30. - The UCS icon at the corner is placed by its turned arms' bounds, so it stays on the canvas at any angle, and takes clicks only near its arms rather than anywhere in their boxes. - getpoint/getcorner previews start at the routine's base point in the world (it is a UCS point) and getcorner's rectangle runs along the UCS. - UCS Previous history lives in the drawing (never written to a file): model space's on the Drawing, each layout's on its Layout. Undo and redo restore it with the UCS, it follows a layout rename, and goes with a delete. - The hostile layout UCS test really tests parallel axes, accepts a refused file, and saves and reopens what it reads. --- crates/doc/src/lib.rs | 5 ++ crates/doc/src/tables.rs | 14 +++- crates/engine/src/cmd/layout.rs | 10 ++- crates/engine/src/lib.rs | 4 -- crates/engine/src/lisp/mod.rs | 9 ++- crates/engine/src/lisp/ucs_tests.rs | 31 ++++++++ crates/engine/src/sysvars/table.rs | 2 +- crates/engine/src/ucs.rs | 39 +++++++---- crates/engine/tests/ucs.rs | 52 ++++++++++++++ crates/io/tests/ucs_roundtrip.rs | 32 +++++++-- crates/ui-egui/src/viewcube.rs | 105 ++++++++++++++++++++++++---- 11 files changed, 259 insertions(+), 44 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6462d3ac8..cec0176b2 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -118,6 +118,10 @@ pub struct Drawing { /// Objects hidden for this session by ISOLATEOBJECTS / HIDEOBJECTS. Never written to a file: /// a drawing opens with everything shown again. pub hidden_objects: BTreeSet, + /// Model space's earlier UCSs for UCS Previous, oldest first (each layout keeps its own, + /// [`Layout::ucs_previous`]). Part of the drawing so undo restores them with the UCS. Never + /// written to a file. + pub ucs_previous: Vec, /// What reading the file left out (a DWG's object records the reader couldn't decode), told /// to the user when the drawing opens. Never written to a file. pub read_notes: Vec, @@ -180,6 +184,7 @@ impl Drawing { scales: imperial_scales(), handseed: 0x100, hidden_objects: BTreeSet::new(), + ucs_previous: Vec::new(), read_notes: Vec::new(), refedit: None, skipped_records: BTreeMap::new(), diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index 522b3e96a..5ac335673 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -788,11 +788,23 @@ pub struct Layout { /// `None`: the World UCS. Its name is empty when it isn't a named UCS. #[serde(default, skip_serializing_if = "Option::is_none")] pub ucs: Option, + /// The layout's earlier UCSs for UCS Previous, oldest first: they go with the layout when it + /// is renamed and with it when it is deleted. Never written to a file. + #[serde(skip)] + pub ucs_previous: Vec, } impl Layout { pub fn new(name: &str, tab_order: u32) -> Self { - Layout { name: name.into(), tab_order, page: PageSetup::default(), entities: EntityStore::new(), view: None, ucs: None } + Layout { + name: name.into(), + tab_order, + page: PageSetup::default(), + entities: EntityStore::new(), + view: None, + ucs: None, + ucs_previous: Vec::new(), + } } } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 9c9d6f935..6476923cb 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -305,7 +305,15 @@ fn run_copy(s: &mut Session, p: &Value) -> Result { let h = d.new_handle(); store.push(Entity { handle: h, ..Entity::clone(e) }); } - d.layouts.push(Layout { name: to.clone(), tab_order: order, page: src.page, entities: store, view: src.view, ucs: src.ucs }); + d.layouts.push(Layout { + name: to.clone(), + tab_order: order, + page: src.page, + entities: store, + view: src.view, + ucs: src.ucs, + ucs_previous: Vec::new(), + }); Ok(json!({ "name": to })) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2c927ba6f..427ace1b6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -144,9 +144,6 @@ pub struct DocState { /// The Block Editor (BEDIT), when it is open: `doc` is then the editor's drawing, and the /// drawing itself waits in it ([`DocState::drawing`]). pub block_edit: Option, - /// Earlier UCSs for UCS Previous, oldest first, with the space each was current in (at most - /// [`ucs::MAX_PREVIOUS`] per space; not saved with the drawing). - pub ucs_previous: Vec<(Space, ucs::UcsFrame, String)>, /// The user was told that the current UCS is tilted ([`Session::note_tilted_ucs`]). pub ucs_tilted_noted: bool, } @@ -175,7 +172,6 @@ impl DocState { uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), binary_dxf: false, block_edit: None, - ucs_previous: Vec::new(), ucs_tilted_noted: false, } } diff --git a/crates/engine/src/lisp/mod.rs b/crates/engine/src/lisp/mod.rs index ac42d53cd..5a7fb033b 100644 --- a/crates/engine/src/lisp/mod.rs +++ b/crates/engine/src/lisp/mod.rs @@ -504,10 +504,15 @@ impl Session { let Need::Get(req) = self.lisp.run.as_ref()?.waiting.as_ref()? else { return None }; let line = |a: cadcraft_geom::Vec2, b: cadcraft_geom::Vec2| cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: a.to3(0.0), b: b.to3(0.0) }); - let Some(b) = req.first.or(req.base).map(|p| cadcraft_geom::Vec2::new(p[0], p[1])) else { return Some(Vec::new()) }; + // The base is a UCS point (as the routine gave it); the preview is drawn in world space. + let ucs = self.input_ucs(); + let Some(bu) = req.first.or(req.base).map(|p| cadcraft_geom::Vec2::new(p[0], p[1])) else { return Some(Vec::new()) }; + let b = ucs.to_wcs(bu); Some(match req.kind { input::GetKind::Corner => { - let (c1, c2) = (cadcraft_geom::Vec2::new(cursor.x, b.y), cadcraft_geom::Vec2::new(b.x, cursor.y)); + // The rectangle runs along the UCS axes, as the corner it returns is measured. + let cu = ucs.to_ucs(cursor); + let (c1, c2) = (ucs.to_wcs(cadcraft_geom::Vec2::new(cu.x, bu.y)), ucs.to_wcs(cadcraft_geom::Vec2::new(bu.x, cu.y))); vec![line(b, c1), line(c1, cursor), line(cursor, c2), line(c2, b)] } input::GetKind::Point | input::GetKind::Dist | input::GetKind::Angle { .. } => vec![line(b, cursor)], diff --git a/crates/engine/src/lisp/ucs_tests.rs b/crates/engine/src/lisp/ucs_tests.rs index f03b27a42..bf2dbf4ef 100644 --- a/crates/engine/src/lisp/ucs_tests.rs +++ b/crates/engine/src/lisp/ucs_tests.rs @@ -121,6 +121,37 @@ fn getpoint_answers_in_the_ucs_and_command_reads_ucs_points() { assert!(last.a.xy().dist(Vec2::new(100.0, 60.0)) < 1e-9 && last.b.xy().dist(Vec2::new(96.0, 53.0)) < 1e-9, "{last:?}"); } +/// The rubber band of `getpoint`/`getcorner` with a base point starts where that UCS point is in +/// the world, and `getcorner`'s rectangle runs along the UCS axes. +#[test] +fn getpoint_and_getcorner_previews_start_at_the_ucs_base() { + let ends = |k: &cadcraft_doc::EntityKind| match k { + cadcraft_doc::EntityKind::Line(l) => (l.a.xy(), l.b.xy()), + other => panic!("{other:?}"), + }; + let near = |a: Vec2, b: Vec2| a.dist(b) < 1e-9; + let mut s = session(); + turned(&mut s); + // UCS (0, 0) is world (100, 50); the cursor is at world (90, 70), UCS (20, 10). + let cursor = Vec2::new(90.0, 70.0); + s.cmdline("(setq p (getpoint '(0 0)))").unwrap(); + let band = s.lisp_preview(cursor).unwrap(); + assert_eq!(band.len(), 1); + let (a, b) = ends(&band[0]); + assert!(near(a, Vec2::new(100.0, 50.0)) && near(b, cursor), "{a:?} {b:?}"); + s.input(crate::Input::Point(cursor)).unwrap(); + s.cmdline("(setq c (getcorner '(0 0)))").unwrap(); + let rect: Vec<(Vec2, Vec2)> = s.lisp_preview(cursor).unwrap().iter().map(ends).collect(); + // Along UCS X (world +Y) to UCS (20, 0), the cursor, UCS (0, 10) (world (90, 50)), back. + let want = [(100.0, 50.0), (100.0, 70.0), (90.0, 70.0), (90.0, 50.0)].map(|(x, y)| Vec2::new(x, y)); + assert_eq!(rect.len(), 4); + for (i, (a, b)) in rect.iter().enumerate() { + assert!(near(*a, want[i]) && near(*b, want[(i + 1) % 4]), "side {i}: {a:?} {b:?}"); + } + s.input(crate::Input::Point(cursor)).unwrap(); + assert!(close(pt(&to_text(&s.lisp_var("C"), true)), [20.0, 10.0, 0.0]), "the corner it returns, in the UCS"); +} + #[test] fn getangle_and_getdist_measure_in_the_ucs() { let mut s = session(); diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index df668c1a2..fcae610cd 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -73,7 +73,7 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("TEXTFILL", Kind::Choice(&[0, 1]), Def::Int(1)), ("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)), - ("UCSAXISANG", Kind::Choice(&[5, 10, 15, 18, 22, 45, 90, 180]), Def::Int(90)), + ("UCSAXISANG", Kind::Choice(&[5, 10, 15, 18, 22, 30, 45, 90, 180]), Def::Int(90)), // 1: the UCS icon is shown; 2: at the UCS origin when that is on screen. ("UCSICON", Kind::Int(0, 3), Def::Int(3)), ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), diff --git a/crates/engine/src/ucs.rs b/crates/engine/src/ucs.rs index c23190bed..bf6eeb78b 100644 --- a/crates/engine/src/ucs.rs +++ b/crates/engine/src/ucs.rs @@ -196,6 +196,15 @@ pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str) } } +/// `space`'s UCS Previous history, kept in the drawing (so undo restores it) and, for a layout, +/// with the layout (so it follows a rename and goes with a delete). `None`: no such layout. +fn previous_mut<'a>(d: &'a mut Drawing, space: &Space) -> Option<&'a mut Vec> { + match space { + Space::Model => Some(&mut d.ucs_previous), + Space::Paper(layout) => d.layouts.iter_mut().find(|l| l.name.eq_ignore_ascii_case(layout)).map(|l| &mut l.ucs_previous), + } +} + /// The named UCS `name` of the drawing's UCS table, if it has one with usable axes. pub fn named(d: &Drawing, name: &str) -> Option<(UcsFrame, String)> { let u = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name.trim()))?; @@ -244,14 +253,14 @@ impl Session { if old == frame && old_name.eq_ignore_ascii_case(name) { return Ok(()); } - set_current(self.doc_mut()?, &space, &frame, name); - let st = self.state_mut()?; - st.ucs_previous.push((space.clone(), old, old_name)); - // At most MAX_PREVIOUS per space: drop that space's oldest. - if st.ucs_previous.iter().filter(|(s, _, _)| *s == space).count() > MAX_PREVIOUS - && let Some(i) = st.ucs_previous.iter().position(|(s, _, _)| *s == space) - { - st.ucs_previous.remove(i); + let d = self.doc_mut()?; + set_current(d, &space, &frame, name); + if let Some(h) = previous_mut(d, &space) { + h.push(old.record(&old_name)); + // At most MAX_PREVIOUS: drop the oldest. + if h.len() > MAX_PREVIOUS { + h.remove(0); + } } Ok(()) } @@ -259,11 +268,15 @@ impl Session { /// Go back to the UCS before the current one in this space; `false` when there is none. pub fn ucs_previous(&mut self) -> Result { let space = self.space(); - let st = self.state_mut()?; - let Some(i) = st.ucs_previous.iter().rposition(|(s, _, _)| *s == space) else { return Ok(false) }; - let (_, frame, name) = st.ucs_previous.remove(i); - set_current(self.doc_mut()?, &space, &frame, &name); - Ok(true) + let d = self.doc_mut()?; + // An entry with unusable axes (none is ever stored) is skipped, not restored. + while let Some(u) = previous_mut(d, &space).and_then(|h| h.pop()) { + if let Some(frame) = UcsFrame::of(&u) { + set_current(d, &space, &frame, &u.name); + return Ok(true); + } + } + Ok(false) } /// UCSICON: 1 the icon is shown, 2 at the UCS origin (when that is on screen). diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs index 37baaa9ec..5adebbde2 100644 --- a/crates/engine/tests/ucs.rs +++ b/crates/engine/tests/ucs.rs @@ -125,6 +125,10 @@ fn ucs_z_turns_about_z_and_defaults_to_ucsaxisang() { assert!(cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(33)).is_err(), "only the listed angles"); typed(&mut s, &["ucs z -165"]); assert!(ang_eq(s.ucs().rotation(), 0.0)); + // 30 is one of the listed angles too. + cadcraft_engine::sysvars::set(&mut s, "UCSAXISANG", &json!(30)).unwrap(); + typed(&mut s, &["ucs z "]); + assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians())); } #[test] @@ -276,6 +280,54 @@ fn a_ucs_change_is_undone_like_an_edit() { assert!(near3(s.ucs().origin, Vec3::new(100.0, 50.0, 0.0))); } +/// Undo restores UCS Previous's history with the UCS: undoing UCS Previous gives back the entry +/// it used, and undoing a UCS change takes away the entry it added. +#[test] +fn undo_restores_the_ucs_previous_history() { + let previous = |s: &mut Session| s.execute("ucs", &json!({"option": "previous"})).is_ok(); + let mut s = session(); + typed(&mut s, &["ucs z 30"]); + assert!(previous(&mut s) && s.ucs().is_world()); + s.undo().unwrap(); + assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()), "undo of UCS Previous"); + assert!(previous(&mut s) && s.ucs().is_world(), "its history entry came back too"); + s.redo().unwrap(); + let mut s = session(); + typed(&mut s, &["ucs z 30", "ucs z 30"]); + assert!(ang_eq(s.ucs().rotation(), 60f64.to_radians())); + s.undo().unwrap(); + assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians())); + // The 30° the undone step remembered is gone: Previous goes straight to the World UCS. + assert!(previous(&mut s) && s.ucs().is_world()); + assert!(!previous(&mut s), "nothing before the World UCS"); +} + +/// A layout's UCS Previous history goes with the layout: it follows a rename, and a layout +/// deleted and made again under the same name starts without one. +#[test] +fn a_layouts_ucs_history_follows_it_and_goes_with_it() { + let previous = |s: &mut Session| s.execute("ucs", &json!({"option": "previous"})).is_ok(); + let set = |s: &mut Session, name: &str| s.execute("layout.set", &json!({"name": name})).unwrap(); + let mut s = session(); + s.execute("layout", &json!({"option": "new", "name": "A"})).unwrap(); + set(&mut s, "A"); + typed(&mut s, &["ucs z 30"]); + set(&mut s, "Model"); + s.execute("layout", &json!({"option": "rename", "name": "A", "to": "B"})).unwrap(); + set(&mut s, "B"); + assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians())); + assert!(previous(&mut s) && s.ucs().is_world(), "the history followed the rename"); + typed(&mut s, &["ucs z 45"]); + set(&mut s, "Model"); + s.execute("layout", &json!({"option": "delete", "name": "B"})).unwrap(); + s.execute("layout", &json!({"option": "new", "name": "B"})).unwrap(); + set(&mut s, "B"); + assert!(s.ucs().is_world() && !previous(&mut s), "a new layout B has none of the old B's history"); + // Model space's history is its own throughout. + set(&mut s, "Model"); + assert!(!previous(&mut s)); +} + #[test] fn paper_space_has_its_own_ucs() { let mut s = session(); diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index b79ee3b00..1f78834f8 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -188,8 +188,14 @@ fn hostile_layout_ucs_groups_are_ignored() { let d = Drawing::default(); let text = cadcraft_io::write_dxf(&d); let name = d.layouts[0].name.clone(); - // Rewrite the layout's UCS groups as nonsense: no length, along each other, a dangling 345. - for (x, y, h) in [("0.0", "0.0", "FFFF"), ("1.0", "1.0", "0"), ("nan", "1.0", "ZZ")] { + // Rewrite the layout's UCS axes (X: groups 16/26, Y: 17/27) as nonsense, each with a dangling + // 345 handle: no length, Y along X, not a number. + let usable = |l: &cadcraft_doc::Layout| l.ucs.as_ref().is_none_or(|u| u.name.is_empty() && u.x_axis.cross(u.y_axis).len() > 1e-9); + for (case, [x16, x26, y17, y27], h) in [ + ("no length", ["0.0", "0.0", "0.0", "0.0"], "FFFF"), + ("Y along X", ["1.0", "0.0", "2.0", "0.0"], "0"), + ("not a number", ["nan", "0.0", "0.0", "1.0"], "ZZ"), + ] { let mut out = String::new(); let mut in_layout = false; let mut lines = text.lines(); @@ -199,9 +205,10 @@ fn hostile_layout_ucs_groups_are_ignored() { in_layout = vt == "LAYOUT"; } let v = match (in_layout, ct) { - (true, "16") => x.to_string(), - (true, "27") => y.to_string(), - (true, "17") => y.to_string(), + (true, "16") => x16.to_string(), + (true, "26") => x26.to_string(), + (true, "17") => y17.to_string(), + (true, "27") => y27.to_string(), _ => v.to_string(), }; out.push_str(&format!("{c}\n{v}\n")); @@ -209,9 +216,20 @@ fn hostile_layout_ucs_groups_are_ignored() { out.push_str(&format!("345\n{h}\n")); } } - let back = cadcraft_io::read_dxf(out.as_bytes()).unwrap(); + // Refusing the file is fine; reading it must leave no unusable UCS, saved and reopened too. + // Parallel axes are plain numbers: that file must read, so the rejection below runs. + let back = match cadcraft_io::read_dxf(out.as_bytes()) { + Ok(back) => back, + Err(e) if case == "Y along X" => panic!("{case}: {e}"), + Err(_) => continue, + }; let l = back.layout(&name).unwrap(); - assert!(l.ucs.as_ref().is_none_or(|u| u.name.is_empty() && u.x_axis.cross(u.y_axis).len() > 1e-9), "{x},{y},{h}: {:?}", l.ucs); + assert!(usable(l), "{case}: {:?}", l.ucs); + if case == "Y along X" { + assert!(l.ucs.is_none(), "parallel axes are rejected: {:?}", l.ucs); + } + let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&back).as_bytes()).unwrap(); + assert!(usable(again.layout(&name).unwrap()), "{case} after save and reopen"); } } diff --git a/crates/ui-egui/src/viewcube.rs b/crates/ui-egui/src/viewcube.rs index e871ec069..0dfb9660f 100644 --- a/crates/ui-egui/src/viewcube.rs +++ b/crates/ui-egui/src/viewcube.rs @@ -156,6 +156,10 @@ fn paint_home(p: &egui::Painter, r: Rect, hot: bool) { /// How long the UCS icon's arms are, in points. pub const ARM: f32 = 60.0; +/// How far past an arm's end its X or Y label reaches, in points. +const LABEL: f32 = 16.0; +/// How close to an arm a pointer counts as on the icon, in points. +const HIT: f32 = 8.0; /// Where the UCS icon is drawn: the point its arms start from, the screen directions of its X /// and Y arms (unit vectors: the current UCS's axes seen in the plan view) and whether the UCS is @@ -183,13 +187,13 @@ impl IconPlace { let l = d.length(); if l.is_finite() && l > 1e-6 { d / l } else { or } }; - let mut place = IconPlace { x: dir(u.x, vec2(1.0, 0.0)), y: dir(u.y, vec2(0.0, -1.0)), world: u.is_world(), ..IconPlace::corner(canvas) }; + let mut place = IconPlace::corner_turned(canvas, dir(u.x, vec2(1.0, 0.0)), dir(u.y, vec2(0.0, -1.0)), u.is_world()); // At the origin only where the screen shows the space the UCS belongs to (not from paper // space into an active viewport). let same_space = app.session.space() == app.session.layout_space(); if app.session.ucsicon_bits() & 2 != 0 && same_space { let at = to_screen(u.origin.xy()); - let reach = ARM + 16.0; + let reach = ARM + LABEL; let inner = canvas.shrink(12.0); if [at, at + place.x * reach, at + place.y * reach].iter().all(|p| p.x.is_finite() && p.y.is_finite() && inner.contains(*p)) { place.origin = at; @@ -198,10 +202,34 @@ impl IconPlace { place } - /// The icon's arms with room around them: the X arm and the Y arm. - pub fn arms(&self) -> [Rect; 2] { + /// The icon with arms along `x` and `y` at the lower-left corner: placed so the arms and their + /// labels take the corner the World UCS's icon does, whichever way they point. + pub fn corner_turned(canvas: Rect, x: egui::Vec2, y: egui::Vec2, world: bool) -> IconPlace { + let home = IconPlace::corner(canvas).origin; + let reach = ARM + LABEL; + let (ends_x, ends_y) = ([0.0, x.x * reach, y.x * reach], [0.0, x.y * reach, y.y * reach]); + // The World icon's arms run right and up from `home`: shift so the turned arms' left and + // bottom edges sit where those do. + let left = ends_x.iter().copied().fold(0.0f32, f32::min); + let bottom = ends_y.iter().copied().fold(0.0f32, f32::max); + let origin = pos2(home.x - left, home.y - bottom); + IconPlace { origin: if origin.x.is_finite() && origin.y.is_finite() { origin } else { home }, x, y, world } + } + + /// The icon's arms out to their labels: the X arm and the Y arm, as screen segments. + pub fn arms(&self) -> [[Pos2; 2]; 2] { let o = self.origin; - [Rect::from_two_pos(o, o + self.x * (ARM + 20.0)).expand(8.0), Rect::from_two_pos(o, o + self.y * (ARM + 22.0)).expand(8.0)] + [[o, o + self.x * (ARM + 20.0)], [o, o + self.y * (ARM + 22.0)]] + } + + /// Whether `p` is on the icon: within [`HIT`] of an arm (labels included), not merely in the + /// box around a turned arm. + pub fn hit(&self, p: Pos2) -> bool { + self.arms().iter().any(|[a, b]| { + let ab = *b - *a; + let t = if ab.length_sq() > 0.0 { ((p - *a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + (*a + ab * t - p).length() <= HIT + }) } } @@ -221,11 +249,18 @@ fn ucs_label(app: &CadApp) -> String { /// coordinate-system menu. pub fn ucs_icon(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect, place: &IconPlace) { let t = Tokens::get(); - let [x, y] = place.arms(); - let rx = ui.interact(x, ui.id().with("ucs_x"), Sense::click_and_drag()); - let ry = ui.interact(y, ui.id().with("ucs_y"), Sense::click_and_drag()); - let resp = (rx | ry).on_hover_cursor(CursorIcon::PointingHand).on_hover_text(format!("UCS icon: {}", ucs_label(app))); - if resp.hovered() { + // The arms' boxes, but only a pointer near an arm takes clicks (a turned arm's box is mostly + // drawing). The widget stays every frame so its menu, once open, keeps its anchor. + let near = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| place.hit(p)); + let sense = if near { Sense::click_and_drag() } else { Sense::hover() }; + let [x, y] = place.arms().map(|[a, b]| Rect::from_two_pos(a, b).expand(HIT)); + let rx = ui.interact(x, ui.id().with("ucs_x"), sense); + let ry = ui.interact(y, ui.id().with("ucs_y"), sense); + let mut resp = rx | ry; + if near { + resp = resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(format!("UCS icon: {}", ucs_label(app))); + } + if near && resp.hovered() { let o = place.origin; let st = Stroke::new(2.0, t.hover); let p = ui.painter_at(canvas); @@ -374,14 +409,17 @@ mod tests { assert!((p.x - vec2(0.0, -1.0)).length() < 1e-6 && (p.y - vec2(-1.0, 0.0)).length() < 1e-6, "{p:?}"); assert!((p.origin - pos2(c.center().x + 20.0, c.center().y - 10.0)).length() < 1e-3); // Its click areas lie along the turned arms. - let [ax, ay] = p.arms(); - assert!(ax.contains(p.origin + p.x * 40.0) && ay.contains(p.origin + p.y * 40.0)); - // Noorigin, or an origin off screen: the corner. + assert!(p.hit(p.origin + p.x * 40.0) && p.hit(p.origin + p.y * 40.0)); + // Noorigin, or an origin off screen: the corner, the turned icon in the World icon's place. + let corner = IconPlace::corner_turned(c, p.x, p.y, false).origin; app.run("ucsicon", json!({"origin": false})).unwrap(); - assert_eq!(IconPlace::of(&app, c, to_screen).origin, IconPlace::corner(c).origin); + assert_eq!(IconPlace::of(&app, c, to_screen).origin, corner); app.run("ucsicon", json!({"origin": true})).unwrap(); app.run("ucs", json!({"option": "origin", "origin": [1e6, 0]})).unwrap(); - assert_eq!(IconPlace::of(&app, c, to_screen).origin, IconPlace::corner(c).origin); + assert_eq!(IconPlace::of(&app, c, to_screen).origin, corner); + app.run("ucs", json!({"option": "world"})).unwrap(); + app.run("ucs", json!({"option": "origin", "origin": [1e6, 0]})).unwrap(); + assert_eq!(IconPlace::of(&app, c, to_screen).origin, IconPlace::corner(c).origin, "unturned: where it always was"); // The menu switch turns UCSICON off through its command. app.run("ui.toggle.ucsicon", json!({"on": false})).unwrap(); assert_eq!(app.session.ucsicon_bits() & 1, 0); @@ -391,6 +429,43 @@ mod tests { assert_eq!(app.session.ucsicon_bits(), 1); } + /// At the corner, a turned icon's arms and labels stay on the canvas at every angle, inside + /// the World icon's corner box. + #[test] + fn a_turned_corner_icon_stays_on_the_canvas() { + let c = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)); + let home = IconPlace::corner(c).origin; + let reach = ARM + LABEL; + let (box_left, box_bottom) = (home.x, home.y); + for deg in (0..360).step_by(15) { + let a = (deg as f32).to_radians(); + // Screen y runs down: the Y arm is the X arm turned a quarter counterclockwise on screen. + let (x, y) = (vec2(a.cos(), -a.sin()), vec2(-a.sin(), -a.cos())); + let p = IconPlace::corner_turned(c, x, y, false); + for end in [p.origin, p.origin + x * reach, p.origin + y * reach] { + assert!(c.contains(end), "{deg}°: {end:?} off {c:?}"); + assert!(end.x >= box_left - 1e-3 && end.y <= box_bottom + 1e-3, "{deg}°: {end:?}"); + } + } + // Unturned, exactly where the World icon always was. + assert_eq!(IconPlace::corner_turned(c, vec2(1.0, 0.0), vec2(0.0, -1.0), true).origin, home); + } + + /// Only a pointer near an arm is on the icon: on a 45° UCS the corner of the arm's box, well + /// away from the arm, is drawing. + #[test] + fn ucs_icon_hits_follow_the_arms_not_their_boxes() { + let s = std::f32::consts::FRAC_1_SQRT_2; + let p = IconPlace { origin: pos2(200.0, 200.0), x: vec2(s, -s), y: vec2(-s, -s), world: false }; + assert!(p.hit(p.origin) && p.hit(p.origin + p.x * 50.0) && p.hit(p.origin + p.y * (ARM + 20.0))); + assert!(p.hit(p.origin + p.x * 30.0 + p.y * 7.0), "within reach of the X arm"); + // The X arm's box spans 200..257 across; its far corner is 40 points from the arm. + let box_corner = pos2(200.0 + (ARM + 20.0) * s, 200.0); + assert!(!p.hit(box_corner), "{box_corner:?}"); + assert!(!p.hit(p.origin + p.x * (ARM + 40.0)), "past the label"); + assert!(!p.hit(pos2(f32::NAN, 0.0))); + } + #[test] fn ucs_icon_and_wcs_pill_open_the_coordinate_system_menu() { let (mut app, ctx) = app_and_ctx(); From 821b8ad18c083eef004603c6ad307e71a525ab56 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 19 Oct 2026 14:44:41 +1100 Subject: [PATCH 018/531] UCS: UCSICON is undoable, one message per failed menu pick, no stray UCS name in DXF - UCSICON gets its own undo step, as SETVAR does: it lives in the drawing, so undoing the edit before it put the old icon setting back. - A failed pick in the coordinate-system menu is reported once (CadApp::run already echoes it). - Model space's UCS name is written to DXF ($UCSNAME and CADCraft's copy) only for a UCS the drawing has, beside the axes it came with. --- crates/engine/src/cmd/ucs.rs | 3 ++- crates/engine/tests/ucs.rs | 20 ++++++++++++++++++++ crates/io/src/dxf_write.rs | 22 ++++++++++++++++------ crates/io/tests/ucs_roundtrip.rs | 26 ++++++++++++++++++++++++++ crates/ui-egui/src/viewcube.rs | 28 ++++++++++++++++++++++++---- 5 files changed, 88 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/ucs.rs b/crates/engine/src/cmd/ucs.rs index 75a477817..cdc950d3d 100644 --- a/crates/engine/src/cmd/ucs.rs +++ b/crates/engine/src/cmd/ucs.rs @@ -59,7 +59,8 @@ pub fn specs() -> Vec { .interactive(|_| Ok(Box::new(UcsM::starting(Stage::ZAngle)))), CommandSpec::new("ucsicon", "UCS Icon", run_ucsicon) .params("{on?: bool, origin?: bool} (UCSICON: the icon shown, and at the UCS origin when that is on screen) → {on, origin}") - .noundo() + // Undoable like SETVAR: UCSICON lives in the drawing, so without a step of its own an + // undo of the edit before it would put the old value back. .interactive(|_| Ok(Box::new(UcsIconM))), ] } diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs index 5adebbde2..82bd34e2d 100644 --- a/crates/engine/tests/ucs.rs +++ b/crates/engine/tests/ucs.rs @@ -475,6 +475,26 @@ fn ucsicon_options() { assert!(cadcraft_engine::sysvars::set(&mut s, "UCSICON", &json!(9)).is_err()); } +/// UCSICON is its own undo step: undoing it brings the icon back, and an undo never undoes the +/// edit before it while leaving the icon setting behind (or the other way round). +#[test] +fn ucsicon_is_undone_on_its_own() { + let mut s = session(); + let lines = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + typed(&mut s, &["ucsicon off"]); + assert_eq!(s.ucsicon_bits() & 1, 0); + s.undo().unwrap(); + assert_eq!(s.ucsicon_bits() & 1, 1, "undo takes back UCSICON OFF"); + assert_eq!(lines(&s), 1, "and leaves the line drawn before it"); + s.undo().unwrap(); + assert_eq!(lines(&s), 0); + assert_eq!(s.ucsicon_bits() & 1, 1); + s.redo().unwrap(); + s.redo().unwrap(); + assert_eq!((lines(&s), s.ucsicon_bits() & 1), (1, 0), "redo brings both back"); +} + #[test] fn a_tilted_ucs_from_a_file_is_kept_and_input_stays_in_the_world_ucs() { let mut s = session(); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index c979f313d..5384e36a1 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -304,11 +304,15 @@ fn model_ucs(d: &Drawing) -> Ucs { let h = &d.header; let p = |name: &str| h.point(name).filter(|v| v.is_finite()); let axis = |name: &str| p(name).filter(|v| v.len() > 1e-12); - let (x, y) = match (axis("UCSXDIR"), axis("UCSYDIR")) { - (Some(x), Some(y)) if x.cross(y).len() > 1e-9 * x.len() * y.len() => (x, y), - _ => (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)), + let (x, y, usable) = match (axis("UCSXDIR"), axis("UCSYDIR")) { + (Some(x), Some(y)) if x.cross(y).len() > 1e-9 * x.len() * y.len() => (x, y, true), + _ => (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), false), }; - Ucs { name: h.str("UCSNAME", ""), origin: p("UCSORG").unwrap_or(Vec3::ZERO), x_axis: x, y_axis: y } + // The name only of a UCS table record, and only with the axes it came with: a name read from a + // file without its record, or beside axes replaced by the World UCS's, is dropped. + let raw = h.str("UCSNAME", ""); + let name = d.ucss.iter().find(|u| usable && u.name.eq_ignore_ascii_case(raw.trim())).map(|u| u.name.clone()).unwrap_or_default(); + Ucs { name, origin: p("UCSORG").unwrap_or(Vec3::ZERO), x_axis: x, y_axis: y } } fn header_vars(w: &mut W, d: &Drawing) { @@ -344,6 +348,11 @@ fn header_vars(w: &mut W, d: &Drawing) { w.i(c, i); } } + // Only the name of a UCS the drawing has, with the axes written above. + (c, _) if *name == "UCSNAME" => { + w.s(9, "$UCSNAME"); + w.s(c, model_ucs(d).name); + } (c, v) => { if let Some(t) = v.as_str() { w.s(9, format!("${name}")); @@ -1783,8 +1792,9 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { if let Some(name) = d.header.get("CMLEADERSTYLE").and_then(HVal::as_str) { xrecords.push((dxf_ext::MLEADER_STYLE_KEY, w.h(), vec![name.to_string()])); } - if let Some(name) = d.header.get("UCSNAME").and_then(HVal::as_str).map(str::trim).filter(|n| !n.is_empty()) { - xrecords.push((dxf_ext::UCS_NAME_KEY, w.h(), vec![name.to_string()])); + let ucs_name = model_ucs(d).name; + if !ucs_name.is_empty() { + xrecords.push((dxf_ext::UCS_NAME_KEY, w.h(), vec![ucs_name])); } if let Some(chunks) = dxf_ext::constraint_chunks(&d.constraints, &d.parametric) { xrecords.push((dxf_ext::CONSTRAINTS_KEY, w.h(), chunks)); diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index 1f78834f8..e396994b6 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -183,6 +183,32 @@ fn broken_ucs_values_are_not_written_back() { assert!(back.layouts[0].ucs.is_none()); } +/// Model space's UCS name is written only for a UCS the drawing has, with the axes it came with: +/// a name without its record, or beside axes replaced by the World UCS's, is left out of both +/// $UCSNAME and CADCraft's copy of it. +#[test] +fn a_ucs_name_without_its_ucs_is_not_written() { + let name_written = |d: &Drawing| { + let text = cadcraft_io::write_dxf(d); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + ( + group(&header_var(&text, "UCSNAME"), "2").unwrap_or_default().trim().to_string(), + text.contains("CADCRAFT_UCSNAME"), + back.header.str("UCSNAME", ""), + ) + }; + // Kept: SITE is in the UCS table and its axes are current. + assert_eq!(name_written(&drawing()), ("SITE".to_string(), true, "SITE".to_string())); + // No such record (as a file can say). + let mut ghost = drawing(); + ghost.header.set_str("UCSNAME", "GHOST"); + assert_eq!(name_written(&ghost), (String::new(), false, String::new())); + // The record is there, but the axes beside the name are unusable: written as the World UCS. + let mut broken = drawing(); + broken.header.set("UCSXDIR", HVal::Point(Vec3::ZERO)); + assert_eq!(name_written(&broken), (String::new(), false, String::new())); +} + #[test] fn hostile_layout_ucs_groups_are_ignored() { let d = Drawing::default(); diff --git a/crates/ui-egui/src/viewcube.rs b/crates/ui-egui/src/viewcube.rs index 0dfb9660f..26659b8f8 100644 --- a/crates/ui-egui/src/viewcube.rs +++ b/crates/ui-egui/src/viewcube.rs @@ -298,13 +298,17 @@ fn ucs_menu(app: &mut CadApp, popup: egui::Popup<'_>) { ui.close(); } }); - if let Some((id, params)) = action - && let Err(e) = app.run(id, params) - { - app.session.echo(e); + if let Some((id, params)) = action { + menu_action(app, id, params); } } +/// Run a coordinate-system menu pick. A failure is already in the command history: +/// [`CadApp::run`] echoes it (and the icon switch runs UCSICON through it). +fn menu_action(app: &mut CadApp, id: &str, params: serde_json::Value) { + let _ = app.run(id, params); +} + #[cfg(test)] mod tests { use super::*; @@ -348,6 +352,22 @@ mod tests { app.canvas.rect.unwrap_or(Rect::NOTHING) } + /// A menu pick that fails (a tilted named UCS) tells the user once, not twice. + #[test] + fn a_failed_menu_pick_is_reported_once() { + let (mut app, _ctx) = app_and_ctx(); + let tilted = cadcraft_engine::doc::Ucs { + name: "T".into(), + origin: cadcraft_engine::geom::Vec3::ZERO, + x_axis: cadcraft_engine::geom::Vec3::new(1.0, 0.0, 0.0), + y_axis: cadcraft_engine::geom::Vec3::new(0.0, 0.0, 1.0), + }; + app.session.doc_mut().unwrap().ucss.push(tilted); + menu_action(&mut app, "ucs", json!({"option": "named", "action": "restore", "name": "T"})); + let told = app.session.log.iter().filter(|l| l.contains("tilted out of the XY plane")).count(); + assert_eq!(told, 1, "{:?}", app.session.log); + } + fn view(app: &CadApp) -> (f64, f64, f64) { let v = app.session.state().map(|s| s.view()).unwrap_or_default(); (v.center.x, v.center.y, v.height) From d7de5ccdf3487b46305fe80df10e8dadca67e24a Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 19 Oct 2026 15:27:51 +1100 Subject: [PATCH 019/531] UCS: write model space's UCS name only while the UCS is still that named frame A $UCSNAME beside an origin or axes that differ from its UCS table record was written back as the current named UCS, so restoring that name later would move the UCS. The writer now keeps the name only when the current frame is the record's, by the same rule the reader uses to restore it (dxf_ext::is_named_frame, now shared). --- crates/io/src/dxf_ext.rs | 6 ++++++ crates/io/src/dxf_read.rs | 4 +--- crates/io/src/dxf_write.rs | 15 +++++++++++---- crates/io/tests/ucs_roundtrip.rs | 9 +++++++++ 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 781019fae..48760323f 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -38,6 +38,12 @@ pub(crate) const MLEADER_STYLE_KEY: &str = "CADCRAFT_MLEADERSTYLE"; /// Named-object-dictionary key of the XRECORD holding model space's current UCS name ($UCSNAME, /// which the DWG bridge drops). pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME"; + +/// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding): +/// only then is the current UCS still that named one, read or written. +pub(crate) fn is_named_frame(u: &cadcraft_doc::Ucs, origin: cadcraft_geom::Vec3, x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool { + (origin - u.origin).len() <= 1e-9 * (1.0 + origin.len()) && (x - u.x_axis).len() <= 1e-9 && (y - u.y_axis).len() <= 1e-9 +} /// Most plot style tables and plot style names read from a file. pub(crate) const MAX_PLOT_STYLE_TABLES: usize = 1000; pub(crate) const MAX_PLOT_STYLE_NAMES: usize = 100_000; diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 404c4d797..5779fcb56 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -2021,9 +2021,7 @@ impl Objects { && let Some(name) = self.xrecord_text(crate::dxf_ext::UCS_NAME_KEY).map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) && let Some(u) = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(&name)) && let (Some(o), Some(x), Some(y)) = (d.header.point("UCSORG"), d.header.point("UCSXDIR"), d.header.point("UCSYDIR")) - && (o - u.origin).len() <= 1e-9 * (1.0 + o.len()) - && (x - u.x_axis).len() <= 1e-9 - && (y - u.y_axis).len() <= 1e-9 + && crate::dxf_ext::is_named_frame(u, o, x, y) { let n = u.name.clone(); d.header.set_str("UCSNAME", &n); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 5384e36a1..c9da0250f 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -308,11 +308,18 @@ fn model_ucs(d: &Drawing) -> Ucs { (Some(x), Some(y)) if x.cross(y).len() > 1e-9 * x.len() * y.len() => (x, y, true), _ => (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), false), }; - // The name only of a UCS table record, and only with the axes it came with: a name read from a - // file without its record, or beside axes replaced by the World UCS's, is dropped. + // The name only of a UCS table record whose frame the current UCS still is: a name read from + // a file without its record, beside axes replaced by the World UCS's, or beside an origin or + // axes of its own (restoring the name would move the UCS) is dropped. + let origin = p("UCSORG").unwrap_or(Vec3::ZERO); let raw = h.str("UCSNAME", ""); - let name = d.ucss.iter().find(|u| usable && u.name.eq_ignore_ascii_case(raw.trim())).map(|u| u.name.clone()).unwrap_or_default(); - Ucs { name, origin: p("UCSORG").unwrap_or(Vec3::ZERO), x_axis: x, y_axis: y } + let name = d + .ucss + .iter() + .find(|u| usable && u.name.eq_ignore_ascii_case(raw.trim()) && crate::dxf_ext::is_named_frame(u, origin, x, y)) + .map(|u| u.name.clone()) + .unwrap_or_default(); + Ucs { name, origin, x_axis: x, y_axis: y } } fn header_vars(w: &mut W, d: &Drawing) { diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index e396994b6..c75c81834 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -207,6 +207,15 @@ fn a_ucs_name_without_its_ucs_is_not_written() { let mut broken = drawing(); broken.header.set("UCSXDIR", HVal::Point(Vec3::ZERO)); assert_eq!(name_written(&broken), (String::new(), false, String::new())); + // Usable but not SITE's frame (moved, or turned): restoring SITE would move the UCS, so the + // current one is unnamed. + let mut moved = drawing(); + moved.header.set("UCSORG", HVal::Point(Vec3::new(101.0, 50.0, 0.0))); + assert_eq!(name_written(&moved), (String::new(), false, String::new())); + let mut turned = drawing(); + turned.header.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0))); + turned.header.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 1.0, 0.0))); + assert_eq!(name_written(&turned), (String::new(), false, String::new())); } #[test] From be56597e5f24cf3121f9add6d55ba24c30cd3c29 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 19 Oct 2026 21:57:47 +1100 Subject: [PATCH 020/531] UCS in DXF: one axis rule for reading and writing, a tight origin match, layout names only while they fit - A named UCS's origin is matched to printing round-off only (relative 1e-12), so far from the World origin a real move is a different UCS. - Layout UCS axes are written by the rule the reader accepts them by (dxf_ext::usable_axes): short but square axes no longer become the World UCS's on save. - A layout's group 345 (its named UCS) is written only while the layout's frame is still that record's, as for model space. --- crates/io/src/dxf_ext.rs | 12 +++++++-- crates/io/src/dxf_read.rs | 3 +-- crates/io/src/dxf_write.rs | 10 ++++++-- crates/io/tests/ucs_roundtrip.rs | 43 ++++++++++++++++++++++++++++++-- 4 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 48760323f..3fef9abaa 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -40,9 +40,17 @@ pub(crate) const MLEADER_STYLE_KEY: &str = "CADCRAFT_MLEADERSTYLE"; pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME"; /// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding): -/// only then is the current UCS still that named one, read or written. +/// only then is the current UCS still that named one, read or written. The origin may differ by +/// printing round-off only (we write the shortest exact form; other programs 15–16 digits), so +/// even far from the World origin a real move is a different UCS. pub(crate) fn is_named_frame(u: &cadcraft_doc::Ucs, origin: cadcraft_geom::Vec3, x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool { - (origin - u.origin).len() <= 1e-9 * (1.0 + origin.len()) && (x - u.x_axis).len() <= 1e-9 && (y - u.y_axis).len() <= 1e-9 + (origin - u.origin).len() <= 1e-12 * (1.0 + origin.len()) && (x - u.x_axis).len() <= 1e-9 && (y - u.y_axis).len() <= 1e-9 +} + +/// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative +/// to their lengths, so short but square axes are fine). Read and written by the same rule. +pub(crate) fn usable_axes(x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool { + x.is_finite() && y.is_finite() && x.len() > 1e-12 && y.len() > 1e-12 && x.cross(y).len() > 1e-9 * x.len() * y.len() } /// Most plot style tables and plot style names read from a file. pub(crate) const MAX_PLOT_STYLE_TABLES: usize = 1000; diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 5779fcb56..05a833e19 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -2107,8 +2107,7 @@ impl Objects { } // Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset. for (name, origin, x, y, named) in &self.layout_ucss { - let usable = - [*origin, *x, *y].iter().all(|v| v.is_finite()) && x.len() > 1e-12 && y.len() > 1e-12 && x.cross(*y).len() > 1e-9 * x.len() * y.len(); + let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y); let ucs_name = named.as_ref().and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase())).cloned().unwrap_or_default(); let world = origin.len() <= 1e-12 && (*x - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 && (*y - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12; if !usable || (world && ucs_name.is_empty()) { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index c9da0250f..c57418815 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -2480,14 +2480,20 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.p(15, Vec3::ZERO); // The layout's current UCS: origin, X and Y axes, orthographic type, then (after the // block record) the named UCS it is. - let u = ucs.filter(|u| [u.origin, u.x_axis, u.y_axis].iter().all(|v| v.is_finite()) && u.x_axis.cross(u.y_axis).len() > 1e-12); + // Usable by the rule the reader applies, so what is written reads back. + let u = ucs.filter(|u| u.origin.is_finite() && dxf_ext::usable_axes(u.x_axis, u.y_axis)); w.f(146, 0.0); w.p(13, u.map_or(Vec3::ZERO, |u| u.origin)); w.p(16, u.map_or(Vec3::new(1.0, 0.0, 0.0), |u| u.x_axis)); w.p(17, u.map_or(Vec3::new(0.0, 1.0, 0.0), |u| u.y_axis)); w.i(76, 0); w.s(330, brh); - if let Some(h) = u.filter(|u| !u.name.trim().is_empty()).and_then(|u| w.ucss.get(&u.name.trim().to_ascii_uppercase())).cloned() { + // The named UCS it is, only while its frame is still that record's (as for model space). + let named = u.filter(|u| { + !u.name.trim().is_empty() + && d.ucss.iter().any(|r| r.name.eq_ignore_ascii_case(u.name.trim()) && dxf_ext::is_named_frame(r, u.origin, u.x_axis, u.y_axis)) + }); + if let Some(h) = named.and_then(|u| w.ucss.get(&u.name.trim().to_ascii_uppercase())).cloned() { w.s(345, h); } // The saved paper-space view (centre, height) as CADCraft xdata. diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index c75c81834..aa2d1b046 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -115,13 +115,23 @@ fn model_and_layout_ucs_survive_a_dxf_save() { #[test] fn a_layouts_named_ucs_points_at_its_record() { let mut d = drawing(); - d.layouts[0].ucs.as_mut().unwrap().name = "SITE".into(); + // The layout's UCS is SITE (its frame, by name). + let site_rec = d.ucss[0].clone(); + d.layouts[0].ucs = Some(site_rec.clone()); let text = cadcraft_io::write_dxf(&d); let site = records(&text, "UCS").into_iter().find(|r| group(r, "2") == Some("SITE")).and_then(|r| group(&r, "5").map(str::to_string)).unwrap(); let lay = layout_record(&text, &d.layouts[0].name); assert_eq!(group(&lay, "345"), Some(site.as_str())); let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); assert_eq!(back.layouts[0].ucs.as_ref().unwrap().name, "SITE"); + // Named SITE but moved since: not pointed at SITE (reopened, the name would bring SITE's frame + // with the moved one); the layout keeps its own frame unnamed. + let mut moved = d.clone(); + moved.layouts[0].ucs = Some(Ucs { origin: site_rec.origin + Vec3::new(1.0, 0.0, 0.0), ..site_rec.clone() }); + let text = cadcraft_io::write_dxf(&moved); + assert!(group(&layout_record(&text, &d.layouts[0].name), "345").is_none()); + let u = cadcraft_io::read_dxf(text.as_bytes()).unwrap().layouts[0].ucs.clone().unwrap(); + assert!(u.name.is_empty() && near3(u.origin, site_rec.origin + Vec3::new(1.0, 0.0, 0.0)), "{u:?}"); // A deleted named UCS isn't pointed at, and the layout keeps the axes unnamed. let mut gone = back.clone(); gone.ucss.clear(); @@ -130,7 +140,36 @@ fn a_layouts_named_ucs_points_at_its_record() { assert!(group(&lay, "345").is_none()); let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); let u = back.layouts[0].ucs.clone().unwrap(); - assert!(u.name.is_empty() && near3(u.x_axis, Vec3::new(0.0, 1.0, 0.0))); + assert!(u.name.is_empty() && near3(u.x_axis, site_rec.x_axis)); +} + +/// Short but square layout axes are a usable UCS when read, so they are written as they are and +/// not replaced by the World UCS's (the writer and the reader share one rule). +#[test] +fn short_layout_axes_survive_a_save() { + let mut d = drawing(); + let tiny = Ucs { name: String::new(), origin: Vec3::new(2.0, 3.0, 0.0), x_axis: Vec3::new(1e-7, 0.0, 0.0), y_axis: Vec3::new(0.0, 1e-7, 0.0) }; + d.layouts[0].ucs = Some(tiny.clone()); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + let u = back.layouts[0].ucs.clone().expect("kept"); + assert!(near3(u.x_axis, tiny.x_axis) && near3(u.y_axis, tiny.y_axis) && near3(u.origin, tiny.origin), "{u:?}"); +} + +/// Far from the World origin a named UCS's origin is still compared to round-off only: a move of +/// 0.05 at 100,000,000 is a different UCS, an exact save keeps the name. +#[test] +fn a_far_named_ucs_keeps_its_name_only_where_it_is() { + let far = Ucs { name: "FAR".into(), origin: Vec3::new(1e8, 0.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) }; + let mut d = Drawing::default(); + d.ucss.push(far.clone()); + d.header.set("UCSORG", HVal::Point(far.origin)); + d.header.set("UCSXDIR", HVal::Point(far.x_axis)); + d.header.set("UCSYDIR", HVal::Point(far.y_axis)); + d.header.set_str("UCSNAME", "FAR"); + let read = |d: &Drawing| cadcraft_io::read_dxf(cadcraft_io::write_dxf(d).as_bytes()).unwrap().header.str("UCSNAME", ""); + assert_eq!(read(&d), "FAR"); + d.header.set("UCSORG", HVal::Point(Vec3::new(1e8 + 0.05, 0.0, 0.0))); + assert_eq!(read(&d), "", "moved 0.05: no longer FAR"); } #[cfg(not(target_arch = "wasm32"))] From 99b7dc808f87660f388dd1af009df320d0d353f1 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 20 Oct 2026 01:06:04 +1100 Subject: [PATCH 021/531] UCS names in DXF: one rule everywhere, tight at any distance, and the active VPORT names it - A UCS name is kept, read or written, only while the current frame is that record's (dxf_ext::named_ucs): a $UCSNAME or a layout's group 345 read from a file naming a UCS with another frame is dropped, the frame kept unnamed. - The origin matches to printing round-off only (1e-9 + 1e-14 of the value), so a 0.5 move at 1e12 is a different UCS. - The active VPORT carries group 345 for model space's named UCS (its handle filled in once the UCS table has one). - The undo test checks redo of UCS Previous before a new command clears the redo stack. --- crates/engine/tests/ucs.rs | 5 ++- crates/io/src/dxf_ext.rs | 23 +++++++++-- crates/io/src/dxf_read.rs | 36 +++++++++++------ crates/io/src/dxf_write.rs | 52 ++++++++++++++++++------ crates/io/tests/ucs_roundtrip.rs | 68 ++++++++++++++++++++++++++++++++ 5 files changed, 156 insertions(+), 28 deletions(-) diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs index 82bd34e2d..25e2f7ae3 100644 --- a/crates/engine/tests/ucs.rs +++ b/crates/engine/tests/ucs.rs @@ -290,8 +290,11 @@ fn undo_restores_the_ucs_previous_history() { assert!(previous(&mut s) && s.ucs().is_world()); s.undo().unwrap(); assert!(ang_eq(s.ucs().rotation(), 30f64.to_radians()), "undo of UCS Previous"); + // Redo (before any new command clears the redo stack) does UCS Previous again. + assert!(s.redo().unwrap().is_some(), "UCS Previous is on the redo stack"); + assert!(s.ucs().is_world(), "redo of UCS Previous"); + s.undo().unwrap(); assert!(previous(&mut s) && s.ucs().is_world(), "its history entry came back too"); - s.redo().unwrap(); let mut s = session(); typed(&mut s, &["ucs z 30", "ucs z 30"]); assert!(ang_eq(s.ucs().rotation(), 60f64.to_radians())); diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 3fef9abaa..15019dae7 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -41,10 +41,27 @@ pub(crate) const UCS_NAME_KEY: &str = "CADCRAFT_UCSNAME"; /// Whether the UCS at `origin` with axes `x`, `y` is exactly the named UCS `u` (to rounding): /// only then is the current UCS still that named one, read or written. The origin may differ by -/// printing round-off only (we write the shortest exact form; other programs 15–16 digits), so -/// even far from the World origin a real move is a different UCS. +/// printing round-off only: we write the shortest exact form and other programs 15–16 +/// significant digits (half a unit in the 15th is 5e-16 of the value), so 1e-14 of the value, +/// plus 1e-9 near the World origin, covers it while even 1e12 away a 0.5 move is a different UCS. pub(crate) fn is_named_frame(u: &cadcraft_doc::Ucs, origin: cadcraft_geom::Vec3, x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool { - (origin - u.origin).len() <= 1e-12 * (1.0 + origin.len()) && (x - u.x_axis).len() <= 1e-9 && (y - u.y_axis).len() <= 1e-9 + (origin - u.origin).len() <= 1e-9 + 1e-14 * origin.len() && (x - u.x_axis).len() <= 1e-9 && (y - u.y_axis).len() <= 1e-9 +} + +/// The UCS table record named `name` whose frame the UCS at `origin`, `x`, `y` still is: the only +/// case in which a current UCS (model space's or a layout's, read or written) keeps that name. +pub(crate) fn named_ucs<'a>( + ucss: &'a [cadcraft_doc::Ucs], + name: &str, + origin: cadcraft_geom::Vec3, + x: cadcraft_geom::Vec3, + y: cadcraft_geom::Vec3, +) -> Option<&'a cadcraft_doc::Ucs> { + let name = name.trim(); + if name.is_empty() { + return None; + } + ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name) && is_named_frame(u, origin, x, y)) } /// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 05a833e19..b785b483d 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -2015,16 +2015,23 @@ impl Objects { if let Some(style) = self.xrecord_text(crate::dxf_ext::MLEADER_STYLE_KEY).filter(|s| !s.trim().is_empty()) { d.header.set_str("CMLEADERSTYLE", &style); } - // Model space's UCS name when the file lost it ($UCSNAME empty, as through DWG): only - // while the current UCS is still exactly that named UCS. - if d.header.str("UCSNAME", "").trim().is_empty() - && let Some(name) = self.xrecord_text(crate::dxf_ext::UCS_NAME_KEY).map(|n| n.trim().to_string()).filter(|n| !n.is_empty()) - && let Some(u) = d.ucss.iter().find(|u| u.name.eq_ignore_ascii_case(&name)) - && let (Some(o), Some(x), Some(y)) = (d.header.point("UCSORG"), d.header.point("UCSXDIR"), d.header.point("UCSYDIR")) - && crate::dxf_ext::is_named_frame(u, o, x, y) - { - let n = u.name.clone(); - d.header.set_str("UCSNAME", &n); + // Model space's UCS name ($UCSNAME, or CADCraft's copy when the file lost it, as through + // DWG): kept only while the current UCS is still exactly that named UCS, else unnamed. + let header_name = d.header.str("UCSNAME", "").trim().to_string(); + let name = if header_name.is_empty() { + self.xrecord_text(crate::dxf_ext::UCS_NAME_KEY).map(|n| n.trim().to_string()).unwrap_or_default() + } else { + header_name.clone() + }; + let frame = (d.header.point("UCSORG"), d.header.point("UCSXDIR"), d.header.point("UCSYDIR")); + let named = match frame { + (Some(o), Some(x), Some(y)) => crate::dxf_ext::named_ucs(&d.ucss, &name, o, x, y).map(|u| u.name.clone()), + _ => None, + }; + match named { + Some(n) => d.header.set_str("UCSNAME", &n), + None if !header_name.is_empty() => d.header.set_str("UCSNAME", ""), + None => {} } // Table styles (named by their ACAD_TABLESTYLE dictionary entries). for (h, tags) in &self.table_styles { @@ -2108,7 +2115,14 @@ impl Objects { // Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset. for (name, origin, x, y, named) in &self.layout_ucss { let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y); - let ucs_name = named.as_ref().and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase())).cloned().unwrap_or_default(); + // The named UCS group 345 points at, only while the layout's frame is still that + // record's: a valid frame with a stale reference is kept, unnamed. + let ucs_name = named + .as_ref() + .and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase())) + .and_then(|n| crate::dxf_ext::named_ucs(&d.ucss, n, *origin, *x, *y)) + .map(|u| u.name.clone()) + .unwrap_or_default(); let world = origin.len() <= 1e-12 && (*x - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 && (*y - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12; if !usable || (world && ucs_name.is_empty()) { continue; diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index c57418815..461624149 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -21,6 +21,9 @@ struct W { layers: HashMap, /// Upper-case UCS name → its UCS table record handle (group 345 of layouts and viewports). ucss: HashMap, + /// Active VPORT group-345 tags (their index in `t`) waiting for the handle of the named UCS + /// (upper case) they refer to, filled in after the UCS table is written. + vport_ucs: Vec<(usize, String)>, /// Persistent reactors of boundary objects: each source object of an associative hatch → /// the hatches (groups `{ACAD_REACTORS 330 …}`), from [`hatch_reactors`]. reactors: HashMap>, @@ -203,7 +206,15 @@ fn annotative_xdata(w: &mut W) { /// Override (`ACAD` DSTYLE) and associativity (`CADCRAFT` ASSOC) xdata of a dimension. fn dim_xdata(w: &mut W, dm: &Dimension, cx: &Ctx) { - let mut ov = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), ucss: HashMap::new(), reactors: HashMap::new() }; + let mut ov = W { + t: Vec::new(), + next: 0, + pstyles: HashMap::new(), + layers: HashMap::new(), + ucss: HashMap::new(), + vport_ucs: Vec::new(), + reactors: HashMap::new(), + }; let mut sah = false; for (k, v) in &dm.overrides { let Some(field) = DimStyle::field_name(k) else { continue }; @@ -313,12 +324,7 @@ fn model_ucs(d: &Drawing) -> Ucs { // axes of its own (restoring the name would move the UCS) is dropped. let origin = p("UCSORG").unwrap_or(Vec3::ZERO); let raw = h.str("UCSNAME", ""); - let name = d - .ucss - .iter() - .find(|u| usable && u.name.eq_ignore_ascii_case(raw.trim()) && crate::dxf_ext::is_named_frame(u, origin, x, y)) - .map(|u| u.name.clone()) - .unwrap_or_default(); + let name = crate::dxf_ext::named_ucs(&d.ucss, &raw, origin, x, y).filter(|_| usable).map(|u| u.name.clone()).unwrap_or_default(); Ucs { name, origin, x_axis: x, y_axis: y } } @@ -1565,6 +1571,12 @@ fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { w.p(111, ucs.x_axis); w.p(112, ucs.y_axis); w.i(79, 0); + // The named UCS it is (none: unnamed). The UCS table comes after VPORT, so the + // handle is filled in once that table has given it one ([`W::vport_ucs`]). + if !ucs.name.is_empty() { + w.s(345, "0"); + w.vport_ucs.push((w.t.len() - 1, ucs.name.to_ascii_uppercase())); + } w.f(146, 0.0); } } @@ -1636,6 +1648,7 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { pstyles: HashMap::new(), layers: HashMap::new(), ucss: HashMap::new(), + vport_ucs: Vec::new(), reactors: hatch_reactors(d), }; // Pre-allocate handles for block records. @@ -2082,6 +2095,13 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.f(146, 0.0); } w.s(0, "ENDTAB"); + // The active VPORT's named UCS (written before this table had handles). + for (i, name) in std::mem::take(&mut w.vport_ucs) { + let h = w.ucss.get(&name).cloned(); + if let (Some(h), Some(t)) = (h, w.t.get_mut(i)) { + *t = Tag::s(345, h); + } + } let apps = ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP]; let th = table_head(&mut w, "APPID", apps.len()); for app in apps { @@ -2109,7 +2129,15 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.i(70, 0); let v = serde_json::to_value(s).unwrap_or_default(); let defaults = serde_json::to_value(DimStyle::default()).unwrap_or_default(); - let mut newer = W { t: Vec::new(), next: 0, pstyles: HashMap::new(), layers: HashMap::new(), ucss: HashMap::new(), reactors: HashMap::new() }; + let mut newer = W { + t: Vec::new(), + next: 0, + pstyles: HashMap::new(), + layers: HashMap::new(), + ucss: HashMap::new(), + vport_ucs: Vec::new(), + reactors: HashMap::new(), + }; for (field, code, kind) in dxf_ext::DIM_CODES { let Some(enc) = v.get(*field).and_then(|x| cx.encode(*kind, x)) else { continue }; if !dxf_ext::NEWER_CODES.contains(code) { @@ -2489,11 +2517,8 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.i(76, 0); w.s(330, brh); // The named UCS it is, only while its frame is still that record's (as for model space). - let named = u.filter(|u| { - !u.name.trim().is_empty() - && d.ucss.iter().any(|r| r.name.eq_ignore_ascii_case(u.name.trim()) && dxf_ext::is_named_frame(r, u.origin, u.x_axis, u.y_axis)) - }); - if let Some(h) = named.and_then(|u| w.ucss.get(&u.name.trim().to_ascii_uppercase())).cloned() { + let named = u.and_then(|u| dxf_ext::named_ucs(&d.ucss, &u.name, u.origin, u.x_axis, u.y_axis)); + if let Some(h) = named.and_then(|u| w.ucss.get(&u.name.to_ascii_uppercase())).cloned() { w.s(345, h); } // The saved paper-space view (centre, height) as CADCraft xdata. @@ -2738,6 +2763,7 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec) { pstyles: HashMap::new(), layers: HashMap::new(), ucss: HashMap::new(), + vport_ucs: Vec::new(), reactors: HashMap::new(), }; let cx = Ctx { target: Version::R2018, ..Ctx::default() }; diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index aa2d1b046..a79e5db94 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -170,6 +170,74 @@ fn a_far_named_ucs_keeps_its_name_only_where_it_is() { assert_eq!(read(&d), "FAR"); d.header.set("UCSORG", HVal::Point(Vec3::new(1e8 + 0.05, 0.0, 0.0))); assert_eq!(read(&d), "", "moved 0.05: no longer FAR"); + // Further out still: at 1e12 an exact save keeps the name and a 0.5 move drops it. + let mut d = d.clone(); + let far = Ucs { origin: Vec3::new(1e12, 0.0, 0.0), ..far }; + d.ucss = vec![far.clone()]; + d.header.set("UCSORG", HVal::Point(far.origin)); + assert_eq!(read(&d), "FAR"); + d.header.set("UCSORG", HVal::Point(Vec3::new(1e12 + 0.5, 0.0, 0.0))); + assert_eq!(read(&d), "", "moved 0.5 at 1e12: no longer FAR"); +} + +/// DXF text with the value of group `code` in the first record `kind` holding `marker` (code, +/// value) replaced by `value`. +fn replace_group(text: &str, after: (&str, &str), code: &str, value: &str) -> String { + let lines: Vec<&str> = text.lines().collect(); + let mut out = Vec::with_capacity(lines.len()); + let mut armed = false; + let mut done = false; + for pair in lines.chunks(2) { + let [c, v] = pair else { break }; + let (ct, vt) = (c.trim(), v.trim()); + if !done && ct == after.0 && vt == after.1 { + armed = true; + } + let v = if armed && !done && ct == code { + done = true; + value.to_string() + } else { + v.to_string() + }; + out.push(format!("{c}\n{v}")); + } + out.join("\n") + "\n" +} + +/// Read from a file, a UCS name is kept only while its frame is that record's: a $UCSNAME, or a +/// layout's group 345, naming a UCS whose origin differs leaves the frame as it is, unnamed. +#[test] +fn a_stale_ucs_name_in_a_file_is_dropped_on_read() { + // Model space: $UCSNAME SITE, but $UCSORG moved away from SITE's origin. + let text = cadcraft_io::write_dxf(&drawing()); + let moved = replace_group(&text, ("9", "$UCSORG"), "10", "101.0"); + let back = cadcraft_io::read_dxf(moved.as_bytes()).unwrap(); + assert_eq!(back.header.str("UCSNAME", ""), "", "SITE no longer"); + assert!(near3(back.header.point("UCSORG").unwrap(), Vec3::new(101.0, 50.0, 0.0)), "the frame is kept"); + assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE", "unmoved, still SITE"); + // A layout: its UCS is SITE (345 written), then its origin (group 13) moved in the file. + let mut d = drawing(); + d.layouts[0].ucs = Some(d.ucss[0].clone()); + let name = d.layouts[0].name.clone(); + let text = cadcraft_io::write_dxf(&d); + assert!(group(&layout_record(&text, &name), "345").is_some()); + let moved = replace_group(&text, ("1", &name), "13", "7.0"); + let u = cadcraft_io::read_dxf(moved.as_bytes()).unwrap().layout(&name).unwrap().ucs.clone().unwrap(); + assert!(u.name.is_empty() && (u.origin.x - 7.0).abs() < 1e-9, "{u:?}"); + assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().layout(&name).unwrap().ucs.as_ref().unwrap().name, "SITE"); +} + +/// The active VPORT names model space's UCS too: group 345 is the UCS record's handle while the +/// UCS is that named one, and absent while it is unnamed. +#[test] +fn the_active_vport_points_at_the_named_ucs() { + let active = |text: &str| records(text, "VPORT").into_iter().find(|r| group(r, "2") == Some("*Active")).unwrap(); + let text = cadcraft_io::write_dxf(&drawing()); + let site = records(&text, "UCS").into_iter().find(|r| group(r, "2") == Some("SITE")).and_then(|r| group(&r, "5").map(str::to_string)).unwrap(); + assert_eq!(group(&active(&text), "345"), Some(site.as_str())); + let mut unnamed = drawing(); + unnamed.header.set_str("UCSNAME", ""); + assert!(group(&active(&cadcraft_io::write_dxf(&unnamed)), "345").is_none()); } #[cfg(not(target_arch = "wasm32"))] From a0e023d75806cdad65da8f8b555a57ff0a30c594 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 20 Oct 2026 12:09:54 +1100 Subject: [PATCH 022/531] Angles: shown and entered directions are measured in the current UCS AngleSettings::shown and ::unshown (the Properties and Quick Properties palettes' Rotation) now measure from the current UCS's X axis, as typed directions are read: in a turned UCS what is typed as 0 shows as 0, and an entered 0 is that same direction. Unchanged in the World UCS. --- crates/engine/src/units.rs | 39 +++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/units.rs b/crates/engine/src/units.rs index 9ea287c04..8f6c60844 100644 --- a/crates/engine/src/units.rs +++ b/crates/engine/src/units.rs @@ -236,18 +236,20 @@ impl AngleSettings { ucs(self.angbase + if self.clockwise { -a } else { a }) } - /// Direction `dir` (radians counterclockwise from +X) as the drawing shows directions, in - /// radians: from ANGBASE in the ANGDIR sense, 0 up to a full turn. (A block turned 2.23° - /// shows as 87.77 in a drawing measured clockwise from north, as in AutoCAD's Properties.) + /// Direction `dir` (radians counterclockwise from world +X) as the drawing shows directions, + /// in radians: from ANGBASE in the ANGDIR sense, measured in the current UCS (`ucs`) as typed + /// directions are read ([`AngleSettings::direction`]), 0 up to a full turn. (A block turned + /// 2.23° shows as 87.77 in a drawing measured clockwise from north, as in AutoCAD's Properties.) pub fn shown(&self, dir: f64) -> f64 { - let a = if self.clockwise { self.angbase - dir } else { dir - self.angbase }; + let local = dir - self.ucs; + let a = if self.clockwise { self.angbase - local } else { local - self.angbase }; a.rem_euclid(std::f64::consts::TAU) } - /// The direction (radians counterclockwise from +X) the drawing shows as `v` (radians): the - /// inverse of [`AngleSettings::shown`]. + /// The direction (radians counterclockwise from world +X) the drawing shows as `v` + /// (radians): the inverse of [`AngleSettings::shown`]. pub fn unshown(&self, v: f64) -> f64 { - (self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU) + (self.ucs + self.angbase + if self.clockwise { -v } else { v }).rem_euclid(std::f64::consts::TAU) } } @@ -357,6 +359,29 @@ mod tests { assert!((based.shown(45f64.to_radians()).to_degrees() - 15.0).abs() < 1e-9); } + /// In a turned UCS, a shown direction (the Properties palette's Rotation) is measured from + /// the UCS X axis, as typed directions are: what is typed as 0 shows as 0, and back. + #[test] + fn shown_directions_are_measured_in_the_ucs() { + let turned = AngleSettings { ucs: 90f64.to_radians(), ..AngleSettings::default() }; + let typed = turned.direction("0").unwrap(); + assert!((typed - 90f64.to_radians()).abs() < 1e-12, "0 in the UCS is world 90°"); + assert!(turned.shown(typed).abs() < 1e-12, "and shows as 0"); + assert!((turned.unshown(0.0) - typed).abs() < 1e-12, "0 entered is that direction"); + // With ANGBASE and ANGDIR too: every direction shown and entered back is itself. + let s = AngleSettings { aunits: 0, angbase: 30f64.to_radians(), clockwise: true, ucs: 50f64.to_radians() }; + for deg in [0.0, 12.5, 90.0, 181.0, 359.0] { + let dir = f64::to_radians(deg); + let back = s.unshown(s.shown(dir)); + assert!((back - dir).rem_euclid(std::f64::consts::TAU).min((dir - back).rem_euclid(std::f64::consts::TAU)) < 1e-9, "{deg}"); + let typed = s.direction(&format!("{}", s.shown(dir).to_degrees())).unwrap(); + assert!( + ((typed - dir).rem_euclid(std::f64::consts::TAU)).min((dir - typed).rem_euclid(std::f64::consts::TAU)) < 1e-9, + "{deg}: shown then typed" + ); + } + } + #[test] fn decimal_and_arch() { assert_eq!(format_distance(28.98524, 2, 4), "28.9852"); From afcb6aa74345ec188caf8967f3d5dcd06d9ffcaf Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 20 Oct 2026 21:01:57 +1100 Subject: [PATCH 023/531] ATTDEF: justify and style parameters, as TEXT and MTEXT take them (fixes #1658) attdef always made a left/baseline definition in the current text style, so a centred or right-aligned title-block attribute needed an entmod. It now takes justify (TEXT's codes, via draw::justify; any but Left keeps the point as the alignment point) and style (a text style name, any case). An unknown code or style is refused; without them nothing changes. --- crates/engine/src/cmd/blocks.rs | 32 +++++-- crates/engine/tests/attdef_justify_style.rs | 95 +++++++++++++++++++++ 2 files changed, 119 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/attdef_justify_style.rs diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 6b968f8cf..7a72c1d0b 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -41,7 +41,7 @@ pub fn specs() -> Vec { CommandSpec::new("attdef", "Define Attributes...", run_attdef) .menu(&["Draw", "Block", "Define Attributes..."]) .alias(&["att", "-attdef"]) - .params("{tag, prompt?, default?, at, height?, invisible?}") + .params("{tag, prompt?, default?, at, height?, invisible?, justify?: L|C|R|M|TL|TC|TR|ML|MC|MR|BL|BC|BR, style? (default the current text style)}") .interactive(|_| Ok(Box::new(AttdefM::default()))), attedit::attedit_spec(), attedit::dash_attedit_spec(), @@ -296,21 +296,30 @@ fn run_insert(s: &mut Session, p: &Value) -> Result { Ok(attedit::with_unknown_tags(s, h, &vals, json!({ "handle": h.hex() }))) } -fn attdef_kind(s: &Session, tag: &str, prompt: &str, default: &str, at: Vec2, height: f64, invisible: bool) -> EntityKind { - let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()); +/// The current text style (TEXTSTYLE). +fn current_text_style(s: &Session) -> String { + s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()) +} + +/// An attribute definition at `at` with justification `j` (as TEXT: any but Left keeps `at` as +/// its alignment point) in text style `style`. +#[allow(clippy::too_many_arguments)] +fn attdef_kind(tag: &str, prompt: &str, default: &str, at: Vec2, height: f64, invisible: bool, j: (HAlign, VAlign), style: String) -> EntityKind { + let (halign, valign) = j; + let left = halign == HAlign::Left && valign == VAlign::Baseline; EntityKind::AttDef(Attrib { tag: tag.to_ascii_uppercase(), text: Text { insert: v3(at), - align_pt: None, + align_pt: if left { None } else { Some(v3(at)) }, height, value: default.into(), rotation: 0.0, width_factor: 1.0, oblique: 0.0, style, - halign: HAlign::Left, - valign: VAlign::Baseline, + halign, + valign, }, invisible, constant: false, @@ -328,7 +337,14 @@ fn run_attdef(s: &mut Session, p: &Value) -> Result { } let at = point_req("attdef", p, "at")?; let h = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2)); - let k = attdef_kind(s, tag, str_param(p, "prompt").unwrap_or(tag), str_param(p, "default").unwrap_or(""), at, h, bool_or(p, "invisible", false)); + // Justification and text style as TEXT and MTEXT take them (#1658). + let j = super::draw::justify(str_param(p, "justify").unwrap_or("L")).ok_or_else(|| bad("attdef", "unknown justification"))?; + let style = match str_param(p, "style") { + Some(n) => s.doc()?.text_style(n).map(|t| t.name.clone()).ok_or_else(|| bad("attdef", format!("no text style \"{n}\"")))?, + None => current_text_style(s), + }; + let (prompt, default) = (str_param(p, "prompt").unwrap_or(tag), str_param(p, "default").unwrap_or("")); + let k = attdef_kind(tag, prompt, default, at, h, bool_or(p, "invisible", false), j, style); Ok(json!({ "handle": s.add_entity(k)?.hex() })) } @@ -866,7 +882,7 @@ impl Interactive for AttdefM { (Some(tag), Some(pr), Some(def)) => { if let Input::Point(p) = i { let h = s.doc()?.header.f64("TEXTSIZE", 0.2); - let k = attdef_kind(s, tag, pr, def, p, h, false); + let k = attdef_kind(tag, pr, def, p, h, false, (HAlign::Left, VAlign::Baseline), current_text_style(s)); s.add_entity(k)?; return Ok(Step::Done); } diff --git a/crates/engine/tests/attdef_justify_style.rs b/crates/engine/tests/attdef_justify_style.rs new file mode 100644 index 000000000..168265d2a --- /dev/null +++ b/crates/engine/tests/attdef_justify_style.rs @@ -0,0 +1,95 @@ +//! #1658: `attdef` takes a justification and a text style, as `text` and `mtext` do, so a +//! title-block attribute can be built centred or right-aligned in its style without an `entmod`. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Attrib, EntityKind, HAlign, Handle, VAlign}; +use cadcraft_engine::geom::Vec3; +use serde_json::{Value, json}; + +fn h(v: &Value) -> Handle { + v["handle"].as_str().and_then(Handle::parse_hex).unwrap() +} + +fn attdef(s: &Session, h: Handle) -> Attrib { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::AttDef(a) => a.clone(), + k => panic!("{k:?}"), + } +} + +/// Runs `attdef` with `p` and returns the definition it made. +fn add(s: &mut Session, p: Value) -> Attrib { + let made = h(&s.execute("attdef", &p).unwrap()); + attdef(s, made) +} + +/// The issue's drawing: a text style ROMANS beside the current Standard. +fn session() -> Session { + let mut s = Session::new(); + s.execute("style", &json!({"name": "ROMANS", "font": "romans.shx"})).unwrap(); + s.execute("style.current", &json!({"name": "Standard"})).unwrap(); + s +} + +#[test] +fn justify_and_style_are_applied() { + let mut s = session(); + let a = add(&mut s, json!({"tag": "T", "at": [10, 10], "height": 2.5, "justify": "MC", "style": "ROMANS"})); + assert_eq!((a.text.halign, a.text.valign), (HAlign::Center, VAlign::Middle)); + assert_eq!(a.text.style, "ROMANS"); + assert_eq!(a.text.align_pt, Some(Vec3::new(10.0, 10.0, 0.0)), "justified text is placed by its alignment point"); + // Every code `text` takes, and the style name in any case (kept as the table spells it). + for (j, want) in [ + ("BR", (HAlign::Right, VAlign::Bottom)), + ("tl", (HAlign::Left, VAlign::Top)), + ("C", (HAlign::Center, VAlign::Baseline)), + ("M", (HAlign::Middle, VAlign::Baseline)), + ] { + let a = add(&mut s, json!({"tag": "T", "at": [0, 0], "justify": j, "style": "romans"})); + assert_eq!((a.text.halign, a.text.valign), want, "{j}"); + assert_eq!(a.text.style, "ROMANS"); + } +} + +#[test] +fn without_them_nothing_changes() { + let mut s = session(); + let a = add(&mut s, json!({"tag": "T", "at": [10, 10]})); + assert_eq!((a.text.halign, a.text.valign, a.text.align_pt), (HAlign::Left, VAlign::Baseline, None)); + assert_eq!(a.text.style, "Standard", "the current text style"); + let a = add(&mut s, json!({"tag": "T", "at": [10, 10], "justify": "L"})); + assert_eq!((a.text.halign, a.text.valign, a.text.align_pt), (HAlign::Left, VAlign::Baseline, None)); +} + +#[test] +fn a_bad_justification_or_style_is_refused() { + let mut s = session(); + let n = s.doc().unwrap().model.len(); + assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "justify": "XX"})).is_err()); + assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "style": "NOPE"})).is_err()); + assert_eq!(s.doc().unwrap().model.len(), n, "nothing added"); +} + +/// The issue's use: a block built from the definition gives its attributes the same placement, +/// and a save and reopen keeps them. +#[test] +fn a_block_and_a_saved_file_keep_them() { + let mut s = session(); + let ad = + h(&s.execute("attdef", &json!({"tag": "TITLE", "default": "x", "at": [50, 10], "height": 2.5, "justify": "MC", "style": "ROMANS"})).unwrap()); + let l = s.execute("line", &json!({"points": [[0, 0], [100, 0]]})).unwrap()["handles"][0].as_str().and_then(Handle::parse_hex).unwrap(); + s.execute("block", &json!({"name": "TB", "base": [0, 0], "handles": [ad.hex(), l.hex()], "keep": "delete"})).unwrap(); + let ins = h(&s.execute("insert", &json!({"name": "TB", "at": [0, 0], "attribs": {"TITLE": "PLAN"}})).unwrap()); + let EntityKind::Insert(i) = &s.doc().unwrap().entity(ins).unwrap().kind else { panic!() }; + let att = i.attribs.first().unwrap(); + assert_eq!( + (att.text.halign, att.text.valign, att.text.style.as_str(), att.text.value.as_str()), + (HAlign::Center, VAlign::Middle, "ROMANS", "PLAN") + ); + let read = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let def = + read.block("TB").unwrap().entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap(); + assert_eq!((def.text.halign, def.text.valign, def.text.style.as_str()), (HAlign::Center, VAlign::Middle, "ROMANS"), "reopened definition"); + let att = read.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { i.attribs.first().cloned() } else { None }).unwrap(); + assert_eq!((att.text.halign, att.text.valign, att.text.style.as_str()), (HAlign::Center, VAlign::Middle, "ROMANS"), "reopened attribute"); +} From 3e42b346ffc7aba2a7274bdc0fbf932e2e3ea13a Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 20 Oct 2026 23:49:15 +1100 Subject: [PATCH 024/531] ATTDEF: refuse Align and Fit, which need two points; test the current style with a non-Standard one Review follow-up on #1720: justify A or F gave a definition with a zero-length span (attdef takes one point), so they are refused with an error now; the omitted-style test also runs with ROMANS current, so a run that always picked Standard fails it. --- crates/engine/src/cmd/blocks.rs | 4 ++++ crates/engine/tests/attdef_justify_style.rs | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 7a72c1d0b..53c34cd8b 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -339,6 +339,10 @@ fn run_attdef(s: &mut Session, p: &Value) -> Result { let h = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2)); // Justification and text style as TEXT and MTEXT take them (#1658). let j = super::draw::justify(str_param(p, "justify").unwrap_or("L")).ok_or_else(|| bad("attdef", "unknown justification"))?; + // Align and Fit run between two baseline points; `attdef` has one, so it can't express them. + if matches!(j.0, HAlign::Aligned | HAlign::Fit) { + return Err(bad("attdef", "Align and Fit need two points, which attdef doesn't take yet; use L, C, R, M or TL … BR")); + } let style = match str_param(p, "style") { Some(n) => s.doc()?.text_style(n).map(|t| t.name.clone()).ok_or_else(|| bad("attdef", format!("no text style \"{n}\"")))?, None => current_text_style(s), diff --git a/crates/engine/tests/attdef_justify_style.rs b/crates/engine/tests/attdef_justify_style.rs index 168265d2a..0f2d6a3ec 100644 --- a/crates/engine/tests/attdef_justify_style.rs +++ b/crates/engine/tests/attdef_justify_style.rs @@ -57,8 +57,13 @@ fn without_them_nothing_changes() { let a = add(&mut s, json!({"tag": "T", "at": [10, 10]})); assert_eq!((a.text.halign, a.text.valign, a.text.align_pt), (HAlign::Left, VAlign::Baseline, None)); assert_eq!(a.text.style, "Standard", "the current text style"); + // With another current style, that one: not always Standard. + s.execute("style.current", &json!({"name": "ROMANS"})).unwrap(); + let a = add(&mut s, json!({"tag": "T", "at": [10, 10]})); + assert_eq!(a.text.style, "ROMANS", "the current text style"); let a = add(&mut s, json!({"tag": "T", "at": [10, 10], "justify": "L"})); assert_eq!((a.text.halign, a.text.valign, a.text.align_pt), (HAlign::Left, VAlign::Baseline, None)); + assert_eq!(a.text.style, "ROMANS", "the current text style"); } #[test] @@ -67,6 +72,10 @@ fn a_bad_justification_or_style_is_refused() { let n = s.doc().unwrap().model.len(); assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "justify": "XX"})).is_err()); assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "style": "NOPE"})).is_err()); + // Align and Fit need a second baseline point, which attdef has no way to take. + for j in ["A", "ALIGN", "F", "fit"] { + assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "justify": j})).is_err(), "{j}"); + } assert_eq!(s.doc().unwrap().model.len(), n, "nothing added"); } From 80bbcb98bad088a19337ff5ca71d7d28d2003d6b Mon Sep 17 00:00:00 2001 From: Sladrian Pedroso <294190500+Sladrian@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:58:37 -0300 Subject: [PATCH 025/531] A quick right-click is Enter between commands too: it runs the typed command or repeats the last one (fixes #1387) With the time-sensitive right-click on (the default), a quick right-click was Enter only while a command ran, and it sent a bare Enter even when something was typed. Between commands every right-click opened the shortcut menu, so typing `rec` and right-clicking opened the menu instead of starting RECTANG, and at an empty prompt it didn't repeat the last command as AutoCAD does. A quick right-click now does what the Enter key does (cmdline::submit): it enters what was typed (a command name, `@10,0`), ends the input of a running command, and between commands repeats the last one. Held, it still opens the command menu or the shortcut menu; a grip with options keeps its menu; Shift/Ctrl+right-click is still the object snap menu; with the time-sensitive right-click turned off, every right-click opens the menu. With nothing typed and no command run yet, a quick click opens the shortcut menu (there is nothing to enter). time_sensitive_right_click now also checks that a quick click between commands repeats LINE, a held one opens the menu with Repeat LINE and repeats nothing, a typed `circle` starts CIRCLE and a typed `5,5` enters its centre; these checks fail without the change. docs/ui-parity.md describes the new behaviour. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 19 ++++++++------ crates/ui-egui/src/context_menu.rs | 25 +++++++++++++------ crates/ui-egui/src/options/mod.rs | 2 +- crates/ui-egui/tests/context_menus.rs | 36 +++++++++++++++++++++++++++ docs/ui-parity.md | 12 ++++++--- 5 files changed, 73 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 983214190..eee8b7d68 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -105,7 +105,7 @@ pub struct CanvasState { /// A GRIP edit was running last frame (its grips go cold when it ends). grip_editing: bool, /// The grip whose menu (Stretch, Add Vertex, Lengthen…) a right-click opened. - grip_menu: Option<(Handle, usize)>, + pub(crate) grip_menu: Option<(Handle, usize)>, /// Dynamic block grips of the selection (cached), the one being dragged, and the list grip /// whose choices are open (and whether it opened this frame). pub(crate) dyn_grips: crate::dyngrips::Cache, @@ -1701,24 +1701,27 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } } } - // Right-click acts as Enter while a command runs (the classic CAD default; held, it opens the - // command menu); otherwise it opens the shortcut menu (Repeat, Clipboard, …). - // Shift/Ctrl+right-click opens the object snap menu. + // A quick right-click is Enter (the classic CAD default): it enters what was typed, ends the + // input of a running command, and between commands repeats the last one. Held, it opens the + // command menu or the shortcut menu (Repeat, Clipboard, …). Shift/Ctrl+right-click opens the + // object snap menu. let idle = !app.session.prompting(); if inside && pressed_secondary { app.canvas.snap_menu = mods.shift || mods.ctrl; } - if crate::context_menu::in_command(app, ui, inside, pressed_secondary) { - let _ = app.session.input(Input::Enter); - } // Right-click on a grip with options (polyline vertex, line end…) opens the grip menu. if inside && pressed_secondary && idle && !app.canvas.snap_menu { app.canvas.grip_menu = grip_at(app, &xf, hover_pos).filter(|g| !grip_options(app, *g).is_empty()); } + let enter = crate::context_menu::in_command(app, ui, inside, pressed_secondary); + if enter { + // As the Enter key does: what was typed (`rec`, `@10,0`), or Enter when nothing was. + crate::cmdline::submit(app); + } crate::dyngrips::menu(app, ui.ctx(), &xf); if idle && !app.canvas.snap_menu && app.canvas.grip_menu.is_some() { grip_menu(app, &resp); - } else if idle || app.canvas.snap_menu { + } else if (idle && !enter) || app.canvas.snap_menu { crate::context_menu::show(app, &resp); } diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 68f427679..26836d513 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1,6 +1,7 @@ //! The canvas's right-click menus, after AutoCAD's shortcut menus: //! -//! - **No command running** ([`entries`]): Repeat the last command, Recent Commands, the +//! - **No command running** ([`entries`], opened by holding the button: a quick right-click is +//! Enter, which repeats the last command): Repeat the last command, Recent Commands, the //! Clipboard and Isolate; with a selection the editing commands, Draw Order, Group, the edit //! commands of the selected object type, Select Similar and Deselect All; then Undo/Redo, //! Pan/Zoom, Quick Select, Find, Properties and Options. @@ -305,10 +306,11 @@ pub fn show(app: &mut CadApp, resp: &egui::Response) { #[derive(Clone, Copy, Default)] struct Press(f64, egui::Pos2); -/// The canvas's right button while a command runs (Shift/Ctrl+right-click is the snap menu's): a -/// quick click is Enter — returns `true` when the caller should send it — and a click held for -/// [`HOLD_SECS`] opens the command menu ([`command_entries`]) at the pointer (any click does with -/// the time-sensitive right-click turned off). Call it every frame +/// The canvas's right button (Shift/Ctrl+right-click is the snap menu's): a quick click is Enter +/// — returns `true` when the caller should send it; between commands that repeats the last one — +/// and while a command runs a click held for [`HOLD_SECS`] opens the command menu +/// ([`command_entries`]) at the pointer (any click does with the time-sensitive right-click turned +/// off; between commands the caller shows the shortcut menu). Call it every frame /// with whether the pointer is on the canvas and whether a right-click ended there; it also shows /// the menu while it is open. pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked: bool) -> bool { @@ -325,16 +327,23 @@ pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked: ctx.data_mut(|d| d.insert_temp(press_id, Press(now, p))); } let running = app.session.prompting() && !app.canvas.snap_menu; + let timed = app.options.time_sensitive_right_click; let mut open = false; + let mut quick = false; if released && let Some(Press(t0, p0)) = ctx.data_mut(|d| d.remove_temp::(press_id)) { // A drag isn't a click; a click held long enough asks for the menu. let still = pos.is_some_and(|p| p.distance(p0) <= 6.0); - let held = now - t0 >= HOLD_SECS || !app.options.time_sensitive_right_click; + let held = now - t0 >= HOLD_SECS || !timed; open = running && still && held; + quick = !held; } - let enter = running && inside && right_clicked && !open && app.options.time_sensitive_right_click; + let enter = running && inside && right_clicked && !open && timed; if !running { - return false; + // Between commands a quick click is Enter too (as in AutoCAD): it runs the typed command, + // or repeats the last one; held, it opens the shortcut menu. A grip with options keeps + // its menu. + let something = !app.cmd.buffer.trim().is_empty() || app.session.last_command.is_some(); + return timed && quick && inside && right_clicked && !app.canvas.snap_menu && app.canvas.grip_menu.is_none() && something; } let mut clicked = None; let popup = egui::Popup::new(popup_id, ctx, egui::PopupAnchor::PointerFixed, ui.layer_id()) diff --git a/crates/ui-egui/src/options/mod.rs b/crates/ui-egui/src/options/mod.rs index d2f805aa6..9468ae1b7 100644 --- a/crates/ui-egui/src/options/mod.rs +++ b/crates/ui-egui/src/options/mod.rs @@ -15,7 +15,7 @@ //! | `saveVersion` | `"2000"` … `"2018"`: the version drawings with no file yet are saved in | //! | `SAVETIME` | minutes between automatic saves, 0–600 (0: off) | //! | `SAVEFILEPATH` | the folder automatic saves go to | -//! | `timeSensitiveRightClick` | while a command runs, a quick right-click is Enter and holding the button opens the shortcut menu (default); `false`: a right-click always opens the menu | +//! | `timeSensitiveRightClick` | a quick right-click is Enter (between commands it repeats the last one) and holding the button opens the shortcut menu (default); `false`: a right-click always opens the menu | //! | `systemCursor` | keep the system cursor visible over the drawing area | //! | `historyLines` | command-line history lines, 0–12 | //! | `modelBackground`, `paperBackground` | `"#rrggbb"`, or `null` for the default | diff --git a/crates/ui-egui/tests/context_menus.rs b/crates/ui-egui/tests/context_menus.rs index 4957ad80f..7536939c3 100644 --- a/crates/ui-egui/tests/context_menus.rs +++ b/crates/ui-egui/tests/context_menus.rs @@ -257,4 +257,40 @@ fn time_sensitive_right_click() { painted(&mut app, &ctx, Vec::new(), 3.1); assert!(app.session.running.is_none(), "a quick right-click is Enter: {}", app.session.prompt_text()); assert_eq!(app.session.doc().unwrap().model.handles().len(), 1); + + // Between commands a quick right-click is Enter too: it repeats LINE (it opened the shortcut + // menu instead). + painted(&mut app, &ctx, vec![quick(true)], 4.0); + painted(&mut app, &ctx, vec![quick(false)], 4.05); + let text = painted(&mut app, &ctx, Vec::new(), 4.1); + assert!(app.session.running.is_some(), "a quick right-click repeats LINE: {}", app.session.prompt_text()); + assert!(!text.contains("Repeat LINE"), "no shortcut menu on a quick click:\n{text}"); + app.session.input(cadcraft_engine::Input::Cancel).unwrap(); + // Held, it opens the shortcut menu and repeats nothing. + painted(&mut app, &ctx, vec![quick(true)], 5.0); + painted(&mut app, &ctx, Vec::new(), 5.2); + painted(&mut app, &ctx, vec![quick(false)], 5.0 + context_menu::HOLD_SECS + 0.1); + let text = painted(&mut app, &ctx, Vec::new(), 5.5); + assert!(text.contains("Repeat LINE"), "Repeat LINE missing from the painted menu:\n{text}"); + assert!(app.session.running.is_none(), "held, no repeat: {}", app.session.prompt_text()); + + // A quick click enters what was typed, as the Enter key does (#1387): a command name between + // commands (not a repeat of LINE)… + painted( + &mut app, + &ctx, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + 5.6, + ); + app.cmd.buffer = "circle".into(); + painted(&mut app, &ctx, vec![quick(true)], 6.0); + painted(&mut app, &ctx, vec![quick(false)], 6.05); + painted(&mut app, &ctx, Vec::new(), 6.1); + assert!(app.session.prompt_text().contains("center point"), "the typed CIRCLE starts: {}", app.session.prompt_text()); + // …and a point while a command runs. + app.cmd.buffer = "5,5".into(); + painted(&mut app, &ctx, vec![quick(true)], 7.0); + painted(&mut app, &ctx, vec![quick(false)], 7.05); + painted(&mut app, &ctx, Vec::new(), 7.1); + assert!(app.session.prompt_text().contains("radius"), "the typed center is entered: {}", app.session.prompt_text()); } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d0c3fd1e3..bf29a122a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (stable dash anchors on filled-object highlights) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (a quick right-click is Enter between commands too, #1387) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How CADCraft's interaction compares with AutoCAD's: point entry, object snaps, tracking, dynamic input, grips, selection, the command line, chrome and navigation. A drafter's speed in AutoCAD @@ -190,9 +190,12 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. shortcuts. AutoCAD for Mac's defaults are similar in number; F4 (3D osnap) and F6 (dynamic UCS) are missing. - Delete erases the selection on macOS (#64); Escape cancels. -- Right-click on the canvas is Enter while a command runs; holding it (250 ms, AutoCAD's - time-sensitive right-click) opens the command menu: Enter, Cancel, Recent Input, the prompt's - options, Snap Overrides, Pan/Zoom. Otherwise it opens a shortcut menu (Repeat, Recent Commands, +- A quick right-click on the canvas is Enter, as in AutoCAD: it enters what was typed (a command + name, a point), ends the input of a running command, and between commands repeats the last one + (#1387). Holding it (250 ms, AutoCAD's time-sensitive right-click) opens the command menu while + a command runs: Enter, Cancel, Recent Input, the prompt's options, Snap Overrides, Pan/Zoom. + Held between commands (or any right-click with the time-sensitive right-click turned off in + Options), it opens a shortcut menu (Repeat, Recent Commands, Clipboard ▸, Isolate ▸, the selection's editing commands, Draw Order ▸, Group, the selected object type's edit commands, Select Similar, Deselect All, Undo/Redo, Pan/Zoom; #325, #512). The command line, drawing tabs, layout tabs, Layers palette rows and the Properties palette @@ -209,6 +212,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | 2026-10-14 | minor | Holding Shift overrides ortho while it is held (on when ORTHOMODE is off, off when it is on), as in AutoCAD | | 2026-10-16 | minor | ALIASEDIT opens the Command Aliases dialog (#1381) | | 2026-10-18 | minor | In-window menu bar: once a menu is open, pointing at another title closes it and opens that one (#1567) | +| 2026-10-20 | minor | A quick right-click is Enter between commands too: it runs the typed command or repeats the last one, and enters typed input while a command runs (#1387) | | 2026-10-13 | minor | Options ▸ Selection adds Select using two clicks only; PICKDRAG 0 disables drag-window creation/completion, 2 preserves clicks or drag, and the preference survives restart; UI pointer and profile regressions | | 2026-10-12 | minor | Selected and hovered objects redrawn in the selection colour (text and arrowheads included); Options ▸ Selection laid out as AutoCAD's: Object grouping, Show grips, grip object limit, selection preview, Visual Effect Settings (selection area, preview filter) | | 2026-10-12 | minor | Animation effects (dialog and menu fades, smoothed wheel scrolling and ⌘/Ctrl+wheel zoom) follow the operating system's setting; View ▸ Accessibility ▸ Animation Effects chooses System, On or Off | From 77b9560729038601ff922c2724a6732e08525802 Mon Sep 17 00:00:00 2001 From: Sladrian Pedroso <294190500+Sladrian@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:58:38 -0300 Subject: [PATCH 026/531] contributors: add my real name for the About window credits Co-Authored-By: Claude Opus 5.5 --- contributors/people.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 40ae92eb5..735996dcf 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -73,3 +73,8 @@ sync_github_name = false [people.gurparvez] real_name = "Gurparvez" + +[people.Sladrian] +real_name = "Sladrian Pedroso" +display_name = "Sladrian Pedroso" +sync_github_name = false From 8709920931c475fc9b26eaaa4d30616117e91295 Mon Sep 17 00:00:00 2001 From: Sladrian Pedroso <294190500+Sladrian@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:58:04 -0300 Subject: [PATCH 027/531] Document canvas::show, the drawing area for one frame Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index eee8b7d68..ffb10590c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1347,6 +1347,9 @@ fn wheel_zoom_points(events: &[egui::Event], opts: &egui::InputOptions, page: f3 if points.is_finite() { points } else { 0.0 } } +/// The drawing area for one frame: lays out the model viewport tiles, handles the pointer and keys +/// on the canvas (picks and windows, grips, right-click Enter and the shortcut menus, pan and zoom) +/// and draws the drawing with its overlays. pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); let full = ui.available_rect_before_wrap(); From 25714cac283d60a1dbf1c13d2aa48b4ef8344d90 Mon Sep 17 00:00:00 2001 From: Sladrian Pedroso <294190500+Sladrian@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:11:05 -0300 Subject: [PATCH 028/531] docs/ui-parity.md: with the time-sensitive right-click off, a right-click opens the command menu while a command runs Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bf29a122a..f63417e3f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -194,10 +194,11 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. name, a point), ends the input of a running command, and between commands repeats the last one (#1387). Holding it (250 ms, AutoCAD's time-sensitive right-click) opens the command menu while a command runs: Enter, Cancel, Recent Input, the prompt's options, Snap Overrides, Pan/Zoom. - Held between commands (or any right-click with the time-sensitive right-click turned off in - Options), it opens a shortcut menu (Repeat, Recent Commands, - Clipboard ▸, Isolate ▸, the selection's editing commands, Draw Order ▸, Group, the selected - object type's edit commands, Select Similar, Deselect All, Undo/Redo, Pan/Zoom; #325, #512). + Held between commands, it opens a shortcut menu (Repeat, Recent Commands, Clipboard ▸, + Isolate ▸, the selection's editing commands, Draw Order ▸, Group, the selected object type's + edit commands, Select Similar, Deselect All, Undo/Redo, Pan/Zoom; #325, #512). With the + time-sensitive right-click turned off in Options, every right-click opens one of these menus: + the command menu while a command runs, the shortcut menu between commands. The command line, drawing tabs, layout tabs, Layers palette rows and the Properties palette have menus too (#512). Still missing: in-place layout tab rename, Move or Copy, Select All Layouts. From 9e022cf31cb996cbb4d8de47584270a2281f9f94 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 22 Oct 2026 00:46:28 +1100 Subject: [PATCH 029/531] AutoLISP: read block definitions: tblsearch BLOCK gives the first entity (-2), entnext and entget walk a block's entities (part of #1700) A routine couldn't reach the entities of a block definition, so the text a dimension's *D block stores (which CADCraft keeps and draws) was out of reach. tblsearch "BLOCK" now gives the first entity in -2, entnext goes from one entity of a definition to the next (nil after the last), entget lists them without a layout (410), and handent finds them. entmod and entdel still leave definitions alone. --- crates/engine/src/lisp/drawing.rs | 46 +++++++++++++++-- crates/engine/src/lisp/tests.rs | 82 +++++++++++++++++++++++++++++++ docs/autolisp.md | 5 ++ 3 files changed, 128 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 573eaa24a..74aa37bde 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -295,7 +295,14 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 2)?; let h = ename(&a[0])?; let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; - let Some(e) = d.entity(h) else { return Ok(Flow::Value(Value::Nil)) }; + // An entity of a block definition (#1700) has no layout. + let (e, in_block) = match d.entity(h) { + Some(e) => (e, false), + None => match block_entity(d, h) { + Some(e) => (e, true), + None => return Ok(Flow::Value(Value::Nil)), + }, + }; let (kind, mut tags) = (codec()?.groups)(d, e); convert_angles(&kind, &mut tags, f64::to_radians); let layout = match space_of(d, h) { @@ -303,7 +310,7 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { _ => "Model".into(), }; let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))]; - let mut placed_layout = false; + let mut placed_layout = in_block; for v in groups_to_list(&tags) { // The layout name follows the AcDbEntity marker, as AutoCAD lists it. let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity"); @@ -438,6 +445,17 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn entnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 0, 1)?; + // From an entity of a block definition: the next one in that block, nil after the last (#1700). + if let Some(v) = a.first().filter(|v| !v.is_nil()) { + let h = ename(v)?; + if let Ok(d) = ctx.s.doc() + && d.entity(h).is_none() + && let Some(b) = block_of(d, h) + { + let next = b.entities.iter().skip_while(|e| e.handle != h).nth(1).map(|e| Value::Ename(e.handle)); + return Ok(Flow::Value(next.unwrap_or_default())); + } + } let order = handles_in_order(ctx); let next = match a.first() { None | Some(Value::Nil) => order.first().copied(), @@ -453,10 +471,23 @@ pub fn entnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn handent(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; let s = string(&a[0])?; - let h = Handle::parse_hex(&s).filter(|h| ctx.s.doc().is_ok_and(|d| d.entity(*h).is_some())); + let h = Handle::parse_hex(&s).filter(|h| ctx.s.doc().is_ok_and(|d| d.entity(*h).is_some() || block_entity(d, *h).is_some())); Ok(Flow::Value(h.map(Value::Ename).unwrap_or_default())) } +/// The block definition holding entity `h`, when it is one of a block's (not a drawn entity). +fn block_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&cadcraft_doc::Block> { + if h == Handle(0) { + return None; + } + d.blocks.values().map(|b| b.as_ref()).find(|b| b.entities.get(h).is_some()) +} + +/// Entity `h` of a block definition (#1700). +fn block_entity(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&Arc> { + block_of(d, h).and_then(|b| b.entities.get(h)) +} + // ---------------- selection sets ---------------- /// `(ssget [mode] [pt1 [pt2]] [filter])`. Modes: "X" every entity, "L" the last, "P" the @@ -842,12 +873,17 @@ fn table_records(d: &cadcraft_doc::Drawing, table: &str) -> Vec { .blocks .values() .map(|b| { - Value::list(vec![ + let mut items = vec![ pair(0, Value::str("BLOCK")), pair(2, Value::str(&b.name)), pair(70, Value::Int(0)), Value::list(vec![Value::Int(10), Value::Real(b.base.x), Value::Real(b.base.y), Value::Real(b.base.z)]), - ]) + ]; + // Its first entity (-2): entnext walks the rest of the definition (#1700). + if let Some(first) = b.entities.iter().next() { + items.push(pair(-2, Value::Ename(first.handle))); + } + Value::list(items) }) .collect(), "DIMSTYLE" => d diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index c02b48b17..0b1c940fb 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -619,3 +619,85 @@ fn a_panic_inside_a_routine_ends_it_with_an_error() { assert!(s.log.iter().any(|l| l.contains("internal error")), "{:?}", s.log); assert_eq!(ok(&mut s, "(+ 1 2)"), "3"); } + +// ---------------- entities of block definitions (#1700) ---------------- + +/// A drawing with one linear dimension measuring 100 whose `*D1` block, as stored in the file, +/// says 99.5 (a stale block: the defpoints moved, the block wasn't rebuilt). +fn stale_dimension() -> Session { + let mut s = session(); + s.execute("dimlinear", &serde_json::json!({"p1": [0, 0], "p2": [100, 0], "at": [50, -20], "rotation": 0})).unwrap(); + let dxf = cadcraft_io::write_dxf(s.doc().unwrap()); + // The *D1 block's MTEXT says 100 (100.0000 here); make the file say 99.5. + let lines: Vec<&str> = dxf.lines().collect(); + let (mut kind, mut block, mut out, mut changed) = (String::new(), String::new(), Vec::new(), 0); + for (i, l) in lines.iter().enumerate() { + let code = if i % 2 == 0 { l.trim() } else { "" }; + let value = lines.get(i + 1).map(|v| v.trim()).unwrap_or(""); + if code == "0" { + kind = value.to_string(); + } + if code == "2" && kind == "BLOCK" { + block = value.to_string(); + } + if i % 2 == 1 && kind == "MTEXT" && block == "*D1" && lines.get(i - 1).map(|c| c.trim()) == Some("1") && l.trim().starts_with("100") { + out.push("99.5".to_string()); + changed += 1; + continue; + } + out.push(l.to_string()); + } + assert_eq!(changed, 1, "the fixture found the *D1 text"); + let mut s = session(); + s.open_drawing(cadcraft_io::read_dxf(out.join("\n").as_bytes()).unwrap(), "stale", None); + s +} + +/// The issue's use: a routine reads the text a dimension's block stores and compares it with the +/// measurement, so it finds the stale block. +#[test] +fn a_routine_reads_the_text_a_dimension_block_stores() { + let mut s = stale_dimension(); + let code = r#"(progn + (defun dtext (dim / e txt) + (setq e (cdr (assoc -2 (tblsearch "BLOCK" (cdr (assoc 2 (entget dim))))))) + (while e + (if (= (cdr (assoc 0 (entget e))) "MTEXT") (setq txt (cdr (assoc 1 (entget e))))) + (setq e (entnext e))) + txt) + (setq dim (entlast)) + (list (dtext dim) (cdr (assoc 42 (entget dim)))))"#; + assert_eq!(ok(&mut s, code), "(\"99.5\" 100.0)"); +} + +/// tblsearch names a block's first entity (-2); entnext walks the definition in order and ends +/// with nil; entget lists each one (without a layout); handent finds them by handle. +#[test] +fn entnext_and_entget_walk_a_block_definition() { + let mut s = session(); + let l = s.execute("line", &serde_json::json!({"points": [[0, 0], [10, 0]]})).unwrap()["handles"][0].as_str().unwrap().to_string(); + let c = s.execute("circle", &serde_json::json!({"center": [5, 5], "radius": 2})).unwrap()["handle"].as_str().unwrap().to_string(); + s.execute("block", &serde_json::json!({"name": "B", "base": [0, 0], "handles": [l, c], "keep": "delete"})).unwrap(); + s.execute("line", &serde_json::json!({"points": [[50, 0], [60, 0]]})).unwrap(); + let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "B"))) types nil) + (while e (setq types (cons (cdr (assoc 0 (entget e))) types) e (entnext e))) + (reverse types))"#; + assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")", "the block's own entities, not the drawing's"); + let first = "(cdr (assoc -2 (tblsearch \"BLOCK\" \"B\")))"; + assert_eq!(ok(&mut s, &format!("(assoc 410 (entget {first}))")), "nil", "no layout"); + assert_eq!(ok(&mut s, &format!("(equal (handent (cdr (assoc 5 (entget {first})))) {first})")), "T"); + // The drawing's own entities walk as before. + assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext))))"), "\"LINE\""); + assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil"); + // Editing a block's entity through entmod or entdel isn't offered: nil, nothing changes. + assert_eq!(ok(&mut s, &format!("(entdel {first})")), "nil"); + assert_eq!(ok(&mut s, &format!("(entmod (entget {first}))")), "nil"); + assert_eq!(s.doc().unwrap().block("B").unwrap().entities.len(), 2); +} + +#[test] +fn an_empty_block_has_no_first_entity() { + let mut s = session(); + s.doc_mut().unwrap().blocks.insert("EMPTY".into(), std::sync::Arc::new(cadcraft_doc::Block::new("EMPTY"))); + assert_eq!(ok(&mut s, "(assoc -2 (tblsearch \"BLOCK\" \"EMPTY\"))"), "nil"); +} diff --git a/docs/autolisp.md b/docs/autolisp.md index e26702c2c..811c44bf9 100644 --- a/docs/autolisp.md +++ b/docs/autolisp.md @@ -82,6 +82,11 @@ DXF file holds for the object, plus `-1` (its name) and `410` (its layout). Angl are in radians, as in AutoCAD, where the file holds degrees; `entmake`, `entmod` and `ssget` filters take radians too. +Block definitions can be read: `(tblsearch "BLOCK" name)` gives the block's first entity in group +-2, `entnext` goes from one entity of a definition to the next (nil after the last) and `entget` +lists them (without a layout, group 410). So a routine can read what a block stores, such as the +text of a dimension's `*D` block. `entmod` and `entdel` don't change a definition's entities. + ## Testing against the corpus The AutoLISP conformance corpus (#648) lives in its own repository. Point `CADCRAFT_LISP_CORPUS` From 6c72999361ac1b3cdf2c592f1f244243beeb2dea Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 02:23:44 +0400 Subject: [PATCH 030/531] i18n: add Georgian (ka) interface language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a Georgian catalog (ka.tsv, 1,383 rows): the union of the existing catalogs, four menu headings (ზომების დატანა for the Dimension menu, ზომა for the object) and single-form counts, since a Georgian noun stays singular after a numeral. No marked UI literal falls back to English. Prompts read "მიუთითეთ …" for Specify and "შეიყვანეთ …" for Enter; clickable keywords keep the spelling the engine accepts. No Mtavruli. Register the language (Preference::Georgian, `ka`, ქართული) and add locale, preference, count, menu-heading, live-switch, dialog and no-Mtavruli tests. Docs, README and ATTRIBUTION list it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- ATTRIBUTION.md | 1 + README.md | 2 +- ROADMAP.md | 1 + crates/ui-egui/src/i18n/ka.tsv | 1399 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/mod.rs | 23 +- crates/ui-egui/src/i18n/tests.rs | 111 ++- crates/ui-egui/src/options/mod.rs | 2 +- docs/localization-parity.md | 4 +- docs/localization.md | 20 +- 9 files changed, 1554 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/i18n/ka.tsv diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 264c7430f..3779b71bc 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -71,3 +71,4 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker | | `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending | +| `crates/ui-egui/src/i18n/ka.tsv` | @devius with Claude (AI-assisted) | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; no font assets added (the Georgian face comes from craft-fonts) | diff --git a/README.md b/README.md index 655b944f5..c762a223e 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ numbers): | Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF | | Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit | | Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror | -| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar) and Turkish (Türkçe), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | +| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | | Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) | ## Quick start diff --git a/ROADMAP.md b/ROADMAP.md index d54f3bf8b..93b3a701e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,6 +95,7 @@ Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity. | Indonesian | none | 0% | | Japanese | none | 0% | | Greek | complete current catalog | 1,330 current source keys; independent proofreading pending | +| Georgian | complete current catalog | 1,383 rows; native proofreading pending | | German | partial | ≈ 100% of the catalog (989 rows) | | Korean | none | 0% | | Vietnamese | none | 0% | diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv new file mode 100644 index 000000000..25512c91f --- /dev/null +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -0,0 +1,1399 @@ +# CADCraft Georgian (ქართული) interface catalog — original translations by the CADCraft contributors. +# License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE). +# Written from CADCraft's English strings; no proprietary translations were copied. +# Clean room: every entry is written from the plain meaning of the English label in ordinary +# Georgian computing and technical-drawing (ხაზვა) vocabulary (შრე, ზომა, დაშტრიხვა, მომრგვალება, +# ფასკა, წანაცვლება, მოკვეთა, ობიექტზე მიბმა, ხედვის არე, განლაგება). No other product's Georgian +# interface, string table or terminology database was consulted, and no other catalog is used as a source. +# UTF-8: contextEnglish sourceGeorgian translation. +# Empty context = ordinary label; @plural = one form with {n} (a Georgian noun stays singular after +# a numeral: "5 კომიტი"); menu = a menu heading where it differs from the label. +# Commands are verbal nouns (შენახვა, შემობრუნება); prompts read "მიუთითეთ …" for Specify, +# "შეიყვანეთ …" for Enter and "მონიშნეთ …" for Select. Georgian has no letter case: nothing is +# capitalised and Mtavruli is never used. +# Keep command IDs, keywords (Top, Zero, Bottom, _tan to, nX/nXP, Multiple, PICKADD, QPMODE), +# technology/product names and user data unchanged. + + Apply გამოყენება + Attach DWG... DWG-ის მიმაგრება... + Bind ჩაშენება + Detach მოხსნა + Loaded ჩატვირთულია + Make it a block of this drawing, keeping its layer names ამ ნახაზის ბლოკად ქცევა, შრეების სახელების შენარჩუნებით + Make it a block of this drawing; its layers become NAME$0$LAYER ამ ნახაზის ბლოკად ქცევა; შრეების სახელები გახდება NAME$0$LAYER + No external references are attached. გარე მიმართვები მიმაგრებული არ არის. + Not Found ვერ მოიძებნა + Not loaded არ არის ჩატვირთული + Open გახსნა + Overlay ზედდება + Reference Manager მიმართვების მენეჯერი + Reference Name მიმართვის სახელი + References: {n} მიმართვა: {n} + Reload ხელახლა ჩატვირთვა + Reload All ყველას ხელახლა ჩატვირთვა + Saved Path შენახული გზა + Unload განტვირთვა + Unloaded განტვირთულია + Unreferenced მიმართვის გარეშე + Unresolved დაუდგენელი + Cancel გაუქმება + OK OK + or [ ან [ + % of all commits ყველა კომიტის % + * Wildcard Match * შაბლონით დამთხვევა + *VARIES* *სხვადასხვა* + + | Top | 2D Wireframe + | ზედა | 2D კარკასი + +Bin +Bin + +LOC +LOC + 1 Viewport 1 ხედვის არე + 2 Points 2 წერტილი + 2 Viewports 2 ხედვის არე + 2D Solid 2D შევსებული არე + 3 Points 3 წერტილი + 3 Viewports 3 ხედვის არე + 3D Face 3D წახნაგი + 3D Operations 3D ოპერაციები + 3D Polyline 3D ტეხილი + 4 Viewports 4 ხედვის არე + < Less than < ნაკლებია + <> Not Equal <> არ უდრის + = Equals = უდრის + > Greater than > მეტია + A variable name starts with a letter and has only letters, digits and _ ცვლადის სახელი ასოთი იწყება და მხოლოდ ასოებს, ციფრებსა და _-ს შეიცავს + About პროგრამის შესახებ + About CADCraft CADCraft-ის შესახებ + Absolute აბსოლუტური + Add Leader მიმთითებლის დამატება + Additional angles დამატებითი კუთხეები + Align სწორება + Align Text ტექსტის სწორება + Aligned გასწორებული + All ყველა + All Annotation Objects ყველა ანოტაციური ობიექტი + All Used Layers ყველა გამოყენებული შრე + All files ყველა ფაილი + Angle კუთხე + Angular კუთხური + Annotation Visibility ანოტაციის ხილვადობა + Annotation scale ანოტაციის მასშტაბი + Apparent Intersection ხილული გადაკვეთა + Append to current selection set მიმდინარე მონიშნულზე დამატება + Apply to: გამოყენება: + Apply true color ნამდვილი ფერის გამოყენება + Arc რკალი + Arc Length რკალის სიგრძე + Area ფართობი + Arrange Panel პანელის დალაგება + Array მასივი + Attach მიმაგრება + Attribute ატრიბუტი + Attribute Definition ატრიბუტის განსაზღვრა + Attribute Display ატრიბუტების ჩვენება + Audit აუდიტი + Auto (system language) ავტომატური (სისტემის ენა) + Auto Constrain ავტომატური შეზღუდვა + AutoConstrain ავტოშეზღუდვა + Axis, End ღერძი, ბოლო + Base საბაზო წერტილი + Baseline საბაზისო ხაზი + Batch Publish პაკეტური გამოქვეყნება + Binary assets added დამატებული ბინარული ფაილები + Binary assets removed წაშლილი ბინარული ფაილები + Bind... ჩაშენება... + Blend გადასვლა + Block ბლოკი + Block Attribute Manager... ბლოკის ატრიბუტების მენეჯერი... + Block Editor ბლოკის რედაქტორი + Block Reference ბლოკის ჩასმა + Block... ბლოკი... + Blocks ბლოკები + Blue ლურჯი + Bold მუქი + Boolean ლოგიკური + Boundary საზღვარი + Boundary... საზღვარი... + Box პარალელეპიპედი + Break გაწყვეტა + Break At Point წერტილში გაწყვეტა + Break-line Symbol წყვეტის ხაზის სიმბოლო + Bring Above Objects ობიექტებზე ზემოთ გადატანა + Bring Annotations to Front ანოტაციების წინა პლანზე გადმოტანა + Bring to Front წინა პლანზე გადმოტანა + Bulleted list ბურთულებიანი სია + ByBlock ბლოკის მიხედვით + ByColor ფერის მიხედვით + ByLayer შრის მიხედვით + CADCraft Help CADCraft-ის დახმარება + Cancel გაუქმება + Cartesian (x, y) დეკარტული (x, y) + Center ცენტრი + Center Line ღერძული ხაზი + Center Mark ცენტრის ნიშანი + Center X ცენტრი X + Center Y ცენტრი Y + Center Z ცენტრი Z + Center, Diameter ცენტრი, დიამეტრი + Center, Radius ცენტრი, რადიუსი + Center, Start, Angle ცენტრი, დასაწყისი, კუთხე + Center, Start, End ცენტრი, დასაწყისი, ბოლო + Center, Start, Length ცენტრი, დასაწყისი, სიგრძე + Chamfer ფასკა + Change Space სივრცის შეცვლა + Change to Current Layer მიმდინარე შრეზე გადატანა + Changed: {n} შეცვლილი: {n} + Circle წრე + Circumference წრეწირის სიგრძე + Clear History ისტორიის გასუფთავება + Clear გასუფთავება + Clip მოჭრა + Clip Viewport ხედვის არის მოჭრა + Clipboard გაცვლის ბუფერი + Close დახურვა + Close All ყველას დახურვა + Close All Other Drawings ყველა სხვა ნახაზის დახურვა + Closed შეკრული + Close Comparison შედარების დახურვა + Coincident დამთხვევა + Collapse Palettes პალიტრების ჩაკეცვა + Collapse Tool Sets ხელსაწყოთა ნაკრებების ჩაკეცვა + Collinear კოლინეარობა + Color ფერი + Color 8 ფერი 8 + Color 9 ფერი 9 + Color Index ფერის ინდექსი + Color... ფერი... + Command Aliases ბრძანებების ფსევდონიმები + Command History ბრძანებების ისტორია + Clear Command History ბრძანებების ისტორიის გასუფთავება + Command Line ბრძანების სტრიქონი + Command Line History Lines ბრძანების სტრიქონის ისტორიის სტრიქონები + Command Reference ბრძანებების ცნობარი + Commits კომიტები + Company კომპანია + Compare Drawings... ნახაზების შედარება... + Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust. კომპიუტერული დაპროექტება და ხაზვა: ღია კოდის CAD აპლიკაცია, შექმნილი „სუფთა ოთახის“ მეთოდით და დაწერილი სუფთა Rust-ზე. + Concentric კონცენტრულობა + Cone კონუსი + Constraint Bars შეზღუდვების ზოლები + Constraint Settings შეზღუდვების პარამეტრები + Construction Line დამხმარე ხაზი + Contents შიგთავსი + Continue გაგრძელება + Contributors მონაწილეები + Control Vertices მართვის წვეროები + Convert გარდაქმნა + Convert Text to Mtext ტექსტის Mtext-ად გარდაქმნა + Copy კოპირება + Copy Full File Path ფაილის სრული გზის კოპირება + Copy History ისტორიის კოპირება + Copy Layout განლაგების კოპირება + Copy Nested Objects ჩადგმული ობიექტების კოპირება + Copy Selection მონიშნულის კოპირება + Copy with Base Point კოპირება საბაზო წერტილით + Count დათვლა + Count List დათვლის სია + Count Table დათვლის ცხრილი + Create Block ბლოკის შექმნა + Creates a user parameter ქმნის მომხმარებლის პარამეტრს + Ctrl+Enter to finish დასასრულებლად: Ctrl+Enter + Current layer მიმდინარე შრე + Current selection მიმდინარე მონიშნული + Current: {color} მიმდინარე: {color} + Cut ამოჭრა + Cyan ცისფერი + Cylinder ცილინდრი + DWG DWG + DWG Reference... DWG მიმართვა... + DXF DXF + Dark ბნელი + Data Extraction... მონაცემების ამოღება... + Default ნაგულისხმევი + Data Link... მონაცემთა კავშირი... + Default Save Format შენახვის ნაგულისხმევი ფორმატი + Default Save Version შენახვის ნაგულისხმევი ვერსია + Define Attributes ატრიბუტების განსაზღვრა + Define Attributes... ატრიბუტების განსაზღვრა... + Defined width განსაზღვრული სიგანე + Degree გრადუსი + Degrees of Freedom თავისუფლების ხარისხები + Degrees of freedom: {n} თავისუფლების ხარისხი: {n} + Delete წაშლა + Delete Column სვეტის წაშლა + Delete Constraints შეზღუდვების წაშლა + Delete Dimension Style ზომის სტილის წაშლა + Delete Duplicate Objects დუბლიკატი ობიექტების წაშლა + Delete Layer შრის წაშლა + Delete Layer State შრეების მდგომარეობის წაშლა + Delete Layout განლაგების წაშლა + Delete Row სტრიქონის წაშლა + Delete Text Style ტექსტის სტილის წაშლა + Delta X დელტა X + Delta Y დელტა Y + Description აღწერა + Deselect All ყველა მონიშვნის მოხსნა + Diameter დიამეტრი + Dim style ზომის სტილი + Dimension Break ზომის გაწყვეტა + Dimension Edit ზომის რედაქტირება + Dimension ზომა + Dimension Objects Only მხოლოდ ზომის ობიექტები + Dimension Space ზომების დაშორება + Dimension Style Override ზომის სტილის გადაფარვა + Dimension Style... ზომის სტილი... + Dimension Text Edit ზომის ტექსტის რედაქტირება + Dimension style ზომის სტილი + Dimensional Constraint ზომითი შეზღუდვა + Dimensional Constraint Parameters ზომითი შეზღუდვის პარამეტრები + Dimensional Constraints ზომითი შეზღუდვები + Disassociate Dimensions ზომების ასოციაციის მოხსნა + Display name საჩვენებელი სახელი + Distance მანძილი + Divide დაყოფა + Do not plot (click: plot) არ იბეჭდება (დაწკაპეთ: ბეჭდვა) + Donut რგოლი + Double-click to edit the description ორჯერ დაწკაპეთ აღწერის რედაქტირებისთვის + Down ქვემოთ + Drafting ხაზვა + Drafting Settings ხაზვის პარამეტრები + Drafting Settings... ხაზვის პარამეტრები... + Draw ხაზვა + Draw Order ხაზვის რიგი + Drawing (DWG) ნახაზი (DWG) + Drawing (DXF) ნახაზი (DXF) + Drawing Limits ნახაზის ზღვრები + Drawing Template (DWT) ნახაზის შაბლონი (DWT) + Drawing Utilities ნახაზის უტილიტები + Drawings (DWG, DXF) ნახაზები (DWG, DXF) + SVG drawings (SVG, SVGZ) SVG ნახაზები (SVG, SVGZ) + Dynamic დინამიკური + Dynamic Dimensions დინამიკური ზომები + Dynamic Input დინამიკური შეყვანა + Dynamic Input (F12) დინამიკური შეყვანა (F12) + E ა + Edit რედაქტირება + Edit Attributes... ატრიბუტების რედაქტირება... + Edit Text... ტექსტის რედაქტირება... + Edit Table Cell ცხრილის უჯრის რედაქტირება + Elevation ნიშნული + Ellipse ელიფსი + Elliptical Arc ელიფსური რკალი + Enable Dynamic Input (F12) დინამიკური შეყვანის ჩართვა (F12) + End Object Isolation ობიექტების იზოლირების დასრულება + End Width ბოლო სიგანე + End X ბოლო X + End Y ბოლო Y + End angle ბოლო კუთხე + Endpoint ბოლო წერტილი + Enter შეყვანა + Enter Top, Zero or Bottom. შეიყვანეთ Top, Zero ან Bottom. + Enter a fit data option შეიყვანეთ მისადაგების მონაცემების ვარიანტი + Enter a pattern name შეიყვანეთ ნიმუშის სახელი + Enter a vertex editing option შეიყვანეთ წვეროს რედაქტირების ვარიანტი + Enter an option შეიყვანეთ ვარიანტი + Enter angle of xline შეიყვანეთ დამხმარე ხაზის კუთხე + Enter angle of xline (0) or შეიყვანეთ დამხმარე ხაზის კუთხე (0) ან + Enter area of rectangle in current units შეიყვანეთ მართკუთხედის ფართობი მიმდინარე ერთეულებში + Enter attribute prompt შეიყვანეთ ატრიბუტის მოთხოვნა + Enter attribute tag name შეიყვანეთ ატრიბუტის ტეგის სახელი + Enter attribute value შეიყვანეთ ატრიბუტის მნიშვნელობა + Enter block name შეიყვანეთ ბლოკის სახელი + Enter constraint type შეიყვანეთ შეზღუდვის ტიპი + Enter continuity შეიყვანეთ უწყვეტობის ტიპი + Enter default attribute value შეიყვანეთ ატრიბუტის ნაგულისხმევი მნიშვნელობა + Enter degree of spline შეიყვანეთ სპლაინის ხარისხი + Enter delta angle შეიყვანეთ კუთხის ნამატი + Enter delta length or შეიყვანეთ სიგრძის ნამატი ან + Enter dimension text შეიყვანეთ ზომის ტექსტი + Enter dimension text (<> = measurement) შეიყვანეთ ზომის ტექსტი (<> = გაზომილი მნიშვნელობა) + Enter dimension value or [name=expression] შეიყვანეთ ზომის მნიშვნელობა ან [name=expression] + Enter dimension variable name to override შეიყვანეთ გადასაფარავი ზომის ცვლადის სახელი + Enter justification type შეიყვანეთ სწორების ტიპი + Enter leader text შეიყვანეთ მიმთითებლის ტექსტი + Enter mline scale შეიყვანეთ მულტიხაზის მასშტაბი + Enter mode შეიყვანეთ რეჟიმი + Enter name of block to insert შეიყვანეთ ჩასასმელი ბლოკის სახელი + Enter new text შეიყვანეთ ახალი ტექსტი + Enter next point შეიყვანეთ შემდეგი წერტილი + Enter number of columns შეიყვანეთ სვეტების რაოდენობა + Enter number of data rows შეიყვანეთ მონაცემების სტრიქონების რაოდენობა + Enter number of items შეიყვანეთ ელემენტების რაოდენობა + Enter number of items along path შეიყვანეთ ელემენტების რაოდენობა ტრაექტორიის გასწვრივ + Enter number of sides შეიყვანეთ გვერდების რაოდენობა + Enter number of turns შეიყვანეთ ხვიების რაოდენობა + Enter percentage length შეიყვანეთ სიგრძე პროცენტებში + Enter rectangle length შეიყვანეთ მართკუთხედის სიგრძე + Enter rectangle width შეიყვანეთ მართკუთხედის სიგანე + Enter scale factor შეიყვანეთ მასშტაბის კოეფიციენტი + Enter text შეიყვანეთ ტექსტი + Enter text (use \P for new paragraphs) შეიყვანეთ ტექსტი (ახალი აბზაცისთვის გამოიყენეთ \P) + Enter the number of segments შეიყვანეთ სეგმენტების რაოდენობა + Enter twist direction of helix შეიყვანეთ სპირალის დახვევის მიმართულება + Entire drawing მთელი ნახაზი + Equal ტოლობა + Erase წაშლა + Evaluate გამოთვლა + Evaluate LISP LISP-ის გამოთვლა + Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა + Explode დაშლა + Explode Attributes to Text ატრიბუტების ტექსტად დაშლა + Export ექსპორტი + Export Table ცხრილის ექსპორტი + Export to PDF... PDF-ად ექსპორტი... + Express Tools Express Tools + Expression ექსპრესია + Extend გაგრძელება + Extension გაგრძელება + Extents საზღვრები + External Reference გარე მიმართვა + External References გარე მიმართვები + Extrude ამოწევა + File ფაილი + File Tab ფაილის ჩანართი + Fillet მომრგვალება + Filter ფილტრი + Filters ფილტრები + Find and Replace ძებნა და ჩანაცვლება + Find... ძებნა... + First პირველი + First commit პირველი კომიტი + Fit Points მისადაგების წერტილები + Fix ფიქსაცია + Flatten Objects ობიექტების გაბრტყელება + Format ფორმატი + Freehand ხელით ხაზვა + Freeze გაყინვა + Freeze Layer შრის გაყინვა + Freeze in new viewports გაყინვა ახალ ხედვის არეებში + Freeze/Thaw გაყინვა/გალღობა + Freeze/Thaw in all viewports გაყინვა/გალღობა ყველა ხედვის არეში + Freeze/Thaw in the current viewport გაყინვა/გალღობა მიმდინარე ხედვის არეში + From ათვლის წერტილიდან + From Template... შაბლონიდან... + General ზოგადი + Geometric Center გეომეტრიული ცენტრი + Geometric Constraint გეომეტრიული შეზღუდვა + Geometric Constraints გეომეტრიული შეზღუდვები + Geometry გეომეტრია + Get from the Drawing ნახაზიდან აღება + Get Variable ცვლადის მიღება + Get View ხედის მიღება + Global გლობალური + Global width საერთო სიგანე + Grab bag სხვადასხვა + Gradient გრადიენტი + Gradient... გრადიენტი... + Green მწვანე + Grid (F7) ბადე (F7) + Grid Display ბადის ჩვენება + Grid On (F7) ბადის ჩართვა (F7) + Grid snap ბადეზე მიბმა + Grid spacing ბადის ბიჯი + Grip Edit სახელურით რედაქტირება + Grip Mirror სახელურით არეკვლა + Grip Option სახელურის პარამეტრი + Grip Rotate სახელურით შემობრუნება + Grip Scale სახელურით მასშტაბირება + Grip Stretch სახელურით გაწელვა + Group დაჯგუფება + Group Edit ჯგუფის რედაქტირება + Group Options დაჯგუფების პარამეტრები + Group Selection ჯგუფის მონიშვნა + Hatch დაშტრიხვა + Hatch Edit დაშტრიხვის რედაქტირება + Hatch Patterns დაშტრიხვის ნიმუშები + Hatch... დაშტრიხვა... + Height სიმაღლე + Height: {height} სიმაღლე: {height} + Helix სპირალი + Help დახმარება + Hide All ყველას დამალვა + Hide All Constraint Bars შეზღუდვების ყველა ზოლის დამალვა + Hide All Dynamic Dimensions ყველა დინამიკური ზომის დამალვა + Hide Layer List შრეების სიის დამალვა + Hide Objects ობიექტების დამალვა + Hide Palettes პალიტრების დამალვა + History ისტორია + Home საწყისი პოზიცია + Horizontal ჰორიზონტალური + HorizontalDistance ჰორიზონტალური მანძილი + How to apply: გამოყენების წესი: + ID Point წერტილის კოორდინატები + Import იმპორტი + Align Multileaders მულტიმიმთითებლების სწორება + Collect შეგროვება + Collect Multileaders მულტიმიმთითებლების შეგროვება + Edit Multileader მულტიმიმთითებლის რედაქტირება + In გადიდება + In-window Menu Bar მენიუს ზოლი ფანჯარაში + Include in new selection set ახალ მონიშნულ ნაკრებში ჩართვა + Increment angle კუთხის ბიჯი + Index Color ინდექსური ფერი + Index color: {index} ინდექსური ფერი: {index} + Infer Constraints შეზღუდვების ავტომატური დადგენა + Inquiry ინფორმაცია + Insert ჩასმა + Insert Block ბლოკის ჩასმა + Insert Column სვეტის ჩასმა + Insert Row სტრიქონის ჩასმა + Insert tab ტაბულაციის ჩასმა + Insert this block ამ ბლოკის ჩასმა + Insert Table Formula ცხრილში ფორმულის ჩასმა + Insertion ჩასმის წერტილი + Insertion X ჩასმის წერტილი X + Insertion Y ჩასმის წერტილი Y + Insertion Z ჩასმის წერტილი Z + Inspect Constraints შეზღუდვების შემოწმება + Inspect Drawing ნახაზის შემოწმება + Inspection შემოწმება + Interface Language ინტერფეისის ენა + Interface Theme ინტერფეისის თემა + Intersect გადაკვეთა + Intersection გადაკვეთა + Isolate იზოლირება + Isolate Layer შრის იზოლირება + Isolate Objects ობიექტების იზოლირება + Isometric Drafting იზომეტრიული ხაზვა + Jogged გატეხილი + Jogged Linear გატეხილი წრფივი + Join შეერთება + Join the ArtCraft Discord… შემოუერთდით ArtCraft-ის Discord-ს… + Join us on Discord შემოგვიერთდით Discord-ზე + Isometric Plane იზომეტრიული სიბრტყე + Isometric snap იზომეტრიული მიბმა + Language ენა + Last ბოლო + Last commit ბოლო კომიტი + Layer შრე + Layer Delete შრის წაშლა + Layer Match შრის მისადაგება + Layer Merge შრეების შერწყმა + Layer Off შრის გამორთვა + Layer Properties შრის თვისებები + Layer Properties Manager შრის თვისებების მენეჯერი + Layer Properties Manager — current viewport შრის თვისებების მენეჯერი — მიმდინარე ხედვის არე + Layer State შრის მდგომარეობა + Layer States Manager... შრის მდგომარეობების მენეჯერი... + Layer Tools შრის ხელსაწყოები + Layer contains objects (double-click to make current) შრეში ობიექტებია (მიმდინარედ გასახდომად ორჯერ დაწკაპეთ) + Layer is empty (double-click to make current) შრე ცარიელია (მიმდინარედ გასახდომად ორჯერ დაწკაპეთ) + Layers შრეები + Layers Palette შრეების პალიტრა + Hide Palette პალიტრის დამალვა + Layers displayed: {shown} of {total}. Current layer: {layer} ნაჩვენები შრეები: {shown} / {total}. მიმდინარე შრე: {layer} + Layout განლაგება + Layout list განლაგებების სია + Leader მიმთითებელი + Leaders Only მხოლოდ მიმთითებლები + Left მარცხნივ + Length სიგრძე + Length X სიგრძე X + Length Y სიგრძე Y + Lengthen დაგრძელება + Light ღია + Line ხაზი + Line delta სტრიქონების სხვაობა + Linear წრფივი + Lines +/− სტრიქონები +/− + Lines added დამატებული სტრიქონები + Lines deleted წაშლილი სტრიქონები + Lines of Command History ბრძანებების ისტორიის სტრიქონები + Linetype ხაზის ტიპი + Linetype Scale ხაზის ტიპის მასშტაბი + Linetype scale ხაზის ტიპის მასშტაბი + Ltscale ხაზის ტიპის მასშტაბი + Linetype... ხაზის ტიპი... + Lineweight ხაზის სისქე + Lineweight... ხაზის სისქე... + List სია + List Blocks ბლოკების სია + List Dimension Styles ზომის სტილების სია + List Groups ჯგუფების სია + List Layer States შრის მდგომარეობების სია + List Layouts განლაგებების სია + List System Variables სისტემური ცვლადების სია + List Text Styles ტექსტის სტილების სია + Load all ყველას ჩატვირთვა + Load... ჩატვირთვა... + Load Application... აპლიკაციის ჩატვირთვა... + Loaded linetypes ჩატვირთული ხაზის ტიპები + Lock ჩაკეტვა + Lock Layer შრის ჩაკეტვა + Lock viewport ხედვის არის ჩაკეტვა + Lock/Unlock ჩაკეტვა/განბლოკვა + Loft კვეთებით აგება + MIT OR Apache-2.0. Not affiliated with Autodesk, Inc. MIT OR Apache-2.0. Autodesk, Inc.-თან კავშირი არ აქვს. + MODEL მოდელი + MText MText + Magenta მეწამული + Major line every მთავარი ხაზის ბიჯი + Make Current მიმდინარედ დაყენება + Make Object's Layer Current ობიექტის შრის მიმდინარედ დაყენება + Make... შექმნა... + Match Layer შრის მისადაგება + Match Properties თვისებების გადატანა + Measure გაზომვა + Measure Distance მანძილის გაზომვა + Measure Geometry გეომეტრიის გაზომვა + Merge Cells უჯრების შერწყმა + Merged PRs გაერთიანებული PR-ები + Mid Between 2 Points შუა 2 წერტილს შორის + Midpoint შუა წერტილი + Mirror არეკვლა + Model მოდელი + Model Space (in viewport) მოდელის სივრცე (ხედვის არეში) + Modeling მოდელირება + Models მოდელები + Modify შეცვლა + Move გადაადგილება + Move/Copy/Rotate გადაადგილება/კოპირება/შემობრუნება + Multileader მულტიმიმთითებელი + Multileader Style... მულტიმიმთითებლის სტილი... + Multileader style მულტიმიმთითებლის სტილი + Multiline მულტიხაზი + Multiline Text მრავალსტრიქონიანი ტექსტი + Multiline Text... მრავალსტრიქონიანი ტექსტი... + Multiple რამდენიმე + Multiple Point რამდენიმე წერტილი + My ჩემი + My properties: not available yet ჩემი თვისებები: ჯერ ხელმისაწვდომი არ არის + N ჩ + Name სახელი + Name (A–Z) სახელი (ა–ჰ) + Named Views... დასახელებული ხედები... + Nearest უახლოესი + New ახალი + New (metric) ახალი (მეტრული) + New Drawing ახალი ნახაზი + New Drawing (⌘N) ახალი ნახაზი (⌘N) + New Drawing... ახალი ნახაზი... + New Layer ახალი შრე + New Layout ახალი განლაგება + New VP Freeze გაყინვა ახალ ხედვის არეებში + New Viewports... ახალი ხედვის არეები... + New from Template... ახალი შაბლონიდან... + New layout ახალი განლაგება + New state name მდგომარეობის ახალი სახელი + Next Change შემდეგი ცვლილება + No არა + No blocks defined in this drawing. ამ ნახაზში ბლოკები არ არის განსაზღვრული. + No contributor data was built into this copy. ამ ასლში მონაწილეების მონაცემები არ არის ჩაშენებული. + No model credits were built into this copy. ამ ასლში მოდელების მონაცემები არ არის ჩაშენებული. + No saved layer states შრის შენახული მდგომარეობები არ არის + No selection მონიშნული არაფერია + Node კვანძი + None არცერთი + Not available მიუწვდომელია + Not available yet ჯერ ხელმისაწვდომი არ არის + Numbered list დანომრილი სია + OK OK + Object ობიექტი + Object Snap ობიექტზე მიბმა + Object Snap (F3) ობიექტზე მიბმა (F3) + Object Snap On (F3) ობიექტზე მიბმის ჩართვა (F3) + Object Snap Tracking მიბმის მიდევნება + Object Snap Tracking (F11) მიბმის მიდევნება (F11) + Object Snap Tracking Settings მიბმის მიდევნების პარამეტრები + Object type: ობიექტის ტიპი: + Oblique დახრა + Off გამორთული + Offset წანაცვლება + On ჩართული + On/Off ჩართვა/გამორთვა + One of the Crafting Apps by the ArtCraft team and community. ArtCraft-ის გუნდისა და საზოგადოების ერთ-ერთი Crafting App. + Only in this drawing: {n} მხოლოდ ამ ნახაზში: {n} + Only in {name}: {n} მხოლოდ ფაილში {name}: {n} + Open (⌘O) გახსნა (⌘O) + Open Sample Drawing სანიმუშო ნახაზის გახსნა + Open sample drawing სანიმუშო ნახაზის გახსნა + Open Xref გარე მიმართვის გახსნა + Open... გახსნა... + Open Recent ბოლოს გახსნილი ფაილების გახსნა + Clear Recent Files ბოლოს გახსნილი ფაილების სიის გასუფთავება + Operator: ოპერატორი: + Orbit ორბიტა + Ordinate კოორდინატული + Ortho (F8) ორთო (F8) + Ortho Mode ორთო რეჟიმი + Ortho Mode (F8) ორთო რეჟიმი (F8) + Osnap Settings... ობიექტზე მიბმის პარამეტრები... + Out დაპატარავება + Over-constrained ზედმეტად შეზღუდული + Override გადაფარვა + PAPER ფურცელი + Percent პროცენტი + Polar (distance < angle) პოლარული (მანძილი < კუთხე) + PRs PR-ები + Page Setup Manager გვერდის პარამეტრების მენეჯერი + Page Setup Manager... გვერდის პარამეტრების მენეჯერი... + Pan პანორამა + Pan Down პანორამა ქვემოთ + Pan Left პანორამა მარცხნივ + Pan Right პანორამა მარჯვნივ + Pan Up პანორამა ზემოთ + Paper Space ფურცლის სივრცე + Parallel პარალელური + Parameters Manager პარამეტრების მენეჯერი + Parametric პარამეტრული + Paste ჩასმა + Paste as Block ბლოკად ჩასმა + Paste to Command Line ბრძანების სტრიქონში ჩასმა + Paste to Original Coordinates საწყის კოორდინატებზე ჩასმა + Path Array ტრაექტორიული მასივი + Pattern ნიმუში + Perpendicular მართობი + Plot დაბეჭდვა + Plot (click: do not plot) იბეჭდება (დაწკაპეთ, რომ არ დაიბეჭდოს) + Plot Preview ნახვა ამობეჭდვამდე + Plot Window ბეჭდვის ფანჯარა + Plot style ბეჭდვის სტილი + Plot style attached to მიმაგრებული ბეჭდვის სტილი + Plot style table ბეჭდვის სტილების ცხრილი + Plot Style... ბეჭდვის სტილი... + Plot Style Manager ბეჭდვის სტილების მენეჯერი + Plot Style Manager... ბეჭდვის სტილების მენეჯერი... + Plot Styles... ბეჭდვის სტილები... + Plotter Manager პლოტერების მენეჯერი + Plotter Manager... პლოტერების მენეჯერი... + New CTB ახალი CTB + New STB ახალი STB + New style ახალი სტილი + Reset Panel Layout პანელების განლაგების ჩამოყრა + Send Hatches to Back დაშტრიხვების უკანა პლანზე გადატანა + Send Under Objects ობიექტების ქვეშ გადატანა + Text Objects Only მხოლოდ ტექსტური ობიექტები + Use for this layout ამ განლაგებისთვის გამოყენება + Display plot styles ბეჭდვის სტილების ჩვენება + No plot style tables. ბეჭდვის სტილების ცხრილები არ არის. + A built-in table: editing it keeps an edited copy in the drawing. ჩაშენებული ცხრილი: რედაქტირებისას შეცვლილი ასლი ნახაზში ინახება. + Keep an editable copy of this table in the drawing ამ ცხრილის რედაქტირებადი ასლის ნახაზში შენახვა + Layout {name}: {table} განლაგება {name}: {table} + Grayscale ნაცრისფერი ტონები + Screening ფერის ინტენსივობა + Use object linetype ობიექტის ხაზის ტიპის გამოყენება + Use object lineweight ობიექტის ხაზის სისქის გამოყენება + Remove წაშლა + Add დამატება + Open a drawing first. ჯერ გახსენით ნახაზი. + Plot table type ბეჭდვის ცხრილის ტიპი + Color-dependent ფერზე დამოკიდებული + Named დასახელებული + Plus/minus პლუს/მინუს + Point წერტილი + Point Filters წერტილის ფილტრები + Point Style... წერტილის სტილი... + Polar Array პოლარული მასივი + Polar Tracking პოლარული მიდევნება + Polar Tracking (F10) პოლარული მიდევნება (F10) + Polar Tracking On (F10) პოლარული მიდევნების ჩართვა (F10) + Polar angle measurement პოლარული კუთხის ათვლა + Polar distance პოლარული მანძილი + Polar: {distance} < {angle}° პოლარული: {distance} < {angle}° + PolarSnap პოლარული მიბმა + Polygon მრავალკუთხედი + Polygonal მრავალკუთხა + Polygonal Viewport მრავალკუთხა ხედვის არე + Polyline ტეხილი + Polyline Edit ტეხილის რედაქტირება + Position X პოზიცია X + Position Y პოზიცია Y + Position Z პოზიცია Z + Previous წინა + Previous Change წინა ცვლილება + Previous Layer წინა შრე + Primitives პრიმიტივები + Print დაბეჭდვა + Print... დაბეჭდვა... + Properties თვისებები + Properties Inspector თვისებების ინსპექტორი + Properties: თვისებები: + Proxy პროქსი + Purge გაწმენდა + Pyramid პირამიდა + Quadrant კვადრანტი + Query Entities ობიექტების მოთხოვნა + Quick სწრაფი + Quick Dimension სწრაფი ზომა + Quick Properties სწრაფი თვისებები + Quick Select სწრაფი მონიშვნა + Quick Select Properties სწრაფი მონიშვნის თვისებები + Quick Select... სწრაფი მონიშვნა... + QuickCalc სწრაფი კალკულატორი + QuickCalc Pick სწრაფი კალკულატორი: არჩევა + Quit CADCraft CADCraft-იდან გასვლა + Radius რადიუსი + Raster Image რასტრული გამოსახულება + Ray სხივი + Read-only მხოლოდ წასაკითხი + Real name ნამდვილი სახელი + Realtime რეალურ დროში + Reassociate Dimensions ზომების ხელახლა მიბმა + Recent ბოლოდროინდელი + Recent Commands ბოლოდროინდელი ბრძანებები + Recent Input ბოლოდროინდელი შეყვანა + Recover... აღდგენა... + Rectangle მართკუთხედი + Recalculate Table Formulas ცხრილის ფორმულების გადათვლა + Rectangular მართკუთხა + Rectangular snap მართკუთხა მიბმა + Rectangular Array მართკუთხა მასივი + Red წითელი + Redo ხელახლა შესრულება + Redo (⇧⌘Z) ხელახლა შესრულება (⇧⌘Z) + Redraw გადახატვა + Regen რეგენერაცია + Regen All ყველაფრის რეგენერაცია + Region რეგიონი + Region/Mass Properties რეგიონის/მასის თვისებები + Reinitialize ხელახლა ინიციალიზება + Relative ფარდობითი + Relative to last segment ბოლო სეგმენტის მიმართ + Remove Leader მიმთითებლის მოცილება + Remove the viewport override ხედვის არის ცალკე პარამეტრის მოცილება + Rename Dimension Style ზომის სტილის სახელის შეცვლა + Rename Layer შრის სახელის შეცვლა + Rename Layer State შრეების მდგომარეობის სახელის შეცვლა + Rename Layout განლაგების სახელის შეცვლა + Rename Text Style ტექსტის სტილის სახელის შეცვლა + Rename... სახელის შეცვლა... + Repeat {command} გამეორება: {command} + Requires a point (x,y, @dx,dy or @d მიუთითეთ მეორე წერტილი ან <პირველი წერტილი გამოიყენეთ წანაცვლებად> + Specify second source point მიუთითეთ მეორე საწყისი წერტილი + Specify side to offset მიუთითეთ წანაცვლების მხარე + Specify start angle მიუთითეთ საწყისი კუთხე + Specify start point მიუთითეთ საწყისი წერტილი + Specify start point of arc მიუთითეთ რკალის საწყისი წერტილი + Specify start point of polyline მიუთითეთ ტეხილის საწყისი წერტილი + Specify start point of text მიუთითეთ ტექსტის საწყისი წერტილი + Specify starting width მიუთითეთ საწყისი სიგანე + Specify starting width for next segment მიუთითეთ შემდეგი სეგმენტის საწყისი სიგანე + Specify tangent direction for the start point of arc მიუთითეთ მხების მიმართულება რკალის საწყის წერტილში + Specify the elevation for rectangles მიუთითეთ მართკუთხედების დონე + Specify thickness for rectangles მიუთითეთ მართკუთხედების სისქე + Specify third point on circle მიუთითეთ წრის მესამე წერტილი + Specify third point on circle: _tan to მიუთითეთ წრის მესამე წერტილი: _tan to + Specify third source point or მიუთითეთ მესამე საწყისი წერტილი ან <გაგრძელება> + Specify through point მიუთითეთ გავლის წერტილი + Specify top diameter მიუთითეთ ზედა დიამეტრი + Specify top radius or მიუთითეთ ზედა რადიუსი ან + Specify total angle მიუთითეთ სრული კუთხე + Specify total length or მიუთითეთ სრული სიგრძე ან + Specify width for rectangles მიუთითეთ მართკუთხედების სიგანე + Sphere სფერო + Spline სპლაინი + Spline Edit სპლაინის რედაქტირება + Stack (type 1/2 then select) წილადი (აკრიფეთ 1/2 და მონიშნეთ) + Standard სტანდარტული + Start დასაწყისი + Start Width საწყისი სიგანე + Start X საწყისი X + Start Y საწყისი Y + Start angle საწყისი კუთხე + Start, Center, Angle დასაწყისი, ცენტრი, კუთხე + Start, Center, End დასაწყისი, ცენტრი, ბოლო + Start, Center, Length დასაწყისი, ცენტრი, სიგრძე + Start, End, Angle დასაწყისი, ბოლო, კუთხე + Start, End, Direction დასაწყისი, ბოლო, მიმართულება + Start, End, Radius დასაწყისი, ბოლო, რადიუსი + Status სტატუსი + Status Bar სტატუსის ზოლი + Stretch გაწელვა + Style: Standard სტილი: Standard + Subtract გამოკლება + Sweep ტრაექტორიით აგება + Switch Drawing ნახაზის გადართვა + Switch Layout განლაგების გადართვა + Switch between model space in a viewport and paper space გადართვა ხედვის არეში მოდელის სივრცესა და ფურცლის სივრცეს შორის + Symmetric სიმეტრია + Synchronize Attributes ატრიბუტების სინქრონიზაცია + To სადამდე + Toggle PICKADD (off: each pick replaces the selection) PICKADD-ის გადართვა (გამორთული: ყოველი არჩევა ცვლის მონიშნულს) + Toggle PICKADD (on: picks add to the selection) PICKADD-ის გადართვა (ჩართული: არჩეული ემატება მონიშნულს) + TOP ზედა + Table ცხრილი + Table Breaks ცხრილის გაწყვეტა + Table Cell Style ცხრილის უჯრის სტილი + Table Style... ცხრილის სტილი... + Table style ცხრილის სტილი + Table... ცხრილი... + Tan, Tan, Radius მხები, მხები, რადიუსი + Tan, Tan, Tan მხები, მხები, მხები + Tangent მხები + Temporary track point დროებითი მიდევნების წერტილი + Text ტექსტი + Text Editor ტექსტის რედაქტორი + Text Height ტექსტის სიმაღლე + Text Style... ტექსტის სტილი... + Text height ტექსტის სიმაღლე + Text override ტექსტის ჩანაცვლება + Text style ტექსტის სტილი + Thaw All Layers ყველა შრის გალღობა + Thaw Layer შრის გალღობა + There is nothing here yet. აქ ჯერ არაფერია. + Thickness სისქე + Time დრო + To get started, create or open a drawing. დასაწყებად შექმენით ან გახსენით ნახაზი. + Tool Bar ხელსაწყოთა ზოლი + Tool Sets ხელსაწყოთა ნაკრებები + Tools ხელსაწყოები + Torus ტორი + Trace სქელი ხაზი + Track orthogonally only მიდევნება მხოლოდ ორთოგონალურად + Track using all polar angle settings მიდევნება პოლარული კუთხის ყველა პარამეტრით + Transparency გამჭვირვალობა + Trim მოკვეთა + True Color ნამდვილი ფერი + Turn All Layers On ყველა შრის ჩართვა + Turn Off Layer შრის გამორთვა + Turn On Layer შრის ჩართვა + Turn Quick Properties off (QPMODE) სწრაფი თვისებების გამორთვა (QPMODE) + Type ტიპი + Type a command აკრიფეთ ბრძანება + Type text; Enter starts a new paragraph აკრიფეთ ტექსტი; Enter იწყებს ახალ აბზაცს + UCS Icon UCS-ის ხატულა + Undo დაბრუნება + Undo (⌘Z) დაბრუნება (⌘Z) + Ungroup დაჯგუფების მოხსნა + Union გაერთიანება + Unisolate Layer შრის იზოლირების მოხსნა + Units Conversion ერთეულების გარდაქმნა + Units... ერთეულები... + Unlock Layer შრის განბლოკვა + Unlock viewport ხედვის არის განბლოკვა + Unmerge Cells უჯრების შერწყმის გაუქმება + Unsaved Layer State შრეების შეუნახავი მდგომარეობა + Up ზემოთ + Update Data Links მონაცემთა ბმულების განახლება + Update განახლება + Use System Setting სისტემის პარამეტრის გამოყენება + User მომხმარებელი + User Parameters მომხმარებლის პარამეტრები + Username მომხმარებლის სახელი + Volume მოცულობა + VP Color ხედვის არის ფერი + VP Freeze ხედვის არეში გაყინვა + Value მნიშვნელობა + Value: მნიშვნელობა: + Variables ცვლადები + Version ვერსია + Version 2000 ვერსია 2000 + Version 2004 ვერსია 2004 + Version 2007 ვერსია 2007 + Version 2010 ვერსია 2010 + Version 2013 ვერსია 2013 + Version 2018 ვერსია 2018 + Version {version} ვერსია {version} + Vertical ვერტიკალური + VerticalDistance ვერტიკალური მანძილი + View ხედი + ViewCube ViewCube + Viewport ხედვის არე + Viewport Layer Freeze შრის გაყინვა ხედვის არეში + Viewport Properties ხედვის არის თვისებები + Viewport is locked ხედვის არე ჩაკეტილია + Viewport scale ხედვის არის მასშტაბი + Viewport {id} ხედვის არე {id} + Viewports ხედვის არეები + W დ + WCS WCS + White თეთრი + Width factor სიგანის კოეფიციენტი + Window ფანჯარა + Wipeout დამფარავი არე + Workspace Switching სამუშაო სივრცის გადართვა + Write Block ბლოკის ჩაწერა + Xline დამხმარე ხაზი + Yellow ყვითელი + Yes დიახ + Zoom მასშტაბი + Zoom All მასშტაბი: ყველაფერი + Zoom Dynamic მასშტაბი: დინამიკური + Zoom Extents მასშტაბი: საზღვრები + Zoom In გადიდება + Zoom Object მასშტაბი: ობიექტი + Zoom Out დაპატარავება + Zoom Previous მასშტაბი: წინა + Zoom Realtime მასშტაბი: რეალურ დროში + Zoom Window მასშტაბი: ფანჯარა + error შეცდომა + {contributors} · {commits} {contributors} · {commits} + {kind} (constraint {id}) {kind} (შეზღუდვა {id}) + {kind} constraint {name} = {expression} (double-click to edit) {kind} შეზღუდვა {name} = {expression} (ორმაგი დაწკაპება — რედაქტირება) + {name}: {distance} < {angle}° {name}: {distance} < {angle}° + ƒx New User Parameter ƒx ახალი მომხმარებლის პარამეტრი + ΔLOC ΔLOC + −Bin −Bin + −LOC −LOC + ⌘↩ to finish ⌘↩ — დასრულება +@plural {n} commit {n} კომიტი +@plural {n} contributor {n} მონაწილე + Drawing as bytes ნახაზი ბაიტებად + Services სერვისები + Hide CADCraft CADCraft-ის დამალვა + Hide Others სხვების დამალვა + Accessibility ხელმისაწვდომობა + Show System Cursor სისტემური კურსორის ჩვენება + Animation Effects ანიმაციის ეფექტები + Animation effects ანიმაციის ეფექტები + Interface scale ინტერფეისის მასშტაბი + Import... იმპორტი... + Export... ექსპორტი... + Batch Publish... პაკეტური გამოქვეყნება... + Scale List... მასშტაბების სია... + Annotative Object Scale ანოტაციური ობიექტის მასშტაბი + Add Current Scale მიმდინარე მასშტაბის დამატება + Delete Current Scale მიმდინარე მასშტაბის წაშლა + Add/Delete Scales... მასშტაბების დამატება/წაშლა... + Synchronize Multiple-scale Positions მრავალმასშტაბიანი პოზიციების სინქრონიზაცია + Annotative Update ანოტაციურის განახლება + Show Annotative Objects ანოტაციური ობიექტების ჩვენება + Current Scale Only მხოლოდ მიმდინარე მასშტაბი + All Scales ყველა მასშტაბი + Drawing Recovery Manager... ნახაზების აღდგენის მენეჯერი... + Tolerance... დაშვება... + Add Vertex წვეროს დამატება + Remove Vertex წვეროს მოშორება + Convert to Arc რკალად გარდაქმნა + Convert to Line ხაზად გარდაქმნა + Stretch Vertex წვეროს გაწელვა + Edit Array მასივის რედაქტირება + Close Array Editing მასივის რედაქტირების დახურვა + Multiline... მულტიხაზი... + Multiline Style... მულტიხაზის სტილი... + Solid Editing სხეულის რედაქტირება + 3D Mouse... 3D მაუსი... + 3D Mouse 3D მაუსი + Calibrate 3D Mouse 3D მაუსის კალიბრაცია + 3D Mouse Navigation 3D მაუსით ნავიგაცია + 3D mouse input is unavailable on this platform 3D მაუსის შეყვანა ამ პლატფორმაზე მიუწვდომელია + No supported 3D mouse found მხარდაჭერილი 3D მაუსი ვერ მოიძებნა + Release the 3D mouse to calibrate its resting position გაუშვით 3D მაუსი ხელიდან, რომ მისი უძრავი მდგომარეობა დაკალიბრდეს + 3D mouse connected 3D მაუსი დაკავშირებულია + 3D mouse busy, possibly 3DxWare or missing device permissions 3D მაუსი დაკავებულია: შესაძლოა, 3DxWare-ის ან მოწყობილობის ნებართვების არქონის გამო + 3D mouse disconnected 3D მაუსი გათიშულია + 3D mouse input could not be started 3D მაუსის შეყვანა ვერ ჩაირთო + Enable 3D mouse navigation 3D მაუსით ნავიგაციის ჩართვა + Pan sensitivity პანორამის მგრძნობელობა + Zoom sensitivity მასშტაბის მგრძნობელობა + Reverse zoom direction მასშტაბის მიმართულების შებრუნება + Calibrate კალიბრაცია + Move sideways to pan; push/pull or twist to zoom. გვერდზე გაწევით — პანორამა; მიწევით/გამოწევით ან მობრუნებით — მასშტაბი. + Left device button: zoom extents. Right device button: calibrate. მოწყობილობის მარცხენა ღილაკი: მასშტაბი საზღვრებით. მარჯვენა ღილაკი: კალიბრაცია. + More toolbar commands ხელსაწყოთა ზოლის სხვა ბრძანებები + Default save version შენახვის ნაგულისხმევი ვერსია + Automatic save every ავტომატური შენახვა ყოველ + min წთ + Automatic save file location ავტომატური შენახვის ფაილის მდებარეობა + Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. ჯერ ფაილის არმქონე ნახაზები ნაგულისხმევ ვერსიაში ინახება. 0 წუთი ავტომატურ შენახვას გამორთავს. + Time-sensitive right-click: a quick click is Enter, holding opens the menu დროზე დამოკიდებული მარჯვენა დაწკაპება: მოკლე დაწკაპება Enter-ია, დაჭერით გაიხსნება მენიუ + Turned off, a right-click while a command runs always opens the shortcut menu. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება ყოველთვის კონტექსტურ მენიუს ხსნის. + Hatch Pattern დაშტრიხვის ნიმუში + Search for pattern ნიმუშის ძიება + Run Script... სკრიპტის გაშვება... + Query Texts ტექსტების მოთხოვნა + Analyze Shapes ფიგურების ანალიზი + Hatch Pick დაშტრიხვის არჩევა + Hatch and Gradient დაშტრიხვა და გრადიენტი + Color 1 ფერი 1 + Color 2 ფერი 2 + Shape ფიგურა + Curved მრუდი + Spherical სფერული + Hemispherical ნახევარსფერული + Inverted შებრუნებული + Centered ცენტრში + Hatch origin დაშტრიხვის საწყისი წერტილი + Use current origin მიმდინარე საწყისი წერტილის გამოყენება + Specified origin მითითებული საწყისი წერტილი + Click to set new origin დაწკაპეთ ახალი საწყისი წერტილის დასაყენებლად + Default to boundary extents ნაგულისხმევად საზღვრის გაბარიტები + Bottom left ქვედა მარცხენა + Bottom right ქვედა მარჯვენა + Top left ზედა მარცხენა + Top right ზედა მარჯვენა + Boundaries საზღვრები + Add: Pick points დამატება: წერტილების არჩევა + Add: Select objects დამატება: ობიექტების მონიშვნა + Boundaries picked: {n} არჩეული საზღვრები: {n} + Select boundaries to remove მონიშნეთ მოსაშორებელი საზღვრები + Island კუნძული + Associative ასოციაციური + Create separate hatches ცალკეული დაშტრიხვების შექმნა + Island detection კუნძულების აღმოჩენა + Normal ჩვეულებრივი + Outer გარე + Ignore უგულებელყოფა + Origin: {x}, {y} საწყისი წერტილი: {x}, {y} + Sheet Books to PDF... ფურცლების წიგნები PDF-ში... + Not a number or distance: {text} არც რიცხვია და არც მანძილი: {text} + Dynamic Block Data დინამიკური ბლოკის მონაცემები + Custom მორგებული + Dynamic Block Reference დინამიკური ბლოკის ჩასმა + Set Dynamic Property დინამიკური თვისების დაყენება + Dynamic Block Grips დინამიკური ბლოკის სახელურები + Drag Dynamic Grip დინამიკური სახელურის გადათრევა + Save Block ბლოკის შენახვა + Save Block As ბლოკის შენახვა როგორც + Close Block Editor ბლოკის რედაქტორის დახურვა + Unsaved changes შეუნახავი ცვლილებები + Edit Block Definition ბლოკის განსაზღვრების რედაქტირება + Block to create or edit შესაქმნელი ან დასარედაქტირებელი ბლოკი + Open in Block Editor ბლოკის რედაქტორში გახსნა + This drawing ეს ნახაზი + contains authoring elements. Open in Block Editor? შეიცავს ბლოკის აგების ელემენტებს. გაიხსნას ბლოკის რედაქტორში? + New block ახალი ბლოკი + Italic დახრილი + Underline ხაზგასმული + Overline ზედა ხაზი + Justify ორმხრივი სწორება + Text color ტექსტის ფერი + Click the ruler to add a tab stop, right-click to remove one დაწკაპეთ სახაზავზე ტაბულაციის პოზიციის დასამატებლად, მარჯვენა დაწკაპებით — წასაშლელად + Select using two clicks only მონიშვნა მხოლოდ ორი დაწკაპებით + Define each corner of the selection window with a separate click. მონიშვნის ფანჯრის თითოეული კუთხე ცალკე დაწკაპებით განისაზღვრება. + Type an alias name. აკრიფეთ ფსევდონიმის სახელი. + Choose the command the alias starts. აირჩიეთ ბრძანება, რომელსაც ფსევდონიმი გაუშვებს. + {command} is an unknown command. {command} უცნობი ბრძანებაა. + {alias} is already defined; select it and use Edit. {alias} უკვე განსაზღვრულია; მონიშნეთ და გამოიყენეთ „რედაქტირება“. + More than {n} aliases. {n}-ზე მეტი ფსევდონიმი. + Alias file: {file} ფსევდონიმების ფაილი: {file} + No alias file loaded. REINIT replaces these aliases with a file's. ფსევდონიმების ფაილი არ არის ჩატვირთული. REINIT ამ ფსევდონიმებს ფაილიდან წაკითხულით ჩაანაცვლებს. + Alias ფსევდონიმი + Command ბრძანება + overrides built-in ჩაშენებულს ჩაანაცვლებს + built-in ჩაშენებული + Add… დამატება… + Edit… რედაქტირება… + Save alias ფსევდონიმის შენახვა + Discard მოშორება + Customize მორგება + Edit Command Aliases (PGP)... ბრძანებების ფსევდონიმების რედაქტირება (PGP)... + B B + CADCraft CADCraft + X X + Y Y +menu Dimension ზომების დატანა +menu Draw ხაზვა +menu Modify შეცვლა +menu View ხედი + Arrow size ისრის ზომა + Dim scale overall ზომის საერთო მასშტაბი + Precision სიზუსტე + Layouts განლაგებები + Printer/plotter პრინტერი/პლოტერი + Paper size ფურცლის ზომა + Orientation ორიენტაცია + Portrait ვერტიკალური + Landscape ჰორიზონტალური + Plot area ბეჭდვის არე + Fit to paper ფურცელში ჩატევა + Center the plot ნაბეჭდის ცენტრირება + Plot object lineweights ობიექტების ხაზის სისქეების ბეჭდვა + Plot transparency გამჭვირვალობის ბეჭდვა + Apply to Layout განლაგებაზე გამოყენება + Enter name of LISP file to load შეიყვანეთ ჩასატვირთი LISP ფაილის სახელი + Enter geometric characteristic შეიყვანეთ გეომეტრიული მახასიათებელი + Enter block names to extract შეიყვანეთ ამოსაღები ბლოკების სახელები + Limits ზღვრები + Plot offset ბეჭდვის წანაცვლება + X offset (mm) X წანაცვლება (მმ) + Y offset (mm) Y წანაცვლება (მმ) + First corner პირველი კუთხე + Opposite corner საპირისპირო კუთხე + Window < ფანჯარა < diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index a0bf590db..673ed2151 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -45,10 +45,12 @@ pub enum Preference { Hungarian, #[serde(rename = "tr")] Turkish, + #[serde(rename = "ka")] + Georgian, } impl Preference { - pub const ALL: [Self; 17] = [ + pub const ALL: [Self; 18] = [ Self::Auto, Self::English, Self::Greek, @@ -66,6 +68,7 @@ impl Preference { Self::Arabic, Self::Hungarian, Self::Turkish, + Self::Georgian, ]; /// The codes a preference can be given as, for messages ("auto, en or uk"). @@ -96,6 +99,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Georgian => "ka", } } @@ -124,6 +128,15 @@ impl Preference { Self::Arabic => "العربية", Self::Hungarian => "Magyar", Self::Turkish => "Türkçe", + // Georgian letters come from the craft-fonts Georgian face; a build without it shows + // the English name (as Korean does) and keeps the interface in English. + Self::Georgian => { + if crate::theme::can_show("ka") { + "ქართული" + } else { + "Georgian" + } + } } } @@ -154,6 +167,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Georgian => "ka", Self::Auto => locales.iter().find_map(|s| locale_language(s)).unwrap_or("en"), } } @@ -170,7 +184,7 @@ pub struct Language { catalog: OnceLock>, } -pub static LANGUAGES: [Language; 16] = [ +pub static LANGUAGES: [Language; 17] = [ Language { code: "en", name: "English", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() }, // Greek: one for exactly 1; other for zero and all other integer counts. Language { code: "el", name: "Ελληνικά", source: include_str!("el.tsv"), plural: plural_en, plural_forms: 2, catalog: OnceLock::new() }, @@ -211,6 +225,11 @@ pub static LANGUAGES: [Language; 16] = [ Language { code: "hu", name: "Magyar", source: include_str!("hu.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() }, // Turkish keeps a noun singular after a number ("3 commit"), so like Korean it has one form. Language { code: "tr", name: "Türkçe", source: include_str!("tr.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() }, + // Georgian keeps a noun singular after a numeral ("5 კომიტი"), so one form, the Korean rule. + // Its letters come from the craft-fonts `Geor` face (`theme::can_show`). + Language { + code: "ka", name: "ქართული", source: include_str!("ka.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() + }, ]; /// BCP 47 and POSIX locale tags, including `uk-UA`, `uk_UA.UTF-8` and `pt_BR.UTF-8`. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index bbbcded39..052cae5fb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -39,7 +39,7 @@ fn catalog_is_valid_and_preserves_placeholders_and_ellipses() { /// to English for what they don't cover yet; their gaps are reported, not enforced, so adding a /// command doesn't require a row in every language. const REQUIRED: &[&str] = &["uk"]; -const REPORTED: &[&str] = &["pt-BR", "de", "es", "cs", "ru", "fr", "zh", "it", "ko", "sv", "ar", "hu", "tr", "el"]; +const REPORTED: &[&str] = &["pt-BR", "de", "es", "cs", "ru", "fr", "zh", "it", "ko", "sv", "ar", "hu", "tr", "el", "ka"]; fn check(language: &str, what: &str, missing: Vec) { if REQUIRED.contains(&language) { @@ -1172,3 +1172,112 @@ fn default_fonts_cover_all_greek_letters_in_the_catalog() { } }); } + +#[test] +fn georgian_locales_preferences_and_single_count_form() { + for tag in ["ka", "ka-GE", "ka_GE", "ka_GE.UTF-8", "KA-ge", " ka-GE "] { + assert_eq!(locale_language(tag), Some("ka"), "{tag}"); + } + // `kat`/`geo` are the three-letter codes and `kab` is Kabyle; none picks Georgian. + for tag in ["kat", "geo", "kab", "kartuli"] { + assert_eq!(locale_language(tag), None, "{tag}"); + } + assert_eq!(Preference::parse("ka"), Some(Preference::Georgian)); + assert_eq!(Preference::Georgian.code(), "ka"); + assert_eq!(Preference::Georgian.name(), if crate::theme::can_show("ka") { "ქართული" } else { "Georgian" }); + assert_eq!(Preference::Georgian.resolve(&["en-US".into()]), "ka"); + assert_eq!(Preference::Auto.resolve(&["pl-PL".into(), "ka-GE".into(), "en-US".into()]), "ka"); + let saved = serde_json::to_string(&Preference::Georgian).unwrap(); + assert_eq!(saved, "\"ka\""); + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.interface_language = Preference::Georgian; + let mut restored = CadApp::new(Session::new(), Services::default()); + restored.load_prefs(&app.prefs_json()); + assert_eq!(restored.ui.interface_language, Preference::Georgian); + with_language("ka", || { + // A Georgian noun stays singular after a numeral, 1 included. + for n in [0, 1, 2, 5, 21, u64::MAX] { + assert_eq!(count(n, "{n} contributor", "{n} contributors"), format!("{n} მონაწილე")); + assert_eq!(count(n, "{n} commit", "{n} commits"), format!("{n} კომიტი")); + } + assert_eq!(t("Open"), "გახსნა"); + assert_eq!(menu("Dimension"), "ზომების დატანა"); + assert_eq!(t("Dimension"), "ზომა"); + assert_eq!(menu("Draw"), "ხაზვა"); + assert_eq!(menu("File"), "ფაილი"); + }); + assert_eq!(t("Open"), "Open", "language must not leak outside a render scope"); +} + +#[test] +fn georgian_catalog_covers_marked_ui_literals_without_mtavruli() { + assert!(missing_marked_ui_literals("ka").is_empty(), "{:?}", missing_marked_ui_literals("ka")); + assert!(missing_commands_menus_tools_and_snap_labels("ka").is_empty(), "{:?}", missing_commands_menus_tools_and_snap_labels("ka")); + // Mtavruli (U+1C90–U+1CBF) is a display style, not upper-case Georgian: never in the catalog. + let mtavruli: Vec = include_str!("ka.tsv").chars().filter(|c| ('\u{1c90}'..='\u{1cbf}').contains(c)).collect(); + assert!(mtavruli.is_empty(), "{mtavruli:?}"); +} + +#[test] +fn georgian_live_switch_keeps_drawing_and_falls_back_without_font() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.in_window_menu = true; + app.session.state_mut().unwrap().title = "Open".into(); + let ctx = egui::Context::default(); + app.logic(&ctx); + assert!(render(&mut app, &ctx).contains("Properties")); + app.start("line"); + let prompt = crate::control::cmdline_state(&app); + let commands = crate::control::all_commands(&app); + let result = app.run("ui.language", json!({"lang": "ka"})).unwrap(); + let supported = crate::theme::can_show("ka"); + assert_eq!(result["shown"], if supported { "ka" } else { "en" }); + assert_eq!(app.ui.interface_language, Preference::Georgian); + app.logic(&ctx); + assert_eq!(app.fonts_language, Some(app.language())); + let text = render(&mut app, &ctx); + if supported { + for label in ["თვისებები", "ფაილი", "ხედი", "ხაზვა", "ზომების დატანა", "მიუთითეთ პირველი წერტილი"] + { + assert!(text.contains(label), "missing {label}: {text}"); + } + } else { + assert!(text.contains("Properties")); + } + assert_eq!(app.session.state().unwrap().title, "Open"); + assert_eq!(crate::control::cmdline_state(&app), prompt); + assert_eq!(crate::control::all_commands(&app), commands); + app.run("ui.language", json!({"lang": "en"})).unwrap(); + app.logic(&ctx); + assert!(render(&mut app, &ctx).contains("Properties")); +} + +#[test] +fn georgian_dialogs_render_with_stable_ids() { + if !crate::theme::can_show("ka") { + return; // The fallback path is covered above; do not claim glyph rendering here. + } + for (dialog, source) in [ + ("dsettings", "Drafting Settings"), + ("about", "About CADCraft"), + ("commands", "Command Reference"), + ("blocks", "Blocks"), + ("layers", "Layer Properties Manager"), + ("qselect", "Quick Select"), + ("parameters", "Parameters Manager"), + ("language", "Interface Language"), + ("options:preferences", "User Preferences"), + ] { + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.interface_language = Preference::Georgian; + app.ui.dialog = Some(dialog.into()); + let ctx = egui::Context::default(); + app.logic(&ctx); + let text = render(&mut app, &ctx); + assert!(text.contains(tr("ka", source)), "{dialog}: {text}"); + if dialog == "language" { + assert!(text.contains("ქართული"), "{dialog}: {text}"); + } + assert_eq!(app.ui.dialog.as_deref(), Some(dialog)); + } +} diff --git a/crates/ui-egui/src/options/mod.rs b/crates/ui-egui/src/options/mod.rs index d2f805aa6..a3fbd37fc 100644 --- a/crates/ui-egui/src/options/mod.rs +++ b/crates/ui-egui/src/options/mod.rs @@ -10,7 +10,7 @@ //! |---|---| //! | `theme` | `"system"`, `"light"` or `"dark"` | //! | `animations` | `"system"`, `"on"` or `"off"`: dialog and menu fades and smoothed scrolling | -//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"hu"`, `"tr"` or `"el"` | +//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"hu"`, `"tr"`, `"el"` or `"ka"` | //! | `saveFormat` | `"dxf"` or `"dwg"`: the format Save As suggests for new drawings | //! | `saveVersion` | `"2000"` … `"2018"`: the version drawings with no file yet are saved in | //! | `SAVETIME` | minutes between automatic saves, 0–600 (0: off) | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 3dbd01e22..a4ededd9b 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -70,9 +70,10 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | +| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | AI-assisted (Claude), written from the English strings with Georgian technical-drawing vocabulary; native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | -Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian and Turkish. +Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian, Turkish, Greek and Georgian. Czech, Swedish, Hungarian and Brazilian Portuguese cover the reference catalog and every marked UI literal; engine diagnostics and uncatalogued text remain English. AutoCAD for Mac ships 7 non-English languages (zh-Hans, es, fr, ja, de, ko, it); of those, CADCraft now ships German and Korean, @@ -86,6 +87,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Georgian (`ka`) added: 1,383 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the craft-fonts `Geor` face in release and web builds (pin a71c20e3); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; native proofreading pending | | 2026-10-15 | minor | Greek (`el`) catalog: 1,330 rows, context/plural/locale/font tests; review pending | | 2026-10-14 | minor | Swedish completed: 95 rows for strings added since (Hatch and Gradient dialog, Block Editor, REFEDIT, multileader editing, Options selection settings, MTEXT editor, recent files); 1,330 rows, every key of the Ukrainian reference catalog | | 2026-10-18 | minor | Turkish added: 1,330 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; locale/preferences/menu/live-switch/dialog/font tests; no gaps in the marked UI literals; AI-assisted, the running app reviewed by a native speaker | diff --git a/docs/localization.md b/docs/localization.md index d3c6cc4e1..03af02bfb 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,7 +1,7 @@ # Interface languages Choose **Edit → Interface Language** and select **Auto (system language)**, **English**, -**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), or **Ελληνικά** (Greek). +**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), or **ქართული** (Georgian). The interface updates without restarting, including the native macOS menus. The choice is saved with the other interface preferences (`cadcraft.prefs`, beside the theme): eframe storage on the desktop, browser local storage on the web. Installations without a saved @@ -11,7 +11,7 @@ Auto uses the first supported language in the operating system's preferred local browser's `navigator.languages` on the web. BCP 47 and POSIX tags select their primary language: `uk-UA` → `uk`, `de_AT.UTF-8` → `de`, `es-MX` → `es`, `pt_BR.UTF-8` → `pt-BR`, `cs-CZ` and `cs_CZ.UTF-8` → `cs`, `it-IT` and `it_CH.UTF-8` → `it`, `ko-KR` and `ko_KR.UTF-8` → `ko`, -`sv-SE`, `sv-FI` and `sv_SE.UTF-8` → `sv`, `hu-HU` and `hu_HU.UTF-8` → `hu`, `tr-TR` and `tr_TR.UTF-8` → `tr`. Unsupported languages fall back to English. +`sv-SE`, `sv-FI` and `sv_SE.UTF-8` → `sv`, `hu-HU` and `hu_HU.UTF-8` → `hu`, `tr-TR` and `tr_TR.UTF-8` → `tr`, `ka-GE` and `ka_GE.UTF-8` → `ka`. Unsupported languages fall back to English. Set `CADCRAFT_LOCALE=cs-CZ` to override the desktop's locale for a launch. An explicit saved language choice takes precedence over that override. @@ -22,7 +22,7 @@ Automation can select the language through the existing control channel: ``` The `ui.set` method also accepts `{"interfaceLanguage":"cs"}`. Supported values are `auto`, -`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, and `el`; invalid values are rejected without changing the current +`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el`, and `ka`; invalid values are rejected without changing the current selection. Resetting palettes keeps the language choice. ## Translation coverage @@ -115,6 +115,20 @@ original AI-assisted work contributed by @Camthalion77 with language review; it from Autodesk localization files. Independent native proofreading and visual checks remain follow-up work. +## Georgian (`ka`) interface + +Georgian has **1,383 rows**: 1,377 ordinary labels, four contextual menu headings (**ზომების +დატანა** for the Dimension menu, **ზომა** for the object; **ხაზვა** for Draw) and two single-form +count templates, since a Georgian noun stays singular after a numeral ("5 კომიტი"). It covers the +union of the existing catalogs, and no marked UI literal falls back to English. Commands are verbal +nouns (**შენახვა**, **შემობრუნება**); prompts read "მიუთითეთ …" for Specify, "შეიყვანეთ …" for +Enter and "მონიშნეთ …" for Select, and clickable keywords keep the spelling the engine accepts. +Georgian has no letter case, so nothing is capitalised, and Mtavruli (a display style, not upper +case) never appears; a test checks that. The translation is original, AI-assisted work written from +the English strings with Georgian technical-drawing vocabulary (შრე, დაშტრიხვა, მომრგვალება, ფასკა, +წანაცვლება, ობიექტზე მიბმა, ხედვის არე); no other product's localization was consulted. Native +proofreading of the running app is still to do. + ## Adding translations The implementation follows the display-time catalog pattern used by From 93e4ff10c47bbfafe2b807671465c3abc8e74107 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 02:23:44 +0400 Subject: [PATCH 031/531] fonts: draw the Georgian interface with the craft-fonts Georgian face MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bump craft-fonts-ref to a71c20e3, which adds Noto Sans Georgian (`Geor`), and build the web release with craft-fonts (`web-craft-fonts: true`). The interface loads the embedded `Geor` face after the CJK faces in every language (the picker names ქართული), and the web build embeds it too (232 KB). Without it `can_show("ka")` is false: the saved choice is kept, the interface stays English and the language command says why. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- .github/workflows/freebsd.yml | 2 +- .github/workflows/release.yml | 3 +- crates/fonts/build.rs | 10 +++---- crates/fonts/src/craft_fonts.rs | 3 +- crates/ui-egui/src/menus.rs | 12 +++++--- crates/ui-egui/src/theme.rs | 52 +++++++++++++++++++++++++++------ docs/control-protocol.md | 4 +-- docs/localization.md | 7 +++++ 8 files changed, 70 insertions(+), 23 deletions(-) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index e7a607181..b23a86341 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -26,4 +26,4 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: - craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 04206b9c8..12fc211ae 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,8 @@ jobs: with: app-name: cadcraft app-title: CADCraft - craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + web-craft-fonts: true version: ${{ inputs.version }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} diff --git a/crates/fonts/build.rs b/crates/fonts/build.rs index 7eb2a784b..833ba6f63 100644 --- a/crates/fonts/build.rs +++ b/crates/fonts/build.rs @@ -3,9 +3,9 @@ //! empty, `CRAFT_FONTS` is empty and the build is unchanged. It only reads the local checkout //! (no network). A bad checkout is a warning, or an error with `CRAFT_FONTS_REQUIRED=1`. //! -//! On wasm32 it embeds only BIZ UDPGothic Regular and the `Arab` faces (about 5.5 MB), to keep the -//! web build within hosting limits (Cloudflare Pages: 25 MiB per file). The web build has no -//! system fonts, so these are its only fallback for Japanese and Arabic-script text. +//! On wasm32 it embeds only BIZ UDPGothic Regular and the `Arab` and `Geor` faces (about 5.7 MB), +//! to keep the web build within hosting limits (Cloudflare Pages: 25 MiB per file). The web build +//! has no system fonts, so these are its only fallback for Japanese, Arabic-script and Georgian text. use std::fmt::Write as _; use std::path::PathBuf; @@ -50,8 +50,8 @@ fn craft_fonts(dir: &std::path::Path) -> Result { println!("cargo::warning=craft-fonts: not embedding {family} {style} (AGENTS.md: no Adobe fonts)"); continue; } - let arabic = scripts.split(',').any(|s| s.trim() == "Arab"); - let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || arabic; + let web_script = scripts.split(',').any(|s| matches!(s.trim(), "Arab" | "Geor")); + let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || web_script; if wasm && !web_face { continue; } diff --git a/crates/fonts/src/craft_fonts.rs b/crates/fonts/src/craft_fonts.rs index fb290775f..713b6632a 100644 --- a/crates/fonts/src/craft_fonts.rs +++ b/crates/fonts/src/craft_fonts.rs @@ -1,7 +1,7 @@ //! Fonts from the optional craft-fonts build input (). //! //! Built with `CRAFT_FONTS_DIR=`, `build.rs` embeds the fonts listed in its -//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular and the Arabic faces). +//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular and the Arabic and Georgian faces). //! Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`]) //! lists the embedded fonts with the installed ones, under [`CraftFont::stem`]. A text style //! can name one (`BIZ UDPGothic`), and they are fallbacks for characters a text's font lacks. @@ -84,6 +84,7 @@ mod tests { Some("Jpan") => '\u{3042}', Some("Arab") => '\u{0628}', Some("Hang" | "Kore") => '가', + Some("Geor") => 'ა', _ => 'A', }; assert!(face.is_some_and(|x| x.has_glyph(sample)), "{} lacks {sample}", f.family); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d4ac0d3e6..35e381c7a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -137,10 +137,14 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { + "No font covers the Korean interface, so it stays in English. Install a Hangul font (Malgun Gothic or Nanum Gothic), or build with a Hang/Kore craft-fonts face." + } + "ka" => "This build has no Georgian font, so the interface stays in English. Build with craft-fonts (its Geor face) to use Georgian.", + _ => { + "No Chinese font is installed, so the interface stays in English. Install one (Noto Sans CJK, for example) to use Chinese." + } }); } Ok(json!({"interfaceLanguage": preference.code(), "shown": shown})) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 6c8dd83d0..9105423c1 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -307,7 +307,8 @@ pub fn mono() -> FontId { /// language: file, layout and layer names can be Japanese or Chinese whatever the interface /// shows (#513). In a Chinese interface (`language` "zh…") the Chinese font comes first, else a /// Japanese one, so names take their own glyph forms; in an Arabic interface an installed -/// Arabic font follows. A font embedded from craft-fonts comes +/// Arabic font follows. The embedded Georgian face loads in every language, so the language +/// picker can show ქართული. A font embedded from craft-fonts comes /// last, for systems without any (and the web build, which has no system fonts). A Korean /// interface adds a Hangul font only when the CJK font found doesn't cover Hangul /// ([`korean_font`]). @@ -391,7 +392,8 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) { /// shows (#513), with the interface's own face leading. A sans-serif face reads best, and a /// Chinese interface takes the face with its own glyphs ahead of a Japanese one — a Japanese face /// shares most ideographs but lacks the simplified-only ones (图 园 测), which would be tofu. -/// العربية adds its Arabic face after those, egui's bundled faces carrying no Arabic glyphs. +/// The Georgian face follows in every language (egui's bundled faces carry no Georgian glyphs, and +/// the picker names the language ქართული); العربية adds its Arabic face after those. fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str) -> Vec<&'a cadcraft_fonts::CraftFont> { let cjk = |f: &&cadcraft_fonts::CraftFont| f.style == "Regular" && f.scripts.iter().any(|s| matches!(*s, "Jpan" | "Hans" | "Hant")); let mut out: Vec<_> = faces.iter().copied().filter(cjk).collect(); @@ -399,6 +401,7 @@ fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str if language.starts_with("zh") { out.sort_by_key(|f| !f.scripts.contains(&"Hans")); } + out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Geor"))); if language == "ar" { out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Arab"))); } @@ -636,11 +639,13 @@ pub fn shows_hangul(language: &str) -> bool { /// Whether the interface can show `language` without missing-glyph boxes: Chinese needs a font /// with its glyphs (installed, or the CJK face this build embedded from craft-fonts), Korean a -/// font with Hangul, العربية an installed Arabic font or the embedded Arabic face. +/// font with Hangul, العربية an installed Arabic font or the embedded Arabic face, ქართული the +/// embedded Georgian face. pub fn can_show(language: &str) -> bool { match language { "ko" => shows_hangul("ko"), "ar" => arabic_font().is_some() || embedded_script("Arab"), + "ka" => embedded_script("Geor"), l if l.starts_with("zh") => cjk_font().is_some() || embedded_script("Hans") || embedded_script("Hant"), _ => true, } @@ -738,13 +743,16 @@ mod tests { let japanese = face("BIZ UDPGothic", &["Jpan", "Latn"]); let chinese = face("Han Test Face", &["Hans", "Latn"]); let arabic = face("Noto Sans Arabic", &["Arab"]); - let faces = [&japanese, &chinese, &arabic]; + let georgian = face("Noto Sans Georgian", &["Geor"]); + let faces = [&japanese, &chinese, &arabic, &georgian]; // Every interface reads CJK names, so both CJK faces load, the sans-serif face first. - assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face"]); + // The Georgian face loads in every interface too, after them: the picker shows ქართული. + assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // A Chinese interface takes the Han face first: a Japanese face lacks 图 园 测. - assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic", "Noto Sans Georgian"]); // العربية adds the Arabic face, after the CJK ones egui's bundled faces have no glyphs for. - assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ka")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // Another weight is a style of a face, not an interface face of its own. let bold = CraftFont { family: "BIZ UDPGothic", style: "Bold", scripts: &["Jpan"], bytes: &[] }; assert!(super::embedded_ui_faces(&[&bold], "en").is_empty()); @@ -755,13 +763,39 @@ mod tests { /// leaving the installed-font answer the gate had before. #[test] fn embedded_faces_answer_for_their_scripts() { - let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"])]; - assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab")); + let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"]), face("Noto Sans Georgian", &["Geor"])]; + assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab") && super::any_script(&faces, "Geor")); assert!(!super::any_script(&faces, "Hans") && !super::any_script(&faces, "Hant")); // A `Bold`-only face is not the interface's, and a script code is matched whole. let bold = CraftFont { family: "Some Han Bold", style: "Bold", scripts: &["Hans"], bytes: &[] }; assert!(!super::any_script(&[bold], "Hans") && !super::any_script(&faces, "Ara")); assert!(!super::embedded_script("Hans") || super::can_show("zh")); + // ქართული rides on the embedded Georgian face alone. + assert_eq!(super::can_show("ka"), super::embedded_script("Geor")); assert!(super::can_show("en") && super::can_show("uk")); } + + /// With the craft-fonts Georgian face (release and web builds), every Mkhedruli letter and the + /// picker's ქართული render in both families, in a Georgian and in an English interface. + #[test] + fn embedded_georgian_face_covers_the_alphabet_in_every_interface() { + if !super::embedded_script("Geor") { + return; + } + let letters: Vec = ('ა'..='ჰ').chain("ქართული".chars()).collect(); + for language in ["ka", "en"] { + let ctx = egui::Context::default(); + super::install_fonts(&ctx, language); + let mut output = ctx.run_ui(Default::default(), |_| {}); + output.textures_delta.clear(); + ctx.fonts_mut(|view| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let mut font = view.fonts.font(&family); + for c in &letters { + assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + } + } + }); + } + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b1e91a52c..168e34b24 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -182,9 +182,9 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar` and `hu`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the -optional craft-fonts input or the operating system. Without a suitable font, the saved choice is +optional craft-fonts input or the operating system; Georgian needs the craft-fonts Georgian (`Geor`) face. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts `{"interfaceLanguage":"uk"}`; `ui.inspect` reports the saved choice in its UI state. Invalid choices leave the current language unchanged. Menus, command labels and prompt text diff --git a/docs/localization.md b/docs/localization.md index d3c6cc4e1..ec198bd02 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -98,6 +98,13 @@ catalog, the saved `ko` preference is kept but the interface falls back to Engli command reports that a font is needed, and the picker uses the readable label **Korean** wherever Hangul can't be shown. This change does not fix platform IME issues or localize engine output. +The bundled egui fonts have no Georgian letters. Georgian is drawn with the Noto Sans Georgian face +(`Geor`) of the craft-fonts build input, which release builds embed (`craft-fonts-ref` in the +workflows, and `web-craft-fonts` for the web build, whose embedded faces include it). The face loads +in every interface language, so the picker shows **ქართული**. A build without craft-fonts keeps the +saved `ka` choice but shows the interface in English, names the language **Georgian** in the picker, +and the language command reports that a Georgian font is needed. + ## Greek (`el`) interface The Greek translation covers all **1,330** distinct source keys collected from the existing From bf1c514615c5a082044b2582774d6df02005e58c Mon Sep 17 00:00:00 2001 From: MrBeeboh Date: Thu, 22 Oct 2026 20:35:39 -0700 Subject: [PATCH 032/531] LISP: append checks the cell cap before building its result (#1930) --- crates/engine/src/lisp/builtins.rs | 6 +++++- crates/engine/src/lisp/tests.rs | 15 +++++++++++++++ crates/engine/src/lisp/value.rs | 6 ++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lisp/builtins.rs b/crates/engine/src/lisp/builtins.rs index e421686c0..2f11ce19e 100644 --- a/crates/engine/src/lisp/builtins.rs +++ b/crates/engine/src/lisp/builtins.rs @@ -423,7 +423,11 @@ fn list(a: &[Value]) -> R { fn append(a: &[Value]) -> R { let mut items = Vec::new(); for v in a { - items.extend(list_arg(v)?); + let l = list_arg(v)?; + // Check the result's cells before holding them: the same long list given many times + // would otherwise grow far past the cell cap inside this one call (#1930). + super::value::check_new_cells(items.len().saturating_add(l.len()))?; + items.extend(l); } Ok(Value::list(items)) } diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 9104e2525..826f60f99 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -746,3 +746,18 @@ fn a_panic_inside_a_routine_ends_it_with_an_error() { assert!(s.log.iter().any(|l| l.contains("internal error")), "{:?}", s.log); assert_eq!(ok(&mut s, "(+ 1 2)"), "3"); } + +/// #1930: `append` over many references to one long list is refused before it builds the +/// result, not after it has filled memory. +#[test] +fn append_checks_the_cell_cap_before_building_its_result() { + let _heavy = super::value::HEAVY_CELLS.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + s.lisp.limits.cells = 50_000; + let before = super::value::live_cells(); + let e = + eval(&mut s, "(setq l nil) (repeat 10000 (setq l (cons 1 l))) (setq m nil) (repeat 1000 (setq m (cons l m))) (apply 'append m)").unwrap_err(); + assert!(e.contains("too many list cells"), "{e}"); + assert!(super::value::live_cells() < before + 50_000, "no oversized result was built"); + assert_eq!(ok(&mut s, "(setq l nil m nil) (length (append '(1) '(2 3)))"), "3"); +} diff --git a/crates/engine/src/lisp/value.rs b/crates/engine/src/lisp/value.rs index 09da1d27a..72e29bcc9 100644 --- a/crates/engine/src/lisp/value.rs +++ b/crates/engine/src/lisp/value.rs @@ -76,6 +76,12 @@ pub fn check_cells() -> Result<(), LispError> { if live_cells() > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) } } +/// `n` more cons cells would exceed the cap: checked before a built-in allocates a result many +/// times the size of its arguments (`append` over the same long list, #1930). +pub fn check_new_cells(n: usize) -> Result<(), LispError> { + if live_cells().saturating_add(n) > CELL_LIMIT.with(Cell::get) { Err(LispError::quit("out of memory: too many list cells")) } else { Ok(()) } +} + /// Start a slice of a run on this thread: it has made `used` bytes of its `budget`. pub fn set_string_budget(used: u64, budget: u64) { STRING_BYTES.with(|c| c.set((used, budget))); From 77b301439db57a4d4e7b2f80155d4c1b30843dd4 Mon Sep 17 00:00:00 2001 From: MrBeeboh Date: Thu, 22 Oct 2026 20:37:35 -0700 Subject: [PATCH 033/531] LISP: a relative load name is looked up in the support folder, not the working folder (#1927) --- crates/engine/src/lisp/drawing.rs | 18 ++++++++++++++---- crates/engine/src/lisp/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 53c7af868..a02d3f20c 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -1003,8 +1003,18 @@ pub fn load_source(s: &Session, name: &str) -> Option { } let candidates = if std::path::Path::new(name).extension().is_none() { vec![format!("{name}.lsp"), name.to_string()] } else { vec![name.to_string()] }; - // As given (a path, or relative to the working folder), then in the support folder. - let support = - s.lisp_support_dir().map(|d| candidates.iter().map(|c| d.join(c).to_string_lossy().into_owned()).collect::>()).unwrap_or_default(); - candidates.iter().chain(&support).find_map(|c| super::builtins::read_text_file(c)) + // An absolute path is read as given. A relative name is looked up in the support folder only, + // never in the process working folder: that can be the folder of a drawing just opened from a + // file manager, and a `tools.lsp` shipped beside it must not answer a startup file's + // `(load "tools")` (#1927). Without a support folder (the command-line tool, which has no + // startup files) a relative name is read as given. + let dir = match s.lisp_support_dir() { + Some(d) if !std::path::Path::new(name).is_absolute() => d, + _ => return candidates.iter().find_map(|c| super::builtins::read_text_file(c)), + }; + // A relative name stays inside the support folder. + if std::path::Path::new(name).components().any(|c| matches!(c, std::path::Component::ParentDir)) { + return None; + } + candidates.iter().find_map(|c| super::builtins::read_text_file(&dir.join(c).to_string_lossy())) } diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 9104e2525..af8324a7c 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -746,3 +746,30 @@ fn a_panic_inside_a_routine_ends_it_with_an_error() { assert!(s.log.iter().any(|l| l.contains("internal error")), "{:?}", s.log); assert_eq!(ok(&mut s, "(+ 1 2)"), "3"); } + +/// #1927: with a support folder, a relative `load` name is found there, never through the +/// process working folder; an absolute path is still read as given. +#[cfg(unix)] +#[test] +fn relative_load_uses_the_support_folder_not_the_working_folder() { + let base = std::env::temp_dir().join(format!("cadcraft-lisp-loadpath-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (support, other) = (base.join("support"), base.join("other")); + std::fs::create_dir_all(&support).unwrap(); + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(support.join("tools.lsp"), "(setq which \"support\")").unwrap(); + std::fs::write(other.join("tools.lsp"), "(setq which \"other\")").unwrap(); + std::fs::write(other.join("only.lsp"), "(setq only 1)").unwrap(); + // `other/…` as a path relative to the working folder. + let cwd = std::env::current_dir().unwrap(); + let up = "../".repeat(cwd.components().count().saturating_sub(1)); + let rel = |f: &str| format!("{up}{}", other.join(f).to_string_lossy().trim_start_matches('/')); + + let mut s = session(); + s.set_lisp_support_dir(Some(support.clone())); + assert_eq!(ok(&mut s, "(load \"tools\") which"), "\"support\""); + let r = eval(&mut s, &format!("(load \"{}\") only", rel("only.lsp"))); + assert!(!matches!(r.as_deref(), Ok("1")), "not read through the working folder: {r:?}"); + assert_eq!(ok(&mut s, &format!("(load \"{}\") which", other.join("tools.lsp").to_string_lossy())), "\"other\""); + let _ = std::fs::remove_dir_all(&base); +} From 096e20629e348361d8944a00a4935447eab45ec2 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 12:28:32 +0400 Subject: [PATCH 034/531] i18n(ka): apply the native speaker's terminology review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Draw = ხატვა, Bind = მიბმა, Elevation = დონე, zoom In/Out = მოახლოება/დაშორება, Latin ViewCube compass letters, and the other decided terms; credit the review. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- ATTRIBUTION.md | 2 +- ROADMAP.md | 2 +- crates/ui-egui/src/i18n/ka.tsv | 64 ++++++++++++++++---------------- crates/ui-egui/src/i18n/tests.rs | 4 +- docs/localization-parity.md | 4 +- docs/localization.md | 10 ++--- 6 files changed, 43 insertions(+), 43 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3779b71bc..e876c198c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -71,4 +71,4 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker | | `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending | -| `crates/ui-egui/src/i18n/ka.tsv` | @devius with Claude (AI-assisted) | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; no font assets added (the Georgian face comes from craft-fonts) | +| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) | diff --git a/ROADMAP.md b/ROADMAP.md index 93b3a701e..b093a478a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,7 +95,7 @@ Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity. | Indonesian | none | 0% | | Japanese | none | 0% | | Greek | complete current catalog | 1,330 current source keys; independent proofreading pending | -| Georgian | complete current catalog | 1,383 rows; native proofreading pending | +| Georgian | complete current catalog | 1,383 rows; terminology decided by a native speaker | | German | partial | ≈ 100% of the catalog (989 rows) | | Korean | none | 0% | | Vietnamese | none | 0% | diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25512c91f..5a4d7b4bb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -16,7 +16,7 @@ Apply გამოყენება Attach DWG... DWG-ის მიმაგრება... - Bind ჩაშენება + Bind მიბმა Detach მოხსნა Loaded ჩატვირთულია Make it a block of this drawing, keeping its layer names ამ ნახაზის ბლოკად ქცევა, შრეების სახელების შენარჩუნებით @@ -94,12 +94,12 @@ Auto Constrain ავტომატური შეზღუდვა AutoConstrain ავტოშეზღუდვა Axis, End ღერძი, ბოლო - Base საბაზო წერტილი + Base ბაზა Baseline საბაზისო ხაზი Batch Publish პაკეტური გამოქვეყნება Binary assets added დამატებული ბინარული ფაილები Binary assets removed წაშლილი ბინარული ფაილები - Bind... ჩაშენება... + Bind... მიბმა... Blend გადასვლა Block ბლოკი Block Attribute Manager... ბლოკის ატრიბუტების მენეჯერი... @@ -256,8 +256,8 @@ Drafting ხაზვა Drafting Settings ხაზვის პარამეტრები Drafting Settings... ხაზვის პარამეტრები... - Draw ხაზვა - Draw Order ხაზვის რიგი + Draw ხატვა + Draw Order ხატვის რიგი Drawing (DWG) ნახაზი (DWG) Drawing (DXF) ნახაზი (DXF) Drawing Limits ნახაზის ზღვრები @@ -269,12 +269,12 @@ Dynamic Dimensions დინამიკური ზომები Dynamic Input დინამიკური შეყვანა Dynamic Input (F12) დინამიკური შეყვანა (F12) - E ა + E E Edit რედაქტირება Edit Attributes... ატრიბუტების რედაქტირება... Edit Text... ტექსტის რედაქტირება... Edit Table Cell ცხრილის უჯრის რედაქტირება - Elevation ნიშნული + Elevation დონე Ellipse ელიფსი Elliptical Arc ელიფსური რკალი Enable Dynamic Input (F12) დინამიკური შეყვანის ჩართვა (F12) @@ -340,7 +340,7 @@ Export Table ცხრილის ექსპორტი Export to PDF... PDF-ად ექსპორტი... Express Tools Express Tools - Expression ექსპრესია + Expression გამოსახულება Extend გაგრძელება Extension გაგრძელება Extents საზღვრები @@ -358,7 +358,7 @@ First commit პირველი კომიტი Fit Points მისადაგების წერტილები Fix ფიქსაცია - Flatten Objects ობიექტების გაბრტყელება + Flatten Objects ობიექტების სიბრტყეზე დაგეგმილება Format ფორმატი Freehand ხელით ხაზვა Freeze გაყინვა @@ -367,7 +367,7 @@ Freeze/Thaw გაყინვა/გალღობა Freeze/Thaw in all viewports გაყინვა/გალღობა ყველა ხედვის არეში Freeze/Thaw in the current viewport გაყინვა/გალღობა მიმდინარე ხედვის არეში - From ათვლის წერტილიდან + From წერტილიდან From Template... შაბლონიდან... General ზოგადი Geometric Center გეომეტრიული ცენტრი @@ -423,14 +423,14 @@ Collect შეგროვება Collect Multileaders მულტიმიმთითებლების შეგროვება Edit Multileader მულტიმიმთითებლის რედაქტირება - In გადიდება + In მოახლოება In-window Menu Bar მენიუს ზოლი ფანჯარაში Include in new selection set ახალ მონიშნულ ნაკრებში ჩართვა Increment angle კუთხის ბიჯი Index Color ინდექსური ფერი Index color: {index} ინდექსური ფერი: {index} Infer Constraints შეზღუდვების ავტომატური დადგენა - Inquiry ინფორმაცია + Inquiry მოთხოვნა Insert ჩასმა Insert Block ბლოკის ჩასმა Insert Column სვეტის ჩასმა @@ -510,7 +510,7 @@ List Groups ჯგუფების სია List Layer States შრის მდგომარეობების სია List Layouts განლაგებების სია - List System Variables სისტემური ცვლადების სია + List System Variables სისტემის ცვლადების სია List Text Styles ტექსტის სტილების სია Load all ყველას ჩატვირთვა Load... ჩატვირთვა... @@ -525,7 +525,7 @@ MODEL მოდელი MText MText Magenta მეწამული - Major line every მთავარი ხაზის ბიჯი + Major line every ყოველი N-ე ხაზი მთავარია Make Current მიმდინარედ დაყენება Make Object's Layer Current ობიექტის შრის მიმდინარედ დაყენება Make... შექმნა... @@ -556,7 +556,7 @@ Multiple Point რამდენიმე წერტილი My ჩემი My properties: not available yet ჩემი თვისებები: ჯერ ხელმისაწვდომი არ არის - N ჩ + N N Name სახელი Name (A–Z) სახელი (ა–ჰ) Named Views... დასახელებული ხედები... @@ -616,7 +616,7 @@ Ortho Mode ორთო რეჟიმი Ortho Mode (F8) ორთო რეჟიმი (F8) Osnap Settings... ობიექტზე მიბმის პარამეტრები... - Out დაპატარავება + Out დაშორება Over-constrained ზედმეტად შეზღუდული Override გადაფარვა PAPER ფურცელი @@ -646,7 +646,7 @@ Plot Preview ნახვა ამობეჭდვამდე Plot Window ბეჭდვის ფანჯარა Plot style ბეჭდვის სტილი - Plot style attached to მიმაგრებული ბეჭდვის სტილი + Plot style attached to ბეჭდვის სტილი მიმაგრებულია Plot style table ბეჭდვის სტილების ცხრილი Plot Style... ბეჭდვის სტილი... Plot Style Manager ბეჭდვის სტილების მენეჯერი @@ -710,7 +710,7 @@ Purge გაწმენდა Pyramid პირამიდა Quadrant კვადრანტი - Query Entities ობიექტების მოთხოვნა + Query Entities ობიექტების გამოთხოვნა Quick სწრაფი Quick Dimension სწრაფი ზომა Quick Properties სწრაფი თვისებები @@ -726,7 +726,7 @@ Read-only მხოლოდ წასაკითხი Real name ნამდვილი სახელი Realtime რეალურ დროში - Reassociate Dimensions ზომების ხელახლა მიბმა + Reassociate Dimensions ზომების ხელახლა ასოცირება Recent ბოლოდროინდელი Recent Commands ბოლოდროინდელი ბრძანებები Recent Input ბოლოდროინდელი შეყვანა @@ -767,7 +767,7 @@ Right მარჯვნივ Rotate შემობრუნება Rotation შემობრუნება - S ს + S S Save შენახვა Save (⌘S) შენახვა (⌘S) Save As შენახვა როგორც @@ -878,7 +878,7 @@ Single Line Text ერთსტრიქონიანი ტექსტი Single Point ერთი წერტილი Single... ცალკეული... - Smooth გლუვი შეერთება + Smooth დაგლუვება Snap მიბმა Snap Mode მიბმის რეჟიმი Snap Mode (F9) მიბმის რეჟიმი (F9) @@ -969,7 +969,7 @@ Indicate selection area მიუთითეთ მონიშვნის არე Interface language ინტერფეისის ენა Interface theme ინტერფეისის თემა - Keep the system cursor visible over the drawing area სისტემური კურსორი ნახაზის არეზე ხილული დარჩეს + Keep the system cursor visible over the drawing area სისტემის კურსორი ნახაზის არეზე ხილული დარჩეს Largest array ყველაზე დიდი მასივი Layout paper განლაგების ფურცელი Model background მოდელის ფონი @@ -988,7 +988,7 @@ Reset keeps the interface language. ჩამოყრის შემდეგ ინტერფეისის ენა უცვლელი რჩება. Reset to Defaults ნაგულისხმევზე დაბრუნება Save new drawings as ახალი ნახაზების შენახვა როგორც - Screen magnifiers, screen readers and recorders follow the system cursor. ეკრანის გამადიდებლები, ეკრანის წამკითხველები და ჩამწერები სისტემურ კურსორს მიჰყვება. + Screen magnifiers, screen readers and recorders follow the system cursor. ეკრანის გამადიდებლები, ეკრანის წამკითხველები და ჩამწერები სისტემის კურსორს მიჰყვება. Select objects first, then choose a command ჯერ მონიშნეთ ობიექტები, შემდეგ აირჩიეთ ბრძანება Selection მონიშვნა Selection Area Effect მონიშვნის არის ეფექტი @@ -1079,7 +1079,7 @@ Sphere სფერო Spline სპლაინი Spline Edit სპლაინის რედაქტირება - Stack (type 1/2 then select) წილადი (აკრიფეთ 1/2 და მონიშნეთ) + Stack (type 1/2 then select) დასტად დალაგება (აკრიფეთ 1/2 და მონიშნეთ) Standard სტანდარტული Start დასაწყისი Start Width საწყისი სიგანე @@ -1191,12 +1191,12 @@ Viewport scale ხედვის არის მასშტაბი Viewport {id} ხედვის არე {id} Viewports ხედვის არეები - W დ + W W WCS WCS White თეთრი Width factor სიგანის კოეფიციენტი Window ფანჯარა - Wipeout დამფარავი არე + Wipeout მასკირება Workspace Switching სამუშაო სივრცის გადართვა Write Block ბლოკის ჩაწერა Xline დამხმარე ხაზი @@ -1206,9 +1206,9 @@ Zoom All მასშტაბი: ყველაფერი Zoom Dynamic მასშტაბი: დინამიკური Zoom Extents მასშტაბი: საზღვრები - Zoom In გადიდება + Zoom In მოახლოება Zoom Object მასშტაბი: ობიექტი - Zoom Out დაპატარავება + Zoom Out დაშორება Zoom Previous მასშტაბი: წინა Zoom Realtime მასშტაბი: რეალურ დროში Zoom Window მასშტაბი: ფანჯარა @@ -1229,7 +1229,7 @@ Hide CADCraft CADCraft-ის დამალვა Hide Others სხვების დამალვა Accessibility ხელმისაწვდომობა - Show System Cursor სისტემური კურსორის ჩვენება + Show System Cursor სისტემის კურსორის ჩვენება Animation Effects ანიმაციის ეფექტები Animation effects ანიმაციის ეფექტები Interface scale ინტერფეისის მასშტაბი @@ -1242,7 +1242,7 @@ Delete Current Scale მიმდინარე მასშტაბის წაშლა Add/Delete Scales... მასშტაბების დამატება/წაშლა... Synchronize Multiple-scale Positions მრავალმასშტაბიანი პოზიციების სინქრონიზაცია - Annotative Update ანოტაციურის განახლება + Annotative Update ანოტაციური განახლება Show Annotative Objects ანოტაციური ობიექტების ჩვენება Current Scale Only მხოლოდ მიმდინარე მასშტაბი All Scales ყველა მასშტაბი @@ -1287,7 +1287,7 @@ Hatch Pattern დაშტრიხვის ნიმუში Search for pattern ნიმუშის ძიება Run Script... სკრიპტის გაშვება... - Query Texts ტექსტების მოთხოვნა + Query Texts ტექსტების გამოთხოვნა Analyze Shapes ფიგურების ანალიზი Hatch Pick დაშტრიხვის არჩევა Hatch and Gradient დაშტრიხვა და გრადიენტი @@ -1369,7 +1369,7 @@ X X Y Y menu Dimension ზომების დატანა -menu Draw ხაზვა +menu Draw ხატვა menu Modify შეცვლა menu View ხედი Arrow size ისრის ზომა diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 052cae5fb..9455b716b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1203,7 +1203,7 @@ fn georgian_locales_preferences_and_single_count_form() { assert_eq!(t("Open"), "გახსნა"); assert_eq!(menu("Dimension"), "ზომების დატანა"); assert_eq!(t("Dimension"), "ზომა"); - assert_eq!(menu("Draw"), "ხაზვა"); + assert_eq!(menu("Draw"), "ხატვა"); assert_eq!(menu("File"), "ფაილი"); }); assert_eq!(t("Open"), "Open", "language must not leak outside a render scope"); @@ -1237,7 +1237,7 @@ fn georgian_live_switch_keeps_drawing_and_falls_back_without_font() { assert_eq!(app.fonts_language, Some(app.language())); let text = render(&mut app, &ctx); if supported { - for label in ["თვისებები", "ფაილი", "ხედი", "ხაზვა", "ზომების დატანა", "მიუთითეთ პირველი წერტილი"] + for label in ["თვისებები", "ფაილი", "ხედი", "ხატვა", "ზომების დატანა", "მიუთითეთ პირველი წერტილი"] { assert!(text.contains(label), "missing {label}: {text}"); } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index a4ededd9b..0b2ae3745 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -70,7 +70,7 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | -| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | AI-assisted (Claude), written from the English strings with Georgian technical-drawing vocabulary; native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | +| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian, Turkish, Greek and Georgian. @@ -87,7 +87,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| -| 2026-10-23 | minor | Georgian (`ka`) added: 1,383 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the craft-fonts `Geor` face in release and web builds (pin a71c20e3); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; native proofreading pending | +| 2026-10-23 | minor | Georgian (`ka`) added: 1,383 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the craft-fonts `Geor` face in release and web builds (pin a71c20e3); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; terminology decided by a native speaker | | 2026-10-15 | minor | Greek (`el`) catalog: 1,330 rows, context/plural/locale/font tests; review pending | | 2026-10-14 | minor | Swedish completed: 95 rows for strings added since (Hatch and Gradient dialog, Block Editor, REFEDIT, multileader editing, Options selection settings, MTEXT editor, recent files); 1,330 rows, every key of the Ukrainian reference catalog | | 2026-10-18 | minor | Turkish added: 1,330 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; locale/preferences/menu/live-switch/dialog/font tests; no gaps in the marked UI literals; AI-assisted, the running app reviewed by a native speaker | diff --git a/docs/localization.md b/docs/localization.md index 03af02bfb..7ebdea1a7 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -118,16 +118,16 @@ follow-up work. ## Georgian (`ka`) interface Georgian has **1,383 rows**: 1,377 ordinary labels, four contextual menu headings (**ზომების -დატანა** for the Dimension menu, **ზომა** for the object; **ხაზვა** for Draw) and two single-form +დატანა** for the Dimension menu, **ზომა** for the object; **ხატვა** for Draw) and two single-form count templates, since a Georgian noun stays singular after a numeral ("5 კომიტი"). It covers the union of the existing catalogs, and no marked UI literal falls back to English. Commands are verbal nouns (**შენახვა**, **შემობრუნება**); prompts read "მიუთითეთ …" for Specify, "შეიყვანეთ …" for Enter and "მონიშნეთ …" for Select, and clickable keywords keep the spelling the engine accepts. Georgian has no letter case, so nothing is capitalised, and Mtavruli (a display style, not upper -case) never appears; a test checks that. The translation is original, AI-assisted work written from -the English strings with Georgian technical-drawing vocabulary (შრე, დაშტრიხვა, მომრგვალება, ფასკა, -წანაცვლება, ობიექტზე მიბმა, ხედვის არე); no other product's localization was consulted. Native -proofreading of the running app is still to do. +case) never appears; a test checks that. The translation is original: written with Claude Code from +the meaning of each English string, with Georgian technical-drawing vocabulary (შრე, დაშტრიხვა, +მომრგვალება, ფასკა, წანაცვლება, ობიექტზე მიბმა, ხედვის არე); terminology and doubtful strings +were decided by a native Georgian speaker (@devius). No other product's localization was consulted. ## Adding translations From 85df54b88c098b2d9b7b7596b366d11b3af71b5b Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 13:33:34 +0400 Subject: [PATCH 035/531] i18n(ka): apply the second terminology review Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5a4d7b4bb..d30ace406 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -35,7 +35,7 @@ Unload განტვირთვა Unloaded განტვირთულია Unreferenced მიმართვის გარეშე - Unresolved დაუდგენელი + Unresolved გადაუჭრელი Cancel გაუქმება OK OK or [ ან [ @@ -238,7 +238,7 @@ Dimension ზომა Dimension Objects Only მხოლოდ ზომის ობიექტები Dimension Space ზომების დაშორება - Dimension Style Override ზომის სტილის გადაფარვა + Dimension Style Override ზომის სტილის ლოკალური ცვლილება Dimension Style... ზომის სტილი... Dimension Text Edit ზომის ტექსტის რედაქტირება Dimension style ზომის სტილი @@ -413,7 +413,7 @@ Hide Objects ობიექტების დამალვა Hide Palettes პალიტრების დამალვა History ისტორია - Home საწყისი პოზიცია + Home საწყისი ხედი Horizontal ჰორიზონტალური HorizontalDistance ჰორიზონტალური მანძილი How to apply: გამოყენების წესი: @@ -611,7 +611,7 @@ Clear Recent Files ბოლოს გახსნილი ფაილების სიის გასუფთავება Operator: ოპერატორი: Orbit ორბიტა - Ordinate კოორდინატული + Ordinate ორდინატა Ortho (F8) ორთო (F8) Ortho Mode ორთო რეჟიმი Ortho Mode (F8) ორთო რეჟიმი (F8) @@ -668,7 +668,7 @@ Keep an editable copy of this table in the drawing ამ ცხრილის რედაქტირებადი ასლის ნახაზში შენახვა Layout {name}: {table} განლაგება {name}: {table} Grayscale ნაცრისფერი ტონები - Screening ფერის ინტენსივობა + Screening ტონირება Use object linetype ობიექტის ხაზის ტიპის გამოყენება Use object lineweight ობიექტის ხაზის სისქის გამოყენება Remove წაშლა From b5f6df8fece29616cd4e3da46e8e2822f601c93b Mon Sep 17 00:00:00 2001 From: filforce95 <49290121+filforce95@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:31:43 +0200 Subject: [PATCH 036/531] test(pickdrag): the second corner is set where the button goes down With clicks counting on press (#1001), a press after the first corner closes the window there even with PICKDRAG 0; letting go elsewhere after a drag changes nothing. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/pickdrag.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/tests/pickdrag.rs b/crates/ui-egui/tests/pickdrag.rs index fe5ad2f8b..8b9e7a96e 100644 --- a/crates/ui-egui/tests/pickdrag.rs +++ b/crates/ui-egui/tests/pickdrag.rs @@ -83,13 +83,11 @@ fn drag_is_disabled_but_two_clicks_still_complete_the_window() { button(&mut h, a, true); button(&mut h, a, false); assert!(h.state().session.pending_window.is_some()); - // A held-button movement after the first click must not consume the second corner. - drag(&mut h, a, b); - assert!(h.state().session.pending_window.is_some()); - assert!(h.state().session.selection().is_empty()); - h.run_steps(30); // Separate deliberate clicks from egui's double-click interval. - button(&mut h, b, true); - button(&mut h, b, false); + // The second corner is where the button goes down (#1001): a drag on from there, let go + // elsewhere, changes nothing. + h.run_steps(30); // Separate deliberate clicks from the double-click interval. + let away = xf.to_screen(Vec2::new(30.0, 8.0)); + drag(&mut h, b, away); assert!(h.state().session.pending_window.is_none()); assert_eq!(h.state().session.selection().len(), 1); } From 2830c7c17621d6ea9e22468f6126aae6f1404f00 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Fri, 23 Oct 2026 11:41:26 -0600 Subject: [PATCH 037/531] Merge upstream/main into feat/mleader-text The multileader text test moves into tests/it (one test binary per crate, #1989). Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/{ => it}/mleader_text_edit.rs | 0 2 files changed, 1 insertion(+) rename crates/engine/tests/{ => it}/mleader_text_edit.rs (100%) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b6e088a13..fb51cf645 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -67,6 +67,7 @@ mod measure_distance_snapping; mod metric_linetypes; mod mleader_content; mod mleader_remember; +mod mleader_text_edit; mod mline; mod mocoro; mod modify_curves; diff --git a/crates/engine/tests/mleader_text_edit.rs b/crates/engine/tests/it/mleader_text_edit.rs similarity index 100% rename from crates/engine/tests/mleader_text_edit.rs rename to crates/engine/tests/it/mleader_text_edit.rs From d75e2a0ae02dd01dfdc7f1ae4cb520c31e2612e6 Mon Sep 17 00:00:00 2001 From: filforce95 <49290121+filforce95@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:50:50 +0200 Subject: [PATCH 038/531] test: press_first_clicks joins the ui-egui test binary (#1989) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/{ => it}/press_first_clicks.rs | 0 2 files changed, 1 insertion(+) rename crates/ui-egui/tests/{ => it}/press_first_clicks.rs (100%) diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 2e2451579..b0e3e4932 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -19,6 +19,7 @@ mod mspace_viewport_view; mod options_dialog; mod parameters_rename; mod pickdrag; +mod press_first_clicks; mod properties_units; mod rapid_clicks; mod selection_cycling; diff --git a/crates/ui-egui/tests/press_first_clicks.rs b/crates/ui-egui/tests/it/press_first_clicks.rs similarity index 100% rename from crates/ui-egui/tests/press_first_clicks.rs rename to crates/ui-egui/tests/it/press_first_clicks.rs From a5391d6ebb6a7e9319dd8f0e0ebb13be722b6aa9 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 24 Oct 2026 00:12:13 +0400 Subject: [PATCH 039/531] fonts: load the embedded Georgian face where can_show accepts it; parity status line The same embedded_ui_faces lines as #1971, so a build whose craft-fonts has the Geor face draws Georgian instead of boxes whichever PR lands first (CodeRabbit). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/theme.rs | 7 +++++-- docs/localization-parity.md | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 7f93d43c2..47aaa3c67 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -307,7 +307,8 @@ pub fn mono() -> FontId { /// language: file, layout and layer names can be Japanese or Chinese whatever the interface /// shows (#513). In a Chinese interface (`language` "zh…") the Chinese font comes first, else a /// Japanese one, so names take their own glyph forms; in an Arabic interface an installed -/// Arabic font follows. A font embedded from craft-fonts comes +/// Arabic font follows. The embedded Georgian face loads in every language, so the language +/// picker can show ქართული. A font embedded from craft-fonts comes /// last, for systems without any (and the web build, which has no system fonts). A Korean /// interface adds a Hangul font only when the CJK font found doesn't cover Hangul /// ([`korean_font`]). @@ -391,7 +392,8 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) { /// shows (#513), with the interface's own face leading. A sans-serif face reads best, and a /// Chinese interface takes the face with its own glyphs ahead of a Japanese one — a Japanese face /// shares most ideographs but lacks the simplified-only ones (图 园 测), which would be tofu. -/// العربية adds its Arabic face after those, egui's bundled faces carrying no Arabic glyphs. +/// The Georgian face follows in every language (egui's bundled faces carry no Georgian glyphs, and +/// the picker names the language ქართული); العربية adds its Arabic face after those. fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str) -> Vec<&'a cadcraft_fonts::CraftFont> { let cjk = |f: &&cadcraft_fonts::CraftFont| f.style == "Regular" && f.scripts.iter().any(|s| matches!(*s, "Jpan" | "Hans" | "Hant")); let mut out: Vec<_> = faces.iter().copied().filter(cjk).collect(); @@ -399,6 +401,7 @@ fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str if language.starts_with("zh") { out.sort_by_key(|f| !f.scripts.contains(&"Hans")); } + out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Geor"))); if language == "ar" { out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Arab"))); } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 0b2ae3745..d34add571 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (Swedish catalog completed with the 95 strings added since; previously: Swedish catalog added: complete catalog, menu headings, native-speaker terminology review; previously: complete current Korean catalog with Hangul font coverage) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (Georgian catalog added: complete catalog, menu headings, single count form; previously: Swedish catalog completed with the 95 strings added since; previously: Swedish catalog added: complete catalog, menu headings, native-speaker terminology review; previously: complete current Korean catalog with Hangul font coverage) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How far CADCraft's interface and drawing text are from AutoCAD's languages. Summarised in [ROADMAP.md](../ROADMAP.md#languages); work items in [gaps.md](gaps.md#localization). From f84e458ccfe8e5f677f5d683fd4b6f1086a60469 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:18:29 -0300 Subject: [PATCH 040/531] Keep a landscape media's size order and rotation when saving DXF/DWG Page setups keep a portrait size and a landscape flag, so a layout read with 44 = 420, 45 = 297, 73 = 0 and the media ISO_full_bleed_A3_(420.00_x_297.00_MM) was written back as 297 x 420 with rotation 1. ZWCAD takes the media's size from its name and turns it a quarter on top, so the sheet plotted as a shrunk portrait page (#1463). When the media's name gives it wider than tall, write 44/45 in that order and the rotation relative to it. Other media are written as before. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/dxf_write.rs | 34 ++++++++++++++++++++++--- crates/io/src/tests.rs | 52 ++++++++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 1 + 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 34bee75b2..539f8b6ee 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -2559,13 +2559,14 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.s(2, if device.is_empty() || device.eq_ignore_ascii_case("None") { "none_device" } else { device }); w.s(4, page.paper.replace(' ', "_")); w.s(6, ""); + let (paper_w, paper_h, rotation) = plot_paper(page); for (c, v) in [ (40, page.margins_mm[0]), (41, page.margins_mm[1]), (42, page.margins_mm[2]), (43, page.margins_mm[3]), - (44, page.width_mm), - (45, page.height_mm), + (44, paper_w), + (45, paper_h), (46, 0.0), (47, 0.0), (48, page.plot_window[0]), @@ -2580,7 +2581,7 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.i(70, plot_flags); // Plot paper units: 1 millimetres, 0 inches (#1058). w.i(72, i64::from(cadcraft_render::paper::page_unit_mm(d, page) == 1.0)); - w.i(73, i64::from(page.landscape)); + w.i(73, rotation); w.i(74, plot_type); w.s(7, &page.plot_style_table); w.i(75, if page.scale_to_fit { 0 } else { 16 }); @@ -2639,6 +2640,33 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { /// Write DXF Reference group 91 on every CLASS record. Count records after `dxf_raw::finish` /// restores foreign classes and objects so every class gets its actual instance count. +/// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups +/// keep a portrait size and a landscape flag. A media whose name makes it wider than tall, such +/// as `ISO_full_bleed_A3_(420.00_x_297.00_MM)`, gets its size in that order and the rotation +/// relative to it, so readers that take the media's size from its name agree with groups 44 and +/// 45 (#1463). Other media are written as before. +fn plot_paper(page: &PageSetup) -> (f64, f64, i64) { + if media_is_landscape(&page.paper) { + let (short, long) = (page.width_mm.min(page.height_mm), page.width_mm.max(page.height_mm)); + (long, short, i64::from(!page.landscape)) + } else { + (page.width_mm, page.height_mm, i64::from(page.landscape)) + } +} + +/// Whether a media name ends in a size wider than tall, like `… (420.00 x 297.00 MM)`. +fn media_is_landscape(paper: &str) -> bool { + let name = paper.replace('_', " "); + let Some(open) = name.rfind('(') else { return false }; + let mut sides = name[open + 1..].splitn(2, ['x', 'X', '×']); + let num = |s: Option<&str>| { + let s = s?.trim_start(); + let end = s.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(s.len()); + s[..end].parse::().ok() + }; + matches!((num(sides.next()), num(sides.next())), (Some(w), Some(h)) if w > h) +} + fn add_class_instance_counts(tags: &mut Vec) { let mut counts: HashMap = HashMap::new(); for t in tags.iter().filter(|t| t.code == 0) { diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 2c741b803..cae9cc749 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -560,6 +560,58 @@ fn dxf_roundtrips_page_setup() { assert_eq!(p.paper, a3.name); } +/// Groups 44, 45 and 73 of a layout's AcDbPlotSettings in DXF text. +fn plot_paper_groups(dxf: &str, layout: &str) -> (f64, f64, i64) { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let pairs: Vec<(&str, &str)> = lines.chunks(2).filter(|c| c.len() == 2).map(|c| (c[0], c[1])).collect(); + let name = pairs.windows(2).position(|w| w[0] == ("100", "AcDbLayout") && w[1] == ("1", layout)).unwrap_or_else(|| panic!("no LAYOUT {layout}")); + let start = pairs[..name].iter().rposition(|p| *p == ("100", "AcDbPlotSettings")).unwrap(); + let get = |code: &str| pairs[start..name].iter().find(|p| p.0 == code).map(|p| p.1).unwrap(); + (get("44").parse().unwrap(), get("45").parse().unwrap(), get("73").parse().unwrap()) +} + +#[test] +fn landscape_media_keeps_its_size_order_and_rotation() { + // A media defined wider than tall, as ZWCAD and AutoCAD name it (#1463). + let media = "ISO full bleed A3 (420.00 x 297.00 MM)"; + for (landscape, rotation) in [(true, 0), (false, 1)] { + let mut d = sample(); + { + let p = &mut d.layouts[0].page; + p.paper = media.into(); + p.width_mm = 297.0; + p.height_mm = 420.0; + p.landscape = landscape; + } + let dxf = write_dxf(&d); + assert_eq!(plot_paper_groups(&dxf, "Layout1"), (420.0, 297.0, rotation), "DXF, landscape {landscape}"); + let r = read_dxf(dxf.as_bytes()).unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (297.0, 420.0, landscape), "DXF read back"); + assert_eq!(p.paper, media); + + let dwg = write(&d, "t.dwg").unwrap(); + let back = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned(); + assert_eq!(plot_paper_groups(&back, "Layout1"), (420.0, 297.0, rotation), "DWG, landscape {landscape}"); + let r = read(&dwg, "t.dwg").unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (297.0, 420.0, landscape), "DWG read back"); + } +} + +#[test] +fn portrait_media_is_written_as_before() { + let mut d = sample(); + { + let p = &mut d.layouts[0].page; + p.paper = "ISO A3 (297.00 x 420.00 MM)".into(); + p.width_mm = 297.0; + p.height_mm = 420.0; + p.landscape = true; + } + assert_eq!(plot_paper_groups(&write_dxf(&d), "Layout1"), (297.0, 420.0, 1)); +} + // --------------------------------------------------------------------------------------------- // Round trips of styles, overrides, associativity, constraints and tables. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c598193d7..6c92c30a7 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -138,6 +138,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | DXF/DWG save: a layout whose media is named wider than tall (`ISO_full_bleed_A3_(420.00_x_297.00_MM)`) keeps its paper size in that order (44 = 420, 45 = 297) and its plot rotation relative to the media, instead of a portrait size with rotation 1 that ZWCAD plotted as a shrunk portrait page (#1463); other media are written as before | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | | 2026-10-12 | minor | PDF output: object transparency plotted as PDF alpha (`/ExtGState` `/ca` `/CA`) when the page setup's or the plot's "Plot transparency" is on; PNG plots blend it, SVG uses `opacity`; plots without it are unchanged byte for byte | | 2026-10-12 | minor | DXF/DWG save: the Model layout's plot settings are written as CADCraft plots model space, drawing extents scaled to fit (PLOTSETTINGS 74 = 1, 75 = 0), instead of plot type 5 "Layout information", which other programs' Plot dialogs can't use for model space | From 241aad2425938a4311733dc4b9087ed0c44cd286 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:35:10 -0300 Subject: [PATCH 041/531] docs: file-format parity status line for the page setup change Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/file-format-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6c92c30a7..9d4553ecb 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (DWG read leaves out orphaned DGN line style components) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (DXF/DWG save keeps a landscape media's paper size order and plot rotation) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds From 6a5e8eda3576a2eac375b190fd4fc8d75b5abbbb Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 24 Oct 2026 13:16:07 +0400 Subject: [PATCH 042/531] fonts: test the Georgian face in the face order and its glyphs in a ka and an en interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Same tests as #1971: embedded_ui_faces yields the Geor face for ka (and for every interface, which names the language ქართული in the picker), can_show("ka") follows the embedded face, and with a craft-fonts that carries Geor every Mkhedruli letter renders in both families. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/theme.rs | 41 +++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 47aaa3c67..9105423c1 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -743,13 +743,16 @@ mod tests { let japanese = face("BIZ UDPGothic", &["Jpan", "Latn"]); let chinese = face("Han Test Face", &["Hans", "Latn"]); let arabic = face("Noto Sans Arabic", &["Arab"]); - let faces = [&japanese, &chinese, &arabic]; + let georgian = face("Noto Sans Georgian", &["Geor"]); + let faces = [&japanese, &chinese, &arabic, &georgian]; // Every interface reads CJK names, so both CJK faces load, the sans-serif face first. - assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face"]); + // The Georgian face loads in every interface too, after them: the picker shows ქართული. + assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // A Chinese interface takes the Han face first: a Japanese face lacks 图 园 测. - assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic", "Noto Sans Georgian"]); // العربية adds the Arabic face, after the CJK ones egui's bundled faces have no glyphs for. - assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ka")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // Another weight is a style of a face, not an interface face of its own. let bold = CraftFont { family: "BIZ UDPGothic", style: "Bold", scripts: &["Jpan"], bytes: &[] }; assert!(super::embedded_ui_faces(&[&bold], "en").is_empty()); @@ -760,13 +763,39 @@ mod tests { /// leaving the installed-font answer the gate had before. #[test] fn embedded_faces_answer_for_their_scripts() { - let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"])]; - assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab")); + let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"]), face("Noto Sans Georgian", &["Geor"])]; + assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab") && super::any_script(&faces, "Geor")); assert!(!super::any_script(&faces, "Hans") && !super::any_script(&faces, "Hant")); // A `Bold`-only face is not the interface's, and a script code is matched whole. let bold = CraftFont { family: "Some Han Bold", style: "Bold", scripts: &["Hans"], bytes: &[] }; assert!(!super::any_script(&[bold], "Hans") && !super::any_script(&faces, "Ara")); assert!(!super::embedded_script("Hans") || super::can_show("zh")); + // ქართული rides on the embedded Georgian face alone. + assert_eq!(super::can_show("ka"), super::embedded_script("Geor")); assert!(super::can_show("en") && super::can_show("uk")); } + + /// With the craft-fonts Georgian face (release and web builds), every Mkhedruli letter and the + /// picker's ქართული render in both families, in a Georgian and in an English interface. + #[test] + fn embedded_georgian_face_covers_the_alphabet_in_every_interface() { + if !super::embedded_script("Geor") { + return; + } + let letters: Vec = ('ა'..='ჰ').chain("ქართული".chars()).collect(); + for language in ["ka", "en"] { + let ctx = egui::Context::default(); + super::install_fonts(&ctx, language); + let mut output = ctx.run_ui(Default::default(), |_| {}); + output.textures_delta.clear(); + ctx.fonts_mut(|view| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let mut font = view.fonts.font(&family); + for c in &letters { + assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + } + } + }); + } + } } From 2409afe7f00de47def4c3ce7bc7a05e52553a8c0 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 24 Oct 2026 14:15:14 +0400 Subject: [PATCH 043/531] i18n(ka): translate the six strings main added (Analyze Usage, Implied Loops, units of new drawings) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d30ace406..3db7c923a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -988,6 +988,10 @@ Reset keeps the interface language. ჩამოყრის შემდეგ ინტერფეისის ენა უცვლელი რჩება. Reset to Defaults ნაგულისხმევზე დაბრუნება Save new drawings as ახალი ნახაზების შენახვა როგორც + Units of new drawings ახალი ნახაზების ერთეულები + Imperial (inches) იმპერიული (დუიმები) + Metric (millimetres) მეტრული (მილიმეტრები) + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). ახალი ნახაზი და გაშვებისას გახსნილი პირველი ნახაზი ამ ერთეულებს იყენებს, თუ ნაგულისხმევი შაბლონი არ არის მითითებული (QNEWTEMPLATE). Screen magnifiers, screen readers and recorders follow the system cursor. ეკრანის გამადიდებლები, ეკრანის წამკითხველები და ჩამწერები სისტემის კურსორს მიჰყვება. Select objects first, then choose a command ჯერ მონიშნეთ ობიექტები, შემდეგ აირჩიეთ ბრძანება Selection მონიშვნა @@ -1289,6 +1293,8 @@ Run Script... სკრიპტის გაშვება... Query Texts ტექსტების გამოთხოვნა Analyze Shapes ფიგურების ანალიზი + Analyze Usage გამოყენების ანალიზი + Implied Loops არაცხადი შეკრული კონტურები Hatch Pick დაშტრიხვის არჩევა Hatch and Gradient დაშტრიხვა და გრადიენტი Color 1 ფერი 1 From b52d5fbdff20771f3ac5ec2560464a8bde23fa26 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:09:52 -0300 Subject: [PATCH 044/531] io: put the CLASS group 91 doc comment back on its function plot_paper had been inserted between add_class_instance_counts and its doc comment (review on #2028). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/dxf_write.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 43cca500d..0e4a6e916 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -2694,8 +2694,6 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.t } -/// Write DXF Reference group 91 on every CLASS record. Count records after `dxf_raw::finish` -/// restores foreign classes and objects so every class gets its actual instance count. /// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups /// keep a portrait size and a landscape flag. A media whose name makes it wider than tall, such /// as `ISO_full_bleed_A3_(420.00_x_297.00_MM)`, gets its size in that order and the rotation @@ -2723,6 +2721,8 @@ fn media_is_landscape(paper: &str) -> bool { matches!((num(sides.next()), num(sides.next())), (Some(w), Some(h)) if w > h) } +/// Write DXF Reference group 91 on every CLASS record. Count records after `dxf_raw::finish` +/// restores foreign classes and objects so every class gets its actual instance count. fn add_class_instance_counts(tags: &mut Vec) { let mut counts: HashMap = HashMap::new(); for t in tags.iter().filter(|t| t.code == 0) { From 61483802a1b39533b91a5af958d478eb25d88c2e Mon Sep 17 00:00:00 2001 From: ZachAR3 Date: Sun, 25 Oct 2026 00:19:11 +0200 Subject: [PATCH 045/531] TRIM and EXTEND: a pick in empty space starts a fence in Quick mode (fixes #1594) In Quick mode AutoCAD reads two picks in empty space as a crossing fence: everything the fence crosses is trimmed or extended, without choosing the Fence option first. CADCraft opened a crossing window there. A pick in empty space now starts that two-point fence in Quick mode; the next point applies it and the command asks for the next object again. Standard mode keeps the crossing window. --- crates/engine/src/cmd/trimextend.rs | 19 ++++++++++++++++-- crates/engine/tests/it/trim_extend_options.rs | 20 +++++++++++++++++-- docs/geometry-parity.md | 5 +++-- 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 4640c58ac..110e0c90f 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -220,6 +220,8 @@ enum Stage { Edges(Vec), /// Fence points so far. Fence(Vec), + /// Quick mode's two-point fence, started by a pick in empty space: its first point. + QuickFence(Vec2), /// A crossing window: its first corner once picked. Crossing(Option), Mode, @@ -356,6 +358,7 @@ impl Interactive for TrimM { None => Prompt::new("Specify first fence point", Accept::POINT), Some(l) => Prompt::new("Specify next fence point", Accept::POINT).kw(&["Undo"]).base(*l), }, + Stage::QuickFence(a) => Prompt::new("Specify next fence point", Accept::POINT).base(*a), Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT), Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT), Stage::Mode => { @@ -455,6 +458,16 @@ impl Interactive for TrimM { } Ok(Step::Continue) } + Stage::QuickFence(a) => { + self.stage = Stage::Pick; + if let Input::Point(b) = i { + let r = self.step(s, |m, s| fence(s, &[a, b], extending, m.edges(quick, implied), quick).map(|_| ())); + if let Err(e) = r { + s.echo(e.to_string()); + } + } + Ok(Step::Continue) + } Stage::Crossing(first) => { match (first, i) { (None, Input::Point(p)) => self.stage = Stage::Crossing(Some(p)), @@ -475,8 +488,9 @@ impl Interactive for TrimM { let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; let space = s.space(); let Some(h) = crate::select::pick(s.doc()?, &space, p, ap) else { - // A pick in empty space opens a crossing window there. - self.stage = Stage::Crossing(Some(p)); + // A pick in empty space starts a two-point fence in Quick mode (as in + // AutoCAD, #1594) and a crossing window in Standard mode. + self.stage = if quick { Stage::QuickFence(p) } else { Stage::Crossing(Some(p)) }; return Ok(Step::Continue); }; let r = self.step(s, |m, s| apply(s, h, p, extending, m.edges(quick, implied), quick).map(|_| ())); @@ -525,6 +539,7 @@ impl Interactive for TrimM { .windows(2) .filter_map(|w| Some(line(*w.first()?, *w.get(1)?))) .collect(), + Stage::QuickFence(a) => vec![line(*a, c)], Stage::Crossing(Some(a)) => vec![lwpoly(rect_vertices(*a, c), true)], _ => Vec::new(), } diff --git a/crates/engine/tests/it/trim_extend_options.rs b/crates/engine/tests/it/trim_extend_options.rs index 5302a68c9..0f4d50f15 100644 --- a/crates/engine/tests/it/trim_extend_options.rs +++ b/crates/engine/tests/it/trim_extend_options.rs @@ -112,10 +112,26 @@ fn crossing_window_trims_what_it_touches() { s.script("TRIM C 4,-1 6,1\n\n").unwrap(); assert!(s.running.is_none(), "{}", s.prompt_text()); assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))])); - // A pick in empty space opens a crossing window too. +} + +#[test] +fn a_pick_in_empty_space_starts_a_fence_in_quick_mode_and_a_window_in_standard_mode() { + // #1594: Quick mode's two-point fence trims what it crosses and returns to the first prompt. + for cmd in ["TRIM", "EXTEND"] { + let mut s = ladder(); + s.cmdline(cmd).unwrap(); + s.cmdline("4,-4").unwrap(); + assert!(s.prompt_text().contains("Specify next fence point"), "{cmd}: {}", s.prompt_text()); + } let mut s = ladder(); - s.script("TRIM 4,-4 6,1\n\n").unwrap(); + s.script("TRIM 4,-4 6,1\n").unwrap(); + assert!(s.prompt_text().contains("Select object to trim"), "{}", s.prompt_text()); + s.cmdline("").unwrap(); assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))])); + // Standard mode keeps the crossing window. + let mut s = ladder(); + s.script("TRIM O S\n\n4,-4\n").unwrap(); + assert!(s.prompt_text().contains("Specify opposite corner"), "{}", s.prompt_text()); } #[test] diff --git a/docs/geometry-parity.md b/docs/geometry-parity.md index 74dfc1585..3dc60ccd6 100644 --- a/docs/geometry-parity.md +++ b/docs/geometry-parity.md @@ -1,6 +1,6 @@ # Geometry parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (bounded constraint expression and parameter depth) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (TRIM/EXTEND Quick mode two-point fence) · **Target:** Autodesk AutoCAD 2027 CAD users trust numbers: a trimmed endpoint, an offset, an intersection or an area is either right to the last displayed digit or the tool is unusable for production drawings. This document @@ -80,7 +80,7 @@ constraints 10%. | Command | AutoCAD supports | CADCraft supports | |---|---|---| -| TRIM | every curve type, quick and standard modes | line, arc, circle, polyline; ellipse and spline via sampled cutting (`modify.rs:485-656`, `modify2.rs` `trim_other`); a closed spline leaves one open spline On a closed polyline a pick before the first or after the last cut keeps the run between the cuts and nothing more (#726). | +| TRIM | every curve type, quick and standard modes | line, arc, circle, polyline; ellipse and spline via sampled cutting (`modify.rs:485-656`, `modify2.rs` `trim_other`); a closed spline leaves one open spline On a closed polyline a pick before the first or after the last cut keeps the run between the cuts and nothing more (#726). In Quick mode TRIM and EXTEND start a two-point fence from a pick in empty space, Standard mode a crossing window (#1594). | | EXTEND | every open curve | line, arc, polyline, elliptical arc, open spline (runs on along its end tangent, `modify2/curve_edits.rs`) | | FILLET | lines, arcs, circles, polylines, ellipses, splines, xlines, rays; Trim/No trim | lines, arcs, circles (TTR circle), polyline mode, Trim/No trim, Multiple; elliptical arcs and splines with any of these (tangent circle from sampled offsets refined by Newton's method, `geom/src/fillet.rs`; arcs trimmed or extended round the ellipse, splines split at the touch point); two straight segments of one polyline (adjacent, or with one between that the corner replaces), a polyline's straight end segment with a line (the line joins it); not polyline arc segments, xlines or rays | | CHAMFER | lines, polylines, xlines, rays | lines, Distance/Angle, whole polylines (Polyline option), polyline segments as for FILLET (`modify2/fillet_pline.rs`); refuses arcs, ellipses and splines with a message, as AutoCAD; not xlines or rays | @@ -157,6 +157,7 @@ Total ≈ 90–140 h; items 1–6 parallelise across two or three agents. | Date | Change | Summary | |---|---|---| +| 2026-10-25 | minor | TRIM and EXTEND in Quick mode: a pick in empty space starts a two-point fence, as in AutoCAD; Standard mode keeps the crossing window (#1594) | | 2026-10-22 | minor | Constraint expressions count operator chains toward the syntax-tree depth limit; evaluation shares one depth limit across operators and parameter references, with a 1 MiB-stack regression (#1936) | | 2026-10-14 | trivial | JOIN Close: a single arc becomes its circle, a single elliptical arc its full ellipse (#1175) | | 2026-10-12 | trivial | TRIM on a closed polyline keeps only the complementary run when the pick lies past the last cut (#726) | From 84ba9a8040f239c5fb540d70c8ff2d853f974f91 Mon Sep 17 00:00:00 2001 From: assamaraleman <217119886+assamaraleman@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:19:43 -0300 Subject: [PATCH 046/531] DXF read: number viewports in file order when every id is unknown (#1463) ZWCAD writes every paper-space VIEWPORT with id (69) -1. The reader cast it to u32, so no viewport was the sheet (id 1); on save paper_views() added a second sheet viewport ahead of the real one, which DWG readers then numbered 2: a model viewport showing the whole sheet, inflating the layout's extents. A non-positive 69 now reads as 0, and a layout whose viewports all have id 0 gets them numbered in file order, the first being the sheet. A layout mixing known ids with -1 is left as before (pinned by a test). Co-Authored-By: Claude Fable 5.1 --- crates/io/src/dxf_read.rs | 17 +++++++++++++- crates/io/src/tests.rs | 48 ++++++++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 3 ++- 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 5860b1e03..65deabde3 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -492,7 +492,8 @@ fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_left: &mut usi height: t.fd(41, 1.0), view_center: Vec2::new(t.fd(12, 0.0), t.fd(22, 0.0)), view_height: t.fd(45, 1.0), - id: t.i(69).unwrap_or(0) as u32, + // ZWCAD writes -1 (unknown): 0 here, numbered in order below. + id: t.i(69).filter(|i| *i > 0).unwrap_or(0) as u32, locked: t.i(90).unwrap_or(0) & 16384 != 0, frozen_layers: crate::dxf_ext::read_frozen(tags), layer_colors: crate::dxf_ext::read_layer_colors(tags), @@ -1866,6 +1867,20 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { d.model.push(e); } } + // A layout whose viewports all lack an id (ZWCAD writes 69 = -1) gets them numbered in file + // order, as DWG readers do: its first viewport is the paper-space one (id 1), so saving does + // not add a second sheet viewport ahead of it (#1463). + for l in d.layouts.iter_mut() { + let vps: Vec = l.entities.iter().filter(|e| matches!(&e.kind, EntityKind::Viewport(_))).map(|e| (**e).clone()).collect(); + if vps.iter().all(|e| matches!(&e.kind, EntityKind::Viewport(v) if v.id == 0)) { + for (i, mut e) in vps.into_iter().enumerate() { + if let EntityKind::Viewport(v) = &mut e.kind { + v.id = i as u32 + 1; + } + l.entities.replace(e); + } + } + } apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); crate::dxf_image::resolve(&secs, &mut d); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 7b8f38385..33d4fd611 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -604,6 +604,54 @@ fn viewport_frozen_layers_roundtrip() { assert!(frozen.contains(&(3, Vec::new())), "{frozen:?}"); } +/// `Layout1` with viewports 1 (the sheet), 2 and 3, written to DXF and read back with the id (69) +/// of every viewport `blank` names replaced by -1 (ZWCAD's "unknown"): the ids and widths read. +fn viewport_ids_read_back(blank: impl Fn(&str) -> bool) -> (Drawing, Vec<(u32, f64)>) { + let mut d = sample(); + let paper = Space::Paper("Layout1".into()); + for (id, w) in [(1, 420.0), (2, 8.0), (3, 4.0)] { + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: w, + height: 6.0, + view_center: Vec2::new(5.0, 4.0), + view_height: 6.0, + id, + ..Viewport::default() + }; + d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); + } + let text = write_dxf(&d); + let mut lines: Vec = text.lines().map(String::from).collect(); + for i in (0..lines.len() - 1).step_by(2) { + if lines[i].trim() == "69" && blank(lines[i + 1].trim()) { + lines[i + 1] = "-1".into(); + } + } + let back = read_dxf(lines.join("\n").as_bytes()).unwrap(); + let ids = + back.layouts[0].entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some((v.id, v.width)) } else { None }).collect(); + (back, ids) +} + +/// ZWCAD writes every VIEWPORT with id (69) -1: they are numbered in file order, the first being +/// the paper-space viewport, so saving adds no second sheet viewport (#1463). +#[test] +fn viewport_ids_unknown_are_numbered_in_order() { + let (back, ids) = viewport_ids_read_back(|_| true); + assert_eq!(ids, [(1, 420.0), (2, 8.0), (3, 4.0)]); + assert!(!write_dxf(&back).contains("PAPERVIEW"), "the layout already has its paper-space viewport"); +} + +/// A layout that mixes known ids with -1 is left alone: the known ids stay, the unknown one reads +/// as 0 (not numbered), as before #1463. +#[test] +fn viewport_ids_mixed_are_kept() { + let (back, ids) = viewport_ids_read_back(|v| v == "2"); + assert_eq!(ids, [(1, 420.0), (0, 8.0), (3, 4.0)]); + assert!(!write_dxf(&back).contains("PAPERVIEW"), "viewport 1 is still the sheet"); +} + /// A layout with viewport 2 frozen on `Walls` and `A B` (both real layers), and its written DXF as /// (code, value) pairs. fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6c852ba76..f9091e77d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (DIMASSOC objects for angular, diametric and radial dimensions) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (DXF read: viewports without ids numbered in file order) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | DXF read: a layout whose VIEWPORTs all carry id (69) -1 (ZWCAD writes no ids) gets them numbered in file order, the first being the paper-space viewport, so a save no longer adds a second sheet viewport that turns the real one into a model viewport and inflates the drawing extents (#1463) | | 2026-10-22 | minor | DXF/DWG save: angular, diametric and radial dimensions get standard DIMASSOC objects (one centre reference to the circle for radial/diametric, the definition points for angular), so AutoCAD follows their geometry; the standard objects of those kinds are read back too, without CADCraft's xdata (#1651) | | 2026-10-19 | minor | DXF/DWG save: angular dimension block text honors DIMDSEP, including per-dimension overrides (#1646) | | 2026-10-19 | minor | A file's own arrowhead blocks with standard names (AutoCAD's `_Dot`, `_DotSmall`), named only by a dimension style, are kept and saved as they were instead of being replaced by CADCraft's solids; PURGE keeps arrowhead blocks dimension styles name | From 9431ad6ad9baf83207074ae8fc48ebf6d322c85e Mon Sep 17 00:00:00 2001 From: assamaraleman <217119886+assamaraleman@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:22:23 -0300 Subject: [PATCH 047/531] contributors: add assamaraleman Co-Authored-By: Claude Fable 5.1 --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 5c5d61005..ba968ffd3 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -87,3 +87,6 @@ real_name = "Richard Sauer" display_name = "Richard Sauer" sync_github_name = false +[people.assamaraleman] +real_name = "assamaral" +sync_github_name = false From 683dd0bfec8a2c8e4d28245147e19525c8c24752 Mon Sep 17 00:00:00 2001 From: ZachAR3 Date: Sun, 25 Oct 2026 02:09:31 +0100 Subject: [PATCH 048/531] TRIM and EXTEND: test Quick-mode EXTEND through its fence (#1594) The empty-space fence test now drives EXTEND through the second fence point and checks the extended lines, not only the prompt. --- crates/engine/tests/it/trim_extend_options.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/engine/tests/it/trim_extend_options.rs b/crates/engine/tests/it/trim_extend_options.rs index 0f4d50f15..6fe76ee17 100644 --- a/crates/engine/tests/it/trim_extend_options.rs +++ b/crates/engine/tests/it/trim_extend_options.rs @@ -128,6 +128,13 @@ fn a_pick_in_empty_space_starts_a_fence_in_quick_mode_and_a_window_in_standard_m assert!(s.prompt_text().contains("Select object to trim"), "{}", s.prompt_text()); s.cmdline("").unwrap(); assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))])); + // EXTEND's fence extends both lines it crosses to the boundary at x = 10. + let mut s = session(&["10,-5 10,5", "0,0 4,0", "0,2 4,2"]); + s.script("EXTEND 3,-1 3,3\n").unwrap(); + assert!(s.prompt_text().contains("Select object to extend"), "{}", s.prompt_text()); + s.cmdline("").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(lines(&s), vec![((0.0, 0.0), (10.0, 0.0)), ((0.0, 2.0), (10.0, 2.0)), ((10.0, -5.0), (10.0, 5.0))]); // Standard mode keeps the crossing window. let mut s = ladder(); s.script("TRIM O S\n\n4,-4\n").unwrap(); From 800b0319ac194583365f7241acce631319663135 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 24 Oct 2026 18:56:37 -0700 Subject: [PATCH 049/531] Dimensions: a negative DIMGAP draws a frame around the dimension text CADCraft used only the size of DIMGAP, so a negative value (Draw Frame Around Text on the Text tab of the Dimension Style Manager) placed the text like a positive one and drew no frame. A dimension whose DIMGAP is below 0 now draws a rectangle around its text: the text box widened by |DIMGAP| on every side, turned with the text, as four dimension lines in DIMCLRD. On an arc-length dimension with DIMARCSYM 1 the frame also takes in the arc symbol over the text. The frame is one of the dimension's lines, so the screen, plots and PDF draw it, the dimension's *D block holds it, and EXPLODE turns it into four LINEs. No help page says how this frame combines with a DIMINSPECT frame; CADCraft draws an inspection frame with round or angular ends in place of the DIMGAP frame. The arc symbol over the text now turns with a DIMTEDIT text angle. It was placed at the angle from before the override, so the text turned and the symbol did not. --- crates/engine/tests/it/dim_text_frame.rs | 30 +++++ crates/engine/tests/it/main.rs | 1 + crates/io/tests/it/dim_text_frame.rs | 73 ++++++++++++ crates/io/tests/it/main.rs | 1 + crates/render/src/dim.rs | 139 ++++++++++++++++++++++- 5 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 crates/engine/tests/it/dim_text_frame.rs create mode 100644 crates/io/tests/it/dim_text_frame.rs diff --git a/crates/engine/tests/it/dim_text_frame.rs b/crates/engine/tests/it/dim_text_frame.rs new file mode 100644 index 000000000..a76f42d14 --- /dev/null +++ b/crates/engine/tests/it/dim_text_frame.rs @@ -0,0 +1,30 @@ +//! A negative DIMGAP draws a frame around the dimension text: SETVAR takes the negative value, a +//! new dimension draws the frame, and EXPLODE turns it into four lines. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle}; +use serde_json::json; + +/// Draw a linear dimension with DIMGAP `gap`, explode it, and return the number of lines the +/// dimension drew and the number of LINEs EXPLODE left. +fn explode_with_gap(gap: f64) -> (usize, usize) { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "DIMGAP", "value": gap })).unwrap(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [30, 0], "at": [15, 5] })).unwrap(); + let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + let drawn = match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Dimension(dm) => cadcraft_engine::render::dimension_in(s.doc().unwrap(), dm).lines.len(), + k => panic!("not a dimension: {k:?}"), + }; + s.execute("explode", &json!({ "handles": [h.hex()] })).unwrap(); + let lines = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(); + (drawn, lines) +} + +#[test] +fn negative_dimgap_frame_is_drawn_and_exploded() { + let (plain_drawn, plain_lines) = explode_with_gap(0.09); + let (drawn, lines) = explode_with_gap(-0.09); + assert_eq!(drawn, plain_drawn + 4); + assert_eq!(lines, plain_lines + 4); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3edc0db95..416c1d01d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -28,6 +28,7 @@ mod dim_explode_text; mod dim_properties; mod dim_radial_inside; mod dim_radial_outside; +mod dim_text_frame; mod dim_vars; mod dimtedit_prompts; mod drafting_spacing; diff --git a/crates/io/tests/it/dim_text_frame.rs b/crates/io/tests/it/dim_text_frame.rs new file mode 100644 index 000000000..1ae29fc8a --- /dev/null +++ b/crates/io/tests/it/dim_text_frame.rs @@ -0,0 +1,73 @@ +//! A negative DIMGAP draws a frame around the dimension text. The `*D` block written for the +//! dimension holds the frame's four sides, the negative DIMGAP reads back from the file, and a +//! PDF plot draws the frame. + +use cadcraft_doc::{Common, DimKind, Dimension, Drawing, EntityKind, Space}; +use cadcraft_geom::Vec3; + +use crate::pdf_read; + +fn linear() -> Dimension { + Dimension { + kind: DimKind::Linear { rotation: 0.0 }, + defpt: Vec3::new(15.0, 5.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(30.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 0.0, + text_rotation: 0.0, + user_text_pos: false, + block: None, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + } +} + +/// Save a drawing with one dimension in a Standard style of DIMGAP `gap`, read it back, and +/// return the style's DIMGAP and the number of LINEs in the dimension's `*D` block. +fn roundtrip(gap: f64) -> (f64, usize) { + let mut d = Drawing::new_imperial(); + d.dim_styles.iter_mut().for_each(|s| s.text_gap = gap); + d.add(&Space::Model, Common::default(), EntityKind::Dimension(linear())).unwrap(); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + let dm = back + .model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Dimension(dm) => Some(dm.clone()), + _ => None, + }) + .unwrap(); + let block = back.block(dm.block.as_deref().unwrap()).unwrap(); + let lines = block.entities.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(); + (back.dim_style("Standard").unwrap().text_gap, lines) +} + +/// The number of path segments (`l`) in the PDF of a drawing with one dimension in a Standard +/// style of DIMGAP `gap`. +fn pdf_segments(gap: f64) -> usize { + let mut d = Drawing::new_imperial(); + d.dim_styles.iter_mut().for_each(|s| s.text_gap = gap); + d.add(&Space::Model, Common::default(), EntityKind::Dimension(linear())).unwrap(); + let doc = pdf_read::read(&cadcraft_io::plot(&d, &Space::Model, &serde_json::json!({"compress": false})).unwrap()); + pdf_read::count(&doc.pages[0].content, "l") +} + +#[test] +fn pdf_draws_the_text_frame() { + assert_eq!(pdf_segments(-0.09), pdf_segments(0.09) + 4); +} + +#[test] +fn dimension_block_holds_the_text_frame() { + let (gap, plain) = roundtrip(0.09); + assert!((gap - 0.09).abs() < 1e-12, "{gap}"); + let (gap, framed) = roundtrip(-0.09); + assert!((gap + 0.09).abs() < 1e-12, "{gap}"); + assert_eq!(framed, plain + 4); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index e6382aec8..7cc599e94 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -12,6 +12,7 @@ mod codepages; mod dim_block_resave_roundtrip; mod dim_block_text; mod dim_marks_roundtrip; +mod dim_text_frame; mod dimstyle_vars_roundtrip; mod drafting_spacing; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index c05a20014..23fa97ee2 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -555,6 +555,8 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font }; let mut text_angle = 0.0; let mut text_mid = d.text_mid.xy(); + // DIMARCSYM 1: the arc symbol's half width and how far its top is above the text's middle. + let mut arc_over: Option<(f64, f64)> = None; // Place an end marker: tick or arrowhead. Returns how far the dimension line stops short. let end = |g: &mut DimGeometry, kind: Arrowhead, tip: Vec2, dir: Vec2| -> f64 { if ticks { @@ -978,9 +980,12 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font if st.arc_symbol == 1 { // A small arc over the text. let (tw, tht) = measure(&g.mtext); - let (x, y) = (Vec2::from_angle(text_angle), Vec2::from_angle(text_angle).perp()); + // The symbol turns with the text, a DIMTEDIT Angle included. + let a = if d.text_rotation != 0.0 && d.text_rotation.is_finite() { d.text_rotation } else { text_angle }; + let (x, y) = (Vec2::from_angle(a), Vec2::from_angle(a).perp()); let half = (tw / 2.0).max(th / 2.0); let base = text_mid + y * (tht / 2.0 + gap / 2.0); + arc_over = Some((half, tht / 2.0 + gap / 2.0 + th * 0.35)); let sym: Vec = (0..=12) .map(|i| { let t = f64::from(i) / 6.0 - 1.0; @@ -1045,6 +1050,19 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font g.text_glyphs.extend(p.shaped.glyphs); } } + // DIMGAP below 0: a frame around the text and the arc symbol over it, widened by |DIMGAP| on + // every side. A DIMINSPECT frame takes its place. + if st.text_gap < 0.0 && !g.mtext.is_empty() && d.marks.inspect.as_ref().is_none_or(|ins| ins.shape >= 2) { + let (w, h) = measure(&g.mtext); + let (x, y) = (Vec2::from_angle(text_angle), Vec2::from_angle(text_angle).perp()); + let (hw, top) = arc_over.map_or((w / 2.0, h / 2.0), |(half, peak)| ((w / 2.0).max(half), (h / 2.0).max(peak))); + let (hw, top, bottom) = (hw + gap, top + gap, h / 2.0 + gap); + let corners: Vec = + [(-hw, -bottom), (hw, -bottom), (hw, top), (-hw, top)].into_iter().map(|(px, py)| text_mid + x * px + y * py).collect(); + for (a, b) in corners.iter().zip(corners.iter().cycle().skip(1)) { + g.dim(vec![*a, *b]); + } + } g.text_pos = text_mid; g.text_angle = text_angle; g @@ -1212,6 +1230,125 @@ mod tests { assert!(outside2.text_pos.y < 5.0); } + /// The last four lines of `g` as a frame: four sides, each starting where the one before ends. + fn frame_of(g: &DimGeometry) -> Vec> { + let sides: Vec> = g.lines.iter().rev().take(4).rev().cloned().collect(); + assert_eq!(sides.len(), 4); + for (a, b) in sides.iter().zip(sides.iter().cycle().skip(1)) { + assert_eq!(a.len(), 2); + assert!(a[1].dist(b[0]) < 1e-9, "{sides:?}"); + } + sides + } + + #[test] + fn negative_dimgap_draws_a_frame_around_the_text() { + let d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0); + let plain = dimension_geometry(&d, &st_with(|s| s.text_gap = 0.09), 1.0); + let framed = dimension_geometry(&d, &st_with(|s| s.text_gap = -0.09), 1.0); + // The same text place and dimension line break as DIMGAP 0.09, and four more lines. + assert!(framed.text_pos.dist(plain.text_pos) < 1e-12); + assert_eq!(framed.lines.len(), plain.lines.len() + 4); + assert_eq!(framed.lines_of(LineRole::Dim).count(), plain.lines_of(LineRole::Dim).count() + 4); + // The frame is the text box widened by 0.09 on every side, around the text. + let frame = bbox(&frame_of(&framed)); + let l = cadcraft_fonts::layout_mtext_with(&framed.mtext, &MTextParams { attach: 5, ..MTextParams::new(Vec2::ZERO, 0.18) }); + assert!((frame.width() - (l.bounds.width() + 0.18)).abs() < 1e-9, "{frame:?}"); + assert!((frame.height() - (l.bounds.height() + 0.18)).abs() < 1e-9, "{frame:?}"); + let text = bbox(&framed.text); + assert!(frame.min.x < text.min.x && text.max.x < frame.max.x && frame.min.y < text.min.y && text.max.y < frame.max.y); + assert!((frame.center().dist(framed.text_pos)) < 1e-9, "{frame:?}"); + // DIMGAP 0 and above: no frame. + assert_eq!(dimension_geometry(&d, &st_with(|s| s.text_gap = 0.0), 1.0).lines.len(), plain.lines.len()); + } + + #[test] + fn the_frame_turns_with_the_text() { + let d = lin((0.0, 0.0), (0.0, 10.0), (5.0, 0.0), std::f64::consts::FRAC_PI_2); + let g = dimension_geometry( + &d, + &st_with(|s| { + s.text_gap = -0.09; + s.text_inside_horizontal = false; + }), + 1.0, + ); + assert!((g.text_angle.abs() - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{}", g.text_angle); + // Two sides along the text, two across it, the long ones along the dimension line. + for s in frame_of(&g) { + let v = s[1] - s[0]; + assert!(v.x.abs() < 1e-9 || v.y.abs() < 1e-9, "{v:?}"); + } + let frame = bbox(&frame_of(&g)); + assert!(frame.height() > frame.width(), "{frame:?}"); + assert!(bbox(&g.text).max.y < frame.max.y && frame.min.y < bbox(&g.text).min.y); + } + + #[test] + fn the_frame_takes_in_the_arc_symbol_over_the_text() { + let mut d = lin((10.0, 0.0), (0.0, 10.0), (12.0, 0.0), 0.0); + d.kind = DimKind::ArcLength; + let g = dimension_geometry( + &d, + &st_with(|s| { + s.text_gap = -0.09; + s.arc_symbol = 1; + s.text_inside_horizontal = true; + }), + 1.0, + ); + let frame = bbox(&frame_of(&g)); + // The arc symbol is the line drawn just before the frame. + let sym = &g.lines[g.lines.len() - 5]; + assert_eq!(sym.len(), 13); + let s = bbox(std::slice::from_ref(sym)); + assert!((frame.max.y - (s.max.y + 0.09)).abs() < 1e-9, "{frame:?} {s:?}"); + assert!(frame.min.x < s.min.x && s.max.x < frame.max.x, "{frame:?} {s:?}"); + let text = bbox(&g.text); + assert!(frame.min.y < text.min.y && text.max.y < frame.max.y, "{frame:?} {text:?}"); + } + + #[test] + fn the_arc_symbol_and_the_frame_turn_with_a_text_angle() { + let mut d = lin((10.0, 0.0), (0.0, 10.0), (12.0, 0.0), 0.0); + d.kind = DimKind::ArcLength; + d.text_rotation = 0.5; + let g = dimension_geometry( + &d, + &st_with(|s| { + s.text_gap = -0.09; + s.arc_symbol = 1; + }), + 1.0, + ); + assert!((g.text_angle - 0.5).abs() < 1e-12); + // In the text's own axes, the frame is upright and holds the symbol 0.09 below its top. + let (x, y) = (Vec2::from_angle(0.5), Vec2::from_angle(0.5).perp()); + let local = |pts: &[Vec]| -> Vec> { + pts.iter().map(|l| l.iter().map(|p| Vec2::new((*p - g.text_pos).dot(x), (*p - g.text_pos).dot(y))).collect()).collect() + }; + let frame = bbox(&local(&frame_of(&g))); + let sym = bbox(&local(std::slice::from_ref(&g.lines[g.lines.len() - 5]))); + assert!((frame.max.y - (sym.max.y + 0.09)).abs() < 1e-9, "{frame:?} {sym:?}"); + assert!(frame.min.x < sym.min.x && sym.max.x < frame.max.x, "{frame:?} {sym:?}"); + // The symbol's ends sit level in the text's axes. + let s = &local(std::slice::from_ref(&g.lines[g.lines.len() - 5]))[0]; + assert!((s[0].y - s[12].y).abs() < 1e-9, "{s:?}"); + } + + #[test] + fn an_inspection_frame_takes_the_place_of_the_dimgap_frame() { + let mut d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0); + d.marks.inspect = Some(cadcraft_doc::Inspection { shape: 0, label: "A".into(), rate: "50%".into() }); + let st = |gap: f64| st_with(|s| s.text_gap = gap); + let inspected = dimension_geometry(&d, &st(0.09), 1.0).lines.len(); + assert_eq!(dimension_geometry(&d, &st(-0.09), 1.0).lines.len(), inspected); + // Shape none draws no inspection frame, so DIMGAP's frame is drawn. + d.marks.inspect = Some(cadcraft_doc::Inspection { shape: 2, label: String::new(), rate: String::new() }); + let none = dimension_geometry(&d, &st(0.09), 1.0).lines.len(); + assert_eq!(dimension_geometry(&d, &st(-0.09), 1.0).lines.len(), none + 4); + } + #[test] fn dimtad_one_uses_autocad_text_clearance() { let d = lin((0.0, 0.10), (0.0, 0.70), (0.30, 0.40), std::f64::consts::FRAC_PI_2); From d11c418fe608def4d28d8783c075ac8cc2336b4a Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:17:07 +0400 Subject: [PATCH 050/531] theme: the Georgian glyph test asks FontsView::has_glyph (egui 0.37 made its fonts field private) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/theme.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9627becb4..75dd4f6ac 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -813,9 +813,8 @@ mod tests { output.textures_delta.clear(); ctx.fonts_mut(|view| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - let mut font = view.fonts.font(&family); for c in &letters { - assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + assert!(view.has_glyph(&egui::FontId::new(12.0, family.clone()), *c), "{language}: missing Georgian glyph {c} in {family:?}"); } } }); From 8e84e57ac8e3712edcb26b03988f87c74c56add5 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:17:17 +0400 Subject: [PATCH 051/531] theme: the Georgian glyph test asks FontsView::has_glyph (egui 0.37 made its fonts field private) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/theme.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9627becb4..75dd4f6ac 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -813,9 +813,8 @@ mod tests { output.textures_delta.clear(); ctx.fonts_mut(|view| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - let mut font = view.fonts.font(&family); for c in &letters { - assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + assert!(view.has_glyph(&egui::FontId::new(12.0, family.clone()), *c), "{language}: missing Georgian glyph {c} in {family:?}"); } } }); From 9c8519da2f6675c30fdd81277697caedc938ba64 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:57:06 +0400 Subject: [PATCH 052/531] docs: ka among the supported ui.language values Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1c3f30626..f7fa57e4e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,7 +188,7 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar` and `hu`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the optional craft-fonts input or the operating system. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts From 4cd88a3815009417e159a27dc614a588d55739a9 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:57:06 +0400 Subject: [PATCH 053/531] docs: ka joins the supported ui.language values with the language PR, not this one (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6e642497a..46e2d379d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,7 +188,7 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr` and `el`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the optional craft-fonts input or the operating system; Georgian needs the craft-fonts Georgian (`Geor`) face. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts From 963267abe856c39d11dcfecdc4857df645078eac Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 21:30:23 +0400 Subject: [PATCH 054/531] docs: list tr and el among the ui.language values Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f7fa57e4e..5bbd4b083 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,7 +188,7 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu` and `ka`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the optional craft-fonts input or the operating system. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts From 1fba38238f67ee97392d110468e7449e7e7bf6fb Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 22:09:24 +0400 Subject: [PATCH 055/531] i18n(ka): shorter wording for labels that were cut off Decided in the native-speaker review of the screens (all-t01). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3db7c923a..716a01417 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -572,7 +572,7 @@ New Viewports... ახალი ხედვის არეები... New from Template... ახალი შაბლონიდან... New layout ახალი განლაგება - New state name მდგომარეობის ახალი სახელი + New state name ახალი მდგომარეობა Next Change შემდეგი ცვლილება No არა No blocks defined in this drawing. ამ ნახაზში ბლოკები არ არის განსაზღვრული. From f02ac726baafff61a2a803f77694cb7a6c7b3b75 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sun, 25 Oct 2026 16:53:24 -0600 Subject: [PATCH 056/531] MTEXT editor: a state kept for another MTEXT is not reused The editor's state was kept between frames and only dropped by a frame with no text prompt, so TEXTEDIT moving to the next MTEXT within one frame (Enter, then a point) opened it with the first one's text, and OK wrote that text to it. The state now remembers the MTEXT it was made for (its insertion point and contents when it opened) and is made afresh for another. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/mtext_editor.rs | 60 +++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 6700b592e..4741491c0 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -76,6 +76,9 @@ struct State { /// 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)>, } fn state_id() -> egui::Id { @@ -106,7 +109,9 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { }; 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 mut st = ctx.data_mut(|d| d.get_temp::(state_id())).unwrap_or_else(|| { + 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(&mt.contents) }; if let Some(f) = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).map(|s| s.font.clone())) { @@ -117,7 +122,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } // 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 } + State { fmt, typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret, focused: false, target: Some(target.clone()) } }); 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); @@ -615,8 +620,16 @@ mod tests { /// 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 { fmt: Formatted::default(), typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None, focused: false }; + 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)).with_context_setup(install_diameter_glyph).build_ui_state( |ui, state| { toolbar(ui, state, 2.5); @@ -636,8 +649,16 @@ mod tests { /// 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. #[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 }; + 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 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"] { @@ -729,6 +750,33 @@ mod tests { /// #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(); From b077e22f40aebe0d0af19d0333c17300841e5682 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 26 Oct 2026 11:46:25 +1100 Subject: [PATCH 057/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9c2186c90..f172c901f 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-26 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 296 / 491 items (60%)** · 441 registered commands. +**Menu breadth: 303 / 491 items (62%)** · 448 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 36 | 48% | +| View | 75 | 37 | 49% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 52 | 46% | | Window | 22 | 3 | 14% | @@ -66,7 +66,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -81,15 +80,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -127,7 +121,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From e660b0dbe435f3f514e4fb6333c34bdbc8a4c4b5 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 26 Oct 2026 12:01:42 +1100 Subject: [PATCH 058/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9c2186c90..f172c901f 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-26 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 296 / 491 items (60%)** · 441 registered commands. +**Menu breadth: 303 / 491 items (62%)** · 448 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 36 | 48% | +| View | 75 | 37 | 49% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 52 | 46% | | Window | 22 | 3 | 14% | @@ -66,7 +66,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -81,15 +80,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -127,7 +121,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From f8f81b431da9c8ee402a41849522923ceb542c52 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 26 Oct 2026 12:07:16 +1100 Subject: [PATCH 059/531] cursor_contrast test: turn the UCS icon off through UCSICON, which replaced UiState::show_ucs_icon --- crates/ui-egui/tests/cursor_contrast.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/cursor_contrast.rs b/crates/ui-egui/tests/cursor_contrast.rs index a707cbe72..39fd6bfd5 100644 --- a/crates/ui-egui/tests/cursor_contrast.rs +++ b/crates/ui-egui/tests/cursor_contrast.rs @@ -30,7 +30,8 @@ impl Canvas { let mut app = CadApp::new(session, Services::default()); app.canvas.zoom_pending = false; app.ui.show_command_line = false; - app.ui.show_ucs_icon = false; + // The UCS icon is UCSICON, which the drawing keeps. + app.run("ucsicon", json!({"on": false})).unwrap(); app.ui.show_viewcube = false; app.run("options", json!({"theme": "dark", "systemCursor": false, "PICKBOX": 4, "SELECTIONPREVIEW": 1})).unwrap(); let mut canvas = Self { app, ctx: Context::default(), previous_theme }; From 4346beec728b3483c69c89496959d420ad09fa4b Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 26 Oct 2026 12:07:19 +1100 Subject: [PATCH 060/531] Format annotate.rs after merging main --- crates/engine/src/cmd/annotate.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index ef96bb242..cdbd52591 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -1070,15 +1070,8 @@ impl Interactive for LinearM { } (_, Input::Point(at)) => { let (Some(&a), Some(&b)) = (self.pts.first(), self.pts.get(1)) else { return Ok(Step::Continue) }; - let k = self.text.apply(dim( - s, - linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), - at, - a, - b, - Vec2::ZERO, - "", - )); + let k = + self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), at, a, b, Vec2::ZERO, "")); add_dim(s, k)?; if let Some(EntityKind::Dimension(d)) = s.last_dim.and_then(|h| s.doc().ok()?.entity(h).map(|e| e.kind.clone())) { let st = s.doc()?.dim_style(&d.style).cloned().unwrap_or_default(); From 36272cdd28b41bbfb0d6ad28af4fa27a576b4188 Mon Sep 17 00:00:00 2001 From: assamaral <217119886+assamaral@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:28:29 -0300 Subject: [PATCH 061/531] contributors: key the entry by the renamed username (assamaral) Co-Authored-By: Claude Fable 5.1 --- contributors/people.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributors/people.toml b/contributors/people.toml index ba968ffd3..53e50fb17 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -87,6 +87,6 @@ real_name = "Richard Sauer" display_name = "Richard Sauer" sync_github_name = false -[people.assamaraleman] +[people.assamaral] real_name = "assamaral" sync_github_name = false From 97f889733d0f178b4bba117c6292308349b68b6b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 01:33:26 +0000 Subject: [PATCH 062/531] Hide the UCS icon in the cursor contrast test through UCSICON --- crates/ui-egui/tests/cursor_contrast.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/cursor_contrast.rs b/crates/ui-egui/tests/cursor_contrast.rs index a707cbe72..b4b13f5ca 100644 --- a/crates/ui-egui/tests/cursor_contrast.rs +++ b/crates/ui-egui/tests/cursor_contrast.rs @@ -27,10 +27,10 @@ impl Canvas { session.execute("view.set", &json!({"center": [100, 100], "height": 400})).unwrap(); session.settings.gridmode = false; session.settings.dynmode = false; + session.execute("ucsicon", &json!({"on": false})).unwrap(); let mut app = CadApp::new(session, Services::default()); app.canvas.zoom_pending = false; app.ui.show_command_line = false; - app.ui.show_ucs_icon = false; app.ui.show_viewcube = false; app.run("options", json!({"theme": "dark", "systemCursor": false, "PICKBOX": 4, "SELECTIONPREVIEW": 1})).unwrap(); let mut canvas = Self { app, ctx: Context::default(), previous_theme }; From e98201c282fb4f2d02ab69df8d3a50e0cf9f56f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 01:33:47 +0000 Subject: [PATCH 063/531] Format the merged dimension calls --- crates/engine/src/cmd/annotate.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index 9a64d2219..cdbd52591 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -1070,7 +1070,8 @@ impl Interactive for LinearM { } (_, Input::Point(at)) => { let (Some(&a), Some(&b)) = (self.pts.first(), self.pts.get(1)) else { return Ok(Step::Continue) }; - let k = self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), at, a, b, Vec2::ZERO, "")); + let k = + self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), at, a, b, Vec2::ZERO, "")); add_dim(s, k)?; if let Some(EntityKind::Dimension(d)) = s.last_dim.and_then(|h| s.doc().ok()?.entity(h).map(|e| e.kind.clone())) { let st = s.doc()?.dim_style(&d.style).cloned().unwrap_or_default(); @@ -1097,7 +1098,15 @@ impl Interactive for LinearM { fn preview(&self, s: &Session, c: Vec2) -> Vec { match self.pts.as_slice() { [a] => vec![super::helpers::line(*a, c)], - [a, b] => vec![self.text.apply(dim(s, linear_kind(*a, *b, c, self.rotation, self.aligned, s.input_ucs().rotation()), c, *a, *b, Vec2::ZERO, ""))], + [a, b] => vec![self.text.apply(dim( + s, + linear_kind(*a, *b, c, self.rotation, self.aligned, s.input_ucs().rotation()), + c, + *a, + *b, + Vec2::ZERO, + "", + ))], _ => Vec::new(), } } From 25014b77b8ab493b8d0b27281f6ddf74bbafb5d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 03:04:41 +0000 Subject: [PATCH 064/531] Regenerate the parity checklist (cargo xtask parity) --- docs/parity-checklist.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index c7cd4e86b..73f3c5168 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-27 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 296 / 491 items (60%)** · 441 registered commands. +**Menu breadth: 303 / 491 items (62%)** · 448 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 36 | 48% | +| View | 75 | 37 | 49% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 52 | 46% | | Window | 22 | 3 | 14% | @@ -66,7 +66,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights From d204518d8a575344ea17db1cb4598f123eb6edc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 03:04:43 +0000 Subject: [PATCH 065/531] Regenerate the parity checklist (cargo xtask parity) --- docs/parity-checklist.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index c7cd4e86b..73f3c5168 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-27 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 296 / 491 items (60%)** · 441 registered commands. +**Menu breadth: 303 / 491 items (62%)** · 448 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 36 | 48% | +| View | 75 | 37 | 49% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 52 | 46% | | Window | 22 | 3 | 14% | @@ -66,7 +66,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights From 9f7117036845dda3e88468a74f7cf5980583b277 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 27 Oct 2026 19:45:51 +1100 Subject: [PATCH 066/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9c2186c90..10c1b14a1 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-27 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. From 3e0de6246f2fd63bdfbd0fd12c2a78cef5ac673b Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 27 Oct 2026 19:57:10 +1100 Subject: [PATCH 067/531] ATTDEF: reach justify through draw's re-export now that draw.rs is split --- crates/engine/src/cmd/draw.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index 52bf23ace..463098679 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -31,6 +31,7 @@ use line_pline::{LineM, PlineM, run_line, run_pline}; use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray}; use polygon::{PolygonM, run_polygon}; use spline::{SplineM, run_spline}; +pub(crate) use text::justify; use text::{MTextM, TextM, run_mtext, run_text}; /// Every draw command's spec: JSON parameters, menu path, aliases and the interactive prompt From 98a05c66f964dcd2eb777e73e80476ca47fbc92e Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 27 Oct 2026 19:59:02 +1100 Subject: [PATCH 068/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9c2186c90..10c1b14a1 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-27 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. From 53c7d25ee04b98c12db17bf2424880f9ac9a8998 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 27 Oct 2026 15:43:32 +0400 Subject: [PATCH 069/531] i18n(ka): bring the Georgian catalog up to date Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 54 ++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 716a01417..1bd5d65fd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -153,6 +153,7 @@ Close All Other Drawings ყველა სხვა ნახაზის დახურვა Closed შეკრული Close Comparison შედარების დახურვა + Export Comparison შედარების ექსპორტი Coincident დამთხვევა Collapse Palettes პალიტრების ჩაკეცვა Collapse Tool Sets ხელსაწყოთა ნაკრებების ჩაკეცვა @@ -200,6 +201,7 @@ Current selection მიმდინარე მონიშნული Current: {color} მიმდინარე: {color} Cut ამოჭრა + Cut with Base Point ამოჭრა საბაზო წერტილით Cyan ცისფერი Cylinder ცილინდრი DWG DWG @@ -264,6 +266,7 @@ Drawing Template (DWT) ნახაზის შაბლონი (DWT) Drawing Utilities ნახაზის უტილიტები Drawings (DWG, DXF) ნახაზები (DWG, DXF) + AutoLISP (LSP) AutoLISP (LSP) SVG drawings (SVG, SVGZ) SVG ნახაზები (SVG, SVGZ) Dynamic დინამიკური Dynamic Dimensions დინამიკური ზომები @@ -572,7 +575,7 @@ New Viewports... ახალი ხედვის არეები... New from Template... ახალი შაბლონიდან... New layout ახალი განლაგება - New state name ახალი მდგომარეობა + New state name მდგომარეობის ახალი სახელი Next Change შემდეგი ცვლილება No არა No blocks defined in this drawing. ამ ნახაზში ბლოკები არ არის განსაზღვრული. @@ -756,6 +759,7 @@ Rename Text Style ტექსტის სტილის სახელის შეცვლა Rename... სახელის შეცვლა... Repeat {command} გამეორება: {command} + Replace Block... ბლოკის ჩანაცვლება... Requires a point (x,y, @dx,dy or @d Date: Tue, 27 Oct 2026 16:09:18 +0400 Subject: [PATCH 070/531] i18n(ka): translate Font (the text editor's font field) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1bd5d65fd..205f5e821 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -362,6 +362,7 @@ Fit Points მისადაგების წერტილები Fix ფიქსაცია Flatten Objects ობიექტების სიბრტყეზე დაგეგმილება + Font შრიფტი Format ფორმატი Freehand ხელით ხაზვა Freeze გაყინვა From f948acd30b52e01826c85d7033e03485cca4a236 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 27 Oct 2026 23:32:16 +0400 Subject: [PATCH 071/531] i18n(ka): bring the Georgian catalog up to date Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.tsv | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 205f5e821..2126b7cd1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -103,6 +103,7 @@ Blend გადასვლა Block ბლოკი Block Attribute Manager... ბლოკის ატრიბუტების მენეჯერი... + Block Description... ბლოკის აღწერა... Block Editor ბლოკის რედაქტორი Block Reference ბლოკის ჩასმა Block... ბლოკი... @@ -563,6 +564,7 @@ N N Name სახელი Name (A–Z) სახელი (ა–ჰ) + Named Viewports... დასახელებული ხედვის არეები... Named Views... დასახელებული ხედები... Nearest უახლოესი New ახალი @@ -777,6 +779,7 @@ Save (⌘S) შენახვა (⌘S) Save As შენახვა როგორც Save As... შენახვა როგორც... + Save Layout as Template განლაგების შაბლონად შენახვა Save Layer State შრეების მდგომარეობის შენახვა Save State მდგომარეობის შენახვა Scale მასშტაბირება From 811bd3cb4e2f07b46df0bdc0ee9b70084a953e3f Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 21:30:24 +0100 Subject: [PATCH 072/531] Options: Right-Click Customization (click duration; Default, Edit and Command modes) (F20) Options > User Preferences > Right-Click Customization... sets the time-sensitive right-click and its duration (rightClickDuration, 100-2000 ms), what a right-click does with nothing or something selected and no command running (rightClickDefault, rightClickEdit: the shortcut menu or repeat the last command), and, with the time-sensitive right-click off, while a command runs (rightClickCommand: the menu, Enter, or the menu only when the prompt has options). The defaults keep today's behaviour; the settings are kept in the profile. context_menu::show repeats Session::last_command in Repeat mode, and in_command uses the configured hold time and Command mode. Italian and Ukrainian strings; gaps F20 and ui-parity updated. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/src/context_menu.rs | 42 +++- crates/ui-egui/src/i18n/it.tsv | 17 ++ crates/ui-egui/src/i18n/uk.tsv | 17 ++ crates/ui-egui/src/options.rs | 148 +++++++++++- crates/ui-egui/src/options/dialog.rs | 91 +++++++- crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/options_right_click.rs | 210 ++++++++++++++++++ docs/gaps.md | 5 +- docs/ui-parity.md | 11 +- 9 files changed, 524 insertions(+), 18 deletions(-) create mode 100644 crates/ui-egui/tests/it/options_right_click.rs diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbaf48df3..53dc69ca6 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -6,8 +6,12 @@ //! Pan/Zoom, Quick Select, Find, Properties and Options. //! - **While a command runs** ([`command_entries`]): a quick right-click is Enter; holding the //! button for [`HOLD_SECS`] opens Enter, Cancel, Recent Input, the prompt's options, Snap -//! Overrides and Pan/Zoom instead (AutoCAD's time-sensitive right-click). With that turned off -//! in OPTIONS (`timeSensitiveRightClick`), every right-click opens the menu. +//! Overrides and Pan/Zoom instead (AutoCAD's time-sensitive right-click; Options ▸ User +//! Preferences ▸ Right-Click Customization sets how long, `rightClickDuration`). With that turned +//! off (`timeSensitiveRightClick`), Command mode says what a right-click does +//! (`rightClickCommand`: the menu, Enter, or the menu only when the prompt has options). +//! `rightClickDefault` and `rightClickEdit` can make a right-click with no command running +//! repeat the last command instead of opening the menu. //! - **Shift/Ctrl+right-click** ([`snap_entries`]): the object snap menu. Its items type the point //! modifiers and snap overrides (`_from`, `_endp`, `_non`…) at the current point prompt. //! @@ -41,7 +45,8 @@ const SETTINGS: &[&str] = &["options"]; /// How many recent commands and inputs the menus list. pub const RECENT: usize = 8; /// How long the right button must be held while a command runs to open the command menu instead -/// of acting as Enter (AutoCAD's time-sensitive right-click; 250 ms there by default). +/// of acting as Enter, by default (AutoCAD's time-sensitive right-click; 250 ms there by +/// default). OPTIONS `rightClickDuration` changes it. pub const HOLD_SECS: f64 = 0.25; /// Item ids that are not commands: keys, typed text and snap menu items. @@ -290,6 +295,19 @@ pub fn groups_ui(ui: &mut egui::Ui, groups: &[Vec], clicked: &mut Option< pub fn show(app: &mut CadApp, resp: &egui::Response) { let mut clicked = None; let snap = app.canvas.snap_menu; + // Right-Click Customization: with nothing selected (Default mode) or a selection (Edit mode), + // a right-click may repeat the last command instead of opening the menu. + let o = &app.options; + let mode = + if o.right_click_default == o.right_click_edit || app.session.selection().is_empty() { o.right_click_default } else { o.right_click_edit }; + if !snap && mode == crate::options::IdleClick::Repeat { + if resp.secondary_clicked() + && let Some(last) = app.session.last_command.clone() + { + app.start(&last); + } + return; + } resp.context_menu(|ui| { let groups = if snap { snap_entries(app) } else { entries(app) }; groups_ui(ui, &groups, &mut clicked); @@ -307,8 +325,9 @@ struct Press(f64, egui::Pos2); /// The canvas's right button while a command runs (Shift/Ctrl+right-click is the snap menu's): a /// quick click is Enter — returns `true` when the caller should send it — and a click held for -/// [`HOLD_SECS`] opens the command menu ([`command_entries`]) at the pointer (any click does with -/// the time-sensitive right-click turned off). Call it every frame +/// OPTIONS `rightClickDuration` opens the command menu ([`command_entries`]) at the pointer. With +/// the time-sensitive right-click turned off, `rightClickCommand` says whether a click opens the +/// menu or is Enter. Call it every frame /// with whether the pointer is on the canvas and whether a right-click ended there; it also shows /// the menu while it is open. pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked: bool) -> bool { @@ -325,14 +344,23 @@ pub fn in_command(app: &mut CadApp, ui: &egui::Ui, inside: bool, right_clicked: ctx.data_mut(|d| d.insert_temp(press_id, Press(now, p))); } let running = app.session.prompting() && !app.canvas.snap_menu; + let o = &app.options; + let timed = o.time_sensitive_right_click; + // Without the time-sensitive right-click, Command mode says whether a click opens the menu. + let menu = match o.right_click_command { + crate::options::CommandClick::Menu => true, + crate::options::CommandClick::Enter => false, + crate::options::CommandClick::MenuWithOptions => app.session.current_prompt().is_some_and(|p| !p.keywords.is_empty()), + }; + let hold = f64::from(o.right_click_hold_ms) / 1000.0; let mut open = false; if released && let Some(Press(t0, p0)) = ctx.data_mut(|d| d.remove_temp::(press_id)) { // A drag isn't a click; a click held long enough asks for the menu. let still = pos.is_some_and(|p| p.distance(p0) <= 6.0); - let held = now - t0 >= HOLD_SECS || !app.options.time_sensitive_right_click; + let held = if timed { now - t0 >= hold } else { menu }; open = running && still && held; } - let enter = running && inside && right_clicked && !open && app.options.time_sensitive_right_click; + let enter = running && inside && right_clicked && !open && (timed || !menu); if !running { return false; } diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 634249093..a2c879d0a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1367,3 +1367,20 @@ menu Modify Edita Check for Updates… Verifica aggiornamenti… CADCraft is up to date. CADCraft è aggiornato. Could not check for updates. Impossibile verificare gli aggiornamenti. + Right-Click Customization... Personalizzazione pulsante destro... + Right-Click Customization Personalizzazione pulsante destro + Turn on time-sensitive right-click Attiva clic destro sensibile al tempo + Longer click duration: Durata clic lungo: + milliseconds millisecondi + While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Durante un comando un clic rapido equivale a Invio, un clic più lungo apre il menu di scelta rapida. + Default Mode Modalità predefinita + No objects selected and no command running: Nessun oggetto selezionato e nessun comando in corso: + Edit Mode Modalità modifica + Objects selected and no command running: Oggetti selezionati e nessun comando in corso: + Repeat last command Ripeti ultimo comando + Shortcut Menu Menu di scelta rapida + Command Mode Modalità comando + While a command runs: Durante un comando: + ENTER INVIO + Shortcut Menu: always enabled Menu di scelta rapida: sempre attivo + Shortcut Menu: enabled when command options are present Menu di scelta rapida: attivo se il comando ha opzioni diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d71b3ccd7..387be68ef 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1373,3 +1373,20 @@ Check for Updates… Перевірити оновлення… CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. + Right-Click Customization... Налаштування правої кнопки... + Right-Click Customization Налаштування правої кнопки + Turn on time-sensitive right-click Увімкнути залежне від часу клацання правою кнопкою + Longer click duration: Тривалість довгого клацання: + milliseconds мілісекунд + While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Під час команди коротке клацання — Enter, довше відкриває контекстне меню. + Default Mode Режим за замовчуванням + No objects selected and no command running: Нічого не вибрано й команда не виконується: + Edit Mode Режим редагування + Objects selected and no command running: Об'єкти вибрано, команда не виконується: + Repeat last command Повторити останню команду + Shortcut Menu Контекстне меню + Command Mode Режим команди + While a command runs: Під час виконання команди: + ENTER Клавіша Enter + Shortcut Menu: always enabled Контекстне меню: завжди + Shortcut Menu: enabled when command options are present Контекстне меню: коли команда має параметри diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index c8b94c310..e82372394 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -15,7 +15,10 @@ //! | `saveVersion` | `"2000"` … `"2018"`: the version drawings with no file yet are saved in | //! | `SAVETIME` | minutes between automatic saves, 0–600 (0: off) | //! | `SAVEFILEPATH` | the folder automatic saves go to | -//! | `timeSensitiveRightClick` | while a command runs, a quick right-click is Enter and holding the button opens the shortcut menu (default); `false`: a right-click always opens the menu | +//! | `timeSensitiveRightClick` | while a command runs, a quick right-click is Enter and holding the button opens the shortcut menu (default); `false`: `rightClickCommand` decides | +//! | `rightClickDuration` | how long the right button is held to open the menu while a command runs, 100–2000 ms (250) | +//! | `rightClickDefault`, `rightClickEdit` | a right-click with no command running and nothing (`Default`) or something (`Edit`) selected: `"menu"` (the shortcut menu, default) or `"repeat"` (the last command) | +//! | `rightClickCommand` | a right-click while a command runs, with the time-sensitive right-click off: `"menu"` (default), `"enter"`, or `"menuWithOptions"` (the menu when the prompt has options, else Enter) | //! | `systemCursor` | keep the system cursor visible over the drawing area | //! | `historyLines` | command-line history lines, 0–12 | //! | `modelBackground`, `paperBackground` | `"#rrggbb"`, or `null` for the default | @@ -56,6 +59,66 @@ pub const SNAP_MARKER_SIZES: std::ops::RangeInclusive = 5.0..=31.0; /// Interface scales the JSON form accepts (1: the system's own size). pub const INTERFACE_SCALES: std::ops::RangeInclusive = 0.5..=3.0; +/// How long a right-click may be held before it opens the menu, in milliseconds. +pub const RIGHT_CLICK_DURATIONS: std::ops::RangeInclusive = 100..=2000; + +/// What a right-click does with no command running (Right-Click Customization's Default and Edit +/// modes). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum IdleClick { + /// Repeat the last command. + Repeat, + /// The shortcut menu. + #[default] + Menu, +} + +impl IdleClick { + pub const ALL: [IdleClick; 2] = [IdleClick::Repeat, IdleClick::Menu]; + + /// The JSON name. + pub fn as_str(self) -> &'static str { + match self { + IdleClick::Repeat => "repeat", + IdleClick::Menu => "menu", + } + } + + pub fn parse(s: &str) -> Option { + IdleClick::ALL.into_iter().find(|c| c.as_str().eq_ignore_ascii_case(s.trim())) + } +} + +/// What a right-click does while a command runs with the time-sensitive right-click off +/// (Right-Click Customization's Command mode). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum CommandClick { + /// Enter. + Enter, + /// The shortcut menu, always. + #[default] + Menu, + /// The shortcut menu when the prompt has options, else Enter. + MenuWithOptions, +} + +impl CommandClick { + pub const ALL: [CommandClick; 3] = [CommandClick::Enter, CommandClick::Menu, CommandClick::MenuWithOptions]; + + /// The JSON name. + pub fn as_str(self) -> &'static str { + match self { + CommandClick::Enter => "enter", + CommandClick::Menu => "menu", + CommandClick::MenuWithOptions => "menuWithOptions", + } + } + + pub fn parse(s: &str) -> Option { + CommandClick::ALL.into_iter().find(|c| c.as_str().eq_ignore_ascii_case(s.trim())) + } +} + /// The interface's own preferences (the drafting ones are engine settings). #[derive(Clone, Copy, Debug, PartialEq)] pub struct UiOptions { @@ -68,8 +131,16 @@ pub struct UiOptions { /// The selection highlight colour; `None` keeps the theme's. pub selection_color: Option, /// While a command runs: a quick right-click is Enter and a held one opens the shortcut menu - /// (AutoCAD's time-sensitive right-click). Off: a right-click always opens the menu. + /// (AutoCAD's time-sensitive right-click). Off: [`Self::right_click_command`] decides. pub time_sensitive_right_click: bool, + /// How long the right button is held to open the menu while a command runs, in milliseconds. + pub right_click_hold_ms: u32, + /// A right-click with no command running and nothing selected (Default mode) or a selection + /// (Edit mode). + pub right_click_default: IdleClick, + pub right_click_edit: IdleClick, + /// A right-click while a command runs, with the time-sensitive right-click off. + pub right_click_command: CommandClick, /// The size of every menu, palette, dialog and the command line (1: the system's own). pub interface_scale: f32, } @@ -82,6 +153,10 @@ impl Default for UiOptions { snap_marker_size: theme::SNAP_MARKER, selection_color: None, time_sensitive_right_click: true, + right_click_hold_ms: (crate::context_menu::HOLD_SECS * 1000.0) as u32, + right_click_default: IdleClick::Menu, + right_click_edit: IdleClick::Menu, + right_click_command: CommandClick::Menu, interface_scale: 1.0, } } @@ -148,6 +223,10 @@ struct UiChanges { savetime: Option, savefilepath: Option, time_sensitive_right_click: Option, + right_click_hold_ms: Option, + right_click_default: Option, + right_click_edit: Option, + right_click_command: Option, interface_scale: Option, } @@ -191,6 +270,17 @@ fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result { c.save_version = Some(crate::SaveVersion::parse(name.trim()).ok_or("saveVersion must be 2000, 2004, 2007, 2010, 2013 or 2018")?); } "timeSensitiveRightClick" => c.time_sensitive_right_click = Some(v.as_bool().ok_or("timeSensitiveRightClick must be true or false")?), + "rightClickDuration" => { + let (lo, hi) = (f64::from(*RIGHT_CLICK_DURATIONS.start()), f64::from(*RIGHT_CLICK_DURATIONS.end())); + let n = + v.as_f64().filter(|n| n.is_finite() && (lo..=hi).contains(n)).ok_or("rightClickDuration must be from 100 to 2000 milliseconds")?; + c.right_click_hold_ms = Some(n.round() as u32); + } + "rightClickDefault" => c.right_click_default = Some(IdleClick::parse(text()?).ok_or("rightClickDefault must be menu or repeat")?), + "rightClickEdit" => c.right_click_edit = Some(IdleClick::parse(text()?).ok_or("rightClickEdit must be menu or repeat")?), + "rightClickCommand" => { + c.right_click_command = Some(CommandClick::parse(text()?).ok_or("rightClickCommand must be menu, enter or menuWithOptions")?) + } k if k.eq_ignore_ascii_case("SAVETIME") => { let max = cadcraft_engine::autosave::MAX_SAVETIME; let n = v @@ -227,6 +317,10 @@ fn ui_json(app: &CadApp) -> Map { m.insert("SAVETIME".into(), json!(cadcraft_engine::autosave::savetime())); m.insert("SAVEFILEPATH".into(), json!(cadcraft_engine::autosave::savefilepath())); m.insert("timeSensitiveRightClick".into(), json!(o.time_sensitive_right_click)); + m.insert("rightClickDuration".into(), json!(o.right_click_hold_ms)); + m.insert("rightClickDefault".into(), json!(o.right_click_default.as_str())); + m.insert("rightClickEdit".into(), json!(o.right_click_edit.as_str())); + m.insert("rightClickCommand".into(), json!(o.right_click_command.as_str())); m } @@ -300,9 +394,26 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result { if let Some(b) = ui.time_sensitive_right_click { app.options.time_sensitive_right_click = b; } + apply_right_click(&mut app.options, &ui); Ok(report(app)) } +/// Right-Click Customization's settings (the time-sensitive switch aside) from `c`. +fn apply_right_click(o: &mut UiOptions, c: &UiChanges) { + if let Some(ms) = c.right_click_hold_ms { + o.right_click_hold_ms = ms; + } + if let Some(m) = c.right_click_default { + o.right_click_default = m; + } + if let Some(m) = c.right_click_edit { + o.right_click_edit = m; + } + if let Some(m) = c.right_click_command { + o.right_click_command = m; + } +} + /// The interface preferences back to their defaults (the interface language stays). fn reset_ui(app: &mut CadApp) { let d = crate::UiState::default(); @@ -330,6 +441,10 @@ impl CadApp { "selectionColor": color_json(self.options.selection_color), "snapMarkerSize": self.options.snap_marker_size, "timeSensitiveRightClick": self.options.time_sensitive_right_click, + "rightClickDuration": self.options.right_click_hold_ms, + "rightClickDefault": self.options.right_click_default.as_str(), + "rightClickEdit": self.options.right_click_edit.as_str(), + "rightClickCommand": self.options.right_click_command.as_str(), "interfaceScale": self.options.interface_scale, }) .to_string() @@ -346,9 +461,19 @@ impl CadApp { cadcraft_engine::cmd::options::restore(&mut self.session, vars); } let mut c = UiChanges::default(); - for key in - ["systemCursor", "modelBackground", "paperBackground", "selectionColor", "snapMarkerSize", "timeSensitiveRightClick", "interfaceScale"] - { + for key in [ + "systemCursor", + "modelBackground", + "paperBackground", + "selectionColor", + "snapMarkerSize", + "timeSensitiveRightClick", + "rightClickDuration", + "rightClickDefault", + "rightClickEdit", + "rightClickCommand", + "interfaceScale", + ] { if let Some(value) = v.get(key) { let _ = parse_ui(key, value, &mut c); } @@ -372,6 +497,7 @@ impl CadApp { if let Some(b) = c.time_sensitive_right_click { self.options.time_sensitive_right_click = b; } + apply_right_click(&mut self.options, &c); if let Some(n) = c.interface_scale { self.options.interface_scale = n; } @@ -391,4 +517,16 @@ mod tests { assert_eq!(parse_hex(bad), None, "{bad}"); } } + + #[test] + fn idle_and_command_clicks_parse_their_names() { + for c in IdleClick::ALL { + assert_eq!(IdleClick::parse(c.as_str()), Some(c)); + } + for c in CommandClick::ALL { + assert_eq!(CommandClick::parse(c.as_str()), Some(c)); + } + assert_eq!(IdleClick::parse("enter"), None); + assert_eq!(CommandClick::parse("repeat"), None); + } } diff --git a/crates/ui-egui/src/options/dialog.rs b/crates/ui-egui/src/options/dialog.rs index 93f051fd9..8f74fbefd 100644 --- a/crates/ui-egui/src/options/dialog.rs +++ b/crates/ui-egui/src/options/dialog.rs @@ -526,8 +526,9 @@ fn aci_row(ui: &mut egui::Ui, current: u8, key: &str, changes: &mut Map) { + let mut right_click = ui.ctx().data(|d| d.get_temp::(egui::Id::unique(RIGHT_CLICK)).unwrap_or(false)); grid(ui, "options_preferences", |ui| { let language_caption = ui.label(crate::tl!("Interface language")); let mut lang = app.ui.interface_language; @@ -560,6 +561,94 @@ fn preferences(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map changes.insert("timeSensitiveRightClick".into(), json!(timed)); } hint(ui, crate::tl!("Turned off, a right-click while a command runs always opens the shortcut menu.")); + if ui.button(crate::tl!("Right-Click Customization...")).clicked() { + right_click = true; + } + if right_click { + right_click_window(&app.options, ui.ctx(), &mut right_click, changes); + } + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique(RIGHT_CLICK), right_click)); +} + +/// Whether the Right-Click Customization window is open (egui temp data). +const RIGHT_CLICK: &str = "cc_options_right_click"; + +/// Right-Click Customization (Options ▸ User Preferences): the time-sensitive right-click and its +/// duration, and what a right-click does in Default, Edit and Command modes. Changes apply at +/// once, as on the Options tabs. +fn right_click_window(o: &super::UiOptions, ctx: &egui::Context, open: &mut bool, changes: &mut Map) { + use super::{CommandClick, IdleClick}; + let mut close = false; + egui::Window::new(crate::tl!("Right-Click Customization")) + .id(egui::Id::unique("cc_right_click")) + .open(open) + .resizable(false) + .collapsible(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.set_width(460.0); + let mut timed = o.time_sensitive_right_click; + if ui.checkbox(&mut timed, crate::tl!("Turn on time-sensitive right-click")).changed() { + changes.insert("timeSensitiveRightClick".into(), json!(timed)); + } + ui.add_enabled_ui(o.time_sensitive_right_click, |ui| { + ui.horizontal(|ui| { + ui.add_space(20.0); + let caption = ui.label(crate::tl!("Longer click duration:")); + let mut ms = o.right_click_hold_ms; + let range = super::RIGHT_CLICK_DURATIONS; + if ui.add(egui::DragValue::new(&mut ms).range(range).speed(10.0)).labelled_by(caption.id).changed() { + changes.insert("rightClickDuration".into(), json!(ms)); + } + ui.label(crate::tl!("milliseconds")); + }); + hint(ui, crate::tl!("While a command runs, a quick click is Enter and a longer click opens the shortcut menu.")); + }); + ui.add_space(6.0); + for (title, note, key, current) in [ + (crate::tl!("Default Mode"), crate::tl!("No objects selected and no command running:"), "rightClickDefault", o.right_click_default), + (crate::tl!("Edit Mode"), crate::tl!("Objects selected and no command running:"), "rightClickEdit", o.right_click_edit), + ] { + heading(ui, title); + ui.group(|ui| { + ui.set_width(ui.available_width()); + hint(ui, note); + for (choice, label) in [(IdleClick::Repeat, crate::tl!("Repeat last command")), (IdleClick::Menu, crate::tl!("Shortcut Menu"))] { + if ui.radio(current == choice, label).clicked() && current != choice { + changes.insert(key.into(), json!(choice.as_str())); + } + } + }); + } + ui.add_enabled_ui(!o.time_sensitive_right_click, |ui| { + heading(ui, crate::tl!("Command Mode")); + ui.group(|ui| { + ui.set_width(ui.available_width()); + hint(ui, crate::tl!("While a command runs:")); + for (choice, label) in [ + (CommandClick::Enter, crate::tl!("ENTER")), + (CommandClick::Menu, crate::tl!("Shortcut Menu: always enabled")), + (CommandClick::MenuWithOptions, crate::tl!("Shortcut Menu: enabled when command options are present")), + ] { + if ui.radio(o.right_click_command == choice, label).clicked() && o.right_click_command != choice { + changes.insert("rightClickCommand".into(), json!(choice.as_str())); + } + } + }); + }); + ui.separator(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Close")).clicked() { + close = true; + } + }); + }); + }); + if close { + *open = false; + } } fn profiles(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map) { diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c32012e1a..98cc925e4 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -22,6 +22,7 @@ mod named_viewports_dialog; mod native_menu_text_keys; mod native_windows; mod options_dialog; +mod options_right_click; mod parameters_rename; mod pickdrag; mod properties_units; diff --git a/crates/ui-egui/tests/it/options_right_click.rs b/crates/ui-egui/tests/it/options_right_click.rs new file mode 100644 index 000000000..f12de22c8 --- /dev/null +++ b/crates/ui-egui/tests/it/options_right_click.rs @@ -0,0 +1,210 @@ +//! Options ▸ User Preferences ▸ Right-Click Customization: the time-sensitive right-click's +//! duration, and what a right-click does with nothing selected (Default mode), with a selection +//! (Edit mode) and while a command runs (Command mode), through the OPTIONS JSON form, the +//! drawing area and the dialog. + +use cadcraft_engine::Session; +use cadcraft_ui_egui::options::{CommandClick, IdleClick}; +use cadcraft_ui_egui::{CadApp, Services, menus}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn app() -> CadApp { + CadApp::new(Session::new(), Services::default()) +} + +/// One frame at `time` (seconds) with `events`; returns the painted text. +fn frame(app: &mut CadApp, ctx: &egui::Context, events: Vec, time: f64) -> String { + fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(s) => { + text.push_str(s.galley.text()); + text.push('\n'); + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, text)), + _ => {} + } + } + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + time: Some(time), + events, + ..Default::default() + }; + app.logic(ctx); + let mut out = ctx.run_ui(input, |ui| app.ui(ui)); + out.textures_delta.clear(); + let mut text = String::new(); + out.shapes.iter().for_each(|s| collect(&s.shape, &mut text)); + text +} + +const AT: egui::Pos2 = egui::pos2(800.0, 500.0); + +fn button(pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: AT, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE } +} + +/// A right-click on the drawing area from `t` held for `held` seconds; returns the text painted +/// just after. +fn right_click(app: &mut CadApp, ctx: &egui::Context, t: f64, held: f64) -> String { + frame(app, ctx, vec![egui::Event::PointerMoved(AT)], t); + frame(app, ctx, vec![button(true)], t + 0.01); + frame(app, ctx, vec![button(false)], t + 0.01 + held); + frame(app, ctx, Vec::new(), t + 0.05 + held) +} + +#[test] +fn right_click_settings_are_checked_and_survive_a_restart() { + let mut a = app(); + let all = a.run("options", json!({})).unwrap(); + assert_eq!( + (all["rightClickDuration"].clone(), all["rightClickDefault"].clone(), all["rightClickEdit"].clone(), all["rightClickCommand"].clone()), + (json!(250), json!("menu"), json!("menu"), json!("menu")) + ); + let r = a + .run( + "options", + json!({"rightClickDuration": 400, "rightClickDefault": "repeat", "rightClickEdit": "Repeat", "rightClickCommand": "menuWithOptions"}), + ) + .unwrap(); + assert_eq!((r["rightClickDuration"].clone(), r["rightClickEdit"].clone()), (json!(400), json!("repeat"))); + assert_eq!(a.options.right_click_command, CommandClick::MenuWithOptions); + + let before = a.run("options", json!({})).unwrap(); + for bad in [ + json!({"rightClickDuration": 50}), + json!({"rightClickDuration": 2001}), + json!({"rightClickDuration": f64::NAN}), + json!({"rightClickDuration": "long"}), + json!({"rightClickDefault": "enter"}), + json!({"rightClickEdit": 1}), + json!({"rightClickCommand": "repeat", "PICKBOX": 9}), + ] { + assert!(a.run("options", bad.clone()).is_err(), "{bad}"); + assert_eq!(a.run("options", json!({})).unwrap(), before, "{bad} changed nothing"); + } + + let mut b = app(); + b.load_profile(&a.profile_json()); + assert_eq!(b.options, a.options); + let mut c = app(); + c.load_profile(r#"{"rightClickDuration": 99999, "rightClickDefault": "fly", "rightClickCommand": null}"#); + assert_eq!(c.options, app().options, "hostile saved values are skipped"); + let r = a.run("options", json!({"reset": true})).unwrap(); + assert_eq!((r["rightClickDuration"].clone(), r["rightClickDefault"].clone()), (json!(250), json!("menu"))); +} + +#[test] +fn an_idle_right_click_can_repeat_the_last_command() { + let mut a = app(); + a.run("options", json!({"rightClickDefault": "repeat"})).unwrap(); + a.cmdline("circle 0,0 5"); + assert!(!a.session.prompting()); + let ctx = egui::Context::default(); + frame(&mut a, &ctx, Vec::new(), 0.0); + right_click(&mut a, &ctx, 0.1, 0.05); + assert!(a.session.prompting(), "CIRCLE runs again: {}", a.session.prompt_text()); + a.cmdline("10,10 2"); + + // With a selection, Edit mode decides: the menu (its default) opens instead. + a.run("selectall", json!({})).unwrap(); + assert!(!a.session.selection().is_empty()); + let text = right_click(&mut a, &ctx, 1.0, 0.05); + assert!(!a.session.prompting(), "no command started: {}", a.session.prompt_text()); + assert!(text.contains("Erase"), "the shortcut menu opens:\n{text}"); +} + +#[test] +fn command_mode_and_click_duration_decide_enter_or_the_menu() { + let ctx = egui::Context::default(); + + // A longer duration: a 0.5 s click is still Enter. + let mut a = app(); + a.run("options", json!({"rightClickDuration": 1000})).unwrap(); + frame(&mut a, &ctx, Vec::new(), 0.0); + a.cmdline("LINE 0,0 10,0"); + right_click(&mut a, &ctx, 0.1, 0.5); + assert!(a.session.running.is_none(), "a click shorter than the duration is Enter: {}", a.session.prompt_text()); + + // Time-sensitive off, Command mode Enter: every right-click is Enter. + let ctx = egui::Context::default(); + let mut a = app(); + a.run("options", json!({"timeSensitiveRightClick": false, "rightClickCommand": "enter"})).unwrap(); + frame(&mut a, &ctx, Vec::new(), 0.0); + a.cmdline("LINE 0,0 10,0"); + let text = right_click(&mut a, &ctx, 0.1, 0.6); + assert!(a.session.running.is_none(), "Enter ends LINE: {}", a.session.prompt_text()); + assert!(!text.contains("Snap Overrides"), "no menu:\n{text}"); + + // Command mode "enabled when command options are present": CIRCLE's first prompt has + // options, so the menu opens and the command keeps running. + a.run("options", json!({"rightClickCommand": "menuWithOptions"})).unwrap(); + a.cmdline("CIRCLE"); + let text = right_click(&mut a, &ctx, 2.0, 0.05); + assert!(text.contains("Cancel"), "the command menu opens:\n{text}"); + assert!(a.session.prompting(), "CIRCLE still runs"); +} + +/// With `CADCRAFT_OPTIONS_SHOTS` set to a folder, the dialog is rendered there for a look. +const SHOTS: &str = "CADCRAFT_OPTIONS_SHOTS"; + +fn harness(app: CadApp) -> Harness<'static, CadApp> { + let builder = Harness::builder().with_size(egui::vec2(1400.0, 900.0)); + let builder = if std::env::var_os(SHOTS).is_some() { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + h +} + +fn shot(h: &mut Harness<'static, CadApp>, name: &str) { + if let Some(dir) = std::env::var_os(SHOTS).map(std::path::PathBuf::from) { + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join(name)).unwrap(); + } +} + +#[test] +fn the_customization_window_sets_every_mode() { + let mut a = app(); + menus::activate(&mut a, "options"); + a.ui.dialog = Some("options:preferences".into()); + let mut h = harness(a); + h.get_by_label("Right-Click Customization...").click(); + h.run_steps(3); + h.get_by_label("Longer click duration:"); + shot(&mut h, "options-right-click.png"); + + // Default mode's "Repeat last command" comes first, Edit mode's second. + if let Some(n) = h.get_all_by_label("Repeat last command").next() { + n.click(); + } + h.run_steps(3); + assert_eq!(h.state().options.right_click_default, IdleClick::Repeat); + assert_eq!(h.state().options.right_click_edit, IdleClick::Menu); + + // Command mode applies once the time-sensitive right-click is off. + h.get_by_label("Turn on time-sensitive right-click").click(); + h.run_steps(3); + assert!(!h.state().options.time_sensitive_right_click); + h.get_by_label("Shortcut Menu: enabled when command options are present").click(); + h.run_steps(3); + assert_eq!(h.state().options.right_click_command, CommandClick::MenuWithOptions); + + let unnamed = h.unnamed_widgets(); + assert!(unnamed.is_empty(), "unnamed controls: {unnamed:?}"); + // The window's Close comes after the Options dialog's in the tree. + if let Some(n) = h.get_all_by_label("Close").last() { + n.click(); + } + h.run_steps(3); + assert!(h.query_by_label("Longer click duration:").is_none()); + assert_eq!(h.state().ui.dialog.as_deref(), Some("options:preferences")); +} diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..0299d9651 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (Right-Click Customization: F20 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -41,7 +41,7 @@ do them first. | F16 | Groups: no group bounding box or single grip when a group is selected (GROUPDISPLAYMODE), copying a whole group does not make a new group, no Object Grouping dialog (GROUP, GROUPEDIT, UNGROUP, -GROUP, PICKSTYLE group selection and the DXF/DWG round trip landed, #417); PICKSTYLE's associative-hatch bit is stored but unused | `cmd/groups.rs` | Low | 2–4 | | F17 | Attributes (ATTSYNC, global -ATTEDIT, BATTMAN editing and DATAEXTRACTION/EATTEXT landed, #433): no verify, preset or lock-position modes, and multiline attributes (read, drawn and saved since 2026-10-12) can't be created or switched in BATTMAN; data extraction covers block references and attribute values (CSV or a table) only — no wizard, nested blocks, other objects' properties, `.dxe` templates or spreadsheet output | `cmd/blocks/battman.rs`, `cmd/blocks/extract.rs` | Low | 4–6 | | F19 | MATCHPROP Settings is a keyword prompt (no dialog) and has no material, shadow or centre-object settings; TEXTTOFRONT and HATCHTOBACK act on the current space only; OVERKILL doesn't compare polyline segments with other objects (picker and Settings, DRAWORDER Above/Under, TEXTTOFRONT, HATCHTOBACK, OVERKILL tolerance/ignore/overlap/end-to-end options landed, #439) | `props/matchprop.rs`, `draworder.rs`, `overkill.rs` | Low | 2–4 | -| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts. Left: right-click customization, the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export | `ui-egui/src/options/` | Low | 2–4 | +| F20 | OPTIONS dialog done (#23): Display, Open and Save, Drafting, Selection, User Preferences and Profiles tabs, and the user profile (object snap modes, drafting toggles, Dynamic Input, PICKBOX, APERTURE, GRIPSIZE, CURSORSIZE, PICKFIRST, PICKADD, QPMODE, model and paper background, snap marker size, system cursor) survives restarts; User Preferences ▸ Right-Click Customization... (the time-sensitive right-click's duration; Default, Edit and Command modes). Left: the autosave interval and default save version on Open and Save (the features themselves landed, #406, #421), AutoSnap magnet and tooltip toggles, colours of the other drawing-area elements, named profiles with import and export | `ui-egui/src/options/` | Low | 2–4 | | F21 | MLINE, REGION and HELIX are objects since #510, with gaps: MLEDIT tees trim square; UNION/SUBTRACT/INTERSECT only combine regions whose boundaries don't meet; regions are saved as closed polylines (no ACIS data) | `draw2/mline.rs`, `inquiry/regions.rs`, `dxf_region.rs` | Low | 6–10 | | F22 | Inquiry leftovers (COUNT across spaces and nested blocks, the QuickCalc palette and COMPARE landed, #563; MASSPROP on regions, #510): COMPARE compares the tab shown, not every layout at once (COMPAREEXPORT, the comparison as a new drawing, landed); COMPAREEXPORT puts the two sets of objects in model-space groups, where AutoCAD puts them in blocks; QuickCalc keeps its history and variables for the session only | `file/compare.rs`, `palettes/quickcalc.rs` | Low | 3–5 | | F23 | No Sheet Set Manager, eTransmit, Share, Traces, Markup Import, Activity Insights | menu items uncovered | Low-medium (team workflows) | 40–70 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Options ▸ User Preferences ▸ Right-Click Customization...: the time-sensitive right-click's duration (`rightClickDuration`), a right-click with nothing or something selected that repeats the last command (`rightClickDefault`, `rightClickEdit`), and Command mode with the time-sensitive right-click off (`rightClickCommand`: menu, Enter, or the menu only when the prompt has options), kept in the profile: F20 narrowed | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c06e8f242..929f0f5c0 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (distinct polyline midpoint grips) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (Right-Click Customization) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How CADCraft's interaction compares with AutoCAD's: point entry, object snaps, tracking, dynamic input, grips, selection, the command line, chrome and navigation. A drafter's speed in AutoCAD @@ -166,7 +166,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | ViewCube | interactive 3D | clickable for 2D (Top/Home → extents); dragging does nothing (#7) | | Navigation bar, SteeringWheels | yes | no | | Workspaces | Drafting & Annotation, 3D Modeling | no | -| Options / Preferences dialog | many tabs | **no** (issue #23) | +| Options / Preferences dialog | many tabs | yes (#23): Display, Open and Save, Drafting, Selection (with Visual Effect Settings), User Preferences (with Right-Click Customization) and Profiles tabs; changes apply at once and are kept in the profile | | Customisation (CUI, aliases editor, tool palettes) | yes | Command Aliases dialog (ALIASEDIT, #1381); no CUI or tool palettes | | Themes | Dark, Light | Dark, Light, System (#179) | | Accessibility | VoiceOver basics | AccessKit through eframe; screen-reader coverage untested; magnifier issue #39; animation effects follow the OS setting (View ▸ Accessibility ▸ Animation Effects: System, On, Off) | @@ -190,7 +190,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. shortcuts. AutoCAD for Mac's defaults are similar in number; F4 (3D osnap) and F6 (dynamic UCS) are missing. - Delete erases the selection on macOS (#64); Escape cancels. -- Right-click on the canvas is Enter while a command runs; holding it (250 ms, AutoCAD's +- Right-click on the canvas is Enter while a command runs; holding it (250 ms by default, AutoCAD's time-sensitive right-click) opens the command menu: Enter, Cancel, Recent Input, the prompt's options, Snap Overrides, Pan/Zoom. Otherwise it opens a shortcut menu (Repeat, Recent Commands, Clipboard ▸, Isolate ▸, the selection's editing commands, Draw Order ▸, Group, the selected @@ -198,11 +198,16 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. The command line, drawing tabs, layout tabs, Layers palette rows and the Properties palette have menus too (#512). Still missing: in-place layout tab rename, Move or Copy, Select All Layouts. +- Options ▸ User Preferences ▸ Right-Click Customization sets the hold time, what a right-click + does with nothing or something selected (the menu, or repeat the last command) and, with the + time-sensitive right-click off, while a command runs (Enter, the menu, or the menu only when + the prompt has options). ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Options ▸ User Preferences ▸ Right-Click Customization...: the time-sensitive right-click's duration, Default and Edit modes (shortcut menu or repeat the last command) and Command mode (Enter, the menu, or the menu only when the prompt has options), set through OPTIONS and kept in the profile | | 2026-10-22 | minor | Polyline segment midpoint grips use rectangles, distinct from square vertex grips, with matching hover and pick bounds (#1950) | | 2026-10-13 | minor | Filled-region highlight boundaries are traversed in deterministic coordinate order, fixing dash-phase jumps on CPU hover/selection redraws and GPU highlight rebuilds; CPU dash-position, pixel and GPU mesh regressions | | 2026-10-14 | minor | Selection cycling (#1143): the list and badge of SELECTIONCYCLING, Shift+Space through overlapping objects (#1145) | From b600293cfa7388b93efa52fa0718cf56d70bd603 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 22:42:36 +0100 Subject: [PATCH 073/531] arrays: the Key point option of a base point (F5) ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and REPlace) offered Key point but only said it was not available. It now asks for a key point on the source (or replacement) objects and takes their key point nearest the pick (an end point, midpoint, centre, quadrant, vertex or insertion point) as the base point; in ARRAYEDIT the source objects are searched as placed at the item picked. The JSON forms take `keyPoint`. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/array.rs | 71 ++++++++-- crates/engine/src/cmd/array/edit.rs | 49 ++++++- crates/engine/tests/it/array_key_point.rs | 155 ++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + docs/gaps.md | 5 +- docs/target-app-parity.md | 5 +- 6 files changed, 264 insertions(+), 22 deletions(-) create mode 100644 crates/engine/tests/it/array_key_point.rs diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 479b7873a..dbc845d57 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -25,6 +25,10 @@ mod edit; /// Most preview entities drawn while the array is edited. const PREVIEW_LIMIT: usize = 2000; +/// Most objects whose key points are searched for a Key point base point. +const MAX_KEY_OBJECTS: usize = 10_000; +/// The prompt after the Key point option of a base point. +const KEY_POINT_PROMPT: &str = "Specify key point on source objects to use as base point"; /// Keyword-only prompts: each typed token is matched on its own (no free text). const KEYWORDS: Accept = Accept { point: false, number: false, text: false, select: false, enter: true }; @@ -39,13 +43,13 @@ pub fn specs() -> Vec { CommandSpec::new("arrayrect", "Rectangular Array", run_arrayrect) .menu(&["Modify", "Array", "Rectangular Array"]) .params( - "{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", + "{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", ) .interactive(|_| Ok(Box::new(RectM::default()))), CommandSpec::new("arraypolar", "Polar Array", run_arraypolar) .menu(&["Modify", "Array", "Polar Array"]) .params( - "{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", + "{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}", ) .interactive(|_| Ok(Box::new(PolarM::default()))), ] @@ -219,6 +223,32 @@ fn bounds(d: &Drawing, hs: &[Handle]) -> Bounds2 { } /// The centre of the first object (the point a non-rotated polar copy is moved by). +/// The key point of `ents`, placed by `m`, nearest `at`: one of their grips (end points, +/// midpoints, centres, vertices, insertion points). `None` when they have none. +pub(crate) fn nearest_key_point<'a>(ents: impl Iterator, m: &Mat3, at: Vec2) -> Option { + if !at.is_finite() { + return None; + } + let mut best: Option<(Vec2, f64)> = None; + for e in ents.take(MAX_KEY_OBJECTS) { + let mut k = e.kind.clone(); + k.transform(m); + for g in k.grips().into_iter().filter(|g| g.is_finite()) { + let d = g.dist(at); + if best.is_none_or(|(_, bd)| d < bd) { + best = Some((g, d)); + } + } + } + best.map(|b| b.0) +} + +/// The key point of objects `hs` in the drawing nearest `at`. +pub(crate) fn key_point_of(d: &Drawing, hs: &[Handle], at: Vec2) -> Result { + nearest_key_point(hs.iter().filter_map(|h| d.entity(*h)).map(|e| &**e), &Mat3::IDENTITY, at) + .ok_or_else(|| other("The objects have no key point; specify a point.")) +} + fn first_center(d: &Drawing, hs: &[Handle]) -> Option { hs.first().and_then(|h| d.entity(*h)).map(|e| cadcraft_doc::entity_bounds(d, e, 0).center()).filter(|c| c.is_finite()) } @@ -348,9 +378,10 @@ fn run_arrayrect(s: &mut Session, p: &Value) -> Result { row_elevation: f64_or(p, "rowElevation", 0.0), }); let rs = f64_or(p, "rowSpacing", 1.0); - let base = match point_param(p, "base") { - Some(b) => b, - None => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(), + let base = match (point_param(p, "keyPoint"), point_param(p, "base")) { + (Some(k), _) => key_point_of(s.doc()?, &hs, k)?, + (None, Some(b)) => b, + (None, None) => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(), }; let p2 = params(kind, levels, f64_or(p, "levelSpacing", rs)); let associative = bool_or(p, "associative", assoc_default(s)); @@ -364,7 +395,10 @@ fn run_arraypolar(s: &mut Session, p: &Value) -> Result { let rows = count_or(p, "rows", 1); let levels = count_or(p, "levels", 1); check_size(s, n.saturating_mul(rows).saturating_mul(levels), hs.len())?; - let base = point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c); + let base = match point_param(p, "keyPoint") { + Some(k) => key_point_of(s.doc()?, &hs, k)?, + None => point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c), + }; let row_spacing = f64_or(p, "rowSpacing", 1.0); let kind = ArrayKind::Polar(PolarArray { center: c - base, @@ -461,6 +495,8 @@ enum RStage { Main, Assoc, Base, + /// Base point: Key point (a grip of the source objects). + BaseKey, /// COUnt: columns, then rows. CountCols, CountRows, @@ -621,6 +657,7 @@ impl Interactive for RectM { .default("eXit"), Assoc => assoc_prompt(self.assoc), Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"), + BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT), CountCols | ColsCount => cols(), CountRows | RowsCount => rows(), SpaceCols => dist("Specify the distance between columns", self.cs).kw(&["Unit cell"]), @@ -670,10 +707,12 @@ impl Interactive for RectM { self.base = self.centroid; Main } - (Base, Input::Keyword(_)) => { - s.echo("Key points are not available yet; specify a point."); - Base + (Base, Input::Keyword(_)) => BaseKey, + (BaseKey, Input::Point(p)) => { + self.base = key_point_of(s.doc()?, &self.objs, *p)?; + Main } + (BaseKey, Input::Enter) => Base, (CountCols | ColsCount, _) => match count(&i, self.cols, max_count(s, self.rows.saturating_mul(self.levels), n))? { Some(c) => { self.cols = c; @@ -816,6 +855,9 @@ enum PStage { Main, Assoc, Base, + /// Key point of the base point asked from the center prompt, or from the main prompt. + CenterBaseKey, + BaseKey, Items, Between, Fill, @@ -992,6 +1034,7 @@ impl Interactive for PolarM { match self.stage { Center => Prompt::new("Specify center point of array", Accept::POINT).kw(&["Base point", "Axis of rotation"]), CenterBase | Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"), + CenterBaseKey | BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT), Main => Prompt::new("Select grip to edit array", Accept::POINT) .kw(&["ASsociative", "Base point", "Items", "Angle between", "Fill angle", "ROWs", "Levels", "ROTate items", "eXit"]) .default("eXit"), @@ -1050,10 +1093,14 @@ impl Interactive for PolarM { self.base = None; if stage == CenterBase { Center } else { Main } } - (CenterBase | Base, Input::Keyword(_)) => { - s.echo("Key points are not available yet; specify a point."); - stage + (CenterBase, Input::Keyword(_)) => CenterBaseKey, + (Base, Input::Keyword(_)) => BaseKey, + (CenterBaseKey | BaseKey, Input::Point(p)) => { + self.base = Some(key_point_of(s.doc()?, &self.objs, *p)?); + if stage == CenterBaseKey { Center } else { Main } } + (CenterBaseKey, Input::Enter) => CenterBase, + (BaseKey, Input::Enter) => Base, (Items, _) => match count(&i, self.items, max_count(s, self.rows.saturating_mul(self.levels), n))? { Some(c) => { self.items = c; diff --git a/crates/engine/src/cmd/array/edit.rs b/crates/engine/src/cmd/array/edit.rs index 21bf6b132..1708aeb21 100644 --- a/crates/engine/src/cmd/array/edit.rs +++ b/crates/engine/src/cmd/array/edit.rs @@ -18,7 +18,7 @@ use super::super::helpers::v3; use super::super::machines::{SelOutcome, SelectPhase, number}; use super::super::{CommandSpec, bad, bool_or, point_param, targets}; -use super::{KEYWORDS, angle, check_size, count, fmt, nesting, other, yes, yes_no}; +use super::{KEY_POINT_PROMPT, KEYWORDS, angle, check_size, count, fmt, key_point_of, nearest_key_point, nesting, other, yes, yes_no}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; pub(super) fn specs() -> Vec { @@ -26,7 +26,7 @@ pub(super) fn specs() -> Vec { CommandSpec::new("arrayedit", "Edit Array", run_arrayedit) .menu(&["Modify", "Object", "Array"]) .params( - "{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}", + "{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, keyPoint? ([x, y]: the new base point is the source objects' key point nearest it, on the item there), replace?.keyPoint? ([x, y]: the replacement objects' key point nearest it is their base point), source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}", ) .interactive(|_| Ok(Box::new(EditM::default()))), CommandSpec::new("arrayclose", "Close Array Editing", run_arrayclose) @@ -214,6 +214,16 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32) best.map(|b| b.0) } +/// ARRAYEDIT Key point: the key point of the source objects nearest `at`, with the objects as +/// placed at the item under `at` (within `tol`). +fn source_key_point(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Result { + let item = item_at(d, h, at, tol).ok_or_else(|| other("No array item there; specify a point on an item of the array."))?; + let (ins, blk, p) = array_of(d, h)?; + let src = d.block(&p.source).ok_or_else(|| other("The array's source block is missing."))?; + let m = ins.transform(blk.base.xy()).then_before(item_place(&p, item)?).then_before(Mat3::translate(-src.base.xy())); + nearest_key_point(src.entities.iter().map(|e| e.as_ref()), &m, at).ok_or_else(|| other("The source objects have no key point; specify a point.")) +} + /// Move the base point of array `h` to world point `base` without moving the items. fn rebase(s: &mut Session, h: Handle, base: Vec2) -> Result<()> { let d = s.doc()?; @@ -342,6 +352,9 @@ fn close_source(s: &mut Session, save: bool) -> Result { // ---------------- JSON ---------------- +/// How far outside an item's extents a JSON `keyPoint` may be. +const KEY_POINT_TOLERANCE: f64 = 1e-6; + fn item_param(v: &Value) -> Option<(u32, u32, u32)> { let a = v.as_array()?; let n = |k: usize| a.get(k).and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok()); @@ -458,7 +471,10 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result { } if let Some(r) = p.get("replace").filter(|v| !v.is_null()) { let hs = targets(s, r)?; - let base = point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()); + let base = match point_param(r, "keyPoint") { + Some(k) => key_point_of(s.doc()?, &hs, k)?, + None => point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()), + }; let name = block_from(s, h, &hs, base)?; let (_, _, mut a) = array_of(s.doc()?, h)?; match r.get("items") { @@ -476,6 +492,10 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result { if let Some(b) = point_param(p, "base") { rebase(s, h, b)?; } + if let Some(k) = point_param(p, "keyPoint") { + let at = source_key_point(s.doc()?, h, k, KEY_POINT_TOLERANCE)?; + rebase(s, h, at)?; + } let (_, _, mut a) = array_of(s.doc()?, h)?; let before = a.clone(); apply_params(&mut a, p, &to_local)?; @@ -506,6 +526,8 @@ enum Stage { Select, Main, Base, + /// Base point: Key point (of the source objects). + BaseKey, ColsCount, ColsSpace, ColsTotal, @@ -523,6 +545,8 @@ enum Stage { /// REPlace: objects, their base point, then the items to replace. RepSelect, RepBase, + /// REPlace base point: Key point (of the replacement objects). + RepKey, RepItems, /// Source: the item whose objects are placed for editing. SourceItem, @@ -658,6 +682,7 @@ impl Interactive for EditM { .kw(&["Source", "REPlace", "Base point", "Rows", "Columns", "Levels", "RESet", "eXit"]) .default("eXit"), Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"), + BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT), ColsCount => Prompt::new("Enter the number of columns", Accept::NUMBER).default(cols.to_string()), ColsSpace => dist("Specify the distance between columns", cs).kw(&["Total"]), ColsTotal => dist("Specify the distance between the first and last column", total(cols, cs)), @@ -686,6 +711,7 @@ impl Interactive for EditM { Rotate => Prompt::new("Rotate arrayed items?", KEYWORDS).kw(&["Yes", "No"]).default(yes(polar.as_ref().is_none_or(|k| k.rotate))), RepSelect => Prompt::new("Select replacement objects", Accept::SELECT), RepBase => Prompt::new("Select base point of replacement objects", Accept::POINT).kw(&["Key point"]).default("centroid"), + RepKey => Prompt::new("Specify key point on replacement objects to use as base point", Accept::POINT), RepItems => Prompt::new("Select an item in array to replace", Accept::POINT).kw(&["Source objects"]), SourceItem => Prompt::new("Select item in array", Accept::POINT), } @@ -745,10 +771,21 @@ impl Interactive for EditM { } Main } - (Base | RepBase, Input::Keyword(_)) => { - s.echo("Key points are not available yet; specify a point."); - stage + (Base, Input::Keyword(_)) => BaseKey, + (RepBase, Input::Keyword(_)) => RepKey, + (BaseKey, Input::Point(p)) => { + let tol = s.pixel_size() * s.settings.pickbox; + let at = source_key_point(s.doc()?, h, *p, tol)?; + rebase(s, h, at)?; + Main } + (BaseKey, Input::Enter) => Base, + (RepKey, Input::Point(p)) => { + let base = key_point_of(s.doc()?, &self.rep_objs, *p)?; + self.rep_block = Some(block_from(s, h, &self.rep_objs.clone(), base)?); + RepItems + } + (RepKey, Input::Enter) => RepBase, (ColsCount | Items, _) => match count(&i, c64, self.max_for(s, r64.saturating_mul(l64)))? { Some(n) => { let n = super::count32(n); diff --git a/crates/engine/tests/it/array_key_point.rs b/crates/engine/tests/it/array_key_point.rs new file mode 100644 index 000000000..d903fd5a8 --- /dev/null +++ b/crates/engine/tests/it/array_key_point.rs @@ -0,0 +1,155 @@ +//! The Key point option of a base point: ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and +//! REPlace) take the source objects' key point (an end point, midpoint, centre…) nearest the +//! picked point as the base point; the JSON forms take `keyPoint`. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{ArrayKind, ArrayParams, EntityKind, Handle}; +use cadcraft_engine::geom::Vec2; +use serde_json::json; + +fn source_line(s: &mut Session) -> String { + let r = s.execute("line", &json!({"points": [[0, 0], [2, 1]]})).unwrap(); + r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string() +} + +fn handle(v: &serde_json::Value) -> Handle { + Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap() +} + +/// The array's insertion point (its base point) and parameters. +fn array(s: &Session, h: Handle) -> (Vec2, ArrayParams) { + let d = s.doc().unwrap(); + let e = d.entity(h).unwrap(); + let EntityKind::Insert(i) = &e.kind else { panic!("not an array") }; + (i.insert.xy(), d.array_params(e).unwrap()) +} + +fn only_array(s: &Session) -> Handle { + let d = s.doc().unwrap(); + let arrays: Vec = d.model.iter().filter(|e| d.array_params(e).is_some()).map(|e| e.handle).collect(); + assert_eq!(arrays.len(), 1); + arrays[0] +} + +fn typed(s: &mut Session, inputs: &[&str]) { + for t in inputs { + s.cmdline(t).unwrap(); + } +} + +#[test] +fn arrayrect_and_arraypolar_take_a_key_point_as_the_base_point() { + let mut s = Session::new(); + let l = source_line(&mut s); + let r = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "keyPoint": [1.9, 1.05]})).unwrap(); + assert!(array(&s, handle(&r)).0.near(Vec2::new(2.0, 1.0), 1e-9)); + let mut s = Session::new(); + let l = source_line(&mut s); + let r = s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "keyPoint": [1.1, 0.4]})).unwrap(); + assert!(array(&s, handle(&r)).0.near(Vec2::new(1.0, 0.5), 1e-9), "the line's midpoint"); +} + +#[test] +fn typed_key_points_at_arrayrect_and_arraypolar() { + let mut s = Session::new(); + source_line(&mut s); + typed(&mut s, &["arrayrect", "l", "", "b", "k", "1.9,0.95", "x"]); + assert!(array(&s, only_array(&s)).0.near(Vec2::new(2.0, 1.0), 1e-9)); + // Enter at the key point prompt goes back to the base point prompt. + let mut s = Session::new(); + source_line(&mut s); + typed(&mut s, &["arraypolar", "l", "", "b", "k"]); + assert!(s.current_prompt().unwrap().message.contains("key point")); + typed(&mut s, &[""]); + assert!(s.current_prompt().unwrap().message.contains("base point")); + typed(&mut s, &["k", "0.1,0.1", "-10,0", "x"]); + assert!(array(&s, only_array(&s)).0.near(Vec2::new(0.0, 0.0), 1e-9)); +} + +#[test] +fn arrayedit_moves_the_base_point_to_a_key_point_of_an_item() { + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + // Near the start of the third item: the base point goes to (10, 0), the items stay. + s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [10.2, 0.05]})).unwrap(); + let (at, p) = array(&s, h); + assert!(at.near(Vec2::new(10.0, 0.0), 1e-9), "{at:?}"); + assert!(matches!(p.kind, ArrayKind::Rect(r) if r.cols == 3 && r.col_spacing == 5.0)); + let items = s.execute("explode", &json!({"handles": [h.hex()]})).unwrap(); + assert!(items.to_string().len() > 2); + let d = s.doc().unwrap(); + let mut starts: Vec<(i64, i64)> = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) => Some(((l.a.x * 10.0).round() as i64, (l.a.y * 10.0).round() as i64)), + _ => None, + }) + .collect(); + starts.sort(); + assert_eq!(starts, [(0, 0), (50, 0), (100, 0)]); + // Not on an item: refused. + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [3.5, 40]})).is_err()); + assert!(array(&s, h).0.near(Vec2::ZERO, 1e-9)); + // Typed: Base point, Key point, a point on the second item near its end. + s.set_selection(vec![h]); + typed(&mut s, &["arrayedit", "b", "k", "6.9,0.9", "x"]); + assert!(array(&s, h).0.near(Vec2::new(7.0, 1.0), 1e-9)); +} + +#[test] +fn replacement_objects_take_a_key_point_as_their_base_point() { + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone(); + // The circle's right quadrant is the base point: on item 1 (at x = 5) its centre is at x = 4. + s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": [51.2, 50.1], "items": [[1, 0, 0]]}})).unwrap(); + s.execute("explode", &json!({"handles": [h.hex()]})).unwrap(); + let d = s.doc().unwrap(); + // The replaced item stays a reference to the replacement block. + let centres: Vec = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Insert(i) => d.block(&i.block).map(|b| (i.transform(b.base.xy()), b)), + _ => None, + }) + .flat_map(|(m, b)| { + b.entities + .iter() + .filter_map(move |e| match &e.kind { + EntityKind::Circle(c) => Some(m.apply(c.center.xy())), + _ => None, + }) + .collect::>() + }) + .collect(); + assert!(centres.iter().any(|c| c.near(Vec2::new(4.0, 0.0), 1e-9)), "{centres:?}"); +} + +#[test] +fn hostile_key_points_never_panic() { + let mut s = Session::new(); + let l = source_line(&mut s); + for kp in [json!(["a", 1]), json!([1e308, -1e308]), json!([]), json!("x"), json!(null)] { + let _ = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": kp})); + let _ = s.execute("arraypolar", &json!({"handles": [l], "center": [5, 5], "count": 3, "keyPoint": kp})); + } + let mut s = Session::new(); + let l = source_line(&mut s); + let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap()); + for kp in [json!([1e308, 1e308]), json!([-1e308, 0]), json!(["x"]), json!([0.5, 0.25])] { + let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": kp})); + let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [], "keyPoint": kp, "items": [[0, 0, 0]]}})); + } + // Typed key points far away or on nothing are refused without leaving the command broken. + s.set_selection(vec![h]); + typed(&mut s, &["arrayedit", "b", "k"]); + assert!(s.cmdline("1e300,1e300").is_err() || s.running.is_some()); + s.cancel(); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6..3964c7249 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,6 +4,7 @@ mod annotate_options; mod annotative; mod arc_ctrl_direction; mod array_commands; +mod array_key_point; mod assoc_array; mod attdisp_attsync; mod attedit_prompts; diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..974579942 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (Key point base points: F5 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -28,7 +28,7 @@ do them first. | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | | F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | -| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | +| F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click), levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | | F8 | TOLERANCE leftovers (feature control frames landed, #420: model, our own symbol drawing, DXF, command-line prompts, explode, grips): no Geometric Tolerance dialog, no LEADER/QLEADER tolerance annotation, no in-place editing of a frame's contents | `cmd/tolerance.rs` | Low-medium (mechanical) | 2–4 | | F10 | MLEADEREDIT (add/remove leader), MLEADERALIGN and MLEADERCOLLECT landed, but a multileader has one landing and one block (a collection keeps the other blocks as block references beside it; MLEADERALIGN has no Options-menu preview); MLEADERSTYLE has 5 fields (block content and spline/no-leader types are per command, not in the style; block content has no attributes) | `annotate.rs`, `cmd/mleader_content.rs`, `tables.rs:417` | Medium | 8–12 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | F5: the Key point option of a base point works in ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point, REPlace): the source (or replacement) objects' key point nearest the pick becomes the base point; JSON `keyPoint` | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b5407d60..6947678a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (array Key point base points; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -147,7 +147,7 @@ presence: an option that prints "not available yet" doesn't count. | Area | Weight | Parity | Remaining (Opus 5.5 h) | Evidence and main gaps | Doc | |---|---:|---:|---|---|---| | Draw (2D) | 13% | 60% | 15–25 | ARC 11/11 methods, CIRCLE 6/6, RECTANG all options plus a centre construction mode (#1127), REVCLOUD, WIPEOUT, XLINE; PLINE arc options and SPLINE options done (#397, #408); MLINE, REGION and HELIX are objects (#510); isometric drafting (#556) | [gaps](gaps.md#features) | -| Modify | 15% | 50% | 40–60 | TRIM/EXTEND, OFFSET, ROTATE, PEDIT and SPLINEDIT options done (#397, #558, #559); associative arrays with ARRAYEDIT (#448), no array grips; MATCHPROP picker and Settings (#439) | [gaps](gaps.md#features) | +| Modify | 15% | 50% | 40–60 | TRIM/EXTEND, OFFSET, ROTATE, PEDIT and SPLINEDIT options done (#397, #558, #559); associative arrays with ARRAYEDIT (#448) and Key point base points, no array grips; MATCHPROP picker and Settings (#439) | [gaps](gaps.md#features) | | Geometry precision | 10% | 40% | 70–110 | exact for lines/arcs/circles; ellipse and spline intersections, offsets, closest points tessellated; absolute tolerances; polyline offset doesn't recompute bulges | [geometry-parity](geometry-parity.md) | | Layers and properties | 7% | 70% | 10–15 | Layer Properties Manager with filters, states, VP overrides; QSELECT; Quick Properties; transparency; linetype manager thin; 19 linetypes of ~45 | [gaps](gaps.md#features) | | Dimensions | 9% | 45% | 25–35 | all core DIM types and associativity; style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT, QDIM modes (#507) and TOLERANCE (#420); no DIMSTYLE manager dialog or smart DIM | [gaps](gaps.md#features) | @@ -223,6 +223,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Modify row: array base points take a Key point of the source objects (ARRAYRECT, ARRAYPOLAR, ARRAYEDIT); parity percentages and hours not re-measured | | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | From 9c862c01ba259da22f5b43cdf8d69419e55e9ed6 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Wed, 28 Oct 2026 18:43:00 +1100 Subject: [PATCH 074/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a6250d5dc..1a1128509 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-28 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 297 / 491 items (60%)** · 442 registered commands. +**Menu breadth: 305 / 491 items (62%)** · 451 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 37 | 49% | +| View | 75 | 38 | 51% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -65,7 +65,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -80,15 +79,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -126,7 +120,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From 744e99cafd3401fd53521014cc90831093fda9c7 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Wed, 28 Oct 2026 18:50:56 +1100 Subject: [PATCH 075/531] lisp: entnext through block entities uses a cached successor index Replaces the per-call scan of every block (containment) and of the block's entities (successor) with a per-drawing hash map built once, invalidated when ENDBLK redefines a block. --- crates/engine/src/lisp.rs | 4 ++++ crates/engine/src/lisp/block_tests.rs | 19 +++++++++++++++ crates/engine/src/lisp/drawing.rs | 33 +++++++++++++++++++++++---- 3 files changed, 51 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index b3175c512..24afd4c32 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -56,6 +56,9 @@ pub struct Env { pub deleted: HashMap)>, /// Every entity's handle in creation order, for the drawing it was taken from (`entnext`). pub order: Option<(usize, Arc>)>, + /// Each block-definition entity's successor in its block (None for the last), for the drawing + /// it was taken from: `entnext`'s indexed lookup, which also tells whether a handle is a block's. + pub block_next: Option<(usize, Arc>>)>, /// `tblnext`'s place in each table. pub tblnext: HashMap, /// A block definition `entmake` has begun (a BLOCK list) and not yet ended (ENDBLK): the @@ -77,6 +80,7 @@ impl Default for Env { next_file: 1, deleted: HashMap::new(), order: None, + block_next: None, tblnext: HashMap::new(), pending_block: None, printed_at: None, diff --git a/crates/engine/src/lisp/block_tests.rs b/crates/engine/src/lisp/block_tests.rs index 6e85a22ef..1c7589410 100644 --- a/crates/engine/src/lisp/block_tests.rs +++ b/crates/engine/src/lisp/block_tests.rs @@ -234,3 +234,22 @@ fn a_definition_that_isnt_added_leaves_no_layer() { assert_eq!(ok(&mut s, ENDBLK), "\"EB\""); assert!(has(&s, "PARTS"), "the block's layer exists once it is added"); } + +/// entnext walks entmade block entities in order through the cached successor index, and a +/// redefinition (same drawing, same block name) is not served from the stale index. +#[test] +fn entnext_walks_entmade_blocks_and_sees_a_redefinition() { + let mut s = session(); + let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "EB"))) types nil) + (while e (setq types (cons (cdr (assoc 0 (entget e))) types) e (entnext e))) + (reverse types))"#; + for code in [BLOCK_EB, LINE, CIRCLE, ENDBLK] { + ok(&mut s, code); + } + assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")"); + assert_eq!(ok(&mut s, walk), "(\"LINE\" \"CIRCLE\")", "second walk from the cache"); + for code in [BLOCK_EB, CIRCLE, LINE, LINE, ENDBLK] { + ok(&mut s, code); + } + assert_eq!(ok(&mut s, walk), "(\"CIRCLE\" \"LINE\" \"LINE\")"); +} diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index e94fb8cc3..1d330532a 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -7,6 +7,7 @@ //! [`crate::cmd::file::entity_codec`]), so what `entget` shows is what a DXF file holds, except //! for angles, which are radians in a list and degrees in a file. +use std::collections::HashMap; use std::sync::{Arc, Mutex}; use cadcraft_doc::{Entity, Handle, Space}; @@ -461,6 +462,7 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value { } let name = b.name.clone(); d.blocks.insert(name.clone(), Arc::new(b)); + ctx.env.block_next = None; ctx.s.touch(); Value::str(&name) } @@ -545,6 +547,29 @@ fn handles_in_order(ctx: &mut Ctx<'_>) -> Arc> { v } +/// Every block-definition entity's successor within its block, cached per drawing like +/// [`handles_in_order`]: one pass over the blocks, then `entnext` is a hash lookup instead of a +/// scan of the block (and of every block, to find which holds the entity). +fn block_successors(ctx: &mut Ctx<'_>) -> Arc>> { + let Ok(st) = ctx.s.state() else { return Arc::default() }; + let key = Arc::as_ptr(&st.doc) as usize; + if let Some((k, v)) = &ctx.env.block_next + && *k == key + { + return v.clone(); + } + let mut m = HashMap::new(); + for b in st.doc.blocks.values() { + let mut it = b.entities.iter().map(|e| e.handle).peekable(); + while let Some(h) = it.next() { + m.insert(h, it.peek().copied()); + } + } + let m = Arc::new(m); + ctx.env.block_next = Some((key, m.clone())); + m +} + pub fn entlast(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 0, 0)?; Ok(Flow::Value(handles_in_order(ctx).last().map(|h| Value::Ename(*h)).unwrap_or_default())) @@ -555,12 +580,10 @@ pub fn entnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { // From an entity of a block definition: the next one in that block, nil after the last (#1700). if let Some(v) = a.first().filter(|v| !v.is_nil()) { let h = ename(v)?; - if let Ok(d) = ctx.s.doc() - && d.entity(h).is_none() - && let Some(b) = block_of(d, h) + if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none()) + && let Some(next) = block_successors(ctx).get(&h) { - let next = b.entities.iter().skip_while(|e| e.handle != h).nth(1).map(|e| Value::Ename(e.handle)); - return Ok(Flow::Value(next.unwrap_or_default())); + return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())); } } let order = handles_in_order(ctx); From 2cfd068c1f23389edead489bd148c9b9675d4918 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Wed, 28 Oct 2026 18:51:59 +1100 Subject: [PATCH 076/531] ui-egui: explicit imports in canvas/grid.rs (clippy wildcard_imports) --- crates/ui-egui/src/canvas/grid.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 6882e4a76..447b56ca1 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -1,5 +1,5 @@ use super::draw::clip_infinite; -use super::*; +use super::{Bounds2, CadApp, Shape, Stroke, Tokens, Vec2, Xf, pos2}; /// Grid spacing adapted to the zoom: multiply the unit until lines are at least `min_px` apart. fn adaptive(unit: f64, scale: f64, min_px: f64) -> f64 { From a3b81b6ac2c9e262cd233c0aff7b513d76215e3c Mon Sep 17 00:00:00 2001 From: SBaksa Date: Wed, 28 Oct 2026 18:58:54 +1100 Subject: [PATCH 077/531] ui-egui: drop unused imports in canvas/grid.rs --- crates/ui-egui/src/canvas/grid.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 447b56ca1..637debb79 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -1,5 +1,5 @@ use super::draw::clip_infinite; -use super::{Bounds2, CadApp, Shape, Stroke, Tokens, Vec2, Xf, pos2}; +use super::{CadApp, Shape, Stroke, Tokens, Vec2, Xf}; /// Grid spacing adapted to the zoom: multiply the unit until lines are at least `min_px` apart. fn adaptive(unit: f64, scale: f64, min_px: f64) -> f64 { From 9938d5aa0e2b267d133262207a8388db72c3a5df Mon Sep 17 00:00:00 2001 From: SBaksa Date: Wed, 28 Oct 2026 19:04:30 +1100 Subject: [PATCH 078/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a6250d5dc..1a1128509 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-28 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 297 / 491 items (60%)** · 442 registered commands. +**Menu breadth: 305 / 491 items (62%)** · 451 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 37 | 49% | +| View | 75 | 38 | 51% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -65,7 +65,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -80,15 +79,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -126,7 +120,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From d6cc051d99cdb9e3446e7957e6641034db3edcf0 Mon Sep 17 00:00:00 2001 From: assamaral Date: Wed, 28 Oct 2026 08:07:05 -0300 Subject: [PATCH 079/531] Keep the generated sheet of a layout whose viewports lack ids The reader drops the PAPERVIEW sheet viewport the writer adds to a layout with no id-1 viewport. Numbering that layout's remaining viewports from 1 would then make the first of them the sheet on the next save, losing the generated sheet (CodeRabbit, ffishman on #2107). Layouts whose generated sheet was dropped are now left alone, and a write-read-write test with a single id-0 viewport covers it. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/dxf_read.rs | 15 ++++++++++----- crates/io/src/dxf_read/document.rs | 31 ++++++++++++++++++++++-------- crates/io/src/tests.rs | 29 ++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 13 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index ddcc159dc..c4b3a12ea 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -19,7 +19,8 @@ mod tables; mod text; use document::{ - apply_sortents, count_skipped, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, read_objects, setup_layouts, + apply_sortents, count_skipped, dropped_paper_views, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, read_objects, + setup_layouts, }; #[cfg(test)] use entities::acad_table; @@ -56,6 +57,8 @@ struct Rx { block_arrays: HashMap, /// LAYER record handle (upper case) → layer name (VIEWPORT group 341 frozen layers). layers: HashMap, + /// Owner handle and paper flag of each generated sheet viewport (PAPERVIEW) the reader dropped. + paper_views_dropped: Vec<(Option, bool)>, } /// Read a DXF file into a drawing. @@ -120,7 +123,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx); place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout); place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout); - number_unknown_viewport_ids(&mut d); + number_unknown_viewport_ids(&mut d, &dropped_paper_views(&rx, &paper_block_for, &first_layout)); apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); crate::dxf_image::resolve(&secs, &mut d); @@ -141,9 +144,11 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { /// Viewport ids another program left unknown (ZWCAD writes 69 = -1, read as 0). A layout whose /// viewports all lack an id gets them numbered in file order, as DWG readers do; when only /// some lack one and none is 1, the first viewport is the sheet and gets id 1. Either way the -/// sheet keeps id 1, so saving does not add a second sheet viewport ahead of it (#1463). -fn number_unknown_viewport_ids(d: &mut Drawing) { - for l in d.layouts.iter_mut() { +/// sheet keeps id 1, so saving does not add a second sheet viewport ahead of it (#1463). A layout +/// whose generated sheet (PAPERVIEW) the reader just dropped is left alone: none of its viewports +/// is the sheet, and numbering one as 1 would lose the generated sheet on the next save. +fn number_unknown_viewport_ids(d: &mut Drawing, sheet_dropped: &std::collections::HashSet) { + for l in d.layouts.iter_mut().filter(|l| !sheet_dropped.contains(&l.name)) { let mut vps: Vec = l.entities.iter().filter(|e| matches!(&e.kind, EntityKind::Viewport(_))).map(|e| (**e).clone()).collect(); let id = |e: &Entity| if let EntityKind::Viewport(v) = &e.kind { v.id } else { 0 }; if vps.iter().all(|e| id(e) == 0) { diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 245bda331..8d3c63bc2 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -17,6 +17,9 @@ pub(super) fn parse_entities( let owner = crate::dxf_ext::owner(tags); let paper = t.i(67) == Some(1); let handle = t.s(5).and_then(|h| Handle::parse_hex(&h)); + if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) { + rx.paper_views_dropped.push((owner.clone(), paper)); + } let mut kindent = entity_with_table_budget(kind, tags, table_cells_left); if let Some((c, _)) = kindent.as_mut() && let Some(n) = entity_plot_style(tags, rx) @@ -227,6 +230,14 @@ pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, } } +/// The layout an entity record belongs to: paper space when flagged (67=1) or owned by a +/// `*PAPER_SPACE` block, else `None` for model space. +fn paper_layout(owner: Option, paper: bool, rx: &Rx, paper_block_for: &HashMap, first_layout: &str) -> Option { + let owner_name = owner.and_then(|o| rx.brs.get(&o.trim().to_ascii_uppercase()).cloned()).map(|n| n.to_ascii_uppercase()); + let to_paper = paper || owner_name.as_deref().is_some_and(|n| n.starts_with("*PAPER_SPACE")); + to_paper.then(|| owner_name.and_then(|n| paper_block_for.get(&n).cloned()).unwrap_or_else(|| first_layout.to_string())) +} + /// Place the ENTITIES section: model space, or paper space when flagged (67=1). pub(super) fn place_entities( d: &mut Drawing, @@ -237,19 +248,23 @@ pub(super) fn place_entities( ) { for (owner, paper, e) in entities { d.ensure_layer(&e.common.layer); - let owner_name = owner.and_then(|o| rx.brs.get(&o.trim().to_ascii_uppercase()).cloned()).map(|n| n.to_ascii_uppercase()); - let to_paper = paper || owner_name.as_deref().is_some_and(|n| n.starts_with("*PAPER_SPACE")); - if to_paper { - let lname = owner_name.and_then(|n| paper_block_for.get(&n).cloned()).unwrap_or_else(|| first_layout.to_string()); - if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) { - l.entities.push(e); + match paper_layout(owner, paper, rx, paper_block_for, first_layout) { + Some(lname) => { + if let Some(l) = d.layouts.iter_mut().find(|l| l.name == lname) { + l.entities.push(e); + } } - } else { - d.model.push(e); + None => d.model.push(e), } } } +/// Layouts whose generated sheet viewport (PAPERVIEW) the reader dropped: their viewports keep +/// their ids, so the next save generates the sheet again instead of promoting one of them. +pub(super) fn dropped_paper_views(rx: &Rx, paper_block_for: &HashMap, first_layout: &str) -> std::collections::HashSet { + rx.paper_views_dropped.iter().filter_map(|(o, p)| paper_layout(o.clone(), *p, rx, paper_block_for, first_layout)).collect() +} + pub(super) fn count_skipped(skipped: &mut std::collections::BTreeMap, section: &str, n: usize) { if n > 0 { let c = skipped.entry(section.to_string()).or_insert(0); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index a589467f9..daf3e4189 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -661,6 +661,35 @@ fn viewport_ids_unknown_sheet_becomes_one() { assert!(!write_dxf(&back).contains("PAPERVIEW"), "the first viewport is the sheet"); } +/// A layout whose only viewport has id 0 (entmake, MCP): the writer adds the PAPERVIEW sheet ahead +/// of it and the reader drops that sheet again. The id-0 viewport must not be numbered 1, or the +/// next save takes it as the sheet and the generated sheet is lost (#2107). +#[test] +fn viewport_id_zero_keeps_implicit_sheet_across_saves() { + let mut d = sample(); + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: 8.0, + height: 6.0, + view_center: Vec2::new(5.0, 4.0), + view_height: 6.0, + id: 0, + ..Viewport::default() + }; + d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); + let first = write_dxf(&d); + assert!(first.contains("PAPERVIEW"), "the writer adds the sheet"); + let back = read_dxf(first.as_bytes()).unwrap(); + let ids: Vec = + back.layouts[0].entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some(v.id) } else { None }).collect(); + assert_eq!(ids, [0], "the dropped sheet is not replaced by numbering the id-0 viewport"); + let second = write_dxf(&back); + let lines: Vec<&str> = second.lines().map(str::trim).collect(); + let sheet = lines.iter().position(|l| *l == "PAPERVIEW").expect("the second save still generates the sheet"); + let vp0 = (0..lines.len() - 1).find(|i| lines[*i] == "69" && lines[i + 1] == "0").expect("the id-0 viewport is written"); + assert!(sheet < vp0, "the generated sheet comes first"); +} + /// A layout with viewport 2 frozen on `Walls` and `A B` (both real layers), and its written DXF as /// (code, value) pairs. fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { From 853ca574bdb9d51e55955941b542864426abf1b5 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Wed, 28 Oct 2026 23:23:09 +1100 Subject: [PATCH 080/531] lisp: entget and handent on block entities use the cached block index The per-drawing index now maps each block entity handle to the entity and its successor, so entget/handent/entnext are hash lookups instead of scanning every block. Test: entget_and_handent_reach_every_block_entity_also_after_a_redefinition. --- crates/engine/src/lisp.rs | 7 ++-- crates/engine/src/lisp/block_tests.rs | 18 ++++++++++ crates/engine/src/lisp/drawing.rs | 48 ++++++++++++--------------- 3 files changed, 44 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index 24afd4c32..d1d305e7e 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -5,6 +5,9 @@ //! (`getpoint`, `pause`) and carry on later, so the interface keeps drawing while a routine //! waits. Each drawing has its own symbols, as in AutoCAD. A run is one undo step. +/// A block-definition entity and its successor in the block, by handle. +pub type BlockSlots = HashMap, Option)>; + pub mod builtins; mod drawing; pub mod eval; @@ -56,9 +59,9 @@ pub struct Env { pub deleted: HashMap)>, /// Every entity's handle in creation order, for the drawing it was taken from (`entnext`). pub order: Option<(usize, Arc>)>, - /// Each block-definition entity's successor in its block (None for the last), for the drawing + /// Each block-definition entity with its successor in its block (None for the last), for the drawing /// it was taken from: `entnext`'s indexed lookup, which also tells whether a handle is a block's. - pub block_next: Option<(usize, Arc>>)>, + pub block_next: Option<(usize, Arc)>, /// `tblnext`'s place in each table. pub tblnext: HashMap, /// A block definition `entmake` has begun (a BLOCK list) and not yet ended (ENDBLK): the diff --git a/crates/engine/src/lisp/block_tests.rs b/crates/engine/src/lisp/block_tests.rs index 1c7589410..596ed3df3 100644 --- a/crates/engine/src/lisp/block_tests.rs +++ b/crates/engine/src/lisp/block_tests.rs @@ -253,3 +253,21 @@ fn entnext_walks_entmade_blocks_and_sees_a_redefinition() { } assert_eq!(ok(&mut s, walk), "(\"CIRCLE\" \"LINE\" \"LINE\")"); } + +/// entget and handent reach every entity of an entmade block through the cached index, and a +/// redefinition shows the new entities, not the old ones. +#[test] +fn entget_and_handent_reach_every_block_entity_also_after_a_redefinition() { + let mut s = session(); + let walk = r#"(progn (setq e (cdr (assoc -2 (tblsearch "BLOCK" "EB"))) r nil) + (while e (setq r (cons (list (cdr (assoc 0 (entget e))) (equal (handent (cdr (assoc 5 (entget e)))) e)) r) e (entnext e))) + (reverse r))"#; + for code in [BLOCK_EB, LINE, CIRCLE, LINE, ENDBLK] { + ok(&mut s, code); + } + assert_eq!(ok(&mut s, walk), "((\"LINE\" T) (\"CIRCLE\" T) (\"LINE\" T))"); + for code in [BLOCK_EB, CIRCLE, ENDBLK] { + ok(&mut s, code); + } + assert_eq!(ok(&mut s, walk), "((\"CIRCLE\" T))"); +} diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 1d330532a..d5c5810bc 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -8,16 +8,17 @@ //! for angles, which are radians in a list and degrees in a file. use std::collections::HashMap; + use std::sync::{Arc, Mutex}; use cadcraft_doc::{Entity, Handle, Space}; use cadcraft_dxf::Tag; use cadcraft_geom::Vec2; -use super::LispError; use super::builtins::args_err; use super::eval::{Ctx, Flow, Need}; use super::value::{PickSet, Value, to_text}; +use super::{BlockSlots, LispError}; use crate::{Input, Session}; fn arity(a: &[Value], min: usize, max: usize) -> Result<(), LispError> { @@ -318,14 +319,14 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option { pub fn entget(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 2)?; let h = ename(&a[0])?; + let drawn = ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()); + let from_block = if drawn { None } else { block_entity(ctx, h) }; let Ok(d) = ctx.s.doc() else { return Ok(Flow::Value(Value::Nil)) }; // An entity of a block definition (#1700) has no layout. - let (e, in_block) = match d.entity(h) { - Some(e) => (e, false), - None => match block_entity(d, h) { - Some(e) => (e, true), - None => return Ok(Flow::Value(Value::Nil)), - }, + let (e, in_block) = match (d.entity(h), &from_block) { + (Some(e), _) => (e, false), + (None, Some(e)) => (e, true), + (None, None) => return Ok(Flow::Value(Value::Nil)), }; let (kind, mut tags) = (codec()?.groups)(d, e); convert_angles(&kind, &mut tags, f64::to_radians); @@ -547,10 +548,11 @@ fn handles_in_order(ctx: &mut Ctx<'_>) -> Arc> { v } -/// Every block-definition entity's successor within its block, cached per drawing like -/// [`handles_in_order`]: one pass over the blocks, then `entnext` is a hash lookup instead of a -/// scan of the block (and of every block, to find which holds the entity). -fn block_successors(ctx: &mut Ctx<'_>) -> Arc>> { +/// Every block-definition entity with its successor within its block, cached per drawing like +/// [`handles_in_order`]: one pass over the blocks, then `entnext`, `entget` and `handent` on a +/// block's entity are hash lookups instead of scans of the block (and of every block, to find +/// which holds the entity). +fn block_slots(ctx: &mut Ctx<'_>) -> Arc { let Ok(st) = ctx.s.state() else { return Arc::default() }; let key = Arc::as_ptr(&st.doc) as usize; if let Some((k, v)) = &ctx.env.block_next @@ -560,9 +562,9 @@ fn block_successors(ctx: &mut Ctx<'_>) -> Arc>> { } let mut m = HashMap::new(); for b in st.doc.blocks.values() { - let mut it = b.entities.iter().map(|e| e.handle).peekable(); - while let Some(h) = it.next() { - m.insert(h, it.peek().copied()); + let mut it = b.entities.iter().peekable(); + while let Some(e) = it.next() { + m.insert(e.handle, (e.clone(), it.peek().map(|n| n.handle))); } } let m = Arc::new(m); @@ -581,7 +583,7 @@ pub fn entnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { if let Some(v) = a.first().filter(|v| !v.is_nil()) { let h = ename(v)?; if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none()) - && let Some(next) = block_successors(ctx).get(&h) + && let Some((_, next)) = block_slots(ctx).get(&h) { return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default())); } @@ -601,21 +603,13 @@ pub fn entnext(ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn handent(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; let s = string(&a[0])?; - let h = Handle::parse_hex(&s).filter(|h| ctx.s.doc().is_ok_and(|d| d.entity(*h).is_some() || block_entity(d, *h).is_some())); + let h = Handle::parse_hex(&s).filter(|h| ctx.s.doc().is_ok_and(|d| d.entity(*h).is_some()) || block_entity(ctx, *h).is_some()); Ok(Flow::Value(h.map(Value::Ename).unwrap_or_default())) } -/// The block definition holding entity `h`, when it is one of a block's (not a drawn entity). -fn block_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&cadcraft_doc::Block> { - if h == Handle(0) { - return None; - } - d.blocks.values().map(|b| b.as_ref()).find(|b| b.entities.get(h).is_some()) -} - -/// Entity `h` of a block definition (#1700). -fn block_entity(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&Arc> { - block_of(d, h).and_then(|b| b.entities.get(h)) +/// Entity `h` of a block definition (#1700), by the cached index. +fn block_entity(ctx: &mut Ctx<'_>, h: Handle) -> Option> { + block_slots(ctx).get(&h).map(|(e, _)| e.clone()) } // ---------------- selection sets ---------------- From 474df8ede8c7f6a124a0e7727a0e74d87507765b Mon Sep 17 00:00:00 2001 From: assamaral Date: Wed, 28 Oct 2026 10:07:24 -0300 Subject: [PATCH 081/531] Resolve a dropped sheet by its paper-space block, not its owner group A PAPERVIEW sheet inside a *Paper_SpaceN block whose owner group (330) is missing or unknown belongs to that block's layout, where place_blocks puts the block's other viewports; resolving it by owner sent it to the active layout and left the real one open to numbering (CodeRabbit on #2107). The reader now records the enclosing block of each dropped sheet, and a test strips the owner from the sheet of a second layout. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/dxf_read.rs | 7 +++-- crates/io/src/dxf_read/document.rs | 15 +++++++++-- crates/io/src/tests.rs | 42 ++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index c4b3a12ea..5254e0414 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -57,8 +57,11 @@ struct Rx { block_arrays: HashMap, /// LAYER record handle (upper case) → layer name (VIEWPORT group 341 frozen layers). layers: HashMap, - /// Owner handle and paper flag of each generated sheet viewport (PAPERVIEW) the reader dropped. - paper_views_dropped: Vec<(Option, bool)>, + /// Owner handle, paper flag and enclosing block (upper case) of each generated sheet viewport + /// (PAPERVIEW) the reader dropped. + paper_views_dropped: Vec<(Option, bool, Option)>, + /// Upper-case name of the BLOCK whose entities are being read, if any. + block: Option, } /// Read a DXF file into a drawing. diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 8d3c63bc2..c86699652 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -18,7 +18,7 @@ pub(super) fn parse_entities( let paper = t.i(67) == Some(1); let handle = t.s(5).and_then(|h| Handle::parse_hex(&h)); if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) { - rx.paper_views_dropped.push((owner.clone(), paper)); + rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone())); } let mut kindent = entity_with_table_budget(kind, tags, table_cells_left); if let Some((c, _)) = kindent.as_mut() @@ -116,7 +116,9 @@ pub(super) fn read_blocks( j += 1; } let body = recs.get(i + 1..j).unwrap_or(&[]); + rx.block = Some(name.to_ascii_uppercase()); let ents = parse_entities(body, d, rx, &mut n, table_cells_left); + rx.block = None; blocks.push((name, base, description, ents, xref)); i = j + 1; } else { @@ -262,7 +264,16 @@ pub(super) fn place_entities( /// Layouts whose generated sheet viewport (PAPERVIEW) the reader dropped: their viewports keep /// their ids, so the next save generates the sheet again instead of promoting one of them. pub(super) fn dropped_paper_views(rx: &Rx, paper_block_for: &HashMap, first_layout: &str) -> std::collections::HashSet { - rx.paper_views_dropped.iter().filter_map(|(o, p)| paper_layout(o.clone(), *p, rx, paper_block_for, first_layout)).collect() + rx.paper_views_dropped + .iter() + .filter_map(|(owner, paper, block)| match block { + // In a paper-space block the sheet is that block's layout, where `place_blocks` puts + // the block's other entities, whatever its owner group says. + Some(b) if b.starts_with("*PAPER_SPACE") => Some(paper_block_for.get(b).cloned().unwrap_or_else(|| first_layout.to_string())), + Some(_) => None, + None => paper_layout(owner.clone(), *paper, rx, paper_block_for, first_layout), + }) + .collect() } pub(super) fn count_skipped(skipped: &mut std::collections::BTreeMap, section: &str, n: usize) { diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index daf3e4189..54331fbaf 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -690,6 +690,48 @@ fn viewport_id_zero_keeps_implicit_sheet_across_saves() { assert!(sheet < vp0, "the generated sheet comes first"); } +/// The same for a layout written as a `*Paper_SpaceN` block (not the active one) whose PAPERVIEW +/// sheet lost its owner group (330): the sheet still belongs to the block's layout, as +/// `place_blocks` puts the block's other entities there, so that layout is left alone too. +#[test] +fn viewport_id_zero_in_paper_block_keeps_implicit_sheet_without_owner() { + let mut d = sample(); + d.layouts.push(Layout::new("Layout2", 2)); + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: 8.0, + height: 6.0, + view_center: Vec2::new(5.0, 4.0), + view_height: 6.0, + id: 0, + ..Viewport::default() + }; + d.add(&Space::Paper("Layout2".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); + let first = write_dxf(&d); + let lines: Vec<&str> = first.lines().collect(); + let sheet = lines.iter().position(|l| l.trim() == "PAPERVIEW").expect("the writer adds the sheet"); + let start = (0..sheet).rev().find(|i| lines[*i].trim() == "0" && lines[i + 1].trim() == "VIEWPORT").unwrap(); + let owner = (start..sheet).find(|i| lines[*i].trim() == "330").expect("the sheet has an owner"); + assert!(lines[start..sheet].iter().any(|l| l.trim().eq_ignore_ascii_case("*Paper_Space0") || l.trim() == "AcDbViewport"), "sheet record found"); + let stripped: String = lines + .iter() + .enumerate() + .filter(|(i, _)| *i != owner && *i != owner + 1) + .map(|(_, l)| { + format!( + "{l} +" + ) + }) + .collect(); + assert!(stripped.contains("*Paper_Space0"), "the second layout is a paper-space block"); + let back = read_dxf(stripped.as_bytes()).unwrap(); + let l2 = back.layouts.iter().find(|l| l.name == "Layout2").expect("Layout2"); + let ids: Vec = l2.entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some(v.id) } else { None }).collect(); + assert_eq!(ids, [0], "the dropped sheet of Layout2 is not replaced by numbering its id-0 viewport"); + assert!(write_dxf(&back).contains("PAPERVIEW"), "the second save still generates the sheet"); +} + /// A layout with viewport 2 frozen on `Walls` and `A B` (both real layers), and its written DXF as /// (code, value) pairs. fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { From 98240d82d0a08464f84803108e0ef7c8e7564289 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 08:03:36 -0600 Subject: [PATCH 082/531] MENUBAR/TOOLBAR: explicit imports for the wildcard-imports lint Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/interface.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/interface.rs b/crates/engine/src/cmd/interface.rs index 88fea379a..79ca65b1b 100644 --- a/crates/engine/src/cmd/interface.rs +++ b/crates/engine/src/cmd/interface.rs @@ -7,7 +7,7 @@ use serde_json::{Value, json}; -use super::*; +use super::{CommandSpec, always, bad}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; /// The interface bars MENUBAR and TOOLBAR control. From d0ab457f317b5671b1bc8398b00f5a65b1af840e Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 09:24:29 -0600 Subject: [PATCH 083/531] Relative height codes kept when a text opens in the editor \H2x; with no inline height before it scaled nothing and was dropped, so saving a multileader's (or an MTEXT's) text from the editor lost it. The editor now parses the contents against the text's own height. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/mtext_edit.rs | 8 ++++++- crates/ui-egui/src/mtext_editor.rs | 37 +++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/mtext_edit.rs b/crates/engine/src/mtext_edit.rs index 30da0b897..faa802ff3 100644 --- a/crates/engine/src/mtext_edit.rs +++ b/crates/engine/src/mtext_edit.rs @@ -99,6 +99,12 @@ fn arg_end(chars: &[char], from: usize) -> usize { impl Formatted { /// Parse MTEXT contents. Never fails: what isn't understood is kept as atoms or dropped. pub fn from_contents(contents: &str) -> Formatted { + Self::from_contents_with_height(contents, None) + } + + /// [`Self::from_contents`] for a text `height` high: a relative height code (`\H2x;`) with no + /// inline height before it scales that one instead of being dropped. + pub fn from_contents_with_height(contents: &str, height: Option) -> Formatted { let mut f = Formatted::default(); let chars: Vec = contents.chars().collect(); let mut stack: Vec = Vec::new(); @@ -153,7 +159,7 @@ impl Formatted { i = end + 1; match k { 'f' | 'F' => apply_font(&mut cur, &a), - 'H' => cur.height = parse_height(&a, cur.height), + 'H' => cur.height = parse_height(&a, cur.height.or(height)), 'C' => { cur.color = a.trim().parse::().ok().and_then(|v| (v > 0 && v < 256).then_some(MTextColor::Aci(v))); } diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 686acbf19..96640edae 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -108,7 +108,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { let (rect, scale) = app.canvas.xf.map_or((ctx.content_rect(), 20.0), |x| (x.rect, x.scale.max(1e-6))); let mut st = ctx.data_mut(|d| d.get_temp::(state_id())).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(&mt.contents) }; + 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())) { // A family name, not a font file (`txt.shx`, `arial.ttf`). if !f.is_empty() && !f.contains('.') { @@ -761,4 +761,39 @@ mod tests { _ => 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"); + } } From 9c2ebc0e128ac3b39e72160eb922d9c657aadfaa Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 09:25:10 -0600 Subject: [PATCH 084/531] MENUBAR/TOOLBAR: request each bar on its own The request was both bars as one snapshot, so a tool bar change made between MENUBAR and the UI applying it was undone. Each command now asks only for its own bar, and the UI applies only the bars asked for. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/interface.rs | 25 ++++++++++++++++++------- crates/engine/src/lib.rs | 6 +++--- crates/ui-egui/src/lib.rs | 9 ++++++--- crates/ui-egui/tests/menubar_toolbar.rs | 14 ++++++++++++++ 4 files changed, 41 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/interface.rs b/crates/engine/src/cmd/interface.rs index 79ca65b1b..6e864769b 100644 --- a/crates/engine/src/cmd/interface.rs +++ b/crates/engine/src/cmd/interface.rs @@ -23,6 +23,14 @@ impl Default for InterfaceBars { } } +/// A change MENUBAR or TOOLBAR asked for: only the bars a command set, so the UI leaves the other +/// as it is (it may have been changed since). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct BarsRequest { + pub menubar: Option, + pub toolbar: Option, +} + pub fn specs() -> Vec { vec![ CommandSpec::new("menubar", "Menu Bar", run_menubar) @@ -39,11 +47,14 @@ pub fn specs() -> Vec { ] } -fn set(s: &mut Session, f: impl FnOnce(&mut InterfaceBars)) { - let mut b = s.bars_request.unwrap_or(s.bars_shown); - f(&mut b); - s.bars_shown = b; - s.bars_request = Some(b); +fn set_menubar(s: &mut Session, on: bool) { + s.bars_shown.menubar = on; + s.bars_request.menubar = Some(on); +} + +fn set_toolbar(s: &mut Session, show: bool) { + s.bars_shown.toolbar = show; + s.bars_request.toolbar = Some(show); } fn run_menubar(s: &mut Session, p: &Value) -> Result { @@ -55,14 +66,14 @@ fn run_menubar(s: &mut Session, p: &Value) -> Result { .filter(|v| *v <= 1) .ok_or_else(|| bad("menubar", "`value` must be 0 or 1"))?, }; - set(s, |b| b.menubar = v == 1); + set_menubar(s, v == 1); Ok(json!({ "value": v })) } fn run_toolbar(s: &mut Session, p: &Value) -> Result { let Some(show) = p.get("show").filter(|v| !v.is_null()) else { return Ok(json!({ "show": s.bars_shown.toolbar })) }; let show = show.as_bool().ok_or_else(|| bad("toolbar", "`show` must be true or false"))?; - set(s, |b| b.toolbar = show); + set_toolbar(s, show); Ok(json!({ "show": show })) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e12824ef5..33745d6c4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -144,8 +144,8 @@ pub struct Session { pub hatch_picks: Option, /// The window's menu bar and tool bar as the UI shows them (it reports them every frame). pub bars_shown: cmd::interface::InterfaceBars, - /// A change MENUBAR or TOOLBAR asked for, for the UI to apply. - pub bars_request: Option, + /// The bars MENUBAR or TOOLBAR asked to change, for the UI to apply. + pub bars_request: cmd::interface::BarsRequest, } impl Default for Session { @@ -197,7 +197,7 @@ impl Session { lisp_last: None, hatch_picks: None, bars_shown: Default::default(), - bars_request: None, + bars_request: Default::default(), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 03314df5b..64d57d388 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -418,9 +418,12 @@ impl CadApp { /// Apply a menu bar / tool bar change MENUBAR or TOOLBAR asked for, and report the bars shown. fn sync_bars(&mut self) { - if let Some(b) = self.session.bars_request.take() { - self.ui.in_window_menu = b.menubar; - self.ui.show_toolbar = b.toolbar; + let b = std::mem::take(&mut self.session.bars_request); + if let Some(on) = b.menubar { + self.ui.in_window_menu = on; + } + if let Some(show) = b.toolbar { + self.ui.show_toolbar = show; } self.session.bars_shown = cadcraft_engine::cmd::interface::InterfaceBars { menubar: self.ui.in_window_menu, toolbar: self.ui.show_toolbar }; } diff --git a/crates/ui-egui/tests/menubar_toolbar.rs b/crates/ui-egui/tests/menubar_toolbar.rs index 74ca46566..c95665938 100644 --- a/crates/ui-egui/tests/menubar_toolbar.rs +++ b/crates/ui-egui/tests/menubar_toolbar.rs @@ -55,3 +55,17 @@ fn the_json_forms_report_and_set_the_bars() { assert!(app.ui.show_toolbar && app.ui.in_window_menu); assert!(app.session.execute("menubar", &json!({ "value": 3 })).is_err()); } + +/// MENUBAR changes only the menu bar: a tool bar change made before the request is applied +/// stays (a control-API `ui.set` can come between them). +#[test] +fn menubar_leaves_a_later_tool_bar_change() { + let mut app = app(); + app.ui.in_window_menu = true; + app.ui.show_toolbar = true; + app.session.execute("menubar", &json!({ "value": 0 })).unwrap(); + app.ui.show_toolbar = false; + app.cmdline("'REDRAW"); + assert!(!app.ui.in_window_menu, "MENUBAR applied"); + assert!(!app.ui.show_toolbar, "the tool bar keeps its later change"); +} From 4fadc54dbe17efeaf9537c575942b2a670567704 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 09:46:12 -0600 Subject: [PATCH 085/531] MENUBAR/TOOLBAR: control-API calls see the bars as shown now CadApp::run now syncs the bars before and after the engine runs, as the command line does, so a bar query right after a ui.set reports the interface's current bars and a MENUBAR or TOOLBAR request is applied at once. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 4 ++++ crates/ui-egui/tests/menubar_toolbar.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 64d57d388..f0fe6fe69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -373,7 +373,11 @@ impl CadApp { if let Some(r) = menus::run_ui_command(self, id, ¶ms) { return r; } + // The bars as the interface shows them now (a `ui.set` may have just changed one), and any + // MENUBAR or TOOLBAR request applied at once. + self.sync_bars(); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); + self.sync_bars(); if let Ok(v) = &r && let Some(m) = v.get("message").and_then(Value::as_str) { diff --git a/crates/ui-egui/tests/menubar_toolbar.rs b/crates/ui-egui/tests/menubar_toolbar.rs index c95665938..ae304bcbb 100644 --- a/crates/ui-egui/tests/menubar_toolbar.rs +++ b/crates/ui-egui/tests/menubar_toolbar.rs @@ -69,3 +69,16 @@ fn menubar_leaves_a_later_tool_bar_change() { assert!(!app.ui.in_window_menu, "MENUBAR applied"); assert!(!app.ui.show_toolbar, "the tool bar keeps its later change"); } + +/// A bar query through `CadApp::run` reports the bars as the interface shows them now, even when +/// a UI change came just before it with no frame drawn in between. +#[test] +fn a_bar_query_sees_a_ui_change_just_made() { + let mut app = app(); + app.ui.show_toolbar = true; + assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": true })); + app.ui.show_toolbar = false; + assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": false })); + app.run("toolbar", json!({ "show": true })).unwrap(); + assert!(app.ui.show_toolbar, "the request is applied at once"); +} From 9244ffda5d109cf1a371ade4e367552bd8f48b10 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 20:50:16 +0500 Subject: [PATCH 086/531] Open a drawing on the view it was saved at (#1602) A drawing opened fitted to its extents, so one whose extents are dominated by far-off geometry opened at a view hundreds of times its content: the drawing was sub-pixel and there was no way to zoom in. Every other reader opens on the view the file was saved at. The saved view is read from HEADER (`VIEWCTR`/`VIEWSIZE`) and from the first `*ACTIVE` VPORT record, which is the newer of the two and wins -- as it already does for snap and grid spacing. A record that leaves the centre out has no view to give, so the header pair stands. The extents remain the fallback for a drawing that stores no view, and that fallback now fits the width too, through the aspect the record is written with: a drawing 100 wide and 10 tall was given a view 11 tall, a sliver of it, and a horizontal line got 1e-6. Writing keeps it, so a read-and-write round trip no longer loses the view. Rebased onto main, 310 commits on: `open_drawing` and `usable_view` are in engine/src/session/files.rs, the VPORT reading in io/src/dxf_read/tables.rs, the HEADER pair list in io/src/dxf_write/header.rs and the VPORT writing in io/src/dxf_write/layout.rs. The two io tests were already carried by their hunk, so only the engine one needed placing. --- crates/doc/src/header.rs | 17 ++++++++ crates/engine/src/session/files.rs | 14 +++++- crates/engine/src/tests.rs | 34 +++++++++++++++ crates/io/src/dxf_read/tables.rs | 12 +++++- crates/io/src/dxf_write/header.rs | 4 ++ crates/io/src/dxf_write/layout.rs | 16 ++++--- crates/io/src/tests.rs | 69 ++++++++++++++++++++++++++++++ 7 files changed, 158 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/header.rs b/crates/doc/src/header.rs index c6f17fd7e..52b9d34b1 100644 --- a/crates/doc/src/header.rs +++ b/crates/doc/src/header.rs @@ -90,6 +90,23 @@ impl Header { .filter(|p| p.is_finite() && if allow_zero { p.x >= 0.0 && p.y >= 0.0 } else { p.x > 0.0 && p.y > 0.0 }) .unwrap_or(Vec2::new(0.5, 0.5)) } + /// The model view the drawing was saved at: `$VIEWCTR` (centre) and `$VIEWSIZE` (height, in + /// drawing units), when both are present and usable. A DXF file keeps the pair in HEADER and + /// repeats it in the `*ACTIVE` VPORT record (12/22 and 40); a reader opens the drawing on it + /// rather than on the extents, so a drawing saved on one detail of a large sheet opens there. + pub fn saved_view(&self) -> Option<(Vec2, f64)> { + let center = self.point("VIEWCTR")?.xy(); + let height = self.get("VIEWSIZE").and_then(HVal::as_f64)?; + (center.is_finite() && height.is_finite() && height > 1e-9).then_some((center, height)) + } + /// Record the view the drawing is saved at (see [`Header::saved_view`]). A view that cannot + /// be shown is not recorded, so a usable stored view is never replaced by an unusable one. + pub fn set_saved_view(&mut self, center: Vec2, height: f64) { + if center.is_finite() && height.is_finite() && height > 1e-9 { + self.set("VIEWCTR", HVal::Point(center.to3(0.0))); + self.set_f64("VIEWSIZE", height); + } + } pub fn set_f64(&mut self, name: &str, v: f64) { self.set(name, HVal::Real(v)); } diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 95d439f8c..cf0f8a8c2 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -1,5 +1,10 @@ use super::{DocState, Drawing, EngineError, Result, Session, Space, Value, Vec2, View, cmd}; +/// Whether a stored view can be used: a drawing can record a degenerate or non-finite one. +fn usable_view(v: &View) -> bool { + v.center.is_finite() && v.height.is_finite() && v.height > 1e-12 +} + impl Session { /// Append a new untitled drawing (`DrawingN`, metric or imperial default view), end a running command, make it active, bump the document epoch and return its index. pub fn new_drawing(&mut self, metric: bool) -> usize { @@ -17,8 +22,15 @@ impl Session { /// Append a loaded drawing, fit the view to its model extents (aspect-corrected, minimum height 1e-6) when non-empty, end a running command, make it active, bump the epoch and return its index. pub fn open_drawing(&mut self, d: Drawing, title: &str, path: Option) -> usize { let mut st = DocState::new(d, title, path); + // The view the file was saved at is the one every other reader opens on. Fitting the + // extents instead showed a drawing whose extents are dominated by far-off geometry at a + // view hundreds of times its content, with the drawing sub-pixel and no way to zoom in + // (#1602). The extents remain the fallback for a drawing that stores no view. + let saved = st.doc.header.saved_view().map(|(center, height)| View { center, height }).filter(usable_view); let ext = st.doc.extents(&Space::Model); - if !ext.is_empty() { + if let Some(v) = saved { + st.set_view_quiet(v); + } else if !ext.is_empty() { st.set_view_quiet(View { center: ext.center(), height: (ext.height().max(ext.width() * self.viewport_px.1 / self.viewport_px.0.max(1.0)) * 1.1).max(1e-6), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8c590dd97..0a77680dc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -179,6 +179,40 @@ fn json_execute_and_errors() { assert_eq!(s.state().unwrap().undo.len(), 1); } +/// A drawing is opened on the view it was saved at, as every other reader opens it. Fitting the +/// extents instead showed a drawing whose extents are dominated by far-off geometry at a view +/// hundreds of thousands of times its content: sub-pixel, and `ZOOM Extents` fits the same box +/// (#1602). The extents are still the fallback for a drawing that stores no view. +#[test] +fn a_drawing_opens_on_the_view_it_was_saved_at() { + let mut d = cadcraft_doc::Drawing::new_metric(); + for (a, b) in [([0.0, 0.0], [100.0, 60.0]), ([5e6, 5e6], [5e6 + 100.0, 5e6 + 60.0])] { + let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(a[0], a[1], 0.0), b: cadcraft_geom::Vec3::new(b[0], b[1], 0.0) }; + d.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + } + d.header.set_saved_view(Vec2::new(50.0, 50.0), 20.0); + + let mut s = Session::new(); + s.open_drawing(d.clone(), "saved-view.dxf", None); + assert_eq!(s.state().unwrap().view(), View { center: Vec2::new(50.0, 50.0), height: 20.0 }); + + // No stored view: the extents, as before. They are what makes this drawing unusable without + // the stored one -- the fit is more than a hundred thousand times taller than the detail. + let mut plain = d.clone(); + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + let mut s = Session::new(); + s.open_drawing(plain, "no-view.dxf", None); + assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); + + // A stored view that cannot be shown is no view at all. + let mut broken = d; + broken.header.set("VIEWSIZE", cadcraft_doc::HVal::Real(0.0)); + let mut s = Session::new(); + s.open_drawing(broken, "broken-view.dxf", None); + assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); +} + #[test] fn move_with_pickfirst_and_window_selection() { let mut s = Session::new(); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 8a57f7f9e..001944b86 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -276,7 +276,8 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { _ => {} } } - // One *Active viewport is no tiling: the view is the editor's (it zooms to the extents). + // One *Active viewport is no tiling: its single tile is not a configuration to switch to. + // Its view was kept in the HEADER pair as it was read (see `vport_record`). d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active())); } @@ -315,6 +316,12 @@ const MAX_VPORT_TILES: usize = 64; fn vport_record(d: &mut Drawing, t: &T) { let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default(); let (min, max, center) = (t.p(10).xy(), t.p(11).xy(), t.p(12).xy()); + // A modern file keeps the view it was saved at in the first `*ACTIVE` record (12/22 centre, + // 40 height) as well as in the HEADER pair, and as with the snap and grid spacing the record + // is the newer of the two and wins (#1602). A record that leaves the centre out has no view + // to give -- `p` reads a missing coordinate as zero -- so the header pair stays. + let first_active = name.eq_ignore_ascii_case(VportConfig::ACTIVE) && !d.vports.iter().any(|c| c.is_active()); + let centred = t.f(12).is_some() && t.f(22).is_some(); let height = t.fd(40, 0.0); let unit = |v: f64| v.is_finite() && (-1e-9..=1.0 + 1e-9).contains(&v); let ok = [min.x, min.y, max.x, max.y].into_iter().all(unit) @@ -326,6 +333,9 @@ fn vport_record(d: &mut Drawing, t: &T) { if name.is_empty() || !ok { return; } + if first_active && centred { + d.header.set_saved_view(center, height); + } let aspect = t.f(41).filter(|a| a.is_finite() && *a > 0.0).unwrap_or(0.0); let clamp = |p: Vec2| Vec2::new(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0)); let tile = VportTile { min: clamp(min), max: clamp(max), center, height, aspect }; diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index b628a5c3d..6a9c63032 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -44,6 +44,10 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("INSUNITS", 70), ("MEASUREMENT", 70), ("PSLTSCALE", 70), + // The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT + // record below repeats it). Written so a drawing opened on its saved view saves it back. + ("VIEWCTR", -2), + ("VIEWSIZE", 40), ]; /// The current dimension style's variables as header variables (`$DIMTXT`, `$DIMDEC`…), after diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 4ad19ffbb..7384fb766 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -63,13 +63,17 @@ pub(super) fn paper_view(w: &mut W, d: &Drawing, e: &Entity, owner: &str, cx: &C /// The VPORT table: the `*Active` model space tiles (one viewport on the extents when there is no /// tiled configuration) and the saved configurations, each tile a record, the current one first. pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { - let single = VportTile { - min: Vec2::ZERO, - max: Vec2::new(1.0, 1.0), - center: if ext.is_empty() { Vec2::new(6.0, 4.5) } else { ext.center() }, - height: if ext.is_empty() { 9.0 } else { (ext.height() * 1.1).max(1e-6) }, - aspect: 1.6, + // The view the drawing is saved at, so that reading a drawing and writing it back keeps it; + // a drawing that stores none is written on its extents. The fallback fits the width as well, + // through the aspect the record is written with: a drawing 100 wide and 10 tall otherwise got + // a view 11 tall, which shows a sliver of it, and a horizontal line got 1e-6 (#1602). + const ASPECT: f64 = 1.6; + let (center, height) = match d.header.saved_view() { + Some(v) => v, + None if ext.is_empty() => (Vec2::new(6.0, 4.5), 9.0), + None => (ext.center(), (ext.height().max(ext.width() / ASPECT) * 1.1).max(1e-6)), }; + let single = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center, height, aspect: ASPECT }; let tiled = d.vports.iter().find(|c| c.is_active() && c.tiles.len() > 1); let mut records: Vec<(&str, &VportTile)> = match tiled { Some(c) => c.tiles.iter().map(|t| (VportConfig::ACTIVE, t)).collect(), diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 977a7c184..230c202f7 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -518,6 +518,75 @@ fn pdf_hostile_options_and_empty() { } } +/// The view a drawing was saved at is the `*ACTIVE` VPORT record's centre and height, repeated in +/// the `$VIEWCTR`/`$VIEWSIZE` header pair. It used to be dropped on read and replaced on write by +/// a fit of the geometry extents, so a drawing with far-off geometry opened hundreds of times too +/// far out, and a conversion replaced wherever the drawing had been left (#1602). +#[test] +fn dxf_keeps_the_view_the_drawing_was_saved_at() { + const SAVED: &str = "\ +0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1027\n9\n$VIEWCTR\n10\n50.0\n20\n50.0\n30\n0.0\n9\n$VIEWSIZE\n40\n20.0\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n\ +12\n50.0\n22\n50.0\n40\n20.0\n41\n1.5\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n100.0\n21\n60.0\n31\n0.0\n\ +0\nLINE\n8\n0\n10\n5000000.0\n20\n5000000.0\n30\n0.0\n11\n5000100.0\n21\n5000060.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n"; + + // The stored view survives the read, far-away geometry and all: the extents here are + // 5 000 100 x 5 000 060, a fit of which is 275 000 times the height the drawing was saved at. + let d = read_dxf(SAVED.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0))); + assert!(d.extents(&Space::Model).max.x > 5e6, "the far-off line is read too"); + + // And writing the drawing back keeps it, in both places a reader looks. + let text = write_dxf(&d); + let back = read_dxf(text.as_bytes()).unwrap(); + assert_eq!(back.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0))); + let active = text.replace("\r\n", "\n"); + let active = active.split("*Active").nth(1).unwrap_or_default(); + for group in ["\n 12\n50", "\n 22\n50", "\n 40\n20"] { + assert!(active.contains(group), "the *ACTIVE record keeps {group:?}: {}", &active[..active.len().min(400)]); + } + + // A drawing that stores no view is still written on its extents. + let mut plain = d.clone(); + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + assert_eq!(plain.header.saved_view(), None); + let fitted = read_dxf(write_dxf(&plain).as_bytes()).unwrap(); + let (center, height) = fitted.header.saved_view().unwrap(); + assert!(center.x > 2.4e6 && height > 5e6, "the extents fit: {center:?} {height}"); + + // That fit covers the width as well: a wide, flat drawing opened on its height alone would + // show a sliver of it, and a drawing with no height at all would have no view. + let mut wide = cadcraft_doc::Drawing::new_metric(); + for (a, b) in [([0.0, 0.0], [100.0, 10.0]), ([0.0, 10.0], [100.0, 10.0])] { + let line = cadcraft_doc::Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }; + wide.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + } + let back = read_dxf(write_dxf(&wide).as_bytes()).unwrap(); + let (_, height) = back.header.saved_view().unwrap(); + assert!(height > 60.0, "a 100 x 10 drawing needs more than its height: {height}"); + + let mut flat = cadcraft_doc::Drawing::new_metric(); + let line = cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(100.0, 0.0, 0.0) }; + flat.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + let back = read_dxf(write_dxf(&flat).as_bytes()).unwrap(); + let (_, height) = back.header.saved_view().unwrap(); + assert!(height > 60.0, "a horizontal line needs a view with width in it: {height}"); +} + +/// A `*ACTIVE` record that leaves its view centre out (no 12/22) is not a view: `$VIEWCTR` and +/// `$VIEWSIZE` stay, rather than being replaced by the zero the missing groups read as. +#[test] +fn a_viewport_record_without_a_centre_keeps_the_header_view() { + const NO_CENTRE: &str = "\ +0\nSECTION\n2\nHEADER\n9\n$VIEWCTR\n10\n50.0\n20\n50.0\n9\n$VIEWSIZE\n40\n20.0\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n\ +40\n99.0\n0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let d = read_dxf(NO_CENTRE.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the header pair is kept"); +} + #[test] fn dxf_roundtrips_page_setup() { let mut d = sample(); From 1e02e6f2630e8af40c002dc66f8f1b8941065810 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 10:10:04 -0600 Subject: [PATCH 087/531] Text editor: relative heights stay relative, long texts are refused, focus stays put A \H2x; height is written back as \H2x; (relative over the text's own height), so the part keeps scaling when the text's height changes; an absolute height stays absolute. TEXTEDIT refuses a text longer than the editor holds instead of opening it cut short, which OK would have saved. With the text empty the editor takes the focus back only when nothing else has it, so a click on the height field keeps it there. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify2/textedit.rs | 5 ++ crates/engine/src/mtext_edit.rs | 70 ++++++++++++++++++--- crates/engine/tests/it/mleader_text_edit.rs | 22 +++++++ crates/ui-egui/src/mtext_editor.rs | 31 ++++++++- 4 files changed, 117 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index 3a07369b5..a0daa7d40 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -104,6 +104,11 @@ impl Interactive for TextEditM { EntityKind::MLeader(m) => m.text, _ => None, }; + // The editor would cut a text this long short, and saving would shorten it. + if self.mtext.as_ref().is_some_and(|m| !crate::mtext_edit::Formatted::fits(&m.contents)) { + self.mtext = None; + return Err(other("This text is too long to edit; it is left as it is.")); + } self.h = Some((h, old)); Ok(Step::Continue) } diff --git a/crates/engine/src/mtext_edit.rs b/crates/engine/src/mtext_edit.rs index faa802ff3..6fc4a46fd 100644 --- a/crates/engine/src/mtext_edit.rs +++ b/crates/engine/src/mtext_edit.rs @@ -33,6 +33,9 @@ pub struct CharFmt { pub font: Option, /// Absolute character height set inline (`\H`); `None`: the text's. pub height: Option, + /// The inline height was set relative to the text's own (`\H2x;`): this multiplier, written + /// back as it was so the part keeps scaling with the text's height. + pub height_rel: Option, /// Colour set inline (`\C`, `\c`); `None`: the entity's (ByLayer/ByBlock). pub color: Option, } @@ -105,6 +108,17 @@ impl Formatted { /// [`Self::from_contents`] for a text `height` high: a relative height code (`\H2x;`) with no /// inline height before it scales that one instead of being dropped. pub fn from_contents_with_height(contents: &str, height: Option) -> Formatted { + Self::parse(contents, height).0 + } + + /// Whether the editor holds all of `contents`: past [`MAX_CHARS`] characters the rest would + /// be cut off, and saving would shorten the text. + pub fn fits(contents: &str) -> bool { + Self::parse(contents, None).1 + } + + /// The parse, and whether it took in all of `contents`. + fn parse(contents: &str, height: Option) -> (Formatted, bool) { let mut f = Formatted::default(); let chars: Vec = contents.chars().collect(); let mut stack: Vec = Vec::new(); @@ -114,7 +128,7 @@ impl Formatted { let mut i = 0; while let Some(&c) = chars.get(i) { if f.fmt.len() >= MAX_CHARS { - break; + return (f, false); } match c { '{' => { @@ -159,7 +173,7 @@ impl Formatted { i = end + 1; match k { 'f' | 'F' => apply_font(&mut cur, &a), - 'H' => cur.height = parse_height(&a, cur.height.or(height)), + 'H' => apply_height(&mut cur, &a, height), 'C' => { cur.color = a.trim().parse::().ok().and_then(|v| (v > 0 && v < 256).then_some(MTextColor::Aci(v))); } @@ -195,7 +209,7 @@ impl Formatted { } } } - f + (f, true) } fn push_char(&mut self, c: char, fmt: &CharFmt) { @@ -453,7 +467,9 @@ impl Formatted { let fam: String = fam.chars().filter(|c| !matches!(c, ';' | '|' | '{' | '}' | '\\')).collect(); s.push_str(&format!("\\f{fam}|b{}|i{};", u8::from(f.bold), u8::from(f.italic))); } - if let Some(h) = f.height { + if let Some(m) = f.height_rel { + s.push_str(&format!("\\H{}x;", trim(m))); + } else if let Some(h) = f.height { s.push_str(&format!("\\H{};", trim(h))); } match f.color { @@ -470,12 +486,32 @@ fn trim(v: f64) -> String { s.trim_end_matches('0').trim_end_matches('.').to_string() } -fn parse_height(a: &str, cur: Option) -> Option { +/// A `\H` code on `cur`, for a text `base` high. A relative height over the text's own (no +/// inline height before it, or a relative one) stays relative; over an inline absolute height it +/// becomes absolute. +fn apply_height(cur: &mut CharFmt, a: &str, base: Option) { + let valid = |h: f64| (h.is_finite() && h > 0.0 && h < 1e6).then_some(h); let a = a.trim(); - match a.strip_suffix(['x', 'X']) { - // A relative height needs the current one; without it the code is dropped. - Some(r) => r.trim().parse::().ok().zip(cur).map(|(m, h)| h * m).filter(|h| h.is_finite() && *h > 0.0 && *h < 1e6), - None => a.parse::().ok().filter(|h| h.is_finite() && *h > 0.0 && *h < 1e6).or(cur), + let Some(r) = a.strip_suffix(['x', 'X']) else { + if let Some(h) = a.parse::().ok().and_then(valid) { + cur.height = Some(h); + cur.height_rel = None; + } + return; + }; + let Some(m) = r.trim().parse::().ok().and_then(valid) else { return }; + match (cur.height, cur.height_rel) { + (_, Some(r0)) => { + if let Some(m) = valid(r0 * m) { + cur.height_rel = Some(m); + cur.height = base.and_then(|b| valid(b * m)); + } + } + (None, None) => { + cur.height_rel = Some(m); + cur.height = base.and_then(|b| valid(b * m)); + } + (Some(h), None) => cur.height = valid(h * m).or(cur.height), } } @@ -501,6 +537,22 @@ fn apply_font(cur: &mut CharFmt, a: &str) { mod tests { use super::*; + #[test] + fn a_relative_height_is_written_back_relative() { + let f = Formatted::from_contents_with_height("{\\H2x;big} small {\\H3;abs}", Some(5.0)); + assert_eq!(f.fmt_at(0).height, Some(10.0), "shown at twice the text's height"); + let out = f.to_contents(); + assert!(out.contains("\\H2x;big"), "{out}"); + assert!(out.contains("\\H3;abs"), "an absolute height stays absolute: {out}"); + // Opened again for a taller text, the part scales with it. + assert_eq!(Formatted::from_contents_with_height(&out, Some(8.0)).fmt_at(0).height, Some(16.0)); + // Relative over relative multiplies; over an absolute one it is absolute. + let n = Formatted::from_contents_with_height("{\\H2x;a{\\H1.5x;b}}{\\H4;c{\\H2x;d}}", Some(1.0)).to_contents(); + assert!(n.contains("\\H3x;b") && n.contains("\\H8;d"), "{n}"); + // With no height known it is still kept. + assert!(Formatted::from_contents("{\\H2x;x}").to_contents().contains("\\H2x;x")); + } + #[test] fn round_trips_formats_and_atoms() { for src in [ diff --git a/crates/engine/tests/it/mleader_text_edit.rs b/crates/engine/tests/it/mleader_text_edit.rs index ba2887419..bff071cf1 100644 --- a/crates/engine/tests/it/mleader_text_edit.rs +++ b/crates/engine/tests/it/mleader_text_edit.rs @@ -43,3 +43,25 @@ fn textedit_and_properties_change_a_multileaders_text() { s.execute("properties.set", &json!({"handles": [h.hex()], "text": "from properties"})).unwrap(); assert_eq!(text_of(&s), "from properties"); } + +#[test] +fn a_text_too_long_for_the_editor_is_left_as_it_is() { + let mut s = Session::new(); + s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); + let (h, at) = s + .doc() + .unwrap() + .model + .iter() + .find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| (e.handle, t.insert.xy())) } else { None }) + .unwrap(); + let long = format!("example text {}", "x".repeat(cadcraft_engine::mtext_edit::MAX_CHARS)); + s.execute("properties.set", &json!({"handles": [h.hex()], "text": long})).unwrap(); + assert_eq!(text_of(&s), long); + s.cmdline("TEXTEDIT").unwrap(); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("This text is too long to edit; it is left as it is.")); + assert!(s.editing_mtext().is_none(), "the editor doesn't open"); + s.cancel(); + assert_eq!(text_of(&s), long, "the text is not shortened"); +} diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 96640edae..1b020d705 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -260,7 +260,10 @@ 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)); + change(st, |c| { + c.height = (!none).then_some(h); + c.height_rel = None; + }); } ui.separator(); for (flag, label, tip) in [ @@ -579,7 +582,10 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, .layouter(&mut layouter) .show(ui); out.response.response.clone().accessible_name(crate::tl!("Text")); - if !out.response.has_focus() && (!st.focused || (buf.is_empty() && st.fmt.is_empty())) { + // 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; @@ -633,6 +639,27 @@ mod tests { assert!(harness.unnamed_widgets().is_empty()); } + /// With the text empty, a click on the height field keeps the focus there; the editor doesn't + /// take it back. + #[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 }; + let mut harness = Harness::builder().with_size(vec2(1100.0, 300.0)).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(); + 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.run(); + harness.run(); + assert!(!harness.ctx.memory(|m| m.has_focus(edit_id())), "the height field keeps the focus"); + } + /// 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. #[test] fn the_whole_toolbar_uses_bundled_glyphs_and_names_its_controls() { From 71a0ef22602a34b38d989326294641299d3531ce Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 10:12:50 -0600 Subject: [PATCH 088/531] MENUBAR started from the interface offers the bar as shown now CadApp::start syncs the bars before starting the command, as run and cmdline do, so MENUBAR's default is the menu bar as the interface shows it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/tests/menubar_toolbar.rs | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f0fe6fe69..6d085b72d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -396,6 +396,7 @@ impl CadApp { if menus::run_ui_command(self, name, &Value::Null).is_some() { return; } + self.sync_bars(); if let Err(e) = self.session.start(name) { self.session.echo(e.to_string()); } diff --git a/crates/ui-egui/tests/menubar_toolbar.rs b/crates/ui-egui/tests/menubar_toolbar.rs index ae304bcbb..6a312d7c9 100644 --- a/crates/ui-egui/tests/menubar_toolbar.rs +++ b/crates/ui-egui/tests/menubar_toolbar.rs @@ -82,3 +82,14 @@ fn a_bar_query_sees_a_ui_change_just_made() { app.run("toolbar", json!({ "show": true })).unwrap(); assert!(app.ui.show_toolbar, "the request is applied at once"); } + +#[test] +fn menubar_started_from_the_ui_offers_the_bar_as_shown_now() { + let mut app = app(); + app.ui.in_window_menu = true; + app.cmdline(""); + app.ui.in_window_menu = false; + app.start("menubar"); + let prompt = app.session.prompt_text(); + assert!(prompt.contains("<0>"), "{prompt}"); +} From 1c611d610dfb81b593551513144cb451500ca12c Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 10:29:46 -0600 Subject: [PATCH 089/531] Control API: the bars are synced after every request A command a control request runs (MENUBAR, TOOLBAR, also through cmdline.key) may ask for a bar; control::handle now applies that before the next request, so a later query or ui.set sees the bars as they are. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control.rs | 8 ++++++++ crates/ui-egui/tests/menubar_toolbar.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2dc1f898a..85b640b17 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -286,6 +286,14 @@ fn key_from(name: &str) -> Option { } pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + let out = handle_request(app, ctx, req); + // A command the request ran may have asked for a bar (MENUBAR, TOOLBAR): apply it before + // the next request, so a later query or `ui.set` sees the bars as they are now. + app.sync_bars(); + out +} + +fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { let p = &req.params; let s = |k: &str| p.get(k).and_then(Value::as_str); let f = |k: &str| p.get(k).and_then(Value::as_f64); diff --git a/crates/ui-egui/tests/menubar_toolbar.rs b/crates/ui-egui/tests/menubar_toolbar.rs index 6a312d7c9..fca05d82b 100644 --- a/crates/ui-egui/tests/menubar_toolbar.rs +++ b/crates/ui-egui/tests/menubar_toolbar.rs @@ -93,3 +93,15 @@ fn menubar_started_from_the_ui_offers_the_bar_as_shown_now() { let prompt = app.session.prompt_text(); assert!(prompt.contains("<0>"), "{prompt}"); } + +#[test] +fn enter_through_the_control_api_applies_the_bar_before_the_next_request() { + let mut app = app(); + let ctx = egui::Context::default(); + app.ui.show_toolbar = false; + app.start("toolbar"); + let (req, _pending) = cadcraft_ui_egui::control::ControlRequest::new("cmdline.key", serde_json::json!({ "key": "enter" })); + cadcraft_ui_egui::control::handle(&mut app, &ctx, &req); + assert!(app.session.running.is_none()); + assert!(app.ui.show_toolbar, "TOOLBAR's default Show is applied before the next request"); +} From b5f0890b95dcda79ab4f8e27ac017ab96da4a52a Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Thu, 29 Oct 2026 00:58:26 +0400 Subject: [PATCH 090/531] Docs: Georgian needs the embedded craft-fonts Geor face --- docs/control-protocol.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 5bbd4b083..dc23517d6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -190,7 +190,8 @@ Select a language with `engine.execute` and the UI command `ui.language`: Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the -optional craft-fonts input or the operating system. Without a suitable font, the saved choice is +optional craft-fonts input or the operating system; Georgian needs the `Geor` face from craft-fonts (an installed font +does not count). Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts `{"interfaceLanguage":"uk"}`; `ui.inspect` reports the saved choice in its UI state. Invalid choices leave the current language unchanged. Menus, command labels and prompt text From 23d5918a628c468c9968b17b2832b7760c995271 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 14:24:15 -0700 Subject: [PATCH 091/531] Dimensions: draw the DIMGAP frame over a DIMTFILL background --- crates/render/src/dim.rs | 2 +- crates/render/src/dim/tests.rs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index 1b6f67840..73b8932bb 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -374,7 +374,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let corners: Vec = [(-hw, -bottom), (hw, -bottom), (hw, top), (-hw, top)].into_iter().map(|(px, py)| text_mid + x * px + y * py).collect(); for (a, b) in corners.iter().zip(corners.iter().cycle().skip(1)) { - g.dim(vec![*a, *b]); + g.text_mark(vec![*a, *b]); } } g.value = decode_value(&cadcraft_fonts::plain_mtext(&g.mtext)); diff --git a/crates/render/src/dim/tests.rs b/crates/render/src/dim/tests.rs index f3232767f..c5de3ad5e 100644 --- a/crates/render/src/dim/tests.rs +++ b/crates/render/src/dim/tests.rs @@ -198,6 +198,25 @@ fn negative_dimgap_draws_a_frame_around_the_text() { assert_eq!(dimension_geometry(&d, &st_with(|s| s.text_gap = 0.0), 1.0).lines.len(), plain.lines.len()); } +#[test] +fn the_dimgap_frame_is_drawn_over_a_text_background() { + let d = lin((0.0, 0.0), (10.0, 0.0), (0.0, 5.0), 0.0); + let g = dimension_geometry( + &d, + &st_with(|s| { + s.text_gap = -0.09; + s.text_fill = 1; + }), + 1.0, + ); + assert_eq!(g.text_fill.len(), 4); + // The four sides are text marks, which are drawn after the background. + let n = g.lines.len(); + for i in n - 4..n { + assert!(g.text_marks.contains(&i), "{:?}", g.text_marks); + } +} + #[test] fn the_frame_turns_with_the_text() { let d = lin((0.0, 0.0), (0.0, 10.0), (5.0, 0.0), std::f64::consts::FRAC_PI_2); From 42503a8ecd9edd09b6e33c92bef87f7d0c2fc470 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:46:19 -0300 Subject: [PATCH 092/531] Keep a file's own paper size and plot rotation when saving DXF/DWG A media named wider than tall is stored two ways: AutoCAD writes a portrait size and a quarter turn (ISO_A4_(297.00_x_210.00_MM) as 210 x 297, 73 = 1), ZWCAD the media's own size and no turn (420 x 297, 73 = 0). Deriving the groups from the name alone turned the AutoCAD form into the ZWCAD one. The reader now keeps groups 44, 45 and 73 as read (PageSetup::file_paper, not serialized), and the writer puts them back while they still describe the page setup's size and orientation; page setups made or changed in CADCraft are derived from the media name as before. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/doc/src/tables.rs | 8 +++ crates/io/src/dxf_read/objects.rs | 1 + crates/io/src/dxf_write/sections.rs | 17 ++++-- crates/io/src/tests.rs | 52 +++++++++++++++++++ .../io/tests/it/tables_objects_roundtrip.rs | 4 +- 5 files changed, 77 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index a2c63ca6a..692dd2029 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -799,6 +799,13 @@ pub struct PageSetup { /// The layout's paper units are millimetres (plot paper units 1 in DXF) whatever the /// drawing's MEASUREMENT says; otherwise paper units follow MEASUREMENT (#1058). pub paper_mm: bool, + /// Paper size (DXF groups 44, 45) and plot rotation (group 73) as the file stored them. + /// Saving writes them back while they still describe `width_mm`, `height_mm` and + /// `landscape`, so each program's convention for media defined wider than tall survives a + /// round trip: AutoCAD stores a portrait size and a quarter turn, ZWCAD the media's own size + /// and no turn (#1463). `None` for page setups made in CADCraft. + #[serde(skip)] + pub file_paper: Option<(f64, f64, i64)>, } impl Default for PageSetup { @@ -820,6 +827,7 @@ impl Default for PageSetup { show_plot_styles: false, plot_transparency: false, paper_mm: false, + file_paper: None, } } } diff --git a/crates/io/src/dxf_read/objects.rs b/crates/io/src/dxf_read/objects.rs index 4d692ccee..3c36960ff 100644 --- a/crates/io/src/dxf_read/objects.rs +++ b/crates/io/src/dxf_read/objects.rs @@ -241,6 +241,7 @@ pub(super) fn page_setup(t: &T) -> PageSetup { let rotated = matches!(t.i(73), Some(1 | 3)); if w > 0.0 && h > 0.0 { p.landscape = rotated != (w > h); + p.file_paper = Some((w, h, t.i(73).unwrap_or(0))); } else if t.i(73).is_some() { p.landscape = rotated; } diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 9fed1cdcc..f8f199758 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1124,11 +1124,20 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec (f64, f64, i64) { + if let Some((w, h, rotation)) = page.file_paper { + let same = |a: f64, b: f64| (a - b).abs() < 1e-6; + let landscape = matches!(rotation, 1 | 3) != (w > h); + if same(w.min(h), page.width_mm) && same(w.max(h), page.height_mm) && landscape == page.landscape { + return (w, h, rotation); + } + } if media_is_landscape(&page.paper) { let (short, long) = (page.width_mm.min(page.height_mm), page.width_mm.max(page.height_mm)); (long, short, i64::from(!page.landscape)) diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 8bfb4980b..0d603be76 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -576,6 +576,58 @@ fn landscape_media_keeps_its_size_order_and_rotation() { } } +/// A file's own groups 44, 45 and 73 are written back unchanged, in DXF and DWG, whether they +/// follow ZWCAD's convention (the media's size, no turn) or AutoCAD's (a portrait size and a +/// quarter turn) for a media named wider than tall. Once the page setup changes, they no +/// longer describe it and the size and rotation are derived again. +#[test] +fn a_files_own_paper_groups_are_written_back() { + let set = |dxf: &str, (w, h, r): (f64, f64, i64)| -> String { + let mut lines: Vec = dxf.lines().map(String::from).collect(); + let name = (0..lines.len() - 3) + .find(|&i| { + lines[i].trim() == "100" && lines[i + 1].trim() == "AcDbLayout" && lines[i + 2].trim() == "1" && lines[i + 3].trim() == "Layout1" + }) + .unwrap(); + let start = (0..name).rev().find(|&i| lines[i].trim() == "100" && lines[i + 1].trim() == "AcDbPlotSettings").unwrap(); + for i in (start..name).step_by(2) { + match lines[i].trim() { + "44" => lines[i + 1] = w.to_string(), + "45" => lines[i + 1] = h.to_string(), + "73" => lines[i + 1] = r.to_string(), + _ => {} + } + } + lines.join("\n") + }; + // (media, groups as the program wrote them, portrait size and landscape CADCraft reads) + let cases = [ + ("ISO full bleed A3 (420.00 x 297.00 MM)", (420.0, 297.0, 0), (297.0, 420.0, true)), + ("ISO A4 (297.00 x 210.00 MM)", (210.0, 297.0, 1), (210.0, 297.0, true)), + ("ISO A4 (297.00 x 210.00 MM)", (210.0, 297.0, 0), (210.0, 297.0, false)), + ]; + for (media, groups, (pw, ph, landscape)) in cases { + let mut d = sample(); + d.layouts[0].page.paper = media.into(); + let file = set(&write_dxf(&d), groups); + let r = read_dxf(file.as_bytes()).unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (pw, ph, landscape), "{media} {groups:?} read"); + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), groups, "{media} {groups:?} DXF"); + let dwg = write(&r, "t.dwg").unwrap(); + let back = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned(); + assert_eq!(plot_paper_groups(&back, "Layout1"), groups, "{media} {groups:?} DWG"); + let r = read(&dwg, "t.dwg").unwrap(); + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), groups, "{media} {groups:?} DWG read and saved again"); + } + // Turned in CADCraft after reading: the stored groups no longer apply. + let mut d = sample(); + d.layouts[0].page.paper = "ISO full bleed A3 (420.00 x 297.00 MM)".into(); + let mut r = read_dxf(set(&write_dxf(&d), (420.0, 297.0, 0)).as_bytes()).unwrap(); + r.layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page.landscape = false; + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1"), (420.0, 297.0, 1), "portrait after the change"); +} + #[test] fn portrait_media_is_written_as_before() { let mut d = sample(); diff --git a/crates/io/tests/it/tables_objects_roundtrip.rs b/crates/io/tests/it/tables_objects_roundtrip.rs index 0f75e4cd3..5a6ad5a4a 100644 --- a/crates/io/tests/it/tables_objects_roundtrip.rs +++ b/crates/io/tests/it/tables_objects_roundtrip.rs @@ -100,7 +100,9 @@ fn layout_page_setup_and_paper_view_round_trip() { let r = round_trip(&d); for (a, b) in d.layouts.iter().zip(&r.layouts) { assert_eq!(a.name, b.name); - assert_eq!(a.page, b.page, "{}", a.name); + // The groups 44, 45 and 73 the file stored are provenance, not a setting. + let read = cadcraft_doc::PageSetup { file_paper: None, ..b.page.clone() }; + assert_eq!(a.page, read, "{}", a.name); assert_eq!(a.view, b.view, "{}", a.name); } assert_eq!(r.layouts.len(), d.layouts.len()); From c2175377fd7ea8207b60d58f1b3a3162ae312ee0 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 28 Oct 2026 23:55:03 +0100 Subject: [PATCH 093/531] perf(geom): make NURBS derivative allocation-free up to degree 10 derivative_unchecked allocated six Vecs per call and computed the degree p-1 basis separately although the degree p recurrence passes through it. Up to degree 10 both bases now come from one sweep into stack buffers; higher degrees keep the previous heap path. The operations and their order are unchanged, so results are bit-identical. The old implementation stays as a test-only oracle, compared bit for bit over random splines of degree 1 to 12. Closes #2431 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/nurbs.rs | 171 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 168 insertions(+), 3 deletions(-) diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 5268203b1..9fa432cd7 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -8,7 +8,7 @@ use std::f64::consts::FRAC_PI_2; -use crate::spline::{basis, find_span}; +use crate::spline::{MAX_STACK_DEGREE, basis, find_span}; use crate::{EPS, Ellipse, Spline, TAU, Vec2}; /// Highest degree the editing operations work with. @@ -88,6 +88,34 @@ fn elevate_bezier(p: &[H]) -> Vec { .collect() } +/// Basis functions of degree `p` in `n[..=p]` and of degree `p - 1` in `lower[..p]` for `p >= 1`, +/// in one Cox-de Boor sweep: the degree `p - 1` values are the state just before the last step, +/// so they match [`basis`] exactly. `left` and `right` are scratch of `p + 1` values; the outputs +/// stay untouched when a slice is too short. +#[allow(clippy::too_many_arguments)] +fn basis_pair_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], lower: &mut [f64], left: &mut [f64], right: &mut [f64]) { + if p == 0 || n.len() <= p || lower.len() < p || left.len() <= p || right.len() <= p { + return; + } + n[0] = 1.0; + for j in 1..=p { + let k = |i: isize| knots.get(i.max(0) as usize).copied().unwrap_or(0.0); + left[j] = u - k(span as isize + 1 - j as isize); + right[j] = k(span as isize + j as isize) - u; + if j == p { + lower[..p].copy_from_slice(&n[..p]); + } + let mut saved = 0.0; + for r in 0..j { + let den = right[r + 1] + left[j - r]; + let tmp = if den.abs() > 1e-300 { n[r] / den } else { 0.0 }; + n[r] = saved + right[r + 1] * tmp; + saved = left[j - r] * tmp; + } + n[j] = saved; + } +} + impl Spline { fn weight(&self, i: usize) -> f64 { if self.weights.is_empty() { 1.0 } else { self.weights.get(i).copied().unwrap_or(1.0) } @@ -130,14 +158,25 @@ impl Spline { /// First derivative without re-validating the spline. The caller must have confirmed /// [`Spline::is_valid`] already; integration calls this once per sample, and re-running the /// O(knots) validity scan each time would make measuring a valid spline quadratic (CWE-407). + /// Up to degree [`MAX_STACK_DEGREE`] both bases come from one stack-only sweep; higher degrees + /// compute them on the heap. fn derivative_unchecked(&self, t: f64) -> Vec2 { let p = self.degree; let Some(n) = self.control.len().checked_sub(1) else { return Vec2::ZERO }; let (lo, hi) = self.domain(); let t = if t.is_finite() { t.clamp(lo, hi) } else { lo }; let span = find_span(n, p, t, &self.knots); - let nb = basis(span, t, p, &self.knots); - let nd = basis(span, t, p - 1, &self.knots); + let (mut sb, mut sd, mut sl, mut sr) = + ([0.0; MAX_STACK_DEGREE + 1], [0.0; MAX_STACK_DEGREE + 1], [0.0; MAX_STACK_DEGREE + 1], [0.0; MAX_STACK_DEGREE + 1]); + let (hb, hd); + let (nb, nd): (&[f64], &[f64]) = if (1..=MAX_STACK_DEGREE).contains(&p) { + basis_pair_into(span, t, p, &self.knots, &mut sb, &mut sd, &mut sl, &mut sr); + (&sb, &sd) + } else { + hb = basis(span, t, p, &self.knots); + hd = basis(span, t, p - 1, &self.knots); + (&hb, &hd) + }; let k = |i: usize| self.knots.get(i).copied().unwrap_or(0.0); let ratio = |num: Option<&f64>, den: f64| if den.abs() > 1e-300 { num.copied().unwrap_or(0.0) / den } else { 0.0 }; let (mut a, mut w, mut da, mut dw) = (Vec2::ZERO, 0.0, Vec2::ZERO, 0.0); @@ -604,6 +643,132 @@ mod tests { Spline::from_control(vec![Vec2::new(0.0, 0.0), Vec2::new(3.0, 3.0), Vec2::new(6.0, -3.0), Vec2::new(9.0, 0.0), Vec2::new(12.0, 2.0)], 3) } + /// The previous implementation (two heap-allocated bases), kept as the oracle for the + /// allocation-free `derivative_unchecked`. + impl Spline { + fn derivative_unchecked_old(&self, t: f64) -> Vec2 { + let p = self.degree; + let Some(n) = self.control.len().checked_sub(1) else { return Vec2::ZERO }; + let (lo, hi) = self.domain(); + let t = if t.is_finite() { t.clamp(lo, hi) } else { lo }; + let span = find_span(n, p, t, &self.knots); + let nb = basis(span, t, p, &self.knots); + let nd = basis(span, t, p - 1, &self.knots); + let k = |i: usize| self.knots.get(i).copied().unwrap_or(0.0); + let ratio = |num: Option<&f64>, den: f64| if den.abs() > 1e-300 { num.copied().unwrap_or(0.0) / den } else { 0.0 }; + let (mut a, mut w, mut da, mut dw) = (Vec2::ZERO, 0.0, Vec2::ZERO, 0.0); + for j in 0..=p { + let Some(i) = (span + j).checked_sub(p) else { continue }; + let Some(c) = self.control.get(i) else { continue }; + let wi = self.weight(i); + let n0 = nb.get(j).copied().unwrap_or(0.0); + // N'_{i,p} = p (N_{i,p-1} / (u_{i+p} - u_i) - N_{i+1,p-1} / (u_{i+p+1} - u_{i+1})). + let left = if j >= 1 { ratio(nd.get(j - 1), k(i + p) - k(i)) } else { 0.0 }; + let right = if j < p { ratio(nd.get(j), k(i + p + 1) - k(i + 1)) } else { 0.0 }; + let dn = p as f64 * (left - right); + a += *c * (n0 * wi); + w += n0 * wi; + da += *c * (dn * wi); + dw += dn * wi; + } + if w.abs() < 1e-300 { + return Vec2::ZERO; + } + let d = (da - a / w * dw) / w; + if d.is_finite() { d } else { Vec2::ZERO } + } + } + + struct XorShift(u64); + impl XorShift { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + } + + /// A valid random spline of degree `p`: clamped or unclamped knots, repeated interior knots, + /// and non-rational, rational or zero/negative weights. + fn random_spline(r: &mut XorShift, p: usize) -> Spline { + let n = p + 1 + r.below(8); + let control = (0..n).map(|_| Vec2::new(r.unit() * 100.0 - 50.0, r.unit() * 100.0 - 50.0)).collect(); + let total = n + p + 1; + let mut knots: Vec = + (0..total).map(|_| (r.unit() * 8.0).floor() * if r.below(3) == 0 { 0.5 } else { 1.0 } + r.unit() * f64::from(r.below(2) == 0)).collect(); + knots.sort_by(f64::total_cmp); + if r.below(2) == 0 { + // Clamp both ends. + let (lo, hi) = (knots[p], knots[n]); + knots[..=p].fill(lo); + knots[n..].fill(hi); + } + let weights = match r.below(4) { + 0 => Vec::new(), + 1 => (0..n).map(|_| 0.2 + r.unit() * 4.0).collect(), + 2 => (0..n).map(|_| if r.below(5) == 0 { 0.0 } else { r.unit() * 2.0 - 0.5 }).collect(), + _ => (0..n).map(|_| 1.0 + r.unit() * 1e-9).collect(), + }; + Spline { degree: p, knots, control, weights, ..Spline::default() } + } + + fn bits(v: Vec2) -> (u64, u64) { + (v.x.to_bits(), v.y.to_bits()) + } + + #[test] + fn derivative_is_bit_identical_to_the_heap_implementation() { + let mut r = XorShift(0x9E37_79B9_7F4A_7C15); + let mut zero_results = 0usize; + for p in 1..=12usize { + let mut compared = 0usize; + for _ in 0..400 { + let s = random_spline(&mut r, p); + if !s.is_valid() { + continue; + } + let (lo, hi) = s.domain(); + let mut ts = vec![lo, hi, 0.5 * (lo + hi), lo - 1.0, hi + 1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY]; + ts.extend(s.knots.iter().copied()); + ts.extend(s.knots.iter().map(|k| k.next_up())); + ts.extend(s.knots.iter().map(|k| k.next_down())); + ts.extend((0..8).map(|_| lo + (hi - lo) * r.unit())); + for t in ts { + let (new, old) = (s.derivative_unchecked(t), s.derivative_unchecked_old(t)); + assert_eq!(bits(new), bits(old), "degree {p}, t = {t}, knots {:?}, weights {:?}", s.knots, s.weights); + compared += 1; + zero_results += usize::from(old == Vec2::ZERO); + } + } + assert!(compared > 1000, "degree {p}: only {compared} comparisons ran"); + } + // The zero-vector exits (vanishing weight sum, non-finite result) are exercised too. + assert!(zero_results > 0); + } + + #[test] + fn derivative_dispatch_around_the_stack_limit_does_not_change_results() { + // The last stack degree and the first heap degree both match the oracle on a clamped + // uniform spline (the heap degree runs the unchanged old path; this checks the dispatch). + for p in [MAX_STACK_DEGREE, MAX_STACK_DEGREE + 1] { + let ctrl: Vec = (0..p + 4).map(|i| Vec2::new(i as f64, (i * i % 7) as f64)).collect(); + let s = Spline::from_control(ctrl, p); + assert_eq!(s.degree, p); + let (lo, hi) = s.domain(); + for i in 0..=50 { + let t = lo + (hi - lo) * f64::from(i) / 50.0; + assert_eq!(bits(s.derivative_unchecked(t)), bits(s.derivative_unchecked_old(t)), "degree {p}, t = {t}"); + } + } + } + #[test] fn derivative_matches_finite_differences() { let mut s = cubic(); From 1f75a9fb2521f35e8bb5a5b15e8b7e0d290aee17 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 28 Oct 2026 23:57:30 +0100 Subject: [PATCH 094/531] geom: test region candidate pairs once, in their lowest shared grid cell The region build kept a SipHash HashSet of tested pairs over a SipHash HashMap grid. Each pair is now tested only in the lowest grid cell both segments occupy, and the grid is a flat Vec. The pairs tested, the visit and distinct-pair budgets and the output are unchanged; the old search is kept as a test oracle. Closes #2430 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/region.rs | 343 +++++++++++++++++++++++++++++++------- 1 file changed, 281 insertions(+), 62 deletions(-) diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index c186534c9..15ee47adc 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -75,7 +75,108 @@ fn split_pair(segs: &[(Vec2, Vec2)], splits: &mut [Vec], i: usize, j: usize } } +/// Upper bound on candidate-pair *visits*. Every visit counts, including repeats of a pair that shares several grid +/// cells, not only the distinct pairs actually tested. A long segment replicated across many +/// cells makes the same pair reappear in each, so a budget on distinct pairs alone leaves the +/// repeated work unbounded (CWE-407). +const MAX_PAIR_VISITS: u64 = 60_000_000; +/// Upper bound on distinct segment pairs tested for a crossing. +const MAX_PAIRS_TESTED: usize = 20_000_000; + +/// Split parameters of every segment (always `0` and `1`, plus every crossing), found with a uniform grid. +fn pair_splits(segs: &[(Vec2, Vec2)], bb: &Bounds2) -> Option>> { + pair_splits_limited(segs, bb, MAX_PAIR_VISITS, MAX_PAIRS_TESTED) +} + +/// `pair_splits` with explicit budgets: `None` once more than `max_visits` candidate pairs were visited +/// or more than `max_pairs` distinct pairs were tested. +fn pair_splits_limited(segs: &[(Vec2, Vec2)], bb: &Bounds2, max_visits: u64, max_pairs: usize) -> Option>> { + let n = segs.len(); + let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); + let cw = (bb.width() / cells as f64).max(1e-12); + let ch = (bb.height() / cells as f64).max(1e-12); + let cell = |p: Vec2| { + ( + ((p.x - bb.min.x) / cw).floor().clamp(0.0, (cells - 1) as f64) as usize, + ((p.y - bb.min.y) / ch).floor().clamp(0.0, (cells - 1) as f64) as usize, + ) + }; + // Cell lists in a flat grid, indexed `gx * cells + gy`; each list is in ascending segment order. + let mut grid: Vec> = vec![Vec::new(); cells * cells]; + // The lowest cell of each segment's cell range; the lowest cell two segments share is the + // componentwise maximum of their two. + let mut low: Vec<(usize, usize)> = vec![(0, 0); n]; + let mut is_long = vec![false; n]; + let mut long: Vec = Vec::new(); + for (i, (a, b)) in segs.iter().enumerate() { + let (x0, y0) = cell(a.min(*b)); + let (x1, y1) = cell(a.max(*b)); + if let Some(l) = low.get_mut(i) { + *l = (x0, y0); + } + if (x1 - x0 + 1) * (y1 - y0 + 1) > 4096 { + // Very long segment: too many cells to register in; it is tested against every segment below. + long.push(i); + if let Some(f) = is_long.get_mut(i) { + *f = true; + } + continue; + } + for gx in x0..=x1 { + for gy in y0..=y1 { + if let Some(list) = grid.get_mut(gx * cells + gy) { + list.push(i); + } + } + } + } + let mut splits: Vec> = vec![vec![0.0, 1.0]; n]; + let mut tested: usize = 0; + let mut visits: u64 = 0; + for (c, list) in grid.iter().enumerate() { + let (gx, gy) = (c / cells, c % cells); + for (k, &i) in list.iter().enumerate() { + let Some(&(ix, iy)) = low.get(i) else { continue }; + for &j in list.iter().skip(k + 1) { + visits += 1; + if visits > max_visits { + return None; + } + let Some(&(jx, jy)) = low.get(j) else { continue }; + // A pair sharing several cells is tested once, in the lowest cell both occupy. + if i == j || gx != ix.max(jx) || gy != iy.max(jy) { + continue; + } + split_pair(segs, &mut splits, i, j); + tested += 1; + if tested > max_pairs { + return None; + } + } + } + } + // A long segment is in no cell list. Two long segments are tested once, from the lower index. + for &i in &long { + for j in 0..n { + if i == j || (j < i && is_long.get(j).copied().unwrap_or(false)) { + continue; + } + split_pair(segs, &mut splits, i, j); + tested += 1; + if tested > max_pairs { + return None; + } + } + } + Some(splits) +} + fn build(polys: &[Vec], tol: f64) -> Option { + build_with(polys, tol, pair_splits) +} + +/// `build` with the crossing search injected, so tests can run the old and the new search on the same input. +fn build_with(polys: &[Vec], tol: f64, find_splits: impl Fn(&[(Vec2, Vec2)], &Bounds2) -> Option>>) -> Option { let mut segs: Vec<(Vec2, Vec2)> = Vec::new(); let mut owner: Vec = Vec::new(); for (k, pl) in polys.iter().enumerate() { @@ -96,70 +197,9 @@ fn build(polys: &[Vec], tol: f64) -> Option { if segs.is_empty() || segs.len() > MAX_SEGMENTS { return None; } - // Split points per segment (parameters), found with a uniform grid. let bb = Bounds2::from_points(segs.iter().flat_map(|(a, b)| [*a, *b])); let n = segs.len(); - let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); - let cw = (bb.width() / cells as f64).max(1e-12); - let ch = (bb.height() / cells as f64).max(1e-12); - let cell = |p: Vec2| { - ( - ((p.x - bb.min.x) / cw).floor().clamp(0.0, (cells - 1) as f64) as usize, - ((p.y - bb.min.y) / ch).floor().clamp(0.0, (cells - 1) as f64) as usize, - ) - }; - let mut grid: HashMap<(usize, usize), Vec> = HashMap::new(); - let mut long: Vec = Vec::new(); - for (i, (a, b)) in segs.iter().enumerate() { - let (x0, y0) = cell(a.min(*b)); - let (x1, y1) = cell(a.max(*b)); - if (x1 - x0 + 1) * (y1 - y0 + 1) > 4096 { - // Very long segment: too many cells to register in; it is tested against every segment below. - long.push(i); - continue; - } - for gx in x0..=x1 { - for gy in y0..=y1 { - grid.entry((gx, gy)).or_default().push(i); - } - } - } - let mut splits: Vec> = vec![vec![0.0, 1.0]; n]; - let mut tested = std::collections::HashSet::new(); - // Count every candidate-pair *visit*, including repeats of a pair that shares several grid - // cells, not only the distinct pairs actually tested. A long segment replicated across many - // cells makes the same pair reappear in each, so a budget on distinct pairs alone leaves the - // repeated hashing unbounded (CWE-407). - let mut visits: u64 = 0; - const MAX_PAIR_VISITS: u64 = 60_000_000; - for list in grid.values() { - for (k, &i) in list.iter().enumerate() { - for &j in list.iter().skip(k + 1) { - visits += 1; - if visits > MAX_PAIR_VISITS { - return None; - } - if i == j || !tested.insert((i.min(j), i.max(j))) { - continue; - } - split_pair(&segs, &mut splits, i, j); - if tested.len() > 20_000_000 { - return None; - } - } - } - } - for &i in &long { - for j in 0..n { - if i == j || !tested.insert((i.min(j), i.max(j))) { - continue; - } - split_pair(&segs, &mut splits, i, j); - if tested.len() > 20_000_000 { - return None; - } - } - } + let splits = find_splits(&segs, &bb)?; let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new() }; let mut index: HashMap<(i64, i64), usize> = HashMap::new(); let mut vid = |p: Vec2, g: &mut Graph| -> usize { @@ -630,6 +670,185 @@ mod tests { vec![Vec2::new(x0, y0), Vec2::new(x0 + s, y0), Vec2::new(x0 + s, y0 + s), Vec2::new(x0, y0 + s), Vec2::new(x0, y0)] } + /// The crossing search before the lowest-shared-cell rule: a `HashSet` of tested pairs over a `HashMap` grid. + fn pair_splits_oracle(segs: &[(Vec2, Vec2)], bb: &Bounds2, max_visits: u64, max_pairs: usize) -> Option>> { + let n = segs.len(); + let cells = ((n as f64).sqrt().ceil() as usize).clamp(1, 512); + let cw = (bb.width() / cells as f64).max(1e-12); + let ch = (bb.height() / cells as f64).max(1e-12); + let cell = |p: Vec2| { + ( + ((p.x - bb.min.x) / cw).floor().clamp(0.0, (cells - 1) as f64) as usize, + ((p.y - bb.min.y) / ch).floor().clamp(0.0, (cells - 1) as f64) as usize, + ) + }; + let mut grid: HashMap<(usize, usize), Vec> = HashMap::new(); + let mut long: Vec = Vec::new(); + for (i, (a, b)) in segs.iter().enumerate() { + let (x0, y0) = cell(a.min(*b)); + let (x1, y1) = cell(a.max(*b)); + if (x1 - x0 + 1) * (y1 - y0 + 1) > 4096 { + long.push(i); + continue; + } + for gx in x0..=x1 { + for gy in y0..=y1 { + grid.entry((gx, gy)).or_default().push(i); + } + } + } + let mut splits: Vec> = vec![vec![0.0, 1.0]; n]; + let mut tested = std::collections::HashSet::new(); + let mut visits: u64 = 0; + for list in grid.values() { + for (k, &i) in list.iter().enumerate() { + for &j in list.iter().skip(k + 1) { + visits += 1; + if visits > max_visits { + return None; + } + if i == j || !tested.insert((i.min(j), i.max(j))) { + continue; + } + split_pair(segs, &mut splits, i, j); + if tested.len() > max_pairs { + return None; + } + } + } + } + for &i in &long { + for j in 0..n { + if i == j || !tested.insert((i.min(j), i.max(j))) { + continue; + } + split_pair(segs, &mut splits, i, j); + if tested.len() > max_pairs { + return None; + } + } + } + Some(splits) + } + + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn unit(&mut self) -> f64 { + (self.next() >> 11) as f64 / (1u64 << 53) as f64 + } + } + + /// Random segments: short ones, some long ones, and some on a coarse lattice (shared ends, overlaps). + fn random_segments(r: &mut Rng, n: usize, size: f64, long_every: u64) -> Vec<(Vec2, Vec2)> { + let mut out = Vec::new(); + for _ in 0..n { + let a = Vec2::new(r.unit() * size, r.unit() * size); + let seg = match r.next() % 4 { + 0 if long_every > 0 && r.next().is_multiple_of(long_every) => ( + Vec2::new(r.unit() * size * 0.02, r.unit() * size * 0.02), + Vec2::new(size * (0.98 + r.unit() * 0.02), size * (0.98 + r.unit() * 0.02)), + ), + 1 => { + let q = |r: &mut Rng| (r.next() % 9) as f64 * size / 8.0; + (Vec2::new(q(r), q(r)), Vec2::new(q(r), q(r))) + } + _ => (a, a + Vec2::new((r.unit() - 0.5) * size * 0.1, (r.unit() - 0.5) * size * 0.1)), + }; + if !seg.0.near(seg.1, 1e-9) { + out.push(seg); + } + } + out + } + + fn sorted_bits(splits: &[Vec]) -> Vec> { + splits + .iter() + .map(|v| { + let mut v = v.clone(); + v.sort_by(f64::total_cmp); + v.iter().map(|x| x.to_bits()).collect() + }) + .collect() + } + + fn bounds_of(segs: &[(Vec2, Vec2)]) -> Bounds2 { + Bounds2::from_points(segs.iter().flat_map(|(a, b)| [*a, *b])) + } + + fn assert_same_search(segs: &[(Vec2, Vec2)], max_visits: u64, max_pairs: usize) { + let bb = bounds_of(segs); + let old = pair_splits_oracle(segs, &bb, max_visits, max_pairs); + let new = pair_splits_limited(segs, &bb, max_visits, max_pairs); + assert_eq!(old.as_deref().map(sorted_bits), new.as_deref().map(sorted_bits), "n={} visits<={max_visits} pairs<={max_pairs}", segs.len()); + } + + #[test] + fn pair_search_matches_oracle_with_budgets() { + // Small inputs in few cells: many pairs share several cells, and sweeping both budgets + // across their full range hits every exhaustion point (and the exact boundary). + for seed in 1..=150u64 { + let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let n = 2 + (r.next() % 28) as usize; + let segs = random_segments(&mut r, n, 100.0, 0); + if segs.is_empty() { + continue; + } + for v in 0..=400u64 { + assert_same_search(&segs, v, usize::MAX); + } + for p in 0..=400usize { + assert_same_search(&segs, u64::MAX, p); + } + assert_same_search(&segs, 60_000_000, 20_000_000); + } + } + + #[test] + fn pair_search_matches_oracle_with_long_segments() { + // Around 5000 segments give a 71x71 grid, so a diagonal covers more than 4096 cells and takes the long path. + for seed in 1..=3u64 { + let mut r = Rng(seed.wrapping_mul(0xD1B5_4A32_D192_ED03) | 1); + let n = 5_000 + (r.next() % 500) as usize; + let segs = random_segments(&mut r, n, 1000.0, 40); + let bb = bounds_of(&segs); + let cells = ((segs.len() as f64).sqrt().ceil() as usize).clamp(1, 512); + assert!(cells >= 64, "grid too coarse to reach the long path"); + assert_same_search(&segs, 60_000_000, 20_000_000); + // Budget exhausted in the cell phase, and in the long phase. + assert_same_search(&segs, 3_000, 20_000_000); + assert_same_search(&segs, 60_000_000, 200); + let (cw, ch) = ((bb.width() / cells as f64).max(1e-12), (bb.height() / cells as f64).max(1e-12)); + let span = |a: f64, b: f64, o: f64, w: f64| { + (((b.max(a) - o) / w).floor().min((cells - 1) as f64) - ((b.min(a) - o) / w).floor().max(0.0) + 1.0) as usize + }; + let long = segs.iter().filter(|(a, b)| span(a.x, b.x, bb.min.x, cw) * span(a.y, b.y, bb.min.y, ch) > 4096).count(); + assert!(long > 0, "seed {seed}: no segment takes the long path"); + } + } + + #[test] + fn build_matches_oracle_on_random_drawings() { + for seed in 1..=60u64 { + let mut r = Rng(seed.wrapping_mul(0xA076_1D64_78BD_642F) | 1); + let n = 5 + (r.next() % 400) as usize; + let polys: Vec> = random_segments(&mut r, n, 100.0, 0).into_iter().map(|(a, b)| vec![a, b]).collect(); + let old = build_with(&polys, 1e-6, |s, bb| pair_splits_oracle(s, bb, MAX_PAIR_VISITS, MAX_PAIRS_TESTED)); + let new = build(&polys, 1e-6); + let (Some(old), Some(new)) = (old, new) else { panic!("seed {seed}: build failed") }; + assert_eq!(old.pts, new.pts, "seed {seed}"); + assert_eq!(old.adj, new.adj, "seed {seed}"); + assert_eq!(old.src, new.src, "seed {seed}"); + assert_eq!(old.edge_src, new.edge_src, "seed {seed}"); + } + } + #[test] fn long_segment_crossing_in_unsampled_cell_is_split() { // A diagonal long enough to skip the grid, and a short segment crossing it in a cell the old coarse sampling missed. From 98b47c1984d4dfcd6fe799e6a6cad838ba667252 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 28 Oct 2026 23:58:35 +0100 Subject: [PATCH 095/531] perf(geom): limit the spline fit solver to the matrix band `solve` ran dense Gaussian elimination on a banded matrix. The pivot scan, the elimination and the back-substitution now stop at the band measured from the matrix. The skipped operations only combine exact zeros, so results are bit-identical; the cyclic matrix of a closed fit has full bandwidth and keeps the full sweep. The old solver stays as a test-only oracle. Part of #2432 Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/spline.rs | 58 +++++++++- crates/geom/src/spline/tests.rs | 193 ++++++++++++++++++++++++++++++++ 2 files changed, 246 insertions(+), 5 deletions(-) diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index d954e66b1..0c193d577 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -288,21 +288,64 @@ fn basis_into(span: usize, u: f64, p: usize, knots: &[f64], n: &mut [f64], left: } } -/// Gaussian elimination with partial pivoting. +/// Gaussian elimination with partial pivoting. The interpolation and least-squares matrices are +/// banded, so every loop is limited to the band (lower width `kl`, upper width `ku`, measured from +/// the matrix; partial pivoting widens the upper band to at most `kl + ku`). The skipped operations +/// only combine entries that are exactly `+0.0` (they stay `+0.0` through the full sweep), so the +/// result is bit for bit that of the full sweep (for finite input that does not overflow). A matrix with full bandwidth (the cyclic matrix of +/// a closed fit) costs what it did before. +/// +/// A skipped `0 * x` is not zero when `x` is NaN or infinite, so a matrix or right-hand side with +/// NaN, infinity or magnitudes above `1e100` (which could overflow) takes the full sweep, and so +/// does a back-substitution row whose banded sum is zero (skipped zero terms can flip its sign). #[allow(clippy::needless_range_loop)] pub(crate) fn solve(mut a: Vec>, mut b: Vec) -> Option> { + #[cfg(test)] + if tests::DENSE_ORACLE.get() { + return tests::solve_dense(a, b); + } let n = b.len(); + // Per row: how far its non-zero entries reach left and right of the diagonal, and whether one + // is NaN, infinite or large enough to overflow. + let measure = |r: usize, row: &[f64]| { + // Bit test, not `!= 0.0`: a stored `-0.0` is not the `+0.0` the skipped entries rely on. + let row = row.get(..n).unwrap_or(row); + let Some(first) = row.iter().position(|v| v.to_bits() != 0) else { return (0, 0, false) }; + let last = row.iter().rposition(|v| v.to_bits() != 0).unwrap_or(first); + let wild = row.get(first..=last).is_some_and(|band| band.iter().any(|v| v.is_nan() || v.abs() > 1e100)); + (r.saturating_sub(first), last.saturating_sub(r), wild) + }; + let join = |x: (usize, usize, bool), m: (usize, usize, bool)| (x.0.max(m.0), x.1.max(m.1), x.2 | m.2); + // A last row that reaches column 0 (the cyclic matrix of a closed fit) makes every range of the + // sweep full-width whatever the other rows hold, so they need no measuring. + let mut m = (0usize, 0usize, false); + for r in [0, n.saturating_sub(1)] { + if let Some(row) = a.get(r) { + m = join(m, measure(r, row)); + } + } + // (kl = n - 1 widens every range to the full matrix, so the unmeasured rows cannot matter.) + if m.0 + 1 < n { + m = a.iter().enumerate().take(n).fold(m, |x, (r, row)| join(x, measure(r, row))); + } + let (mut kl, mut ku, wild) = m; + if wild || b.iter().any(|v| v.is_nan() || v.abs() > 1e100) { + (kl, ku) = (n, n); + } + let kw = ku + kl; for c in 0..n { - let piv = (c..n).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?; + let end = (c + kl).min(n - 1) + 1; + let piv = (c..end).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?; if a[piv][c].abs() < 1e-14 { return None; } a.swap(c, piv); b.swap(c, piv); - for r in c + 1..n { + let kend = (c + kw).min(n - 1) + 1; + for r in c + 1..end { let f = a[r][c] / a[c][c]; if f != 0.0 { - for k in c..n { + for k in c..kend { a[r][k] -= f * a[c][k]; } b[r] -= f * b[c]; @@ -311,7 +354,12 @@ pub(crate) fn solve(mut a: Vec>, mut b: Vec) -> Option> { } let mut x = vec![0.0; n]; for r in (0..n).rev() { - let s: f64 = (r + 1..n).map(|k| a[r][k] * x[k]).sum(); + let end = (r + kw).min(n - 1) + 1; + let mut s: f64 = (r + 1..end).map(|k| a[r][k] * x[k]).sum(); + if s == 0.0 && end < n { + // The skipped terms are signed zeros; added to a zero they can flip its sign. + s = (r + 1..n).map(|k| a[r][k] * x[k]).sum(); + } x[r] = (b[r] - s) / a[r][r]; } Some(x) diff --git a/crates/geom/src/spline/tests.rs b/crates/geom/src/spline/tests.rs index d953cfabd..5e7a68b72 100644 --- a/crates/geom/src/spline/tests.rs +++ b/crates/geom/src/spline/tests.rs @@ -303,3 +303,196 @@ fn a_normal_low_degree_spline_is_valid() { assert!(s.is_valid()); assert!(s.tessellate(1e-3).len() > 4); } + +thread_local! { + /// While set, `solve` runs `solve_dense` (this thread only, so parallel tests do not mix). + pub(super) static DENSE_ORACLE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `solve` before it was limited to the matrix band, kept as the reference. +#[allow(clippy::needless_range_loop)] +pub(super) fn solve_dense(mut a: Vec>, mut b: Vec) -> Option> { + let n = b.len(); + for c in 0..n { + let piv = (c..n).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?; + if a[piv][c].abs() < 1e-14 { + return None; + } + a.swap(c, piv); + b.swap(c, piv); + for r in c + 1..n { + let f = a[r][c] / a[c][c]; + if f != 0.0 { + for k in c..n { + a[r][k] -= f * a[c][k]; + } + b[r] -= f * b[c]; + } + } + } + let mut x = vec![0.0; n]; + for r in (0..n).rev() { + let s: f64 = (r + 1..n).map(|k| a[r][k] * x[k]).sum(); + x[r] = (b[r] - s) / a[r][r]; + } + Some(x) +} + +fn bits(v: &[f64]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +fn bits2(v: &[Vec2]) -> Vec { + v.iter().flat_map(|p| [p.x.to_bits(), p.y.to_bits()]).collect() +} + +/// Both solvers on one system: `None` together, or the same bits. +fn assert_same_solution(a: &[Vec], b: &[f64], what: &str) { + let old = solve_dense(a.to_vec(), b.to_vec()); + let new = solve(a.to_vec(), b.to_vec()); + assert_eq!(old.as_deref().map(bits), new.as_deref().map(bits), "{what}"); +} + +/// A random matrix with `kl` sub- and `ku` super-diagonals (some entries exactly zero). +fn banded(n: usize, kl: usize, ku: usize, seed: &mut u64) -> Vec> { + let mut a = vec![vec![0.0; n]; n]; + for (r, row) in a.iter_mut().enumerate() { + for (c, v) in row.iter_mut().enumerate() { + if c + kl >= r && c <= r + ku && noise(seed) > 0.15 { + *v = noise(seed) * 4.0 - 2.0; + } + } + } + a +} + +#[test] +fn banded_solve_matches_the_dense_sweep_bit_for_bit() { + let mut seed = 0x5eed_u64; + for n in [1, 2, 3, 4, 5, 8, 17, 40, 120] { + for (kl, ku) in [(0, 0), (1, 0), (0, 2), (1, 1), (3, 3), (2, 5), (n, n)] { + for _ in 0..6 { + let a = banded(n, kl, ku, &mut seed); + // Right-hand sides with zeros of both signs make the zero-sign cases reachable. + let b: Vec = (0..n) + .map(|i| [noise(&mut seed) * 9.0 - 4.0, 0.0, -0.0][(noise(&mut seed) * 3.0) as usize % 3] * (i % 4 != 0) as u8 as f64) + .collect(); + assert_same_solution(&a, &b, &format!("n={n} kl={kl} ku={ku}")); + assert_same_solution(&a, &vec![0.0; n], &format!("zero rhs n={n} kl={kl} ku={ku}")); + assert_same_solution(&a, &vec![-0.0; n], &format!("negative-zero rhs n={n} kl={kl} ku={ku}")); + } + } + } +} + +#[test] +fn solve_handles_negative_zeros_signed_zero_sums_and_hostile_values() { + let mut seed = 77_u64; + for n in [3, 6, 30] { + let mut a = banded(n, 1, 2, &mut seed); + // A stored `-0.0` outside the band is still part of the matrix. + a[0][n - 1] = -0.0; + a[n - 1][0] = -0.0; + let b: Vec = (0..n).map(|i| if i % 2 == 0 { -0.0 } else { 1.0 }).collect(); + assert_same_solution(&a, &b, &format!("negative zeros n={n}")); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e200, 1e101] { + let mut ab = a.clone(); + ab[n / 2][n / 2] = bad; + assert_same_solution(&ab, &b, &format!("{bad:?} in the matrix, n={n}")); + let mut bb = b.clone(); + bb[n - 1] = bad; + assert_same_solution(&a, &bb, &format!("{bad:?} in the rhs, n={n}")); + } + } + // Bad values in a narrow band with no corner entry, so the guard (not a full-width matrix) decides. + for bad in [f64::NAN, f64::INFINITY, 1e200, 1e101] { + let a = banded(12, 1, 2, &mut seed); + let mut ab = a.clone(); + ab[5][5] = bad; + ab[5][6] = 1.0; + assert_same_solution(&ab, &[1.0; 12], &format!("{bad:?} in a narrow band")); + let mut b = vec![1.0; 12]; + b[3] = bad; + assert_same_solution(&a, &b, &format!("{bad:?} in the rhs of a narrow band")); + } + // Singular and empty systems. + assert_same_solution(&[vec![0.0, 0.0], vec![0.0, 1.0]], &[1.0, 1.0], "singular"); + assert_same_solution(&[], &[], "empty"); + assert_eq!(solve(Vec::new(), Vec::new()), Some(Vec::new())); +} + +/// Fit points: a wavy line with noise; every `zero_every`-th coordinate is exactly zero. +fn fit_points(n: usize, seed: &mut u64, zero_every: usize) -> Vec { + (0..n) + .map(|i| { + let x = i as f64 * 3.0 + noise(seed); + let y = (i as f64 * 0.3).sin() * 50.0 + noise(seed) * 5.0; + if zero_every > 0 && i % zero_every == 0 { Vec2::new(x, 0.0) } else { Vec2::new(x, y) } + }) + .collect() +} + +fn spline_bits(s: &Spline) -> (Vec, Vec, Vec, Vec, usize) { + (bits(&s.knots), bits2(&s.control), bits(&s.weights), bits2(&s.fit), s.degree) +} + +/// Fit with the banded `solve`, then with the dense reference, and compare every bit. +/// Clears `DENSE_ORACLE` when dropped, so a failing assertion cannot leave it set. +struct OracleOff; +impl Drop for OracleOff { + fn drop(&mut self) { + DENSE_ORACLE.set(false); + } +} + +fn assert_fit_unchanged(fit: &[Vec2], closed: bool, opts: FitOptions, what: &str) { + let _off = OracleOff; + let new = Spline::fit_with(fit, closed, opts); + DENSE_ORACLE.set(true); + let old = Spline::fit_with(fit, closed, opts); + DENSE_ORACLE.set(false); + assert_eq!(spline_bits(&old), spline_bits(&new), "{what}"); +} + +#[test] +fn fits_are_bit_identical_to_the_dense_solver() { + let mut seed = 2432_u64; + let tolerant = FitOptions { tolerance: 0.5, ..FitOptions::default() }; + let tangents = FitOptions { start_tangent: Some(Vec2::new(0.0, 1.0)), end_tangent: Some(Vec2::new(1.0, -1.0)), ..FitOptions::default() }; + let chord = FitOptions { knots: crate::KnotParam::Chord, ..FitOptions::default() }; + for n in [3, 4, 5, 7, 12, 30, 100] { + for round in 0..4 { + let zero_every = [0, 2, 3, 1][round]; + let pts = fit_points(n, &mut seed, zero_every); + for closed in [false, true] { + for (name, opts) in [("default", FitOptions::default()), ("tolerance", tolerant), ("tangents", tangents), ("chord", chord)] { + assert_fit_unchanged(&pts, closed, opts, &format!("n={n} closed={closed} {name} zero_every={zero_every}")); + } + } + } + } + // Large point sets: open interpolation (banded) and a closed one (full bandwidth), and a + // tolerance fit at the size the approximation search still accepts. + let big = fit_points(1000, &mut seed, 0); + assert_fit_unchanged(&big, false, FitOptions::default(), "n=1000 open"); + assert_fit_unchanged(&big[..150], true, FitOptions::default(), "n=150 closed"); + assert_fit_unchanged(&big[..300], false, tolerant, "n=300 tolerance"); + // Repeated points are kinks, which fit each piece on its own. + let mut kinked = fit_points(40, &mut seed, 0); + kinked.insert(10, kinked[10]); + kinked.insert(25, kinked[25]); + assert_fit_unchanged(&kinked, false, FitOptions::default(), "kinks"); +} + +#[test] +fn the_cyclic_matrix_of_a_closed_fit_keeps_the_full_sweep() { + // Corner entries give the closed matrix a full bandwidth; it must still agree with the dense sweep. + let mut seed = 9_u64; + for n in [4, 9, 60] { + let mut a = banded(n, 1, 1, &mut seed); + a[0][n - 1] = 0.7; + a[n - 1][0] = -0.3; + let b: Vec = (0..n).map(|_| noise(&mut seed)).collect(); + assert_same_solution(&a, &b, &format!("cyclic n={n}")); + } +} From 08ea23ec2dac90c665f63350fc10cc0e043a91d3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 28 Oct 2026 23:59:45 +0100 Subject: [PATCH 096/531] geom: tighten region oracle test budget assertions Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/region.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index 15ee47adc..0c7ddd326 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -791,8 +791,8 @@ mod tests { #[test] fn pair_search_matches_oracle_with_budgets() { - // Small inputs in few cells: many pairs share several cells, and sweeping both budgets - // across their full range hits every exhaustion point (and the exact boundary). + // Small inputs in few cells: many pairs share several cells. Sweeping each budget over + // 0..=400 crosses its exhaustion point for most seeds, including the exact boundary. for seed in 1..=150u64 { let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); let n = 2 + (r.next() % 28) as usize; @@ -821,9 +821,11 @@ mod tests { let cells = ((segs.len() as f64).sqrt().ceil() as usize).clamp(1, 512); assert!(cells >= 64, "grid too coarse to reach the long path"); assert_same_search(&segs, 60_000_000, 20_000_000); - // Budget exhausted in the cell phase, and in the long phase. + // Budgets exhausted in the cell phase (visits, then pairs). assert_same_search(&segs, 3_000, 20_000_000); assert_same_search(&segs, 60_000_000, 200); + assert!(pair_splits_limited(&segs, &bb, 3_000, 20_000_000).is_none()); + assert!(pair_splits_limited(&segs, &bb, 60_000_000, 200).is_none()); let (cw, ch) = ((bb.width() / cells as f64).max(1e-12), (bb.height() / cells as f64).max(1e-12)); let span = |a: f64, b: f64, o: f64, w: f64| { (((b.max(a) - o) / w).floor().min((cells - 1) as f64) - ((b.min(a) - o) / w).floor().max(0.0) + 1.0) as usize From 21d96278400c165969cabde381c8dc4bc3b29bcf Mon Sep 17 00:00:00 2001 From: austin62jake <340374338+austin62jake@users.noreply.github.com> Date: Wed, 28 Oct 2026 22:33:23 -0500 Subject: [PATCH 097/531] fix(ui): Window > Reference Manager closes the open palette Once the External References palette was open, Window > Reference Manager only opened it again, so there was no obvious way to close it (the tab's right-click Close Panel works but is easy to miss). The menu item now closes the palette when it is open, as Window > QuickCalc does for QuickCalc (#2001). Typed XREF still only opens it, as in AutoCAD, and XREF with JSON parameters still only lists the references. Fixes #2273. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/menus.rs | 11 +++++++++-- crates/ui-egui/src/xrefs.rs | 6 ++++++ crates/ui-egui/tests/xref_palette.rs | 19 ++++++++++++++++++- docs/control-protocol.md | 6 ++++++ 4 files changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 58055542f..bc620e053 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -699,13 +699,20 @@ fn switch_on_hover(ctx: &egui::Context, titles: &[egui::Response]) { } } -/// Activate a menu command. QuickCalc toggles transparently; other items clear pending -/// command-line text and start their command interactively. +/// Activate a menu command. QuickCalc toggles transparently, and Reference Manager closes its +/// palette when it is open (typed XREF only opens it); other items clear pending command-line +/// text and start their command interactively. pub fn activate(app: &mut CadApp, id: &str) { if id == "ui.toggle.quickcalc" { run_transparent(app, id); return; } + if id == "xref" && app.ui.docking.layout.contains(&crate::docking::Panel::ExternalRefs) { + if let Err(e) = crate::xrefs::close_palette(app) { + app.set_status(e); + } + return; + } app.cmd.buffer.clear(); app.start(id); } diff --git a/crates/ui-egui/src/xrefs.rs b/crates/ui-egui/src/xrefs.rs index 51a21834f..b7838f645 100644 --- a/crates/ui-egui/src/xrefs.rs +++ b/crates/ui-egui/src/xrefs.rs @@ -43,6 +43,12 @@ fn open_palette(app: &mut CadApp) -> Result { crate::docking::command(app, false, &json!({ "operation": "open", "panel": Panel::ExternalRefs.id() })) } +/// Close the palette: Window ▸ Reference Manager while it is open, as Window ▸ QuickCalc closes +/// QuickCalc (#2273). +pub(crate) fn close_palette(app: &mut CadApp) -> Result { + crate::docking::command(app, false, &json!({ "operation": "close", "panel": Panel::ExternalRefs.id() })) +} + /// A picked file inside the host drawing's folder is attached by its relative path, so the /// project folder can move. fn relative_to_host(app: &CadApp, picked: &str) -> String { diff --git a/crates/ui-egui/tests/xref_palette.rs b/crates/ui-egui/tests/xref_palette.rs index 2f242b277..9d6e3c9bd 100644 --- a/crates/ui-egui/tests/xref_palette.rs +++ b/crates/ui-egui/tests/xref_palette.rs @@ -5,7 +5,7 @@ use cadcraft_engine::Session; use cadcraft_engine::cmd::file::{IoHooks, set_io}; use cadcraft_engine::doc::geom::Vec3; use cadcraft_engine::doc::{Drawing, Entity, EntityKind, Handle, Layer, Line, XrefStatus}; -use cadcraft_ui_egui::{CadApp, Services, docking::Panel}; +use cadcraft_ui_egui::{CadApp, Services, docking::Panel, menus}; use egui::vec2; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -73,6 +73,23 @@ fn xref_opens_the_palette_and_its_buttons_manage_the_xref() { h.get_by_label("site"); } +/// Window ▸ Reference Manager closes the palette when it is open, like Window ▸ QuickCalc; typed, +/// XREF only ever opens it (#2273). +#[test] +fn the_window_menu_item_closes_an_open_palette() { + let mut app = CadApp::new(Session::default(), Services::default()); + let open = |app: &CadApp| app.ui.docking.layout.contains(&Panel::ExternalRefs); + menus::activate(&mut app, "xref"); + assert!(open(&app), "the menu item opens the palette"); + menus::activate(&mut app, "xref"); + assert!(!open(&app), "the menu item closes the open palette"); + menus::activate(&mut app, "xref"); + assert!(open(&app), "and opens it again"); + assert!(app.cmdline("XREF").is_none()); + assert!(app.cmdline("XR").is_none()); + assert!(open(&app), "typed XREF keeps it open"); +} + #[test] fn json_xref_lists_and_never_opens_the_palette() { let mut app = CadApp::new(Session::default(), Services::default()); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 98db28330..e635a6186 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -144,6 +144,12 @@ The shortcut also works with text-field focus. Toggling preserves the running dr and pending command-line input. The expression, history and calculator variables survive closing/reopening within the same session; they are not saved across application restarts. +The External References palette (`externalReferences`) is not part of the default arrangement +either. Typed `XREF`/`XR` opens and activates it. **Window > Reference Manager** (also +`ui.menu.invoke` with `xref`) opens it too, but closes it when it is present, as Window > +QuickCalc does; closing leaves the running command and command-line input alone. `xref` with +JSON parameters lists the references and never opens or closes the palette. + Invoke these UI commands through `engine.execute`, for example `{"command":"ui.dock","params":{"operation":"float","panel":"layers","rect":[100,100,320,440]}}`. Advanced `ui.dock` operations use the same validated transaction as pointer gestures: From 14296dc4f512db28055b002a2fd4ebff16fff8a1 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 18:40:12 +0100 Subject: [PATCH 098/531] blocks: XCLIP and XCLIPFRAME, clipped references kept through DXF and DWG XCLIP clips block and xref references to a rectangular, polygonal or closed-polyline boundary (Invert clip, ON/OFF, Delete, generate Polyline; Clipdepth is ignored in 2D). The boundary is Insert::clip, in block coordinates, so it follows its reference; other references stay whole. Clipped references are drawn, plotted and framed (XCLIPFRAME 0/1/2) cut to the boundary, attributes included, and their extents are cut to it. DXF and DWG read and write it as the reference's ACAD_FILTER/SPATIAL SPATIAL_FILTER; filters the model can't hold stay foreign data. Gap F2. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/constraints/src/model.rs | 1 + crates/constraints/tests/dof.rs | 2 + crates/doc/src/array.rs | 1 + crates/doc/src/entity/block.rs | 19 + crates/doc/src/extents.rs | 7 + crates/doc/src/lib.rs | 2 + crates/doc/src/tests.rs | 5 + crates/doc/src/xclip.rs | 85 ++++ crates/engine/src/cmd/array.rs | 1 + crates/engine/src/cmd/blocks.rs | 3 + crates/engine/src/cmd/blocks/xclip.rs | 462 ++++++++++++++++++ crates/engine/src/cmd/exchange.rs | 1 + crates/engine/src/cmd/mleader_content.rs | 1 + crates/engine/src/snap.rs | 1 + crates/engine/src/spatial.rs | 2 + crates/engine/src/sysvars/table.rs | 2 + crates/engine/tests/audit.rs | 1 + crates/engine/tests/autosave.rs | 1 + crates/engine/tests/clipboard.rs | 1 + crates/engine/tests/compare.rs | 2 + crates/engine/tests/insert_file.rs | 1 + crates/engine/tests/it/blockreplace.rs | 1 + crates/engine/tests/it/compare_export.rs | 1 + crates/engine/tests/it/count.rs | 1 + crates/engine/tests/it/main.rs | 1 + .../tests/it/measure_distance_snapping.rs | 1 + crates/engine/tests/it/purge_mlinestyles.rs | 1 + crates/engine/tests/it/refedit.rs | 2 + crates/engine/tests/it/snap_blocks.rs | 1 + crates/engine/tests/it/snap_tracking.rs | 1 + crates/engine/tests/it/xclip.rs | 214 ++++++++ crates/engine/tests/usage.rs | 1 + crates/engine/tests/xref.rs | 1 + crates/io/src/dxf_clip.rs | 374 ++++++++++++++ crates/io/src/dxf_mleader.rs | 1 + crates/io/src/dxf_read.rs | 1 + crates/io/src/dxf_read/entities.rs | 1 + crates/io/src/dxf_write/sections.rs | 3 + crates/io/src/lib.rs | 2 + crates/io/src/tests.rs | 3 + crates/io/tests/it/annotative_roundtrip.rs | 1 + crates/io/tests/it/assoc_array_roundtrip.rs | 1 + crates/io/tests/it/attrib_modes.rs | 1 + crates/io/tests/it/attrib_props.rs | 1 + .../io/tests/it/dim_block_resave_roundtrip.rs | 1 + crates/io/tests/it/dynblock_read.rs | 2 + crates/io/tests/it/entity_props_roundtrip.rs | 1 + crates/io/tests/it/main.rs | 1 + crates/io/tests/it/mleader_content.rs | 1 + crates/io/tests/it/mleader_roundtrip.rs | 1 + crates/io/tests/it/pdf_layers.rs | 1 + crates/io/tests/it/xclip_roundtrip.rs | 164 +++++++ crates/io/tests/it/xref_roundtrip.rs | 1 + crates/render/src/blocks.rs | 56 ++- crates/render/src/clip.rs | 74 +++ crates/render/src/lib.rs | 18 +- crates/render/src/tests.rs | 2 + crates/render/src/viewports.rs | 55 ++- crates/render/tests/block_ltscale.rs | 1 + crates/render/tests/it/aci7_display.rs | 1 + crates/render/tests/it/plot_styles.rs | 1 + crates/render/tests/it/render_props.rs | 1 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + docs/gaps.md | 7 +- docs/target-app-parity.md | 5 +- 66 files changed, 1603 insertions(+), 11 deletions(-) create mode 100644 crates/doc/src/xclip.rs create mode 100644 crates/engine/src/cmd/blocks/xclip.rs create mode 100644 crates/engine/tests/it/xclip.rs create mode 100644 crates/io/src/dxf_clip.rs create mode 100644 crates/io/tests/it/xclip_roundtrip.rs diff --git a/crates/constraints/src/model.rs b/crates/constraints/src/model.rs index d18646c32..f05d5cb13 100644 --- a/crates/constraints/src/model.rs +++ b/crates/constraints/src/model.rs @@ -735,6 +735,7 @@ mod budget_tests { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); let mut budget = 2; diff --git a/crates/constraints/tests/dof.rs b/crates/constraints/tests/dof.rs index 02fd935c0..59dede1d5 100644 --- a/crates/constraints/tests/dof.rs +++ b/crates/constraints/tests/dof.rs @@ -302,6 +302,7 @@ fn block_reference_moves_rigidly() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ); assert_eq!(obj_dof(&d, ins), Some(3)); @@ -343,6 +344,7 @@ fn hostile_new_geometry_never_panics() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ); let l = line(&mut d, (0.0, 0.0), (0.0, 0.0)); diff --git a/crates/doc/src/array.rs b/crates/doc/src/array.rs index b663785ed..1514bc055 100644 --- a/crates/doc/src/array.rs +++ b/crates/doc/src/array.rs @@ -228,6 +228,7 @@ impl ArrayParams { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; out.push(Entity { handle: d.new_handle(), common: common.clone(), kind: EntityKind::Insert(ins) }); } diff --git a/crates/doc/src/entity/block.rs b/crates/doc/src/entity/block.rs index 3d6665e0b..a3f2e76b4 100644 --- a/crates/doc/src/entity/block.rs +++ b/crates/doc/src/entity/block.rs @@ -161,6 +161,25 @@ pub struct Insert { pub col_spacing: f64, #[serde(default)] pub row_spacing: f64, + /// XCLIP boundary of this reference (other references to the block are not clipped). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub clip: Option, +} +impl Default for Insert { + fn default() -> Self { + Insert { + block: String::new(), + insert: Vec3::ZERO, + scale: unit_scale(), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + } + } } fn unit_scale() -> Vec3 { diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index d7c7c7a8a..a2941ba19 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -123,6 +123,13 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } }; b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) }; + // XCLIP: what shows is within the boundary (an inverted clip can show anything). + if let Some(c) = ins.clip.as_ref().filter(|c| c.active() && !c.inverted) + && !b.is_empty() + { + let cb = Bounds2::from_points(c.polygon().into_iter().map(|p| m.apply(p))); + b = if b.intersects(&cb) { Bounds2 { min: b.min.max(cb.min), max: b.max.min(cb.max) } } else { Bounds2::EMPTY }; + } if ins.cols > 1 || ins.rows > 1 { let off = Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1))) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d970a6a56..50138eadd 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -19,6 +19,7 @@ mod plotter; mod refedit; mod store; mod tables; +mod xclip; use std::collections::{BTreeMap, BTreeSet}; @@ -36,6 +37,7 @@ pub use plotter::*; pub use refedit::{RefEdit, WorkItem}; pub use store::EntityStore; pub use tables::*; +pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES}; /// File data CADCraft doesn't model, kept for saving (#528). pub mod dynblock; diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 067d42ac0..6df62e1b1 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -81,6 +81,7 @@ fn inserts_of_missing_or_empty_blocks_do_not_stretch_extents() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) }; d.blocks.insert("Empty".into(), std::sync::Arc::new(Block::new("Empty"))); @@ -134,6 +135,7 @@ fn visible_attributes_of_a_missing_block_still_count() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ) }; @@ -177,6 +179,7 @@ fn insert_bounds_with_cyclic_block_terminate() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), )); b.entities.push(Entity::new(Handle(2), line((0.0, 0.0), (1.0, 1.0)))); @@ -195,6 +198,7 @@ fn insert_bounds_with_cyclic_block_terminate() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ) .unwrap(); @@ -312,6 +316,7 @@ fn plain_insert(block: &str) -> EntityKind { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) } diff --git a/crates/doc/src/xclip.rs b/crates/doc/src/xclip.rs new file mode 100644 index 000000000..b73be0ca0 --- /dev/null +++ b/crates/doc/src/xclip.rs @@ -0,0 +1,85 @@ +//! XCLIP: the clipping boundary of one block or xref reference. +//! +//! The boundary is kept in the referenced block's coordinates, so it moves, rotates and scales +//! with its reference; the block definition and other references to it are untouched. In a file +//! it is the reference's `ACAD_FILTER` / `SPATIAL` extension-dictionary entry (a SPATIAL_FILTER +//! object, DXF Reference), read and written by the io crate. + +use cadcraft_geom::Vec2; +use serde::{Deserialize, Serialize}; + +/// Most boundary vertices a clip keeps (hostile files and parameters are capped to this). +pub const MAX_CLIP_VERTICES: usize = 4096; + +/// A reference's clipping boundary. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClipBoundary { + /// Vertices in the block's coordinates: two opposite corners for a rectangle, three or more + /// for a closed polygon (not repeating the first vertex). + pub points: Vec, + /// Whether clipping is on (XCLIP ON/OFF); an off boundary is kept but nothing is clipped. + #[serde(default = "on")] + pub enabled: bool, + /// Inverted clip: what is inside the boundary is hidden, what is outside shows. + #[serde(default)] + pub inverted: bool, +} + +fn on() -> bool { + true +} + +impl ClipBoundary { + /// A boundary from `points` (block coordinates), on and not inverted. + pub fn new(points: Vec) -> Self { + ClipBoundary { points, enabled: true, inverted: false } + } + + /// The closed outline in block coordinates: a rectangle's four corners or the polygon's + /// vertices. Empty when the boundary has fewer than two vertices, more than + /// [`MAX_CLIP_VERTICES`] or a non-finite one. + pub fn polygon(&self) -> Vec { + if self.points.len() > MAX_CLIP_VERTICES || !self.points.iter().all(|p| p.is_finite()) { + return Vec::new(); + } + match self.points.as_slice() { + [a, b] => vec![ + Vec2::new(a.x.min(b.x), a.y.min(b.y)), + Vec2::new(a.x.max(b.x), a.y.min(b.y)), + Vec2::new(a.x.max(b.x), a.y.max(b.y)), + Vec2::new(a.x.min(b.x), a.y.max(b.y)), + ], + [_, _, _, ..] => self.points.clone(), + _ => Vec::new(), + } + } + + /// Whether the boundary is a rectangle given by two corners. + pub fn is_rectangle(&self) -> bool { + self.points.len() == 2 + } + + /// Whether drawing the reference is clipped by it now (on, with a usable outline). + pub fn active(&self) -> bool { + self.enabled && self.polygon().len() >= 3 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rectangle_and_polygon_outlines() { + let r = ClipBoundary::new(vec![Vec2::new(2.0, 3.0), Vec2::new(0.0, 0.0)]); + assert_eq!(r.polygon(), vec![Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(2.0, 3.0), Vec2::new(0.0, 3.0)]); + assert!(r.active() && r.is_rectangle()); + let bad = ClipBoundary::new(vec![Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0)]); + assert!(bad.polygon().is_empty() && !bad.active()); + let one = ClipBoundary::new(vec![Vec2::ZERO]); + assert!(!one.active()); + let off = ClipBoundary { enabled: false, ..r }; + assert!(!off.active()); + } +} diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 479b7873a..d65a41046 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -154,6 +154,7 @@ pub(crate) fn make_assoc(s: &mut Session, objs: &[Handle], base: Vec2, mut p: Ar rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, })) } diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index ca4cfffec..0758ac6b5 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -23,6 +23,7 @@ mod description; mod dyngrip; mod extract; pub(crate) mod refedit; +mod xclip; pub fn specs() -> Vec { vec![ @@ -86,6 +87,7 @@ pub fn specs() -> Vec { .chain(attribs::attdisp_menu_specs()) .chain(xref::specs()) .chain(refedit::specs()) + .chain(xclip::specs()) .chain(bedit::specs()) .collect() } @@ -215,6 +217,7 @@ fn insert_entity(blk: &Block, at: Vec2, scale: Vec2, rotation: f64, base: Option rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; if let Some(b) = base { let landed = ins.transform(blk.base.xy()).apply(b); diff --git a/crates/engine/src/cmd/blocks/xclip.rs b/crates/engine/src/cmd/blocks/xclip.rs new file mode 100644 index 000000000..b9e1c0e4f --- /dev/null +++ b/crates/engine/src/cmd/blocks/xclip.rs @@ -0,0 +1,462 @@ +//! XCLIP and XCLIPFRAME: clip block and xref references to a boundary. +//! +//! A boundary belongs to one reference ([`cadcraft_doc::Insert::clip`]), in the block's own +//! coordinates, so it moves, rotates and scales with the reference and other references of the +//! block stay whole. It is a rectangle, a polygon or the outline of a closed polyline, can hide +//! what is inside instead of what is outside (Invert clip), and can be turned off, deleted or +//! turned into a polyline. Clip depth (front and back clipping planes) has no meaning in a 2D +//! drawing and is ignored. XCLIPFRAME says whether the boundary is drawn and plotted. + +use cadcraft_doc::{ClipBoundary, EntityKind, Handle, MAX_CLIP_VERTICES}; +use cadcraft_geom::{PolyVertex, Vec2}; +use serde_json::{Value, json}; + +use super::super::machines::{SelOutcome, SelectPhase}; +use crate::cmd::{CommandSpec, bad, bool_or, has_doc, point_value, str_param, targets}; +use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("xclip", "Clip Xref", run) + .menu(&["Modify", "Clip", "Xref"]) + .alias(&["xc"]) + .params("{handles? | handle? (block or xref references, default the selection), option?: new|on|off|delete|polyline|clipdepth|query (default new with a boundary, else query), rectangle?: [[x,y],[x,y]] | points?: [[x,y],…] (3 to 4096, drawing coordinates) | polyline?: handle of a closed polyline, invert?: bool (hide what is inside)} → {handles, option} (query: {clips: [{handle, boundary, enabled, inverted}]}; polyline: {polylines})") + .enabled(has_doc) + .interactive(|_| Ok(Box::new(XclipM::default()))), + CommandSpec::new("xclipframe", "Xref Clip Frame", run_frame) + .params("{value?: 0 (frames hidden) | 1 (shown and plotted) | 2 (shown, not plotted; the default)} → {XCLIPFRAME}") + .enabled(has_doc) + .interactive(|_| Ok(Box::new(FrameM))), + ] +} + +/// The block references among `hs` (other objects are ignored, as XCLIP's selection does). +fn references(s: &Session, hs: &[Handle]) -> Vec { + let Ok(d) = s.doc() else { return Vec::new() }; + hs.iter().copied().filter(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))).collect() +} + +/// A rectangle's two corners as a closed outline. +fn rectangle(a: Vec2, b: Vec2) -> Vec { + vec![ + Vec2::new(a.x.min(b.x), a.y.min(b.y)), + Vec2::new(a.x.max(b.x), a.y.min(b.y)), + Vec2::new(a.x.max(b.x), a.y.max(b.y)), + Vec2::new(a.x.min(b.x), a.y.max(b.y)), + ] +} + +/// The boundary a JSON call gives, in drawing coordinates, and whether it is a rectangle. +fn world_boundary(s: &Session, p: &Value) -> Result<(Vec, bool)> { + if let Some(r) = p.get("rectangle") { + let pts: Vec = r.as_array().map(|a| a.iter().filter_map(point_value).collect()).unwrap_or_default(); + let [a, b] = pts.as_slice() else { return Err(bad("xclip", "`rectangle` needs two finite corners [[x,y],[x,y]]")) }; + if (a.x - b.x).abs() <= 1e-12 || (a.y - b.y).abs() <= 1e-12 { + return Err(bad("xclip", "the clipping rectangle must have a width and a height")); + } + return Ok((vec![*a, *b], true)); + } + if let Some(v) = p.get("polyline") { + let h = v + .as_str() + .and_then(Handle::parse_hex) + .or_else(|| v.as_u64().map(Handle)) + .ok_or_else(|| bad("xclip", "`polyline` must be an object handle"))?; + let d = s.doc()?; + let e = d.entity(h).ok_or_else(|| bad("xclip", format!("no object {}", h.hex())))?; + let closed = matches!(&e.kind, EntityKind::LwPolyline(pl) if pl.closed) || matches!(&e.kind, EntityKind::Polyline3d(pl) if pl.closed); + if !closed { + return Err(bad("xclip", "select a closed polyline")); + } + let pts = cadcraft_render::clip::boundary_polygon(&e.kind).ok_or_else(|| bad("xclip", "the polyline does not enclose an area"))?; + return Ok((pts, false)); + } + let pts = p.get("points").and_then(Value::as_array).ok_or_else(|| bad("xclip", "a boundary is required: `rectangle`, `points` or `polyline`"))?; + if !(3..=MAX_CLIP_VERTICES).contains(&pts.len()) { + return Err(bad("xclip", format!("a polygonal boundary needs 3 to {MAX_CLIP_VERTICES} points"))); + } + let pts: Vec = + pts.iter().map(|v| point_value(v).ok_or_else(|| bad("xclip", "every boundary point must be a finite [x, y]"))).collect::>()?; + Ok((pts, false)) +} + +fn run(s: &mut Session, p: &Value) -> Result { + let hs = references(s, &targets(s, p)?); + if hs.is_empty() { + return Err(bad("xclip", "select block or xref references")); + } + let has_boundary = ["rectangle", "points", "polyline"].iter().any(|k| p.get(*k).is_some()); + let option = str_param(p, "option").map(str::to_ascii_lowercase).unwrap_or_else(|| if has_boundary { "new".into() } else { "query".into() }); + match option.as_str() { + "new" | "n" => { + let (world, rect) = world_boundary(s, p)?; + let outline = if rect { world.first().zip(world.get(1)).map(|(a, b)| rectangle(*a, *b)).unwrap_or_default() } else { world.clone() }; + if cadcraft_render::clip::PolyClip::new(&outline).is_none() { + return Err(bad("xclip", "the clipping boundary encloses no area")); + } + let invert = bool_or(p, "invert", false); + let mut clips = Vec::with_capacity(hs.len()); + { + let d = s.doc()?; + for h in &hs { + let Some(EntityKind::Insert(ins)) = d.entity(*h).map(|e| &e.kind) else { continue }; + let base = d.block(&ins.block).map(|b| b.base.xy()).ok_or_else(|| bad("xclip", format!("block \"{}\" is missing", ins.block)))?; + let inv = ins.transform(base).inverse().ok_or_else(|| bad("xclip", "a reference with a zero scale can't be clipped"))?; + let points: Vec = world.iter().map(|q| inv.apply(*q)).collect(); + // A rotated or skewed reference sees the rectangle as a polygon. + let r = ins.rotation.rem_euclid(std::f64::consts::FRAC_PI_2); + let square = r < 1e-9 || std::f64::consts::FRAC_PI_2 - r < 1e-9; + let points = if rect && !square { outline.iter().map(|q| inv.apply(*q)).collect() } else { points }; + clips.push((*h, ClipBoundary { points, enabled: true, inverted: invert })); + } + } + for (h, c) in clips { + set_clip(s, h, Some(c))?; + } + } + "on" | "off" => { + let on = option == "on"; + for h in &hs { + let mut c = clip_of(s, *h).ok_or_else(|| bad("xclip", "no clipping boundary on the selected reference"))?; + c.enabled = on; + set_clip(s, *h, Some(c))?; + } + } + "delete" | "d" => { + for h in &hs { + set_clip(s, *h, None)?; + } + } + "polyline" | "p" | "generate" => { + let mut made = Vec::new(); + for h in &hs { + let Some(world) = world_outline(s, *h) else { continue }; + let vertices = world.into_iter().map(|p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect(); + let pl = cadcraft_doc::LwPolyline { vertices, closed: true, const_width: 0.0, elevation: 0.0, plinegen: false }; + made.push(s.add_entity(EntityKind::LwPolyline(pl))?.hex()); + } + if made.is_empty() { + return Err(bad("xclip", "no clipping boundary on the selected references")); + } + return Ok(json!({ "handles": hexes(&hs), "option": "polyline", "polylines": made })); + } + // Front and back clipping planes have no meaning in 2D: nothing changes. + "clipdepth" | "c" => return Ok(json!({ "handles": hexes(&hs), "option": "clipdepth", "ignored": true })), + "query" | "?" => { + let clips: Vec = hs + .iter() + .map(|h| { + let c = clip_of(s, *h); + json!({ + "handle": h.hex(), + "boundary": world_outline(s, *h).map(|w| w.iter().map(|p| [p.x, p.y]).collect::>()), + "enabled": c.as_ref().is_some_and(|c| c.enabled), + "inverted": c.as_ref().is_some_and(|c| c.inverted), + }) + }) + .collect(); + return Ok(json!({ "clips": clips })); + } + o => return Err(bad("xclip", format!("unknown option \"{o}\" (new, on, off, delete, polyline, clipdepth or query)"))), + } + Ok(json!({ "handles": hexes(&hs), "option": option })) +} + +fn hexes(hs: &[Handle]) -> Vec { + hs.iter().map(|h| h.hex()).collect() +} + +fn clip_of(s: &Session, h: Handle) -> Option { + match &s.doc().ok()?.entity(h)?.kind { + EntityKind::Insert(i) => i.clip.clone(), + _ => None, + } +} + +/// Reference `h`'s boundary outline in drawing coordinates. +fn world_outline(s: &Session, h: Handle) -> Option> { + let d = s.doc().ok()?; + let EntityKind::Insert(i) = &d.entity(h)?.kind else { return None }; + let c = i.clip.as_ref()?; + let m = i.transform(d.block(&i.block)?.base.xy()); + let poly = c.polygon(); + (poly.len() >= 3).then(|| poly.into_iter().map(|p| m.apply(p)).collect()) +} + +fn set_clip(s: &mut Session, h: Handle, c: Option) -> Result<()> { + s.doc_mut()? + .modify_entity(h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.clip = c; + } + }) + .map_err(|e| bad("xclip", e.to_string())) +} + +// ---------------- XCLIPFRAME ---------------- + +fn run_frame(s: &mut Session, p: &Value) -> Result { + let v = match p.get("value").or_else(|| p.get("XCLIPFRAME")) { + None | Some(Value::Null) => return Ok(json!({ "XCLIPFRAME": s.doc()?.header.i64("XCLIPFRAME", 2) })), + Some(v) => v.as_i64().or_else(|| v.as_str().and_then(|t| t.trim().parse().ok())), + }; + let v = v.filter(|v| (0..=2).contains(v)).ok_or_else(|| bad("xclipframe", "`value` must be 0, 1 or 2"))?; + s.doc_mut()?.header.set_i64("XCLIPFRAME", v); + Ok(json!({ "XCLIPFRAME": v })) +} + +struct FrameM; + +impl Interactive for FrameM { + fn name(&self) -> &'static str { + "XCLIPFRAME" + } + fn prompt(&self, s: &Session) -> Prompt { + let cur = s.doc().map(|d| d.header.i64("XCLIPFRAME", 2)).unwrap_or(2); + Prompt::new("Enter new value for XCLIPFRAME", Accept::TEXT).kw(&["0", "1", "2"]).default(cur.to_string()) + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let t = match i { + Input::Cancel => return Ok(Step::Cancel), + Input::Enter => return Ok(Step::Done), + Input::Text(t) | Input::Keyword(t) => t, + _ => return Ok(Step::Continue), + }; + match run_frame(s, &json!({ "value": t.trim() })) { + Ok(_) => Ok(Step::Done), + Err(_) => { + s.echo("Requires an integer between 0 and 2."); + Ok(Step::Continue) + } + } + } +} + +// ---------------- interactive XCLIP ---------------- + +#[derive(Default, Clone, Copy, PartialEq, Eq)] +enum Stage { + #[default] + Select, + Option, + DeleteOld, + Boundary, + Corner1, + Corner2, + Polygon, + Polyline, +} + +#[derive(Default)] +struct XclipM { + stage: Stage, + sel: SelectPhase, + refs: Vec, + invert: bool, + pts: Vec, +} + +impl XclipM { + fn selected(&mut self, s: &mut Session, hs: &[Handle]) -> Result { + self.refs = references(s, hs); + if self.refs.is_empty() { + s.echo("No block or xref references selected."); + return Ok(Step::Done); + } + self.stage = Stage::Option; + Ok(Step::Continue) + } + + fn apply(&mut self, s: &mut Session, mut p: Value) -> Result { + p["handles"] = json!(hexes(&self.refs)); + let r = run(s, &p); + s.set_selection(Vec::new()); + match r { + Ok(_) => Ok(Step::Done), + Err(e) => { + s.echo(e.to_string()); + Ok(Step::Done) + } + } + } + + fn any_clipped(&self, s: &Session) -> bool { + self.refs.iter().any(|h| clip_of(s, *h).is_some()) + } +} + +fn kw(i: &Input) -> Option { + match i { + Input::Keyword(k) | Input::Text(k) => Some(k.trim().to_ascii_lowercase()), + _ => None, + } +} + +impl Interactive for XclipM { + fn name(&self) -> &'static str { + "XCLIP" + } + + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + if self.sel.done { + let hs = self.sel.picked.clone(); + return self.selected(s, &hs); + } + Ok(Step::Continue) + } + + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + Stage::Select => self.sel.prompt(), + Stage::Option => Prompt::new("Enter clipping option", Accept::TEXT) + .kw(&["ON", "OFF", "Clipdepth", "Delete", "generate Polyline", "New boundary"]) + .default("New"), + Stage::DeleteOld => Prompt::new("Delete old boundary(s)?", Accept::TEXT).kw(&["Yes", "No"]).default("Yes"), + Stage::Boundary => Prompt::new("Specify clipping boundary or select invert option", Accept::POINT) + .kw(&["Select polyline", "Polygonal", "Rectangular", "Invert clip"]) + .default("Rectangular"), + Stage::Corner1 => Prompt::new("Specify first corner", Accept::POINT), + Stage::Corner2 => { + let p = Prompt::new("Specify opposite corner", Accept::POINT); + match self.pts.first() { + Some(a) => p.corner(*a), + None => p, + } + } + Stage::Polygon => { + let msg = if self.pts.is_empty() { "Specify first point" } else { "Specify next point" }; + let p = Prompt::new(msg, Accept::POINT).base_opt(self.pts.last().copied()); + if self.pts.is_empty() { p } else { p.kw(&["Undo"]) } + } + Stage::Polyline => Prompt::new("Select polyline", Accept::SELECT), + } + } + + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + Stage::Select => match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.selected(s, &hs), + }, + Stage::Option => { + let k = if matches!(i, Input::Enter) { Some("new".to_string()) } else { kw(&i) }; + match k.as_deref() { + Some("on") => self.apply(s, json!({ "option": "on" })), + Some("off") => self.apply(s, json!({ "option": "off" })), + Some(k) if k.starts_with('c') => { + s.echo("Clip depth does not apply to a 2D drawing: front and back clipping planes are ignored."); + Ok(Step::Done) + } + Some(k) if k.starts_with('d') => self.apply(s, json!({ "option": "delete" })), + Some(k) if k.starts_with('p') || k.starts_with('g') => self.apply(s, json!({ "option": "polyline" })), + Some(k) if k.starts_with('n') => { + self.stage = if self.any_clipped(s) { Stage::DeleteOld } else { Stage::Boundary }; + Ok(Step::Continue) + } + _ => { + s.echo("Invalid option keyword."); + Ok(Step::Continue) + } + } + } + Stage::DeleteOld => match kw(&i).as_deref() { + None if matches!(i, Input::Enter) => { + self.stage = Stage::Boundary; + Ok(Step::Continue) + } + Some(k) if k.starts_with('y') => { + self.stage = Stage::Boundary; + Ok(Step::Continue) + } + Some(k) if k.starts_with('n') => Ok(Step::Done), + _ => Ok(Step::Continue), + }, + Stage::Boundary => match (&i, kw(&i).as_deref()) { + (Input::Enter, _) => { + self.stage = Stage::Corner1; + Ok(Step::Continue) + } + (Input::Point(p), _) => { + // A point starts the default rectangle. + self.pts = vec![*p]; + self.stage = Stage::Corner2; + Ok(Step::Continue) + } + (_, Some(k)) if k.starts_with('i') => { + self.invert = !self.invert; + s.echo(if self.invert { + "Inside mode - Objects inside boundary will be hidden." + } else { + "Outside mode - Objects outside boundary will be hidden." + }); + Ok(Step::Continue) + } + (_, Some(k)) if k.starts_with('s') => { + self.stage = Stage::Polyline; + Ok(Step::Continue) + } + (_, Some(k)) if k.starts_with('p') => { + self.pts.clear(); + self.stage = Stage::Polygon; + Ok(Step::Continue) + } + (_, Some(k)) if k.starts_with('r') => { + self.stage = Stage::Corner1; + Ok(Step::Continue) + } + _ => Ok(Step::Continue), + }, + Stage::Corner1 => match i { + Input::Point(p) => { + self.pts = vec![p]; + self.stage = Stage::Corner2; + Ok(Step::Continue) + } + _ => Ok(Step::Continue), + }, + Stage::Corner2 => match (i, self.pts.first().copied()) { + (Input::Point(b), Some(a)) => self.apply(s, json!({ "option": "new", "rectangle": [[a.x, a.y], [b.x, b.y]], "invert": self.invert })), + _ => Ok(Step::Continue), + }, + Stage::Polygon => match i { + Input::Point(p) if self.pts.len() < MAX_CLIP_VERTICES => { + self.pts.push(p); + Ok(Step::Continue) + } + Input::Point(_) => { + s.echo(format!("A boundary has at most {MAX_CLIP_VERTICES} points.")); + Ok(Step::Continue) + } + Input::Keyword(_) | Input::Text(_) => { + self.pts.pop(); + Ok(Step::Continue) + } + Input::Enter if self.pts.len() >= 3 => { + let pts: Vec<[f64; 2]> = self.pts.iter().map(|p| [p.x, p.y]).collect(); + self.apply(s, json!({ "option": "new", "points": pts, "invert": self.invert })) + } + Input::Enter => { + s.echo("A polygonal boundary needs at least three points."); + Ok(Step::Continue) + } + _ => Ok(Step::Continue), + }, + Stage::Polyline => match i { + Input::Pick(hs) => match hs.first() { + Some(h) => { + let h = *h; + self.apply(s, json!({ "option": "new", "polyline": h.hex(), "invert": self.invert })) + } + None => Ok(Step::Continue), + }, + Input::Enter => Ok(Step::Done), + _ => Ok(Step::Continue), + }, + } + } +} diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index f9acc909e..a5cc553d5 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -652,6 +652,7 @@ mod tests { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) } diff --git a/crates/engine/src/cmd/mleader_content.rs b/crates/engine/src/cmd/mleader_content.rs index 3d96c9baa..3b413724e 100644 --- a/crates/engine/src/cmd/mleader_content.rs +++ b/crates/engine/src/cmd/mleader_content.rs @@ -54,6 +54,7 @@ pub(super) fn apply(s: &Session, k: EntityKind, c: &Content) -> Result { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; block_leaves(d, &ins, &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m))); } diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index ca15bd4c4..616f69e11 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -352,6 +352,7 @@ mod tests { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), 8 if i % 40 == 8 => EntityKind::XLine(cadcraft_doc::RayLine { base: v3(x, y), dir: v3(r.r(-1.0, 1.0), 1.0) }), 8 if i % 40 == 18 => EntityKind::Ray(cadcraft_doc::RayLine { base: v3(x, y), dir: v3(1.0, r.r(-1.0, 1.0)) }), @@ -500,6 +501,7 @@ mod tests { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap(); let small = Bounds2::new(Vec2::new(-2.0, -2.0), Vec2::new(2.0, 2.0)); diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index fa319d3f1..e7eb62620 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -74,6 +74,8 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)), ("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)), + // XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted. + ("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)), ]; /// The standard lineweights in hundredths of a millimetre. diff --git a/crates/engine/tests/audit.rs b/crates/engine/tests/audit.rs index 8c1ce9c4a..4084a7b1b 100644 --- a/crates/engine/tests/audit.rs +++ b/crates/engine/tests/audit.rs @@ -24,6 +24,7 @@ fn insert(block: &str) -> EntityKind { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) } diff --git a/crates/engine/tests/autosave.rs b/crates/engine/tests/autosave.rs index da03c0d7d..c45d69c38 100644 --- a/crates/engine/tests/autosave.rs +++ b/crates/engine/tests/autosave.rs @@ -345,6 +345,7 @@ fn a_block_editor_that_cannot_be_composed_is_not_autosaved_as_the_old_host() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }); d.model.push(Entity::new(h, kind)); assert!(s.state().unwrap().recovery_drawing().is_err()); diff --git a/crates/engine/tests/clipboard.rs b/crates/engine/tests/clipboard.rs index 650d63092..b9eeff317 100644 --- a/crates/engine/tests/clipboard.rs +++ b/crates/engine/tests/clipboard.rs @@ -28,6 +28,7 @@ fn insert(d: &mut Drawing, block: &str, at: (f64, f64)) -> Entity { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }); Entity { handle: d.new_handle(), common: Common::default(), kind } } diff --git a/crates/engine/tests/compare.rs b/crates/engine/tests/compare.rs index 0e4486ccb..ed8c9a0b7 100644 --- a/crates/engine/tests/compare.rs +++ b/crates/engine/tests/compare.rs @@ -124,6 +124,7 @@ fn hooks() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).map_err(|e| e.to_string())?; return Ok(d); @@ -175,6 +176,7 @@ fn hostile_inputs_are_errors() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; b.entities.push(Entity::new(cadcraft_engine::doc::Handle(0x900), EntityKind::Insert(ins.clone()))); let d = s.doc_mut().unwrap(); diff --git a/crates/engine/tests/insert_file.rs b/crates/engine/tests/insert_file.rs index 77bfd9d85..57b7f30c9 100644 --- a/crates/engine/tests/insert_file.rs +++ b/crates/engine/tests/insert_file.rs @@ -35,6 +35,7 @@ fn read(bytes: &[u8], _name: &str) -> Result { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.model.push(Entity::new(Handle(0x61), EntityKind::Insert(ins))); Ok(d) diff --git a/crates/engine/tests/it/blockreplace.rs b/crates/engine/tests/it/blockreplace.rs index 86b8c42e3..51e7b9654 100644 --- a/crates/engine/tests/it/blockreplace.rs +++ b/crates/engine/tests/it/blockreplace.rs @@ -40,6 +40,7 @@ fn drawing() -> (Session, Handle) { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Insert(ins)).unwrap(); (s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap()) diff --git a/crates/engine/tests/it/compare_export.rs b/crates/engine/tests/it/compare_export.rs index 1aee1b9db..6a9d58873 100644 --- a/crates/engine/tests/it/compare_export.rs +++ b/crates/engine/tests/it/compare_export.rs @@ -21,6 +21,7 @@ fn insert(block: &str) -> Insert { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, } } diff --git a/crates/engine/tests/it/count.rs b/crates/engine/tests/it/count.rs index c654814aa..d28d28ecf 100644 --- a/crates/engine/tests/it/count.rs +++ b/crates/engine/tests/it/count.rs @@ -20,6 +20,7 @@ fn insert(block: &str, x: f64, cols: u32, rows: u32) -> EntityKind { rows, col_spacing: 5.0, row_spacing: 5.0, + clip: None, }) } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6..3944acb94 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -142,6 +142,7 @@ mod undo_layout_tab; mod viewport_clip; mod vplayer_prompts; mod vports; +mod xclip; mod xdata_follows_entity; mod zoom_keywords; mod zoom_viewport; diff --git a/crates/engine/tests/it/measure_distance_snapping.rs b/crates/engine/tests/it/measure_distance_snapping.rs index 9842b65e0..8fc73fb23 100644 --- a/crates/engine/tests/it/measure_distance_snapping.rs +++ b/crates/engine/tests/it/measure_distance_snapping.rs @@ -310,6 +310,7 @@ fn viewport_frozen_layers_apply_inside_nested_block_references() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) }; let mut outer = Block::new("Outer"); diff --git a/crates/engine/tests/it/purge_mlinestyles.rs b/crates/engine/tests/it/purge_mlinestyles.rs index a037096f5..a0f955c96 100644 --- a/crates/engine/tests/it/purge_mlinestyles.rs +++ b/crates/engine/tests/it/purge_mlinestyles.rs @@ -41,6 +41,7 @@ fn session() -> Session { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); s diff --git a/crates/engine/tests/it/refedit.rs b/crates/engine/tests/it/refedit.rs index df3aa5ea1..0eb63c29f 100644 --- a/crates/engine/tests/it/refedit.rs +++ b/crates/engine/tests/it/refedit.rs @@ -20,6 +20,7 @@ fn insert(s: &mut Session, block: &str, at: (f64, f64), scale: f64, rot_deg: f64 rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }); s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap().hex() } @@ -246,6 +247,7 @@ fn a_block_that_references_itself_in_a_file_does_not_hang() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }); let d = s.doc_mut().unwrap(); let hh = d.new_handle(); diff --git a/crates/engine/tests/it/snap_blocks.rs b/crates/engine/tests/it/snap_blocks.rs index 6d44893d7..6bd3fd09c 100644 --- a/crates/engine/tests/it/snap_blocks.rs +++ b/crates/engine/tests/it/snap_blocks.rs @@ -31,6 +31,7 @@ fn insert(s: &mut Session, block: &str, at: (f64, f64), scale: (f64, f64), rotat rows: grid.1, col_spacing: grid.2, row_spacing: grid.3, + clip: None, }); s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap().hex() } diff --git a/crates/engine/tests/it/snap_tracking.rs b/crates/engine/tests/it/snap_tracking.rs index 3843002df..de62e482c 100644 --- a/crates/engine/tests/it/snap_tracking.rs +++ b/crates/engine/tests/it/snap_tracking.rs @@ -41,6 +41,7 @@ fn insert_block(s: &mut Session, name: &str, at: Vec2) -> String { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ) .unwrap() diff --git a/crates/engine/tests/it/xclip.rs b/crates/engine/tests/it/xclip.rs new file mode 100644 index 000000000..0b1d64443 --- /dev/null +++ b/crates/engine/tests/it/xclip.rs @@ -0,0 +1,214 @@ +//! XCLIP and XCLIPFRAME: clipping block and xref references (gap F2). + +use cadcraft_engine::doc::{ClipBoundary, Common, EntityKind, Handle, Insert, Space}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::render::{self, Options}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn h(v: &Value) -> String { + v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_string() +} + +fn insert(s: &mut Session, block: &str, at: (f64, f64), scale: f64, rot_deg: f64) -> String { + let kind = EntityKind::Insert(Insert { + block: block.into(), + insert: Vec3::new(at.0, at.1, 0.0), + scale: Vec3::new(scale, scale, scale), + rotation: rot_deg.to_radians(), + ..Insert::default() + }); + s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap().hex() +} + +/// Block B: a horizontal line (0,0)-(100,0) and a vertical one (50,-50)-(50,50); two references. +fn setup() -> (Session, String, String) { + let mut s = Session::new(); + let a = h(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + let b = h(&s.execute("line", &json!({ "points": [[50, -50], [50, 50]] })).unwrap()); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [a, b], "keep": "delete" })).unwrap(); + let r1 = insert(&mut s, "B", (0.0, 0.0), 1.0, 0.0); + let r2 = insert(&mut s, "B", (1000.0, 0.0), 2.0, 90.0); + (s, r1, r2) +} + +fn clip(s: &Session, hex: &str) -> Option { + match &s.doc().unwrap().entity(Handle::parse_hex(hex).unwrap()).unwrap().kind { + EntityKind::Insert(i) => i.clip.clone(), + _ => None, + } +} + +/// The x extent of what the drawing shows around reference 1 (x < 500). +fn shown_x(s: &Session) -> (f64, f64) { + let list = render::build(s.doc().unwrap(), &Space::Model, &Options::default()); + let xs: Vec = list.verts.iter().filter(|v| v.x < 500.0).map(|v| v.x).collect(); + (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)) +} + +#[test] +fn rectangular_clip_cuts_only_that_reference() { + let (mut s, r1, r2) = setup(); + assert_eq!(shown_x(&s), (0.0, 100.0)); + s.execute("setvar", &json!({ "name": "XCLIPFRAME", "value": 0 })).unwrap(); + let out = s.execute("xclip", &json!({ "handle": r1, "rectangle": [[20, -10], [70, 10]] })).unwrap(); + assert_eq!(out["option"], "new"); + let c = clip(&s, &r1).unwrap(); + assert!(c.enabled && !c.inverted && c.points.len() == 2); + let (lo, hi) = shown_x(&s); + assert!((lo - 20.0).abs() < 1e-9 && (hi - 70.0).abs() < 1e-9, "{lo} {hi}"); + assert!(clip(&s, &r2).is_none(), "the other reference stays whole"); + // The boundary follows its reference. + s.execute("move", &json!({ "handles": [r1], "delta": [5, 0] })).unwrap(); + let (lo, hi) = shown_x(&s); + assert!((lo - 25.0).abs() < 1e-9 && (hi - 75.0).abs() < 1e-9, "{lo} {hi}"); + // Its extents are the clipped part (ZOOM Extents). + let d = s.doc().unwrap(); + let b = cadcraft_engine::doc::entity_bounds(d, d.entity(Handle::parse_hex(&r1).unwrap()).unwrap(), 0); + assert!((b.min.x - 25.0).abs() < 1e-9 && (b.max.x - 75.0).abs() < 1e-9 && b.max.y <= 10.0 + 1e-9, "{b:?}"); + // Query reports it in drawing coordinates. + let q = s.execute("xclip", &json!({ "handle": r1, "option": "query" })).unwrap(); + assert_eq!(q["clips"][0]["boundary"][0], json!([25.0, -10.0])); + // OFF shows everything, ON clips again, Delete removes it; undo brings it back. + s.execute("xclip", &json!({ "handle": r1, "option": "off" })).unwrap(); + assert_eq!(shown_x(&s), (5.0, 105.0)); + s.execute("xclip", &json!({ "handle": r1, "option": "on" })).unwrap(); + assert!((shown_x(&s).0 - 25.0).abs() < 1e-9); + s.execute("xclip", &json!({ "handle": r1, "option": "delete" })).unwrap(); + assert!(clip(&s, &r1).is_none()); + s.execute("undo", &json!({})).unwrap(); + assert!(clip(&s, &r1).is_some()); +} + +#[test] +fn rotated_and_scaled_reference_gets_a_polygon_in_block_coordinates() { + let (mut s, _, r2) = setup(); + // r2: scale 2, rotated 90 degrees at (1000, 0): the block's x axis points up. + s.execute("xclip", &json!({ "handle": r2, "rectangle": [[990, 10], [1010, 50]] })).unwrap(); + let c = clip(&s, &r2).unwrap(); + // A 90 degree rotation keeps the rectangle a rectangle: (5..25, -5..5) in the block. + let poly = c.polygon(); + let xs: Vec = poly.iter().map(|p| p.x).collect(); + assert!(xs.iter().any(|x| (x - 5.0).abs() < 1e-9) && xs.iter().any(|x| (x - 25.0).abs() < 1e-9), "{poly:?}"); + // 30 degrees: kept as the four corners. + let r3 = insert(&mut s, "B", (2000.0, 0.0), 1.0, 30.0); + s.execute("xclip", &json!({ "handle": r3, "rectangle": [[1990, -10], [2010, 10]] })).unwrap(); + assert_eq!(clip(&s, &r3).unwrap().points.len(), 4); +} + +#[test] +fn inverted_polygonal_and_polyline_boundaries() { + let (mut s, r1, _) = setup(); + s.execute("setvar", &json!({ "name": "XCLIPFRAME", "value": 0 })).unwrap(); + s.execute("xclip", &json!({ "handle": r1, "points": [[40, -10], [60, -10], [60, 10], [40, 10]], "invert": true })).unwrap(); + assert!(clip(&s, &r1).unwrap().inverted); + let list = render::build(s.doc().unwrap(), &Space::Model, &Options::default()); + // The middle of the horizontal line is hidden, both ends show. + assert!(!list.verts.iter().any(|v| v.x > 40.5 && v.x < 59.5 && v.y.abs() < 1e-9)); + assert!(list.verts.iter().any(|v| v.x == 0.0) && list.verts.iter().any(|v| v.x == 100.0)); + // A closed polyline as the boundary. + let pl = h(&s.execute("pline", &json!({ "vertices": [[10, -5], [30, -5], [30, 5], [10, 5]], "closed": true })).unwrap()); + s.execute("xclip", &json!({ "handle": r1, "polyline": pl })).unwrap(); + let c = clip(&s, &r1).unwrap(); + assert!(!c.inverted && c.points.len() == 4); + // An open polyline is refused, a bad boundary changes nothing. + let open = h(&s.execute("pline", &json!({ "vertices": [[0, 0], [5, 5], [9, 0]] })).unwrap()); + assert!(s.execute("xclip", &json!({ "handle": r1, "polyline": open })).is_err()); + assert!(s.execute("xclip", &json!({ "handle": r1, "points": [[0, 0], [1, 1]] })).is_err()); + assert!(s.execute("xclip", &json!({ "handle": r1, "rectangle": [[0, 0], [0, 10]] })).is_err()); + assert_eq!(clip(&s, &r1), Some(c)); + // Generate polyline makes the boundary an object. + let n = s.doc().unwrap().model.len(); + let out = s.execute("xclip", &json!({ "handle": r1, "option": "polyline" })).unwrap(); + assert_eq!(out["polylines"].as_array().unwrap().len(), 1); + assert_eq!(s.doc().unwrap().model.len(), n + 1); + // Clip depth has no effect in 2D. + assert_eq!(s.execute("xclip", &json!({ "handle": r1, "option": "clipdepth" })).unwrap()["ignored"], true); +} + +#[test] +fn hostile_params_never_panic() { + let (mut s, r1, _) = setup(); + for p in [ + json!({ "handle": r1, "points": "x" }), + json!({ "handle": r1, "points": [[1e308, 0], [-1e308, 0], [0, 1e308]] }), + json!({ "handle": r1, "rectangle": [[f64::MAX, 0]] }), + json!({ "handle": r1, "rectangle": 5 }), + json!({ "handle": r1, "polyline": "ZZZZ" }), + json!({ "handle": r1, "option": "bogus" }), + json!({ "handle": "nothex" }), + json!({ "handles": [] }), + json!({ "handle": r1, "points": vec![[0.0, 0.0]; 5000] }), + ] { + let _ = s.execute("xclip", &p); + } + assert!(s.execute("xclipframe", &json!({ "value": 7 })).is_err()); + assert!(s.execute("xclip", &json!({ "handle": r1, "option": "on" })).is_err(), "no boundary to turn on"); +} + +#[test] +fn typed_xclip_follows_the_prompts() { + let (mut s, r1, r2) = setup(); + let pick = |hex: &str| Input::Pick(vec![Handle::parse_hex(hex).unwrap()]); + s.start("xclip").unwrap(); + s.input(pick(&r1)).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.prompt_text().contains("Enter clipping option"), "{}", s.prompt_text()); + s.input(Input::Enter).unwrap(); // New + assert!(s.prompt_text().contains("Invert clip"), "{}", s.prompt_text()); + s.input(Input::Keyword("Invert clip".into())).unwrap(); + assert!(s.log.iter().any(|l| l.contains("Inside mode"))); + s.input(Input::Keyword("Rectangular".into())).unwrap(); + s.input(Input::Point(Vec2::new(10.0, -10.0))).unwrap(); + s.input(Input::Point(Vec2::new(30.0, 10.0))).unwrap(); + let c = clip(&s, &r1).unwrap(); + assert!(c.inverted && c.points.len() == 2); + // Again on the clipped reference: "Delete old boundary(s)?", then a polygon. + s.cmdline("xclip").unwrap(); + s.input(pick(&r1)).unwrap(); + s.input(Input::Enter).unwrap(); + s.cmdline("n").unwrap(); + assert!(s.prompt_text().contains("Delete old boundary"), "{}", s.prompt_text()); + s.cmdline("y").unwrap(); + s.cmdline("p").unwrap(); + for p in ["0,-5", "20,-5", "20,5"] { + s.cmdline(p).unwrap(); + } + s.input(Input::Enter).unwrap(); + let c = clip(&s, &r1).unwrap(); + assert!(!c.inverted && c.points.len() == 3); + // OFF, then Delete on two references at once. + s.start("xclip").unwrap(); + s.input(pick(&r1)).unwrap(); + s.input(Input::Enter).unwrap(); + s.cmdline("off").unwrap(); + assert!(!clip(&s, &r1).unwrap().enabled); + s.execute("xclip", &json!({ "handle": r2, "rectangle": [[0, 0], [1, 1]] })).unwrap(); + s.start("xclip").unwrap(); + s.input(Input::Pick(vec![Handle::parse_hex(&r1).unwrap(), Handle::parse_hex(&r2).unwrap()])).unwrap(); + s.input(Input::Enter).unwrap(); + s.cmdline("d").unwrap(); + assert!(clip(&s, &r1).is_none() && clip(&s, &r2).is_none()); + // XCLIPFRAME typed. + s.cmdline("xclipframe").unwrap(); + s.cmdline("1").unwrap(); + assert_eq!(s.execute("getvar", &json!({ "name": "XCLIPFRAME" })).unwrap()["value"], 1); +} + +#[test] +fn the_frame_shows_and_plots_as_xclipframe_says() { + let (mut s, r1, _) = setup(); + s.execute("xclip", &json!({ "handle": r1, "rectangle": [[20, -10], [70, 10]] })).unwrap(); + let frame_at = |s: &Session, plot: bool| { + let d = s.doc().unwrap(); + let list = + if plot { render::build_plot(d, &Space::Model, &Options::default()) } else { render::build(d, &Space::Model, &Options::default()) }; + list.verts.iter().any(|v| (v.y - 10.0).abs() < 1e-9 && (v.x - 20.0).abs() < 1e-9) + }; + // Default 2: shown, not plotted. + assert!(frame_at(&s, false) && !frame_at(&s, true)); + s.execute("xclipframe", &json!({ "value": 1 })).unwrap(); + assert!(frame_at(&s, false) && frame_at(&s, true)); + s.execute("xclipframe", &json!({ "value": 0 })).unwrap(); + assert!(!frame_at(&s, false) && !frame_at(&s, true)); +} diff --git a/crates/engine/tests/usage.rs b/crates/engine/tests/usage.rs index 9754ce766..e70d9d638 100644 --- a/crates/engine/tests/usage.rs +++ b/crates/engine/tests/usage.rs @@ -50,6 +50,7 @@ fn insert(handle: u64, block: &str, layer: &str) -> Entity { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ); e.common = Common { layer: layer.into(), ..Common::default() }; diff --git a/crates/engine/tests/xref.rs b/crates/engine/tests/xref.rs index d53e37886..06ee79226 100644 --- a/crates/engine/tests/xref.rs +++ b/crates/engine/tests/xref.rs @@ -50,6 +50,7 @@ fn insert(block: &str, x: f64) -> EntityKind { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) } diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs new file mode 100644 index 000000000..fc3d56316 --- /dev/null +++ b/crates/io/src/dxf_clip.rs @@ -0,0 +1,374 @@ +//! XCLIP in a file (DXF Reference, SPATIAL_FILTER): a clipped block reference has an extension +//! dictionary with an `ACAD_FILTER` dictionary whose `SPATIAL` entry is a SPATIAL_FILTER object. +//! The filter holds the boundary vertices in the reference's coordinates (group 70 the count, +//! 10/20 the vertices), whether clipping is on (71), the front and back clip (72/73, 40/41) and +//! two 3×4 matrices (group 40, row by row): the inverse of the reference's transform, which takes +//! the boundary into the block's coordinates, and the boundary's own transform (identity here). +//! +//! An inverted clip is CADCraft's own entry `CADCRAFT_XCLIP` beside `ACAD_FILTER` in the same +//! extension dictionary: an XRECORD with group 70 = 1. Other programs keep it as unknown data and +//! clip normally. +//! +//! Reading takes the planar filters the model can hold out of the kept foreign data and puts them +//! on the references ([`read`]); others (front/back clipping, a skewed boundary transform) stay +//! foreign and are written back untouched. Writing adds the dictionaries and the filter of every +//! clipped reference to a copy of the drawing's foreign data ([`prepare`]), which the raw-data +//! writer (#528) then places on the reference. + +use std::sync::Arc; + +use cadcraft_doc::foreign::{Foreign, ForeignObject}; +use cadcraft_doc::{ClipBoundary, Drawing, EntityKind, Handle, MAX_CLIP_VERTICES, RawTag}; +use cadcraft_geom::{Mat3, Vec2}; + +/// The extension-dictionary entry of CADCraft's inverted-clip flag. +const INVERT_KEY: &str = "CADCRAFT_XCLIP"; +/// Handles above this are not handed out (the DXF handle space is 64-bit, keep a margin). +const MAX_HANDLE: u64 = 1 << 48; + +fn raw(code: i32, value: impl ToString) -> RawTag { + RawTag { code, value: value.to_string() } +} + +/// The handle of dictionary entry `name` (group 3 followed by 350/360). +fn entry(tags: &[RawTag], name: &str) -> Option { + tags.windows(2) + .find(|w| matches!(w, [k, v] if k.code == 3 && k.value.eq_ignore_ascii_case(name) && matches!(v.code, 350 | 360))) + .and_then(|w| w.get(1)) + .and_then(|v| Handle::parse_hex(&v.value)) +} + +/// Remove dictionary entry `name`; returns the handle it named. +fn remove_entry(tags: &mut Vec, name: &str) -> Option { + let mut old = None; + let mut i = 0; + while let (Some(k), Some(v)) = (tags.get(i), tags.get(i + 1)) { + if k.code == 3 && k.value.eq_ignore_ascii_case(name) && matches!(v.code, 350 | 360) { + old = old.or_else(|| Handle::parse_hex(&v.value)); + tags.drain(i..i + 2); + } else { + i += 1; + } + } + old +} + +fn number(tags: &[RawTag], code: i32) -> Option { + tags.iter().find(|t| t.code == code)?.value.trim().parse::().ok().filter(|n| n.is_finite()) +} + +fn object(f: &Foreign, h: Handle) -> Option<&ForeignObject> { + f.objects.iter().find(|o| o.handle == h) +} + +/// The extension dictionary, ACAD_FILTER dictionary and SPATIAL_FILTER of entity `h`. +fn chain(f: &Foreign, h: Handle) -> Option<(Handle, Handle, &ForeignObject)> { + let xd = f.entities.get(&h)?.xdict?; + let fd = entry(&object(f, xd)?.tags, "ACAD_FILTER")?; + let sf = entry(&object(f, fd)?.tags, "SPATIAL")?; + Some((xd, fd, object(f, sf).filter(|o| o.kind.eq_ignore_ascii_case("SPATIAL_FILTER"))?)) +} + +/// A 3×4 matrix (12 values row by row) as a 2D transform, when it is one (no Z mixing). +fn matrix_2d(m: &[f64]) -> Option { + let [a, c, z1, e, b, d, z2, f, z3, z4, one, z5] = <[f64; 12]>::try_from(m).ok()?; + let flat = [z1, z2, z3, z4, z5].iter().all(|v| v.abs() <= 1e-9) && (one - 1.0).abs() <= 1e-9; + (flat && [a, b, c, d, e, f].iter().all(|v| v.is_finite())).then_some(Mat3 { a, b, c, d, e, f }) +} + +fn matrix_values(m: &Mat3) -> [f64; 12] { + [m.a, m.c, 0.0, m.e, m.b, m.d, 0.0, m.f, 0.0, 0.0, 1.0, 0.0] +} + +/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates. `None` for anything +/// the model can't hold as it is (it then stays foreign). +fn parse_filter(o: &ForeignObject) -> Option { + let count = usize::try_from(number(&o.tags, 70)? as i64).ok()?; + if !(2..=MAX_CLIP_VERTICES).contains(&count) { + return None; + } + let normal_up = number(&o.tags, 210).unwrap_or(0.0).abs() <= 1e-9 + && number(&o.tags, 220).unwrap_or(0.0).abs() <= 1e-9 + && (number(&o.tags, 230).unwrap_or(1.0) - 1.0).abs() <= 1e-9; + let no_depth = number(&o.tags, 72).unwrap_or(0.0) == 0.0 && number(&o.tags, 73).unwrap_or(0.0) == 0.0; + if !normal_up || !no_depth { + return None; + } + let m: Vec = o.tags.iter().filter(|t| t.code == 40).map(|t| t.value.trim().parse::().unwrap_or(f64::NAN)).collect(); + let (inverse, own) = match m.len() { + 24 => (matrix_2d(m.get(..12)?)?, matrix_2d(m.get(12..)?)?), + // Without matrices the vertices are taken as the block's own. + 0 => (Mat3::IDENTITY, Mat3::IDENTITY), + _ => return None, + }; + if (own.a - 1.0).abs() > 1e-9 + || own.b.abs() > 1e-9 + || own.c.abs() > 1e-9 + || (own.d - 1.0).abs() > 1e-9 + || own.e.abs() > 1e-9 + || own.f.abs() > 1e-9 + { + return None; + } + let mut points = Vec::with_capacity(count); + for w in o.tags.windows(2) { + let [x, y] = w else { continue }; + if x.code != 10 { + continue; + } + if y.code != 20 || points.len() >= count { + return None; + } + let p = inverse.apply(Vec2::new(x.value.trim().parse().ok()?, y.value.trim().parse().ok()?)); + if !p.is_finite() { + return None; + } + points.push(p); + } + let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted: false }; + (clip.points.len() == count && cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some()).then_some(clip) +} + +/// Whether the extension dictionary `xd` marks the clip inverted. +fn inverted(f: &Foreign, xd: Handle) -> bool { + object(f, xd) + .and_then(|o| entry(&o.tags, INVERT_KEY)) + .and_then(|h| object(f, h)) + .is_some_and(|o| o.kind.eq_ignore_ascii_case("XRECORD") && number(&o.tags, 70).is_some_and(|v| v != 0.0)) +} + +/// Put the planar filters of the file read into `d` on their references, taking them out of +/// the kept foreign data (the model writes them from now on). +pub(crate) fn read(d: &mut Drawing) { + if d.foreign.objects.is_empty() { + return; + } + let found: Vec<(Handle, ClipBoundary)> = d + .foreign + .entities + .keys() + .filter_map(|h| { + let (xd, _, o) = chain(&d.foreign, *h)?; + let mut clip = parse_filter(o)?; + clip.inverted = inverted(&d.foreign, xd); + Some((*h, clip)) + }) + .collect(); + if found.is_empty() { + return; + } + let mut taken = Vec::new(); + for (h, clip) in found { + let set = |e: &mut cadcraft_doc::Entity| { + if let EntityKind::Insert(i) = &mut e.kind { + i.clip = Some(clip.clone()); + } + }; + let is_insert = |e: &cadcraft_doc::Entity| matches!(e.kind, EntityKind::Insert(_)); + let done = if d.entity(h).is_some_and(|e| is_insert(e)) { + d.modify_entity(h, set).is_ok() + } else { + let mut done = false; + for b in d.blocks.values_mut() { + if b.entities.get(h).is_some_and(|e| is_insert(e)) { + done = Arc::make_mut(b).entities.modify(h, set); + break; + } + } + done + }; + if done { + taken.push(h); + } + } + let f = Arc::make_mut(&mut d.foreign); + for h in taken { + forget(f, h); + } +} + +/// Take the clip of entity `h` out of the foreign data: the ACAD_FILTER entry and what it holds, +/// CADCraft's inverted flag, and the extension dictionary when nothing else is left in it. +fn forget(f: &mut Foreign, h: Handle) { + let Some(xd) = f.entities.get(&h).and_then(|x| x.xdict) else { return }; + let mut gone: Vec = Vec::new(); + let mut empty = false; + if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { + gone.extend(remove_entry(&mut o.tags, "ACAD_FILTER")); + gone.extend(remove_entry(&mut o.tags, INVERT_KEY)); + empty = !o.tags.iter().any(|t| t.code == 3); + } + // The filter dictionary's entries go with it. + let mut i = 0; + while let Some(g) = gone.get(i).copied() { + if let Some(o) = object(f, g) + && o.kind.eq_ignore_ascii_case("DICTIONARY") + { + gone.extend(o.tags.windows(2).filter_map(|w| match w { + [k, v] if k.code == 3 && matches!(v.code, 350 | 360) => Handle::parse_hex(&v.value), + _ => None, + })); + } + i += 1; + if i > MAX_CLIP_VERTICES { + break; + } + } + if empty { + gone.push(xd); + if let Some(x) = f.entities.get_mut(&h) { + x.xdict = None; + } + if f.entities.get(&h).is_some_and(|x| x.is_empty()) { + f.entities.remove(&h); + } + } + f.objects.retain(|o| !gone.contains(&o.handle)); +} + +fn dictionary(h: Handle, owner: Handle) -> ForeignObject { + ForeignObject { + handle: h, + kind: "DICTIONARY".into(), + tags: vec![ + raw(5, h.hex()), + raw(102, "{ACAD_REACTORS"), + raw(330, owner.hex()), + raw(102, "}"), + raw(330, owner.hex()), + raw(100, "AcDbDictionary"), + raw(280, 1), + raw(281, 1), + ], + } +} + +fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3, inverse: &Mat3) -> ForeignObject { + let mut tags = vec![ + raw(5, h.hex()), + raw(102, "{ACAD_REACTORS"), + raw(330, owner.hex()), + raw(102, "}"), + raw(330, owner.hex()), + raw(100, "AcDbFilter"), + raw(100, "AcDbSpatialFilter"), + raw(70, clip.points.len()), + ]; + for p in &clip.points { + let q = to_world.apply(*p); + tags.push(raw(10, q.x)); + tags.push(raw(20, q.y)); + } + tags.extend([raw(210, 0.0), raw(220, 0.0), raw(230, 1.0), raw(11, 0.0), raw(21, 0.0), raw(31, 0.0)]); + tags.extend([raw(71, i32::from(clip.enabled)), raw(72, 0), raw(73, 0)]); + for v in matrix_values(inverse).into_iter().chain(matrix_values(&Mat3::IDENTITY)) { + tags.push(raw(40, v)); + } + ForeignObject { handle: h, kind: "SPATIAL_FILTER".into(), tags } +} + +fn invert_record(h: Handle, owner: Handle) -> ForeignObject { + ForeignObject { + handle: h, + kind: "XRECORD".into(), + tags: vec![ + raw(5, h.hex()), + raw(102, "{ACAD_REACTORS"), + raw(330, owner.hex()), + raw(102, "}"), + raw(330, owner.hex()), + raw(100, "AcDbXrecord"), + raw(280, 1), + raw(70, 1), + ], + } +} + +/// A copy of `d` whose foreign data holds the SPATIAL_FILTER of every clipped reference (any +/// filter kept from the file for it is replaced). `None` when no reference is clipped. +pub(crate) fn prepare(d: &Drawing) -> Option { + let mut clips: Vec<(Handle, ClipBoundary, Mat3)> = Vec::new(); + let mut take = |e: &cadcraft_doc::Entity| { + if let EntityKind::Insert(i) = &e.kind + && let Some(c) = &i.clip + && c.polygon().len() >= 3 + && let Some(base) = d.block(&i.block).map(|b| b.base.xy()) + { + clips.push((e.handle, c.clone(), i.transform(base))); + } + }; + d.model.iter().for_each(|e| take(e)); + d.layouts.iter().flat_map(|l| l.entities.iter()).for_each(|e| take(e)); + d.blocks.values().filter(|b| b.xref_path.is_none()).flat_map(|b| b.entities.iter()).for_each(|e| take(e)); + if clips.is_empty() { + return None; + } + let mut out = d.clone(); + let f = Arc::make_mut(&mut out.foreign); + let mut next = d.handseed.max(f.objects.iter().map(|o| o.handle.0).max().unwrap_or(0)).saturating_add(1); + fn fresh(next: &mut u64) -> Handle { + let h = Handle(*next); + *next = next.saturating_add(1); + h + } + for (insert, clip, to_world) in clips { + let Some(inverse) = to_world.inverse() else { continue }; + if next.saturating_add(5) >= MAX_HANDLE { + break; + } + // A filter kept from the file for this reference is replaced. + forget(f, insert); + let xd = match f.entities.get(&insert).and_then(|x| x.xdict).filter(|h| object(f, *h).is_some()) { + Some(h) => h, + None => { + let h = fresh(&mut next); + f.objects.push(dictionary(h, insert)); + f.entities.entry(insert).or_default().xdict = Some(h); + h + } + }; + let (fd, sf) = (fresh(&mut next), fresh(&mut next)); + let flag = clip.inverted.then(|| fresh(&mut next)); + if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { + o.tags.extend([raw(3, "ACAD_FILTER"), raw(360, fd.hex())]); + if let Some(x) = flag { + o.tags.extend([raw(3, INVERT_KEY), raw(360, x.hex())]); + } + } + let mut filters = dictionary(fd, xd); + filters.tags.extend([raw(3, "SPATIAL"), raw(360, sf.hex())]); + f.objects.push(filters); + f.objects.push(spatial_filter(sf, fd, &clip, &to_world, &inverse)); + if let Some(x) = flag { + f.objects.push(invert_record(x, xd)); + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matrices_round_trip_row_by_row() { + let m = Mat3::translate(Vec2::new(10.0, 20.0)).then_before(Mat3::rotate(0.5)).then_before(Mat3::scale(2.0, 2.0)); + let back = matrix_2d(&matrix_values(&m)).unwrap(); + assert!((back.a - m.a).abs() < 1e-12 && (back.c - m.c).abs() < 1e-12 && (back.f - m.f).abs() < 1e-12); + // Translation is the fourth value of each row. + let t = matrix_values(&Mat3::translate(Vec2::new(-5.0, 7.0))); + assert_eq!((t[3], t[7]), (-5.0, 7.0)); + assert!(matrix_2d(&[1.0; 11]).is_none()); + } + + #[test] + fn hostile_filters_stay_foreign() { + let o = |tags: Vec| ForeignObject { handle: Handle(1), kind: "SPATIAL_FILTER".into(), tags }; + assert!(parse_filter(&o(vec![raw(70, 1_000_000_000)])).is_none()); + assert!(parse_filter(&o(vec![raw(70, 3), raw(10, 0), raw(20, 0)])).is_none()); + assert!(parse_filter(&o(vec![raw(70, 2), raw(10, "nan"), raw(20, 0), raw(10, 1), raw(20, 1)])).is_none()); + assert!(parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1), raw(72, 1)])).is_none()); + let ok = parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1)])).unwrap(); + assert_eq!(ok.points.len(), 2); + } +} diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index 04ce90a01..f6c88d41b 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -325,6 +325,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, } }); MLeader { diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 1489f4def..5e3bc3362 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -138,6 +138,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { d.layers.insert(0, Layer::default()); } crate::dxf_raw::read(&secs, &mut d); + crate::dxf_clip::read(&mut d); d.skipped_records = skipped; Ok(d) } diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index aba1bdc4e..003834c6b 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -165,6 +165,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef rows: t.i(71).unwrap_or(1).clamp(1, 10_000) as u32, col_spacing, row_spacing: t.fd(45, 0.0), + clip: None, }) } "DIMENSION" => { diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index fe865515b..e1a6d34b9 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -886,6 +886,9 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ) .unwrap(); @@ -1506,6 +1507,7 @@ fn intl_sample() -> Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ) .unwrap(); @@ -2564,6 +2566,7 @@ fn pdf_strokes_each_transparent_primitive_inside_a_block() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common { transparency: Transparency::Percent(t), ..Common::default() }, EntityKind::Insert(ins)).unwrap(); d diff --git a/crates/io/tests/it/annotative_roundtrip.rs b/crates/io/tests/it/annotative_roundtrip.rs index b7fb62384..52cd6e762 100644 --- a/crates/io/tests/it/annotative_roundtrip.rs +++ b/crates/io/tests/it/annotative_roundtrip.rs @@ -45,6 +45,7 @@ fn drawing() -> Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let on_paper = Common { anno_scales: vec![AnnoScale::unit()], ..Default::default() }; d.add(&Space::Paper("Layout1".into()), on_paper, EntityKind::Insert(ins)).unwrap(); diff --git a/crates/io/tests/it/assoc_array_roundtrip.rs b/crates/io/tests/it/assoc_array_roundtrip.rs index 2b869d9e9..9500671b2 100644 --- a/crates/io/tests/it/assoc_array_roundtrip.rs +++ b/crates/io/tests/it/assoc_array_roundtrip.rs @@ -56,6 +56,7 @@ fn drawing() -> Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); d diff --git a/crates/io/tests/it/attrib_modes.rs b/crates/io/tests/it/attrib_modes.rs index 625ead939..6efa479ff 100644 --- a/crates/io/tests/it/attrib_modes.rs +++ b/crates/io/tests/it/attrib_modes.rs @@ -45,6 +45,7 @@ fn drawing() -> Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).expect("add"); d diff --git a/crates/io/tests/it/attrib_props.rs b/crates/io/tests/it/attrib_props.rs index 32dac1101..3b750fa7a 100644 --- a/crates/io/tests/it/attrib_props.rs +++ b/crates/io/tests/it/attrib_props.rs @@ -66,6 +66,7 @@ fn drawing(attribs: Vec) -> (Drawing, Handle) { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let h = d.add(&Space::Model, Common { layer: "INS".into(), ..Common::default() }, EntityKind::Insert(ins)).expect("add"); (d, h) diff --git a/crates/io/tests/it/dim_block_resave_roundtrip.rs b/crates/io/tests/it/dim_block_resave_roundtrip.rs index f0705d6fd..1879b976e 100644 --- a/crates/io/tests/it/dim_block_resave_roundtrip.rs +++ b/crates/io/tests/it/dim_block_resave_roundtrip.rs @@ -41,6 +41,7 @@ fn insert(block: &str) -> Insert { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, } } diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index d265f9e70..6c039e2af 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -380,6 +380,7 @@ fn parameters_in_a_stretch_selection_are_carried_along() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(ins)).unwrap(); cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); @@ -481,6 +482,7 @@ fn door_at_100(d: &mut cadcraft_doc::Drawing) -> Handle { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(ins)).unwrap() } diff --git a/crates/io/tests/it/entity_props_roundtrip.rs b/crates/io/tests/it/entity_props_roundtrip.rs index d86d0b4b8..f51a5b1e9 100644 --- a/crates/io/tests/it/entity_props_roundtrip.rs +++ b/crates/io/tests/it/entity_props_roundtrip.rs @@ -144,6 +144,7 @@ fn xref_block_flag_and_path_roundtrip() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let h = add(&mut d, 0.0, EntityKind::Insert(ins)); diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 51e7f1965..f3fe05e86 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -67,4 +67,5 @@ mod tolerance_roundtrip; mod user_lin_pat_roundtrip; mod view_tables_roundtrip; mod viewport_clip_roundtrip; +mod xclip_roundtrip; mod xref_roundtrip; diff --git a/crates/io/tests/it/mleader_content.rs b/crates/io/tests/it/mleader_content.rs index 07f4b16bc..f2fb6f1db 100644 --- a/crates/io/tests/it/mleader_content.rs +++ b/crates/io/tests/it/mleader_content.rs @@ -28,6 +28,7 @@ fn spline_leader_and_block_content_are_written() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), }; d.add(&Space::Model, Common::default(), EntityKind::MLeader(m)).unwrap(); diff --git a/crates/io/tests/it/mleader_roundtrip.rs b/crates/io/tests/it/mleader_roundtrip.rs index 4cb1bff34..f55da8925 100644 --- a/crates/io/tests/it/mleader_roundtrip.rs +++ b/crates/io/tests/it/mleader_roundtrip.rs @@ -51,6 +51,7 @@ fn insert(block: &str, at: Vec3) -> Insert { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, } } diff --git a/crates/io/tests/it/pdf_layers.rs b/crates/io/tests/it/pdf_layers.rs index f6da233ca..41c9c47b5 100644 --- a/crates/io/tests/it/pdf_layers.rs +++ b/crates/io/tests/it/pdf_layers.rs @@ -55,6 +55,7 @@ fn layered() -> Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common { layer: "Doors".into(), ..Default::default() }, EntityKind::Insert(ins)).unwrap(); d diff --git a/crates/io/tests/it/xclip_roundtrip.rs b/crates/io/tests/it/xclip_roundtrip.rs new file mode 100644 index 000000000..1e07ecf23 --- /dev/null +++ b/crates/io/tests/it/xclip_roundtrip.rs @@ -0,0 +1,164 @@ +//! XCLIP boundaries (gap F2) through DXF and DWG: SPATIAL_FILTER objects in the references' +//! ACAD_FILTER extension dictionaries. + +use std::sync::Arc; + +use cadcraft_doc::{Block, ClipBoundary, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space}; +use cadcraft_dxf::Version; +use cadcraft_geom::{Vec2, Vec3}; +use cadcraft_io::{SaveOptions, read, write_with}; + +fn drawing() -> Drawing { + let mut d = Drawing::new_metric(); + let mut block = Block::new("Plan"); + block.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::new(-10.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))); + block.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::new(0.0, -10.0, 0.0), b: Vec3::new(0.0, 10.0, 0.0) }))); + d.blocks.insert(block.name.clone(), Arc::new(block)); + let clips = [ + // A rectangle on a moved, scaled, rotated reference. + (Vec3::new(10.0, 20.0, 0.0), 2.0, 0.3, ClipBoundary::new(vec![Vec2::new(-2.0, -1.0), Vec2::new(2.0, 1.0)])), + // A triangle, inverted. + ( + Vec3::new(100.0, 0.0, 0.0), + 1.0, + 0.0, + ClipBoundary { inverted: true, ..ClipBoundary::new(vec![Vec2::new(-5.0, -5.0), Vec2::new(5.0, -5.0), Vec2::new(0.0, 5.0)]) }, + ), + // Turned off. + ( + Vec3::new(200.0, 0.0, 0.0), + 0.5, + 1.0, + ClipBoundary { enabled: false, ..ClipBoundary::new(vec![Vec2::new(-3.0, -3.0), Vec2::new(3.0, 3.0)]) }, + ), + ]; + for (at, scale, rotation, clip) in clips { + let ins = Insert { block: "Plan".into(), insert: at, scale: Vec3::new(scale, scale, 1.0), rotation, clip: Some(clip), ..Insert::default() }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + } + // An unclipped reference stays unclipped. + d.add(&Space::Model, Common::default(), EntityKind::Insert(Insert { block: "Plan".into(), ..Insert::default() })).unwrap(); + d +} + +fn clips(d: &Drawing) -> Vec> { + d.model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Insert(i) => Some(i.clip.clone()), + _ => None, + }) + .collect() +} + +fn same(a: &[Option], b: &[Option]) { + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(b) { + match (x, y) { + (None, None) => {} + (Some(x), Some(y)) => { + assert_eq!((x.enabled, x.inverted, x.points.len()), (y.enabled, y.inverted, y.points.len())); + for (p, q) in x.points.iter().zip(&y.points) { + assert!(p.near(*q, 1e-9), "{p:?} {q:?}"); + } + } + _ => panic!("{x:?} != {y:?}"), + } + } +} + +fn save(d: &Drawing, name: &str, version: Version) -> Vec { + write_with(d, name, &SaveOptions { version: Some(version), ..Default::default() }).unwrap() +} + +#[test] +fn clips_round_trip_through_dxf() { + let d = drawing(); + let bytes = save(&d, "a.dxf", Version::R2018); + let text = String::from_utf8(bytes.clone()).unwrap(); + assert_eq!(text.matches("SPATIAL_FILTER").count(), 3, "one filter per clipped reference"); + assert!(text.contains("ACAD_FILTER") && text.contains("CADCRAFT_XCLIP")); + let first = read(&bytes, "a.dxf").unwrap(); + same(&clips(&first), &clips(&d)); + // The model owns the filters now: nothing of them is left as foreign data. + assert!(!first.foreign.objects.iter().any(|o| o.kind == "SPATIAL_FILTER")); + for v in [Version::R2000, Version::R2004, Version::R2010, Version::R2018] { + let back = read(&save(&first, "a.dxf", v), "a.dxf").unwrap(); + same(&clips(&back), &clips(&d)); + assert_eq!(back.model.len(), first.model.len(), "{}", v.year()); + assert!(!back.foreign.objects.iter().any(|o| o.kind == "SPATIAL_FILTER"), "{}", v.year()); + let again = String::from_utf8(save(&back, "a.dxf", v)).unwrap(); + assert_eq!(again.matches("SPATIAL_FILTER").count(), 3, "no duplicate filters on resave"); + } +} + +#[test] +fn clips_round_trip_through_dwg() { + let d = drawing(); + let first = read(&save(&d, "a.dxf", Version::R2018), "a.dxf").unwrap(); + for v in [Version::R2004, Version::R2010, Version::R2018] { + let back = read(&save(&first, "a.dwg", v), "a.dwg").unwrap(); + same(&clips(&back), &clips(&d)); + assert_eq!(back.model.len(), first.model.len(), "{}", v.year()); + let blk = |d: &Drawing| d.block("Plan").map(|b| b.entities.len()); + assert_eq!(blk(&back), blk(&first), "{}", v.year()); + } +} + +#[test] +fn deleting_a_clip_read_from_a_file_removes_its_filter() { + let mut d = read(&save(&drawing(), "a.dxf", Version::R2018), "a.dxf").unwrap(); + let hs: Vec = d.model.iter().filter(|e| matches!(&e.kind, EntityKind::Insert(i) if i.clip.is_some())).map(|e| e.handle).collect(); + for h in &hs { + d.modify_entity(*h, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + i.clip = None; + } + }) + .unwrap(); + } + let text = String::from_utf8(save(&d, "a.dxf", Version::R2018)).unwrap(); + assert!(!text.contains("SPATIAL_FILTER") && !text.contains("CADCRAFT_XCLIP")); + assert!(clips(&read(text.as_bytes(), "a.dxf").unwrap()).iter().all(Option::is_none)); +} + +#[test] +fn filter_matrices_are_the_inverse_reference_transform() { + // A reference at (150, 0), unrotated: the inverse moves by -150; vertices in drawing units. + let mut d = Drawing::new_metric(); + let mut block = Block::new("P"); + block.entities.push(Entity::new(d.new_handle(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) }))); + d.blocks.insert("P".into(), Arc::new(block)); + let clip = ClipBoundary::new(vec![Vec2::new(20.0, 20.0), Vec2::new(80.0, 20.0), Vec2::new(80.0, 80.0), Vec2::new(20.0, 80.0)]); + let h = d + .add( + &Space::Model, + Common::default(), + EntityKind::Insert(Insert { block: "P".into(), insert: Vec3::new(150.0, 0.0, 0.0), clip: Some(clip), ..Insert::default() }), + ) + .unwrap(); + // Read back without CADCraft taking the filter: look at the DXF groups. + let text = String::from_utf8(save(&d, "a.dxf", Version::R2018)).unwrap(); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let at = lines.windows(2).position(|w| w[0] == "0" && w[1] == "SPATIAL_FILTER").unwrap(); + let end = (at + 2..lines.len()).step_by(2).find(|i| lines[*i] == "0").unwrap(); + let rec = &lines[at..end]; + let values = |code: &str| -> Vec { rec.chunks(2).filter(|w| w[0] == code).map(|w| w[1].parse().unwrap()).collect() }; + assert_eq!(values("70"), vec![4.0]); + assert_eq!(values("10"), vec![170.0, 230.0, 230.0, 170.0]); + assert_eq!( + values("40"), + vec![1.0, 0.0, 0.0, -150.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0] + ); + let _ = h; +} + +#[test] +fn hostile_spatial_filters_do_not_panic() { + let text = String::from_utf8(save(&drawing(), "a.dxf", Version::R2018)).unwrap(); + // Vertex counts, coordinates and matrices replaced by nonsense. + for (from, to) in [(" 70\n3\n", " 70\n999999999\n"), ("\n 40\n1.0\n", "\n 40\nnan\n"), ("\n 10\n", "\n 10\n1e999\n 10\n")] { + let bad = text.replacen(from, to, 1); + let _ = read(bad.as_bytes(), "a.dxf"); + } +} diff --git a/crates/io/tests/it/xref_roundtrip.rs b/crates/io/tests/it/xref_roundtrip.rs index 815d71afa..58869c0d9 100644 --- a/crates/io/tests/it/xref_roundtrip.rs +++ b/crates/io/tests/it/xref_roundtrip.rs @@ -52,6 +52,7 @@ fn host() -> Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).expect("add"); } diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index ad4689682..9782ae177 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -55,19 +55,69 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: let off = Vec2::new(ins.col_spacing * f64::from(c), ins.row_spacing * f64::from(r)).rotate(ins.rotation); let m = Mat3::translate(off).then_before(ins.transform(blk.base.xy())); let sub = Ctx { block_pstyle: b.named, block_transparency: b.transparency, ..sub_ctx(ctx, e, m) }; + // XCLIP: the copy is drawn on its own, then cut to the boundary. + let clip = xclip_region(ins, &sub.xf); + let mut part = clip.as_ref().map(|_| b.part()); + let target = part.as_mut().unwrap_or(&mut *b); + let mut stop = false; for be in blk.entities.iter() { // Constant/visible attribute definitions inside blocks are not drawn; attribs are. if matches!(be.kind, EntityKind::AttDef(_)) { continue; } - if !b.expand() { - break 'copies; + if !target.expand() { + stop = true; + break; } - entity(b, &sub, be); + entity(target, &sub, be); + } + if let (Some(part), Some((region, inverted))) = (part, &clip) { + b.list.expanded = part.list.expanded; + append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }); + xclip_frame(b, ctx, region, rgb); + } + if stop { + break 'copies; } } } } + // Attributes are cut by the reference's clip too. + let attr_clip = ctx.d.block(&ins.block).and_then(|blk| xclip_region(ins, &ctx.xf.then_before(ins.transform(blk.base.xy())))); + let mut part = attr_clip.as_ref().map(|_| b.part()); + attributes(part.as_mut().unwrap_or(&mut *b), ctx, e, ins, rgb); + if let (Some(part), Some((region, inverted))) = (part, &attr_clip) { + append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }); + } +} + +/// The XCLIP region of reference `ins` drawn through `xf` (block to drawing coordinates), and +/// whether it is inverted. `None` when the reference isn't clipped (no boundary, clipping off, a +/// degenerate outline). +fn xclip_region(ins: &cadcraft_doc::Insert, xf: &Mat3) -> Option<(clip::PolyClip, bool)> { + let c = ins.clip.as_ref().filter(|c| c.active())?; + let world: Vec = c.polygon().into_iter().map(|p| xf.apply(p)).collect(); + Some((clip::PolyClip::new(&world)?, c.inverted)) +} + +/// The clipping boundary's frame as XCLIPFRAME says: 0 hidden, 1 shown and plotted, 2 shown but +/// not plotted (the default). +fn xclip_frame(b: &mut Builder, ctx: &Ctx, region: &clip::PolyClip, rgb: Ink) { + let mode = ctx.d.header.i64("XCLIPFRAME", 2); + if mode == 0 || (b.plotting && mode != 1) { + return; + } + let mut frame = region.polygon().to_vec(); + if let Some(first) = frame.first().copied() { + frame.push(first); + } + // The outline is in drawing coordinates already. + let top = Ctx { xf: Mat3::IDENTITY, ..ctx.clone() }; + b.polyline(&top, rgb, 0.0, &frame); +} + +/// The attributes of block reference `e` (`ins`). +fn attributes(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink) { if b.opts.text { // ATTMODE (ATTDISP): 0 shows no attributes, 1 the visible ones, 2 all of them. let attmode = ctx.d.header.i64("ATTMODE", 1); diff --git a/crates/render/src/clip.rs b/crates/render/src/clip.rs index 73d89fdc3..a95455d3d 100644 --- a/crates/render/src/clip.rs +++ b/crates/render/src/clip.rs @@ -423,6 +423,80 @@ impl PolyClip { } out } + + /// Clip a segment the other way round (an inverted XCLIP): the pieces outside the region. + fn clip_segment_outside(&self, a: Vec2, b: Vec2, out: &mut Vec<(Vec2, Vec2)>) { + if !a.is_finite() || !b.is_finite() { + return; + } + if clip_segment(a, b, &self.bounds).is_none() { + out.push((a, b)); + return; + } + let d = b - a; + let mut prev = 0.0; + for t in self.crossings(a, b).into_iter().chain(std::iter::once(1.0)) { + if t - prev > 1e-12 && !self.contains(a + d * ((prev + t) / 2.0)) { + out.push((a + d * prev, a + d * t)); + } + prev = t; + } + } + /// Clip a polyline to outside the region (an inverted XCLIP); the visible pieces. + pub fn clip_polyline_outside(&self, pts: &[Vec2]) -> Vec> { + let mut out: Vec> = Vec::new(); + let mut cur: Vec = Vec::new(); + let mut pieces = Vec::new(); + for w in pts.windows(2) { + let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; + pieces.clear(); + self.clip_segment_outside(*a, *b, &mut pieces); + if pieces.is_empty() { + if cur.len() >= 2 { + out.push(std::mem::take(&mut cur)); + } + cur.clear(); + } + for (p, q) in pieces.drain(..) { + if !cur.last().is_some_and(|l| l.near(p, 1e-12)) { + if cur.len() >= 2 { + out.push(std::mem::take(&mut cur)); + } + cur.clear(); + cur.push(p); + } + cur.push(q); + } + } + if cur.len() >= 2 { + out.push(cur); + } + out + } + /// Clip an infinite line (or a ray) to outside the region: the line cut where it crosses. + pub fn clip_infinite_outside(&self, base: Vec2, dir: Vec2, ray: bool) -> Vec> { + let len = dir.len(); + if !base.is_finite() || !dir.is_finite() || len < 1e-300 { + return Vec::new(); + } + let u = dir * (1.0 / len); + // Far enough past the region and the base point that the cut pieces reach the view. + let far = (self.bounds.width() + self.bounds.height() + (base - self.bounds.center()).len()) * 4.0 + 1e6; + let a = if ray { base } else { base - u * far }; + self.clip_polyline_outside(&[a, base + u * far]) + } + /// Fill triangles outside the region (an inverted XCLIP). A triangle wholly inside goes; one + /// the outline crosses stays whole (fills are not cut against the outside). + pub fn clip_triangles_outside(&self, tris: &[Vec2]) -> Vec { + let mut out = Vec::new(); + for t in tris.as_chunks::<3>().0 { + let inside = t.iter().all(|p| self.contains(*p)) && (0..3).all(|i| self.crossings(t[i], t[(i + 1) % 3]).is_empty()); + if !inside { + out.extend_from_slice(t); + } + } + out + } } /// Clip a polygon to a triangle (Sutherland–Hodgman; the triangle is convex). diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5b9dc83a1..c905992c8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -133,7 +133,7 @@ struct Builder<'a> { /// bounds the depth); past the limit the remaining block contents are not drawn. pub const MAX_BLOCK_EXPANSION: usize = 2_000_000; -impl Builder<'_> { +impl<'a> Builder<'a> { /// `color` and `lw` as the plot style table prints them. fn styled(&self, color: Ink, lw: f32) -> (Ink, f32) { match self.styles { @@ -288,6 +288,21 @@ impl Builder<'_> { len: 2, }); } + /// An empty builder drawing like this one (for contents cut afterwards, an XCLIP), with the + /// block-expansion count carried over. + fn part(&self) -> Builder<'a> { + let mut list = DisplayList::default(); + list.expanded = self.list.expanded; + Builder { + list, + opts: self.opts, + plotting: self.plotting, + styles: self.styles, + named: self.named, + shared_budget: self.shared_budget, + transparency: self.transparency, + } + } /// Take one unit of the block-expansion budget; false once it is spent. fn expand(&mut self) -> bool { self.list.expanded = self.list.expanded.saturating_add(1); @@ -316,6 +331,7 @@ pub use pipeline::{Options, build, build_entities, build_plot}; use props::{default_lineweight, resolve_common}; use text_entity::text_style; pub use text_entity::{layout_mtext_entity, place_text_entity, text_align}; +use viewports::{Clip, append_clipped_keep}; pub use viewports::{viewport_clip, viewport_content}; #[cfg(test)] diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ae35f27f9..98b71e2bf 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -632,6 +632,7 @@ fn hatch_in_a_squashed_block_keeps_lines_that_show() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); // One pixel = 1 unit: 0.125 spacing × 100 along x is far more than a pixel. @@ -676,6 +677,7 @@ fn insert_of(block: &str) -> EntityKind { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) } diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 6f1e57517..a3b585601 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -187,16 +187,50 @@ pub fn viewport_clip(d: &Drawing, handle: Handle, vp: &cadcraft_doc::Viewport) - } /// What viewport contents are clipped to. -enum Clip<'a> { +pub(crate) enum Clip<'a> { /// The viewport rectangle (the fast path). Rect(Bounds2), /// A clip boundary's outline. Poly(&'a clip::PolyClip), + /// Outside a clip boundary's outline (an inverted XCLIP). + Outside(&'a clip::PolyClip), } /// Append `src` to `dst`, clipped to `clip`. -fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { +pub(crate) fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { for p in &src.prims { + clip_prim(dst, src, p, clip); + } +} + +/// Append `src` to `dst` clipped to `clip`, keeping each primitive's plot style pen and, for a +/// glyph that the clip leaves whole, its plotted text (an XCLIP-clipped block reference). +pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { + let texts: std::collections::HashMap = + src.texts.iter().filter(|t| t.prim != PlotText::NONE && t.prim != PlotText::CLIPPED).map(|t| (t.prim as usize, t)).collect(); + for (i, p) in src.prims.iter().enumerate() { + let first = dst.prims.len(); + clip_prim(dst, src, p, clip); + if let Some(pen) = src.pens.get(i).copied().filter(|pen| !pen.is_object()) { + for k in first..dst.prims.len() { + dst.pens.resize(k, Pen::default()); + dst.pens.push(pen); + } + } + if dst.prims.len() == first + 1 + && let (Some(q), Some(t)) = (dst.prims.get(first), texts.get(&i)) + && q.kind == p.kind + && dst.points(q) == src.points(p) + && let Ok(prim) = u32::try_from(first) + { + dst.texts.push(PlotText { prim, ..(**t).clone() }); + } + } +} + +/// Append primitive `p` of `src` to `dst`, clipped to `clip`. +fn clip_prim(dst: &mut DisplayList, src: &DisplayList, p: &DPrim, clip: &Clip) { + { let pts = src.points(p); match (p.kind, clip) { (Kind::Polyline, Clip::Rect(rect)) => { @@ -209,6 +243,11 @@ fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { push_raw(dst, p, Kind::Polyline, &piece); } } + (Kind::Polyline, Clip::Outside(c)) => { + for piece in c.clip_polyline_outside(pts) { + push_raw(dst, p, Kind::Polyline, &piece); + } + } (Kind::Tris | Kind::Mask, Clip::Rect(rect)) => { let t = clip::clip_triangles(pts, rect); push_raw(dst, p, p.kind, &t); @@ -217,10 +256,15 @@ fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { let t = c.clip_triangles(pts); push_raw(dst, p, p.kind, &t); } + (Kind::Tris | Kind::Mask, Clip::Outside(c)) => { + let t = c.clip_triangles_outside(pts); + push_raw(dst, p, p.kind, &t); + } (Kind::Point, _) => { let inside = |q: Vec2| match clip { Clip::Rect(rect) => rect.contains(q), Clip::Poly(c) => c.contains(q), + Clip::Outside(c) => !c.contains(q), }; if let Some(q) = pts.first() && inside(*q) @@ -242,6 +286,13 @@ fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { } } } + (Kind::Infinite { ray }, Clip::Outside(c)) => { + if let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) { + for piece in c.clip_infinite_outside(*base, *dir, ray) { + push_raw(dst, p, Kind::Polyline, &piece); + } + } + } } } } diff --git a/crates/render/tests/block_ltscale.rs b/crates/render/tests/block_ltscale.rs index 4e5863752..3f8334e48 100644 --- a/crates/render/tests/block_ltscale.rs +++ b/crates/render/tests/block_ltscale.rs @@ -29,6 +29,7 @@ fn drawing(ltscale: f64, own: &str) -> Drawing { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, reference, EntityKind::Insert(ins)).unwrap(); d diff --git a/crates/render/tests/it/aci7_display.rs b/crates/render/tests/it/aci7_display.rs index 5881c6bce..943d1ba7b 100644 --- a/crates/render/tests/it/aci7_display.rs +++ b/crates/render/tests/it/aci7_display.rs @@ -27,6 +27,7 @@ fn insert(y: f64) -> EntityKind { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }) } diff --git a/crates/render/tests/it/plot_styles.rs b/crates/render/tests/it/plot_styles.rs index 75134911d..4e027506c 100644 --- a/crates/render/tests/it/plot_styles.rs +++ b/crates/render/tests/it/plot_styles.rs @@ -143,6 +143,7 @@ fn named_styles_by_layer_by_block_and_name() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }); d.add(&Space::Model, Common { plot_style: "Thick".into(), ..Default::default() }, ins).unwrap(); let l = build_plot(&d, &Space::Model, &with_table(PlotStyleTable::builtin("default.stb").unwrap())); diff --git a/crates/render/tests/it/render_props.rs b/crates/render/tests/it/render_props.rs index f210dc4e1..7591d6747 100644 --- a/crates/render/tests/it/render_props.rs +++ b/crates/render/tests/it/render_props.rs @@ -169,6 +169,7 @@ fn attributes_draw_with_their_own_properties() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let common = Common { color: Color::Index(1), lineweight: Lineweight::Mm100(35), ..on("INS") }; d.add(&Space::Model, common, EntityKind::Insert(ins)).unwrap(); diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 634249093..f4fd969b6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -142,6 +142,8 @@ menu Modify Edita Clear Cancella Clip Delimita Clip Viewport Delimita finestra + Clip Xref Ritaglia xrif + Xref Clip Frame Cornice ritaglio xrif Clipboard Appunti Close Chiudi Close All Chiudi tutto diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d71b3ccd7..399e66ddf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -139,6 +139,8 @@ Clear Очистити Clip Обрізати Clip Viewport Обрізати видовий екран + Clip Xref Обрізати зовнішнє посилання + Xref Clip Frame Рамка обрізки зовнішнього посилання Clipboard Буфер обміну Close Закрити Close All Закрити всі diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..8e7bf311a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (Named Viewports dialog: U11 narrowed; MVIEW Restore and PURGE of multiline styles had landed: F15 and F21 corrected) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (XCLIP and XCLIPFRAME: F2 and top-10 row 4 narrowed) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -16,7 +16,7 @@ do them first. | 1 | **[alpha blocker]** **Saving DWG drops what we don't model** (DXF now writes back unknown entities and objects, foreign xdata, extension dictionaries, reactors, layer states and colour books, #528, and native MULTILEADERs, #459 (not yet tested through DWG); through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour books and reactors) | Opening a colleague's DWG and saving it still deletes some content: the one thing a CAD user can't forgive | 6–10 | [file formats](file-format-parity.md) | | 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | All 36 file tests are synthetic; nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 10–15 + human | [file formats](file-format-parity.md#tests) | | 3 | **Ellipse and spline geometry is tessellated** (intersections, offsets, closest points; polyline offset ignores bulges) | Coordinates are subtly wrong; offsets of ellipses come out as polylines | 30–50 | [geometry](geometry-parity.md) | -| 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be edited in place or clipped** (xrefs, #525, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | +| 4 | **[alpha blocker]** **No dynamic blocks or REFEDIT; xrefs can't be edited in place** (xrefs, #525, XCLIP, groups, #417, and the Block Editor for static blocks landed) | Most production drawings use them | 55–90 | [features](#features) | | 5 | **No autosave in the web build** (the desktop app has SAVETIME autosave, Drawing Recovery, AUDIT and RECOVER since #406) | Browser users lose unsaved work when the tab or the browser goes down | 3–5 | [features](#features) | | 6 | **No CI runs the Rust tests on pull requests** (`cargo fmt` on main is fixed) | open PRs land without a gate; regressions go unseen | 2–3 | [stability](#stability) | @@ -25,7 +25,7 @@ do them first. | # | Gap | Evidence | User impact | Est. | |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | -| F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | +| F2 | XREF editing in place: REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XCLIP clips a block or xref reference to a rectangular, polygonal or closed-polyline boundary (Invert clip, ON/OFF, Delete, generate Polyline; Clipdepth is ignored in 2D), drawn, plotted and framed as XCLIPFRAME says, with the extents cut to it, and kept through DXF and DWG as the reference's SPATIAL_FILTER (2026-10-27). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place | 12–20 | | F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | XCLIP (rectangular, polygonal and polyline boundaries, Invert clip, ON/OFF, Delete, generate Polyline) and XCLIPFRAME: a boundary per block or xref reference (`Insert::clip`, block coordinates), drawn, plotted and framed clipped, the extents cut to it, and read and written as the reference's ACAD_FILTER/SPATIAL SPATIAL_FILTER in DXF and DWG: F2 and top-10 row 4 narrowed | | 2026-10-25 | minor | Named Viewports (View ▸ Viewports ▸ Named Viewports..., `vports.named`) lists the saved viewport configurations with a preview and the current one's name, and restores or deletes one; in a layout Restore places it as MVIEW Restore does: U11 narrowed. F15 and U11 no longer list MVIEW Restore (#633), and F21 no longer says PURGE skips multiline styles | | 2026-10-25 | minor | DIMTFILL limits: with DIMTFILL 1 (the drawing's background color) the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI: F7 updated | | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b5407d60..14a235579 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity: CADCraft vs AutoCAD 2027 -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (COMPAREEXPORT; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (XCLIP; numbers not re-measured) · **Target:** Autodesk AutoCAD 2027 The authoritative assessment of how close CADCraft is to AutoCAD, and how much Opus 5.5 work remains. [ROADMAP.md](../ROADMAP.md) summarises it, [gaps.md](gaps.md) lists every shortfall, @@ -154,7 +154,7 @@ presence: an option that prints "not available yet" doesn't count. | Text and MTEXT | 6% | 35% | 30–45 | TrueType, formatting codes, stacking; MTEXT prompt options (#408), indents, tabs, bullets, numbering and columns (#547), annotative scaling (#468); editor is a dialog, not in place; no fields or SPELL (open PR #551), no SHX | [gaps](gaps.md#features) | | Leaders, tables, fields | 4% | 25% | 25–35 | MLEADER options and block content (#408), native MULTILEADER in DXF (#459); tables with cell styles, formulas, breaking and CSV data links (#534); no MLEADEREDIT/ALIGN/COLLECT, no FIELD | [gaps](gaps.md#features) | | Hatch and gradients | 5% | 35% | 15–25 | pick points with islands; 23 patterns of ~85; gradients render flat; origin, gap tolerance, separate hatches, island styles and HATCHEDIT options (#451); Hatch and Gradient / Hatch Edit dialogs (no Preview or Inherit Properties) | [gaps](gaps.md#features) | -| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; no dynamic-block authoring, XCLIP, DesignCenter | [gaps](gaps.md#features) | +| Blocks, attributes, xrefs, groups | 9% | 25% | 80–120 | static blocks and attributes; ATTSYNC, BATTMAN editing, DATAEXTRACTION/EATTEXT (#433); xrefs (#525); groups (#417); Block Editor for static blocks (BEDIT, BSAVE, BSAVEAS, BCLOSE); REFEDIT; dynamic block references read and edited; XCLIP; no dynamic-block authoring, DesignCenter | [gaps](gaps.md#features) | | Layouts, viewports, plotting | 9% | 35% | 35–50 | layouts, per-VP layers, page setups, plot styles (CTB/STB), Plot dialog (#160), Plot Preview and PUBLISH (#186), plotter devices (#564), PDF with text, layers and sheets (#567, #571), polygonal/object/clipped viewports (#453), annotative scales (#468); no MVIEW Restore, no system printers | [gaps](gaps.md#features) | | Inquiry and utilities | 4% | 30% | 30–45 | DIST, AREA, ID, LIST, MEASUREGEOM, CAL, FIND, COUNT across layouts, QuickCalc, COMPARE (#563) and COMPAREEXPORT, MASSPROP on regions (#510), autosave/recovery, AUDIT, RECOVER (#406), OPTIONS (#23); no SPELL (open PR #551), ETRANSMIT | [gaps](gaps.md#features) | | Parametric constraints | 2% | 50% | 20–30 | all 12 geometric and the dimensional constraints, own solver; DOF report, G2 Smooth, ellipse/spline/block geometry and CONSTRAINTINFER landed (#546) | [geometry-parity](geometry-parity.md#constraint-solver--50) | @@ -223,6 +223,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Blocks, attributes, xrefs, groups row: XCLIP and XCLIPFRAME clip block and xref references; parity percentages and hours not re-measured | | 2026-10-24 | minor | Inquiry and utilities row: COMPAREEXPORT exports a comparison to a new drawing; parity percentages and hours not re-measured | | 2026-10-22 | minor | Draw row: RECTANG gained a centre construction mode (`Center` keyword, `center: true`) beside its corner mode (#1127); parity percentages and hours not re-measured | | 2026-10-12 | minor | Hatch row evidence: Hatch and Gradient / Hatch Edit dialogs; percentages and hours not re-measured | From 7917afce5d73c661c3a33fdcffca4473a67a2efb Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Thu, 29 Oct 2026 11:42:25 +0100 Subject: [PATCH 099/531] render: explicit imports for XCLIP clipping after #2239 #2239 replaced the glob imports in blocks.rs and viewports.rs with explicit lists; the XCLIP code relied on the globs for `Clip`, `append_clipped_keep`, `clip` and `Pen`. Import them by name. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/render/src/blocks.rs | 2 +- crates/render/src/viewports.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index 9782ae177..460c7e5da 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -1,7 +1,7 @@ use super::draw::entity; use super::props::{resolve, resolve_common, transparency}; use super::text_entity::{mtext, place_text_entity}; -use super::{Builder, Color, Ctx, Entity, EntityKind, Ink, Lineweight, Mat3, Vec2}; +use super::{Builder, Clip, Color, Ctx, Entity, EntityKind, Ink, Lineweight, Mat3, Vec2, append_clipped_keep, clip}; pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> { let layer = if e.common.layer == "0" { ctx.block_layer.clone() } else { Some(e.common.layer.clone()) }; diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index a3b585601..8edfa39ec 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -5,7 +5,7 @@ use super::draw::entity; #[cfg(not(target_arch = "wasm32"))] use super::pipeline::PARALLEL_CHUNK; use super::pipeline::{Options, style_table, top_ctx, with_point_view}; -use super::{Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, Mat3, Space, Vec2, clip, paper, pen, plotstyle}; +use super::{Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, Mat3, Pen, Space, Vec2, clip, paper, pen, plotstyle}; /// Upper bound on viewports drawn per layout (hostile files). pub(crate) const MAX_VIEWPORTS: usize = 256; From aaaf65487208dae790c3b9492e1499d9600aa11c Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:42:19 +0300 Subject: [PATCH 100/531] io: a group, sortents table or dimension link follows the entity the reader renumbered --- crates/io/src/dxf_read.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index e7b99839a..8c91c0088 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -130,11 +130,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout); // A sortents table orders by the file's entity handles; those follow a renumbered entity. for (_, order) in &mut objs.sortents { - for h in order.keys_mut() { - if let Some(n) = rx.renamed.get(h) { - *h = *n; - } - } + *order = order.iter().map(|(h, o)| (rx.renamed.get(h).copied().unwrap_or(*h), *o)).collect(); } apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); From 33019677a88182824c97770f6995aba513daa431 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:57:01 -0300 Subject: [PATCH 101/531] fix(dwg): read kept objects as the version they came from when saving DWG CADCraft saves DWG through an R2000 DXF bridge, and the objects it keeps without modelling them (render settings, fields, associative and dynamic block data) are written into that bridge in the groups of the file they were read from. acadrust reads several of those differently by version, so reading them as R2000 changed them: - mental ray render settings from a 2013+ file came out one class version too high; the ODA File Converter then refuses the whole DWG ("Object improperly read: AcDbMentalRayRenderSettings"); - RapidRT render settings from a 2013 file came out one class version too low; - a field lost its value flags, format and cached value. The bridge is now read as the version the kept groups came from (the drawing's $ACADVER) when that is newer than R2000: cadcraft_dwg gains dxf_to_dwg_kept_as, which sets $ACADVER before acadrust reads the DXF, decoding a code page to UTF-8 first when the kept version is 2007 or later. Drawings without $ACADVER, or from an R2000 or older file, save as before. Tests: a synthetic DXF (render settings and a field in the named object dictionary) saved as 2018, 2013 and 2004 DWG must hold the same objects as acadrust's own conversion of that DXF; three of the four cases fail without this change. Unit tests cover the $ACADVER rewrite (CRLF, code pages, binary DXF, a $ACADVER outside the header, unknown versions). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dwg/src/lib.rs | 172 ++++++++++++- crates/io/src/lib.rs | 11 +- crates/io/tests/dwg_kept_object_versions.rs | 262 ++++++++++++++++++++ 3 files changed, 437 insertions(+), 8 deletions(-) create mode 100644 crates/io/tests/dwg_kept_object_versions.rs diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index b81bd00d1..03d756226 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -460,13 +460,32 @@ mod native { /// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004 /// (AC1018). pub fn dxf_to_dwg(dxf: &[u8]) -> Result, String> { - convert(dxf, None) + convert(dxf, None, None) } /// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"), /// whatever version the DXF declares. pub fn dxf_to_dwg_as(dxf: &[u8], version: &str) -> Result, String> { - let v = match version.trim().to_ascii_uppercase().as_str() { + convert(dxf, Some(writable(version)?), None) + } + + /// Like [`dxf_to_dwg_as`], for a DXF that declares an older version than the groups it carries + /// over from another file. CADCraft's R2000 DWG bridge holds the objects it keeps without + /// modelling them (render settings, fields, associative and dynamic block data) as they were + /// read from a file of version `kept` ("AC1032"), and acadrust reads several of those + /// differently by version: read as R2000, an AC1032 file's mental ray render settings came out + /// a class version too high, for which the ODA rejects the whole DWG, and a field lost its + /// cached value. So the DXF is read as `kept` declares. A `kept` version that is unknown, or + /// not newer than the DXF's own, changes nothing. + pub fn dxf_to_dwg_kept_as(dxf: &[u8], version: &str, kept: &str) -> Result, String> { + let kept = acadrust::DxfVersion::from_version_string(kept.trim().to_ascii_uppercase().as_str()); + let kept = (kept != acadrust::DxfVersion::Unknown).then_some(kept); + convert(dxf, Some(writable(version)?), kept) + } + + /// The DWG version for a code from [`super::VERSIONS`]. + fn writable(version: &str) -> Result { + Ok(match version.trim().to_ascii_uppercase().as_str() { "AC1015" => acadrust::DxfVersion::AC1015, "AC1018" => acadrust::DxfVersion::AC1018, "AC1021" => acadrust::DxfVersion::AC1021, @@ -474,8 +493,66 @@ mod native { "AC1027" => acadrust::DxfVersion::AC1027, "AC1032" => acadrust::DxfVersion::AC1032, _ => return Err(super::unsupported(version)), + }) + } + + /// The ASCII DXF with its `$ACADVER` set to `kept` when that is newer than the version it + /// declares, or `None` to read it as it is (binary, no `$ACADVER`, or non-ASCII text without a + /// `$DWGCODEPAGE` to decode it by). From AutoCAD 2007 (AC1021) a DXF is UTF-8, so other bytes + /// are first decoded with the code page the DXF declares; `\U+XXXX` escapes read the same in + /// every version, and CADCraft's R2000 DXF is ASCII with such escapes. + pub(super) fn declare_version(dxf: &[u8], kept: acadrust::DxfVersion) -> Option> { + if dxf.starts_with(b"AutoCAD Binary DXF") { + return None; + } + let (_, declared) = header_value(dxf, b"$ACADVER")?; + let declared = acadrust::DxfVersion::from_version_string(std::str::from_utf8(declared).ok()?); + if declared >= kept { + return None; + } + let text: std::borrow::Cow<'_, [u8]> = if dxf.is_ascii() || kept < acadrust::DxfVersion::AC1021 { + std::borrow::Cow::Borrowed(dxf) + } else { + // As acadrust decodes an older DXF: by its code page, Windows-1252 for one it doesn't + // know; a code page that names UTF-8 needs no decoding. + let (_, code_page) = header_value(dxf, b"$DWGCODEPAGE")?; + match acadrust::io::dxf::code_page::encoding_from_code_page(std::str::from_utf8(code_page).ok()?) { + Some(encoding) => { + let (text, errors) = encoding.decode_without_bom_handling(dxf); + if errors { + return None; + } + std::borrow::Cow::Owned(text.into_owned().into_bytes()) + } + None => std::borrow::Cow::Borrowed(std::str::from_utf8(dxf).ok()?.as_bytes()), + } }; - convert(dxf, Some(v)) + let (at, value) = header_value(&text, b"$ACADVER")?; + let code = kept.to_string(); + let mut out = Vec::with_capacity(text.len().saturating_add(code.len())); + out.extend_from_slice(text.get(..at)?); + out.extend_from_slice(code.as_bytes()); + out.extend_from_slice(text.get(at.checked_add(value.len())?..)?); + Some(out) + } + + /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value + /// line after the group code that follows the `9` group naming it. Only the HEADER section + /// (up to the first `ENDSEC`) is searched; lines may end in `\r\n`. + fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> { + let mut lines: Vec<(usize, &[u8])> = Vec::new(); + let mut offset = 0usize; + for line in dxf.split(|b| *b == b'\n') { + let trimmed = line.trim_ascii(); + let lead = line.len() - line.trim_ascii_start().len(); + lines.push((offset.saturating_add(lead), trimmed)); + offset = offset.saturating_add(line.len()).saturating_add(1); + if trimmed == b"ENDSEC" { + break; + } + } + let at = lines.windows(2).position(|w| w[0].1 == b"9" && w[1].1 == name)?; + lines.get(at.checked_add(3)?).copied() } /// The current dimension and text styles' names from their handles: a DWG stores the @@ -512,7 +589,8 @@ mod native { } } - fn convert(dxf: &[u8], version: Option) -> Result, String> { + /// `kept`: the version the DXF's carried-over groups were read from ([`dxf_to_dwg_kept_as`]). + fn convert(dxf: &[u8], version: Option, kept: Option) -> Result, String> { // Reject a pathologically large DXF before handing it to the third-party decoder, which // allocates tables and section buffers from the input's declared sizes and cannot be // interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder @@ -524,7 +602,18 @@ mod native { mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - let data = dxf.to_vec(); + // Decoding a code page to UTF-8 can grow the text, so the limit applies again. + let data = match kept.and_then(|k| declare_version(dxf, k)) { + Some(d) if d.len() > Limits::DEFAULT.max_dxf_bytes => { + return Err(format!( + "DXF: the input is {} as UTF-8, larger than the {} CADCraft converts to DWG", + mb(d.len() as u64), + mb(Limits::DEFAULT.max_dxf_bytes as u64) + )); + } + Some(d) => d, + None => dxf.to_vec(), + }; let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; @@ -642,7 +731,7 @@ mod native { } #[cfg(not(target_arch = "wasm32"))] -pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as}; +pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_kept_as}; /// The error for a DWG version CADCraft can't write. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -671,6 +760,10 @@ pub fn dxf_to_dwg(_dxf: &[u8]) -> Result, String> { pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result, String> { Err("DWG files can't be written in the web build yet; save as DXF".into()) } +#[cfg(target_arch = "wasm32")] +pub fn dxf_to_dwg_kept_as(_dxf: &[u8], _version: &str, _kept: &str) -> Result, String> { + Err("DWG files can't be written in the web build yet; save as DXF".into()) +} #[cfg(test)] mod tests { @@ -911,4 +1004,71 @@ mod tests { assert!(ls.contains(&"LSDEFINITION") && !ls.contains(&"LSINTERNALCOMPONENT"), "{ls:?}"); assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]); } + + /// An R2000 DXF header (`\r\n` lines, as CADCraft writes them) with `extra` after `$ACADVER`. + #[cfg(not(target_arch = "wasm32"))] + fn r2000(extra: &[u8]) -> Vec { + let mut dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n 9\r\n$DWGCODEPAGE\r\n 3\r\nANSI_1252\r\n".to_vec(); + dxf.extend_from_slice(b" 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\n"); + dxf.extend_from_slice(extra); + dxf.extend_from_slice(b"\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"); + dxf + } + + /// The kept version replaces only the `$ACADVER` value; everything else stays byte for byte. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn declare_version_changes_only_acadver() { + let dxf = r2000(b"A\\U+00E7\\U+00E3o"); + let out = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), String::from_utf8(dxf).unwrap().replacen("AC1015", "AC1032", 1)); + } + + /// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER` + /// are read as they are. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn declare_version_leaves_what_it_need_not_change() { + let dxf = r2000(b"x"); + assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1015), None); + assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1009), None); + assert_eq!(native::declare_version(b"AutoCAD Binary DXF\r\n\x1a\0", acadrust::DxfVersion::AC1032), None); + let no_version = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::declare_version(no_version, acadrust::DxfVersion::AC1032), None); + // A `$ACADVER` outside the HEADER section is not the file's version. + let late = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(late, acadrust::DxfVersion::AC1032), None); + } + + /// Declared as 2007 or later, a DXF is UTF-8: code page text is decoded first. Declared as an + /// older version, the code page bytes stay as they are. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn declare_version_decodes_a_code_page_for_utf8_versions() { + let dxf = r2000(b"A\xe7\xe3o"); + let utf8 = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap(); + let text = String::from_utf8(utf8).unwrap(); + assert!(text.contains("\r\nAção\r\n") && text.contains("$ACADVER\r\n 1\r\nAC1032\r\n"), "{text}"); + let legacy = native::declare_version(&dxf, acadrust::DxfVersion::AC1018).unwrap(); + assert!(legacy.windows(4).any(|w| w == b"A\xe7\xe3o"), "the code page bytes stay"); + assert!(legacy.windows(6).any(|w| w == b"AC1018")); + // A code page it doesn't know is read as Windows-1252, as acadrust reads an older DXF. + let at = dxf.windows(9).position(|w| w == b"ANSI_1252").unwrap(); + let unknown = [&dxf[..at], b"NO_SUCH_CP".as_slice(), &dxf[at + 9..]].concat(); + let text = String::from_utf8(native::declare_version(&unknown, acadrust::DxfVersion::AC1032).unwrap()).unwrap(); + assert!(text.contains("\r\nAção\r\n"), "{text}"); + // Without a `$DWGCODEPAGE` there is nothing to decode it by: it is read as it is. + let none = [&dxf[..at - 21], &dxf[at + 11..]].concat(); + assert!(!none.windows(12).any(|w| w == b"$DWGCODEPAGE"), "{}", String::from_utf8_lossy(&none)); + assert_eq!(native::declare_version(&none, acadrust::DxfVersion::AC1032), None); + } + + /// An unknown kept version converts as [`dxf_to_dwg_as`] does. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn unknown_kept_version_converts_as_before() { + let dxf = r2000(b"x"); + assert_eq!(dxf_to_dwg_kept_as(&dxf, "AC1032", "AC9999"), dxf_to_dwg_as(&dxf, "AC1032")); + assert!(dxf_to_dwg_kept_as(&dxf, "AC0000", "AC1032").is_err(), "an unwritable version is still an error"); + } } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 8cad3f24f..c643d4b29 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -100,10 +100,17 @@ pub fn write_with(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Re } // The DWG bridge reads our R2000 DXF and writes the DWG at the version asked for. Without // one, at least 2004: R2000 DWG has no true colours, transparency, table styles or - // gradients, so a drawing from an R2000 DXF doesn't lose them by default. + // gradients, so a drawing from an R2000 DXF doesn't lose them by default. The objects + // CADCraft keeps without modelling them are still in the groups of the file they came + // from (`$ACADVER`), and the bridge reads them as that version. Some(Format::Dwg) if !opts.binary => { let version = opts.version.unwrap_or_else(|| version.max(Version::R2004)); - cadcraft_dwg::dxf_to_dwg_as(dxf_write::dwg_bridge(d, version).as_bytes(), version.code()).map_err(IoError::Format) + let bridge = dxf_write::dwg_bridge(d, version); + match d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str) { + Some(kept) => cadcraft_dwg::dxf_to_dwg_kept_as(bridge.as_bytes(), version.code(), kept), + None => cadcraft_dwg::dxf_to_dwg_as(bridge.as_bytes(), version.code()), + } + .map_err(IoError::Format) } _ if opts.binary => Err(IoError::Format(format!("binary output is for DXF files, not `{}`", ext(name)))), _ => write_framed(d, name, None), diff --git a/crates/io/tests/dwg_kept_object_versions.rs b/crates/io/tests/dwg_kept_object_versions.rs new file mode 100644 index 000000000..ad07c6952 --- /dev/null +++ b/crates/io/tests/dwg_kept_object_versions.rs @@ -0,0 +1,262 @@ +//! Objects CADCraft keeps without modelling them reach the DWG as the file they came from holds +//! them. The DWG bridge is an R2000 DXF, and acadrust reads some objects differently by version: +//! read as R2000, a 2013 or later file's mental ray render settings came out a class version too +//! high (the ODA File Converter then refuses the whole DWG: "Object improperly read: +//! AcDbMentalRayRenderSettings"), RapidRT render settings from a 2013 file a version too low, and +//! a field lost its flags and cached value. The bridge now reads the kept groups as the version +//! they were read from (`$ACADVER`). +//! +//! The drawing is synthetic: render settings and a field in the named object dictionary, with +//! values chosen to be told apart. The reference is acadrust's own conversion of the same DXF to +//! the same DWG version (an older DWG can't hold everything: a 2004 field has no value flags or +//! format), read back; CADCraft's DWG must hold the same objects. When the DWG is the DXF's own +//! version, that reference is also checked against the DXF as read. +#![cfg(not(target_arch = "wasm32"))] + +use std::fmt::Write as _; +use std::io::Cursor; + +use acadrust::objects::{ClassObjectData, Field, ObjectType}; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +/// A minimal DXF of `version` ("AC1032"): a model space MTEXT, and in the named object dictionary +/// mental ray and RapidRT render settings and a field with a non-ASCII cached value. +fn synthetic(version: &str) -> String { + let mut g: Vec<(i32, String)> = Vec::new(); + let mut put = |code: i32, value: &str| g.push((code, value.to_string())); + for (c, v) in [(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, version), (9, "$HANDSEED"), (5, "FFF"), (0, "ENDSEC")] { + put(c, v); + } + put(0, "SECTION"); + put(2, "CLASSES"); + for (name, cpp, app) in [ + ("MENTALRAYRENDERSETTINGS", "AcDbMentalRayRenderSettings", "SCENEOE"), + ("RAPIDRTRENDERSETTINGS", "AcDbRapidRTRenderSettings", "ObjectDBX Classes"), + ("FIELD", "AcDbField", "ObjectDBX Classes"), + ] { + for (c, v) in [(0, "CLASS"), (1, name), (2, cpp), (3, app), (90, "1024"), (91, "1"), (280, "0"), (281, "0")] { + put(c, v); + } + } + put(0, "ENDSEC"); + let mtext = [(0, "MTEXT"), (5, "200"), (100, "AcDbEntity"), (8, "0"), (100, "AcDbMText"), (10, "0"), (20, "0"), (30, "0")]; + for (c, v) in [(0, "SECTION"), (2, "ENTITIES")].into_iter().chain(mtext) { + put(c, v); + } + for (c, v) in [(40, "2.5"), (41, "0"), (71, "1"), (72, "5"), (1, "synthetic"), (0, "ENDSEC")] { + put(c, v); + } + for (c, v) in [(0, "SECTION"), (2, "OBJECTS"), (0, "DICTIONARY"), (5, "C"), (330, "0"), (100, "AcDbDictionary"), (281, "1")] { + put(c, v); + } + for (c, v) in [(3, "ACAD_RENDER_ACTIVE_SETTINGS"), (350, "300"), (3, "ACAD_RENDER_ACTIVE_RAPIDRT_SETTINGS"), (350, "301")] { + put(c, v); + } + put(3, "SYNTHETIC_FIELD"); + put(350, "302"); + // The common AcDbRenderSettings groups; 90 is the class version as a 2013+ DXF stores it. + let base = |name: &str| { + let base: Vec<(i32, String)> = [ + (100, "AcDbRenderSettings"), + (90, "2"), + (1, name), + (290, "1"), + (290, "0"), + (290, "1"), + (290, "0"), + (1, ""), + (1, "synthetic preset"), + (90, "7"), + ] + .into_iter() + .map(|(c, v)| (c, v.to_string())) + .collect(); + base + }; + g.extend([(0, "MENTALRAYRENDERSETTINGS"), (5, "300"), (330, "C")].map(|(c, v)| (c, v.to_string()))); + g.extend(base("SyntheticMR")); + g.push((100, "AcDbMentalRayRenderSettings".into())); + let mental_ray = [ + (90, "2"), + (90, "-1"), + (90, "2"), + (70, "1"), + (40, "2.0"), + (40, "2.0"), + (40, "0.125"), + (40, "0.25"), + (40, "0.375"), + (40, "0.5"), + (70, "1"), + (290, "1"), + (290, "1"), + (90, "3"), + (90, "4"), + (90, "6"), + (290, "1"), + (90, "250"), + (290, "1"), + (40, "2.5"), + (90, "5000"), + (90, "3"), + (90, "4"), + (90, "6"), + (290, "1"), + (90, "100"), + (290, "1"), + (290, "0"), + (290, "1"), + (40, "1.5"), + (40, "0.5"), + (40, "1200.0"), + (70, "1"), + (70, "2"), + (40, "5.0"), + (70, "1"), + (70, "1"), + (290, "0"), + (1, "mr note"), + (90, "16"), + (70, "2"), + (90, "2048"), + (290, "1"), + (40, "1.25"), + ]; + g.extend(mental_ray.map(|(c, v)| (c, v.to_string()))); + g.extend([(0, "RAPIDRTRENDERSETTINGS"), (5, "301"), (330, "C")].map(|(c, v)| (c, v.to_string()))); + g.extend(base("SyntheticRT")); + g.push((100, "AcDbRapidRTRenderSettings".into())); + let rapid_rt = [(90, "3"), (70, "1"), (90, "4"), (90, "5"), (70, "1"), (70, "2"), (40, "2.5"), (40, "1.5"), (290, "1")]; + g.extend(rapid_rt.map(|(c, v)| (c, v.to_string()))); + let field = [ + (0, "FIELD"), + (5, "302"), + (330, "C"), + (100, "AcDbField"), + (1, "AcVar"), + (2, "\\AcVar Filename \\f \"%fn2\""), + (90, "0"), + (97, "0"), + (91, "63"), + (92, "0"), + (94, "59"), + (95, "2"), + (96, "0"), + (300, ""), + (93, "1"), + (6, "Variable"), + (93, "0"), + (90, "4"), + (1, "Filename"), + (94, "0"), + (300, ""), + (302, ""), + (304, "ACVALUE_END"), + (7, "ACFD_FIELD_VALUE"), + (93, "4"), + (90, "4"), + (1, "C:\\synthetic\\Ação-01.dwg"), + (94, "0"), + (300, "%fn2"), + (302, "Ação-01"), + (304, "ACVALUE_END"), + (301, "Ação-01"), + (98, "7"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + g.extend(field.map(|(c, v)| (c, v.to_string()))); + g.iter().fold(String::new(), |mut s, (c, v)| { + let _ = write!(s, "{c:>3}\r\n{v}\r\n"); + s + }) +} + +/// The render settings and the field a document holds (the drawing has one of each). +struct Kept { + mental_ray: Option, + rapid_rt: Option, + field: Option, +} + +fn kept(doc: &acadrust::CadDocument) -> Kept { + let mut k = Kept { mental_ray: None, rapid_rt: None, field: None }; + for o in doc.objects.values() { + match o { + ObjectType::ClassObject(c) if matches!(c.data, ClassObjectData::MentalRayRenderSettings(_)) => k.mental_ray = Some(c.data.clone()), + ObjectType::ClassObject(c) if matches!(c.data, ClassObjectData::RapidRtRenderSettings(_)) => k.rapid_rt = Some(c.data.clone()), + ObjectType::Field(f) => k.field = Some(f.clone()), + _ => {} + } + } + k +} + +/// acadrust's version for a CADCraft one. +fn acad(v: Version) -> acadrust::DxfVersion { + acadrust::DxfVersion::from_version_string(v.code()) +} + +/// The DXF of `version` saved as a `target` DWG holds the render settings and the field that +/// acadrust's own DXF → DWG conversion keeps. +fn kept_objects_survive(version: &str, target: Version) { + let dxf = synthetic(version); + let mut source = acadrust::DxfReader::from_reader(Cursor::new(dxf.clone().into_bytes())).unwrap().read().unwrap(); + let as_read = kept(&source); + assert!(as_read.mental_ray.is_some() && as_read.rapid_rt.is_some() && as_read.field.is_some(), "the synthetic DXF reads"); + source.version = acad(target); + let direct = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + let reference = kept(&acadrust::DwgReader::from_stream(Cursor::new(direct)).read().unwrap()); + if target.code() == version { + assert_eq!(reference.mental_ray, as_read.mental_ray, "the reference DWG keeps the mental ray settings"); + assert_eq!(reference.rapid_rt, as_read.rapid_rt, "the reference DWG keeps the RapidRT settings"); + assert_eq!(reference.field.as_ref().map(|f| &f.value), as_read.field.as_ref().map(|f| &f.value), "the reference DWG keeps the field"); + } + + let d = read(dxf.as_bytes(), "kept.dxf").unwrap(); + let dwg = write_with(&d, "kept.dwg", &SaveOptions { version: Some(target), binary: false }).unwrap(); + let written = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().unwrap(); + let written = kept(&written); + + // Every difference is listed, so a failure names all the objects that came out wrong. + let mut wrong = Vec::new(); + if written.mental_ray != reference.mental_ray { + wrong.push(format!("mental ray render settings: {:?}\n expected {:?}", written.mental_ray, reference.mental_ray)); + } + if written.rapid_rt != reference.rapid_rt { + wrong.push(format!("RapidRT render settings: {:?}\n expected {:?}", written.rapid_rt, reference.rapid_rt)); + } + let field = |f: &Option| { + f.as_ref().map(|f| (f.evaluator_id.clone(), f.code.clone(), f.value.clone(), f.value_string.clone(), f.child_values.clone())) + }; + if field(&written.field) != field(&reference.field) { + wrong.push(format!("field: {:?}\n expected {:?}", field(&written.field), field(&reference.field))); + } + assert!(wrong.is_empty(), "{version} → {target:?}:\n{}", wrong.join("\n")); +} + +#[test] +fn a_2018_files_kept_objects_reach_a_2018_dwg() { + kept_objects_survive("AC1032", Version::R2018); +} + +/// RapidRT render settings are the case whose class version acadrust adjusts only in 2013 files. +#[test] +fn a_2013_files_kept_objects_reach_a_2013_dwg() { + kept_objects_survive("AC1027", Version::R2013); +} + +#[test] +fn a_2018_files_kept_objects_reach_a_2004_dwg() { + kept_objects_survive("AC1032", Version::R2004); +} + +/// A drawing from an R2000 DXF (no newer groups to read differently) saves as before. +#[test] +fn an_r2000_files_drawing_still_saves_as_dwg() { + let dxf = " 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nLINE\r\n 8\r\n0\r\n 10\r\n0\r\n 20\r\n0\r\n 30\r\n0\r\n 11\r\n10\r\n 21\r\n5\r\n 31\r\n0\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + let d = read(dxf.as_bytes(), "line.dxf").unwrap(); + let dwg = write_with(&d, "line.dwg", &SaveOptions::default()).unwrap(); + let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().unwrap(); + assert_eq!(doc.entities().count(), 1); +} From bf137e2c44d13b2c86927d0ae1b8778760422b47 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:46:31 -0300 Subject: [PATCH 102/531] fix(dwg): give proxies their own class in the DWG A DXF proxy object or entity names its class by number: 500 plus the class's place in the DXF's CLASSES (DXF Reference, ACAD_PROXY_OBJECT, group 91). acadrust's DXF reader puts its default classes first and numbers the DXF's after them, and its DWG writer keeps the proxy's DXF number, so in the DWG the number named another class. A 2018 drawing with an MEP plugin's piping proxies wrote them as LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA File Converter refused the whole file ("AcDbProxyObject can't be cast to AcDbBlockTableRecord"). The DWG bridge now reads the DXF's class names in CLASSES order and gives each proxy the number acadrust writes for its class. Before 2013 (AC1027) acadrust writes only the classes it knows such a DWG needs, and a proxy's is not one of them, so the proxy would name a missing class ("No ClassId") or, by its old number, another one; such a DWG now leaves the proxies out, and the save report lists the proxy entities as not kept only for those versions (from 2013 the DWG keeps them). Tests: #1812's proxy drawing saved as 2018, 2013, 2010 and 2004 DWG keeps its proxies' classes from 2013 and leaves them out before (fails before this change: the classes came out as MESH and SCALE); unit test for the CLASSES order; the not-saved report counts proxy entities only before 2013. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dwg/src/lib.rs | 109 ++++++++++++++++++ crates/engine/src/cmd/file.rs | 7 +- crates/engine/tests/save_reports_not_saved.rs | 16 +++ crates/io/src/tests.rs | 44 +++++++ 4 files changed, 175 insertions(+), 1 deletion(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 03d756226..39732d1c8 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -589,6 +589,103 @@ mod native { } } + /// The DXF names of an ASCII DXF's CLASS records, in CLASSES order: a proxy's class number + /// (group 91) is 500 plus its class's place here (DXF Reference, ACAD_PROXY_OBJECT). Empty for + /// a binary DXF or one without a CLASSES section. + pub(super) fn dxf_class_names(dxf: &[u8]) -> Vec { + let mut names = Vec::new(); + if dxf.starts_with(b"AutoCAD Binary DXF") { + return names; + } + let mut lines = dxf.split(|b| *b == b'\n').map(|l| l.trim_ascii()); + let (mut in_classes, mut in_class) = (false, false); + while let (Some(code), Some(value)) = (lines.next(), lines.next()) { + match (code, value) { + (b"0", b"ENDSEC") if in_classes => break, + (b"2", b"CLASSES") => in_classes = true, + (b"0", v) if in_classes => in_class = v == b"CLASS", + (b"1", v) if in_class => { + names.push(String::from_utf8_lossy(v).into_owned()); + in_class = false; + } + _ => {} + } + } + names + } + + /// Proxy objects' and entities' class numbers as the DWG numbers its classes. A DXF proxy + /// names its class by its place in the DXF's CLASSES (`classes`, from 500), but acadrust's + /// reader puts its own default classes first and numbers the DXF's after them, so the DXF + /// number named another class in the DWG: a 2018 drawing's piping proxies became + /// LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA File Converter refused the file. A + /// number that names no class of the DXF is left as it is. + /// + /// Before 2013 (AC1027) acadrust writes only the classes it knows a pre-2013 DWG needs, and a + /// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses + /// the file: "No ClassId") or, by its old number, some other class. Such a DWG leaves the + /// proxies out instead, as it does other programs' data it can't write (`not_saved` reports + /// the entities). Returns how many proxies were left out. + fn proxy_classes(doc: &mut acadrust::CadDocument, classes: &[String]) -> usize { + if doc.version < acadrust::DxfVersion::AC1027 { + let entities: Vec = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { + Some(x.common.handle) + } + _ => None, + }) + .collect(); + let objects: Vec = + doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); + for h in &entities { + doc.remove_entity(*h); + } + for h in &objects { + doc.objects.remove(h); + } + return entities.len() + objects.len(); + } + let number = |id: i32| -> Option { + let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; + doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) + }; + let objects: Vec<(acadrust::Handle, i32)> = doc + .objects + .iter() + .filter_map(|(h, o)| match o { + acadrust::objects::ObjectType::ProxyObject(p) => number(p.class_id).map(|n| (*h, n)), + _ => None, + }) + .collect(); + let entities: Vec<(acadrust::Handle, i32)> = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) => match &x.data { + acadrust::entities::ExtendedEntityData::Proxy(p) => number(p.class_id).map(|n| (x.common.handle, n)), + _ => None, + }, + _ => None, + }) + .collect(); + for (h, n) in objects { + if let Some(acadrust::objects::ObjectType::ProxyObject(p)) = doc.objects.get_mut(&h) { + p.class_id = n; + } + } + let entities: std::collections::HashMap = entities.into_iter().collect(); + for e in doc.entities_mut() { + if let acadrust::entities::EntityType::Extended(x) = e { + let Some(n) = entities.get(&x.common.handle).copied() else { continue }; + if let acadrust::entities::ExtendedEntityData::Proxy(p) = &mut x.data { + p.class_id = n; + } + } + } + 0 + } + /// `kept`: the version the DXF's carried-over groups were read from ([`dxf_to_dwg_kept_as`]). fn convert(dxf: &[u8], version: Option, kept: Option) -> Result, String> { // Reject a pathologically large DXF before handing it to the third-party decoder, which @@ -614,6 +711,7 @@ mod native { Some(d) => d, None => dxf.to_vec(), }; + let classes = dxf_class_names(&data); let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; @@ -625,6 +723,7 @@ mod native { None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, None => {} } + proxy_classes(&mut doc, &classes); other_layout_owners(&mut doc); table_style_rows(&mut doc, true); dimension_flags(&mut doc); @@ -1071,4 +1170,14 @@ mod tests { assert_eq!(dxf_to_dwg_kept_as(&dxf, "AC1032", "AC9999"), dxf_to_dwg_as(&dxf, "AC1032")); assert!(dxf_to_dwg_kept_as(&dxf, "AC0000", "AC1032").is_err(), "an unwritable version is still an error"); } + + /// The CLASS names in CLASSES order; nothing for a binary DXF or one without CLASSES. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn dxf_class_names_in_classes_order() { + let dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nWIDGETA\r\n 2\r\nAcDbWidgetA\r\n 3\r\nApp\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 2\r\nAcDbWidgetB\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\nNOT_A_CLASS\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::dxf_class_names(dxf), ["WIDGETA", "WIDGETB"]); + assert!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n").is_empty()); + assert!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0").is_empty()); + } } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 3a5296e88..c5973acf4 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -538,7 +538,9 @@ pub fn not_saved(d: &Drawing) -> std::collections::BTreeMap { const MODELER_TYPES: [&str; 3] = ["3DSOLID", "REGION", "BODY"]; /// [`not_saved`] for a file saved as `version`. From 2013 on, a 3D solid, region or body the data -/// store has a record for keeps its geometry and is not counted. +/// store has a record for keeps its geometry and is not counted, and neither is another program's +/// proxy entity: the DWG writes it with its class (before 2013 it has no class to name, and the +/// DWG leaves it out). pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap { let mut out: std::collections::BTreeMap = std::collections::BTreeMap::new(); let stored = if version >= Version::R2013 { d.foreign.data_store_entities() } else { Default::default() }; @@ -548,6 +550,9 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&e.handle) { continue; } + if version >= Version::R2013 && u.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") { + continue; + } let n = out.entry(u.dxf_type.clone()).or_insert(0); *n = n.saturating_add(1); } diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 615028a21..6753151fd 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -82,3 +82,19 @@ fn solids_whose_geometry_the_data_store_keeps_are_not_reported_from_2013() { // Before 2013 a file has no data store: every solid loses its geometry. assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2), ("REGION".to_string(), 1)].into_iter().collect()); } + +/// Another program's proxy entity reaches a 2013 or later DWG with its class; before 2013 the DWG +/// leaves it out and says so. +#[test] +fn proxy_entities_are_reported_only_before_2013() { + use cadcraft_engine::cmd::file::{Version, not_saved_as}; + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), unknown("ACAD_PROXY_ENTITY")).unwrap(); + d.add(&Space::Model, Common::default(), unknown("MLINE")).unwrap(); + for v in [Version::R2013, Version::R2018] { + assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1)].into_iter().collect(), "{v:?}"); + } + for v in [Version::R2004, Version::R2010] { + assert_eq!(not_saved_as(&d, v), [("ACAD_PROXY_ENTITY".to_string(), 1), ("MLINE".to_string(), 1)].into_iter().collect(), "{v:?}"); + } +} diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 977a7c184..ec29cc0fa 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2814,6 +2814,50 @@ fn proxies_keep_their_class_when_classes_are_rewritten() { assert_eq!(names, ["VISUALSTYLE", "WIDGETX"]); } +/// The proxies of [`proxy_file`] keep their classes in a DWG too. A proxy names its class by +/// number, 500 plus the class's place in the CLASSES the file lists; acadrust numbers the classes +/// it writes in its own order (its default classes first), so the DXF's numbers named other +/// classes there: a 2018 drawing's piping proxies came out as LARGE_RADIAL_DIMENSION and +/// SECTIONOBJECT, and the ODA File Converter refused the file ("AcDbProxyObject can't be cast to +/// AcDbBlockTableRecord"). A DWG before 2013 leaves them out (acadrust writes no class for them). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn proxies_keep_their_class_in_dwg() { + use acadrust::entities::{EntityType, ExtendedEntityData}; + use acadrust::objects::ObjectType; + let d = read(&proxy_file(), "p.dxf").unwrap(); + for version in [Version::R2018, Version::R2013, Version::R2010, Version::R2004] { + let dwg = write_with(&d, "p.dwg", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let class_of = |id: i32| doc.classes.iter().find(|c| i32::from(c.class_number) == id).map(|c| c.dxf_name.clone()); + let mut objects: Vec> = doc + .objects + .values() + .filter_map(|o| match o { + ObjectType::ProxyObject(p) => Some(class_of(p.class_id)), + _ => None, + }) + .collect(); + objects.sort(); + // Before 2013 acadrust writes no class for a proxy, so the DWG leaves the proxies out. + let legacy = version < Version::R2013; + let expected = if legacy { vec![] } else { vec![Some("VISUALSTYLE".to_string()), Some("WIDGETX".to_string())] }; + assert_eq!(objects, expected, "{version:?}: proxy objects"); + let entities: Vec> = doc + .entities() + .filter_map(|e| match e { + EntityType::Extended(x) => match &x.data { + ExtendedEntityData::Proxy(p) => Some(class_of(p.class_id)), + _ => None, + }, + _ => None, + }) + .collect(); + let expected = if legacy { vec![] } else { vec![Some("WIDGETX".to_string())] }; + assert_eq!(entities, expected, "{version:?}: proxy entity"); + } +} + /// A name that isn't valid Unicode still picks its format by extension. #[cfg(unix)] #[test] From a06bb18b587f9e9aee373bd6fb0b15bfd60a47c0 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 10:57:53 +1100 Subject: [PATCH 103/531] Test: a layout's far named UCS keeps its name only where it is (#1547) --- crates/io/tests/ucs_roundtrip.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index a79e5db94..e297a6fe2 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -413,3 +413,26 @@ fn a_stale_ucs_name_copy_is_not_brought_back() { } assert_eq!(cadcraft_io::read_dxf(same.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE"); } + +/// A layout's UCS far from the World origin keeps its name (and group 345) on an exact save, and +/// loses both when the layout moves by 0.5 at 1e12, in the writer and in the reader. +#[test] +fn a_far_layout_ucs_keeps_its_name_only_where_it_is() { + let far = Ucs { name: "FAR".into(), origin: Vec3::new(1e12, 0.0, 0.0), x_axis: Vec3::new(1.0, 0.0, 0.0), y_axis: Vec3::new(0.0, 1.0, 0.0) }; + let mut d = Drawing::default(); + d.ucss.push(far.clone()); + d.layouts[0].ucs = Some(far.clone()); + let name = d.layouts[0].name.clone(); + let text = cadcraft_io::write_dxf(&d); + assert!(group(&layout_record(&text, &name), "345").is_some(), "exact save: pointed at FAR"); + assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().layouts[0].ucs.as_ref().unwrap().name, "FAR"); + // Writer: the layout moved 0.5 since it was named FAR. + d.layouts[0].ucs = Some(Ucs { origin: Vec3::new(1e12 + 0.5, 0.0, 0.0), ..far.clone() }); + let moved = cadcraft_io::write_dxf(&d); + assert!(group(&layout_record(&moved, &name), "345").is_none(), "moved 0.5 at 1e12: not FAR"); + assert!(cadcraft_io::read_dxf(moved.as_bytes()).unwrap().layouts[0].ucs.as_ref().unwrap().name.is_empty()); + // Reader: a file whose layout origin (group 13) moved but whose 345 still names FAR. + let stale = replace_group(&text, ("1", &name), "13", "1000000000000.5"); + let u = cadcraft_io::read_dxf(stale.as_bytes()).unwrap().layouts[0].ucs.clone().unwrap(); + assert!(u.name.is_empty(), "{u:?}"); +} From adc18768095b88dda9c22da9bfb1a129d602beec Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 13:15:13 +1100 Subject: [PATCH 104/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d0bd6f967..5d605ea55 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,21 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-29 by `cargo xtask parity`. Do not edit by hand. -> **Generated:** 2026-10-28 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 444 registered commands. +**Menu breadth: 305 / 491 items (62%)** · 451 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 37 | 49% | +| View | 75 | 38 | 51% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -66,7 +65,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -81,15 +79,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -127,7 +120,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From 7ce2eea0c08b27b4cb3ac067b17f5707d6fca978 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 13:20:04 +1100 Subject: [PATCH 105/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d0bd6f967..5d605ea55 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,21 +1,20 @@ # Parity checklist -> **Generated:** 2026-10-29 by `cargo xtask parity`. Do not edit by hand. -> **Generated:** 2026-10-28 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 444 registered commands. +**Menu breadth: 305 / 491 items (62%)** · 451 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 37 | 49% | +| View | 75 | 38 | 51% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -66,7 +65,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -81,15 +79,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -127,7 +120,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From 7f590216eb5bca3adb6ef4f1500bc89c71445f74 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 13:34:46 +1100 Subject: [PATCH 106/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d0bd6f967..53ffffc96 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,7 +1,6 @@ # Parity checklist -> **Generated:** 2026-10-29 by `cargo xtask parity`. Do not edit by hand. -> **Generated:** 2026-10-28 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. From 7983a25e38cd7fe1154578423ded84b62c849201 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 13:39:44 +1100 Subject: [PATCH 107/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index d0bd6f967..53ffffc96 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,7 +1,6 @@ # Parity checklist -> **Generated:** 2026-10-29 by `cargo xtask parity`. Do not edit by hand. -> **Generated:** 2026-10-28 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. From d80c05583992d1aadd8b65991d72d708ea4fbe8d Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 14:51:05 +1100 Subject: [PATCH 108/531] xtask: take main's stats.rs (the merge kept a test import Linux clippy rejects) --- xtask/src/stats.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/xtask/src/stats.rs b/xtask/src/stats.rs index 965e3380d..6136de15a 100644 --- a/xtask/src/stats.rs +++ b/xtask/src/stats.rs @@ -146,7 +146,6 @@ mod tests { #[cfg(unix)] #[test] fn walk_does_not_follow_directory_symlinks() { - use super::walk; use std::os::unix::fs::symlink; let base = std::env::temp_dir().join(format!("cadcraft-xtask-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); From abd72f3f19450b6fcf49402ba95f5843eacd3c9a Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 14:51:08 +1100 Subject: [PATCH 109/531] xtask: take main's stats.rs (the merge kept a test import Linux clippy rejects) --- xtask/src/stats.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/xtask/src/stats.rs b/xtask/src/stats.rs index 965e3380d..6136de15a 100644 --- a/xtask/src/stats.rs +++ b/xtask/src/stats.rs @@ -146,7 +146,6 @@ mod tests { #[cfg(unix)] #[test] fn walk_does_not_follow_directory_symlinks() { - use super::walk; use std::os::unix::fs::symlink; let base = std::env::temp_dir().join(format!("cadcraft-xtask-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); From 28428b0cc381ed7c59b94d52e9c866a4da8e6695 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 15:27:25 +1100 Subject: [PATCH 110/531] attdef: a non-string justify or style is an error; the definition takes the style's width factor and oblique (#1720) justify and style given as a number, boolean or array were read as absent, so the definition came out left-aligned in the current style. They are now refused. The definition also kept width factor 1 and oblique 0 whatever the chosen text style said, and the renderer uses the entity's values; it now copies both from the style. Tests: a_non_string_justify_or_style_is_refused, the_definition_takes_the_styles_width_factor_and_oblique. --- crates/engine/src/cmd/blocks.rs | 49 +++++++++++++++++---- crates/engine/tests/attdef_justify_style.rs | 33 ++++++++++++++ 2 files changed, 74 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 41d3fdc7b..880ab9aeb 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -316,11 +316,44 @@ fn current_text_style(s: &Session) -> String { s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()) } +/// A text style's name as the table spells it, with the width factor and oblique angle an +/// attribute definition takes from it (the renderer uses the entity's own values). `None` when +/// the drawing has no such style. +fn style_values(s: &Session, name: &str) -> Result> { + Ok(s.doc()?.text_style(name).map(|t| (t.name.clone(), t.width_factor, t.oblique))) +} + +/// The current text style (TEXTSTYLE) with its width factor and oblique angle. +fn current_style_values(s: &Session) -> (String, f64, f64) { + let name = current_text_style(s); + style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0)) +} + +/// An optional string parameter: absent or null is `None`, a string is `Some`, anything else is +/// an error rather than being ignored. +fn opt_str_param<'a>(cmd: &str, p: &'a Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(v)) => Ok(Some(v)), + Some(v) => Err(bad(cmd, format!("`{key}` must be a string, got {v}"))), + } +} + /// An attribute definition at `at` with justification `j` (as TEXT: any but Left keeps `at` as /// its alignment point) in text style `style`. #[allow(clippy::too_many_arguments)] -fn attdef_kind(tag: &str, prompt: &str, default: &str, at: Vec2, height: f64, invisible: bool, j: (HAlign, VAlign), style: String) -> EntityKind { +fn attdef_kind( + tag: &str, + prompt: &str, + default: &str, + at: Vec2, + height: f64, + invisible: bool, + j: (HAlign, VAlign), + style: (String, f64, f64), +) -> EntityKind { let (halign, valign) = j; + let (style, width_factor, oblique) = style; let left = halign == HAlign::Left && valign == VAlign::Baseline; EntityKind::AttDef(Attrib { tag: tag.to_ascii_uppercase(), @@ -330,8 +363,8 @@ fn attdef_kind(tag: &str, prompt: &str, default: &str, at: Vec2, height: f64, in height, value: default.into(), rotation: 0.0, - width_factor: 1.0, - oblique: 0.0, + width_factor, + oblique, style, halign, valign, @@ -353,14 +386,14 @@ fn run_attdef(s: &mut Session, p: &Value) -> Result { let at = point_req("attdef", p, "at")?; let h = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2)); // Justification and text style as TEXT and MTEXT take them (#1658). - let j = super::draw::justify(str_param(p, "justify").unwrap_or("L")).ok_or_else(|| bad("attdef", "unknown justification"))?; + let j = super::draw::justify(opt_str_param("attdef", p, "justify")?.unwrap_or("L")).ok_or_else(|| bad("attdef", "unknown justification"))?; // Align and Fit run between two baseline points; `attdef` has one, so it can't express them. if matches!(j.0, HAlign::Aligned | HAlign::Fit) { return Err(bad("attdef", "Align and Fit need two points, which attdef doesn't take yet; use L, C, R, M or TL … BR")); } - let style = match str_param(p, "style") { - Some(n) => s.doc()?.text_style(n).map(|t| t.name.clone()).ok_or_else(|| bad("attdef", format!("no text style \"{n}\"")))?, - None => current_text_style(s), + let style = match opt_str_param("attdef", p, "style")? { + Some(n) => style_values(s, n)?.ok_or_else(|| bad("attdef", format!("no text style \"{n}\"")))?, + None => current_style_values(s), }; let (prompt, default) = (str_param(p, "prompt").unwrap_or(tag), str_param(p, "default").unwrap_or("")); let k = attdef_kind(tag, prompt, default, at, h, bool_or(p, "invisible", false), j, style); @@ -901,7 +934,7 @@ impl Interactive for AttdefM { (Some(tag), Some(pr), Some(def)) => { if let Input::Point(p) = i { let h = s.doc()?.header.f64("TEXTSIZE", 0.2); - let k = attdef_kind(tag, pr, def, p, h, false, (HAlign::Left, VAlign::Baseline), current_text_style(s)); + let k = attdef_kind(tag, pr, def, p, h, false, (HAlign::Left, VAlign::Baseline), current_style_values(s)); s.add_entity(k)?; return Ok(Step::Done); } diff --git a/crates/engine/tests/attdef_justify_style.rs b/crates/engine/tests/attdef_justify_style.rs index 0f2d6a3ec..07f7c5e40 100644 --- a/crates/engine/tests/attdef_justify_style.rs +++ b/crates/engine/tests/attdef_justify_style.rs @@ -102,3 +102,36 @@ fn a_block_and_a_saved_file_keep_them() { let att = read.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { i.attribs.first().cloned() } else { None }).unwrap(); assert_eq!((att.text.halign, att.text.valign, att.text.style.as_str()), (HAlign::Center, VAlign::Middle, "ROMANS"), "reopened attribute"); } + +/// A `justify` or `style` that is present but not a string is an error, not a silent default (#1720). +#[test] +fn a_non_string_justify_or_style_is_refused() { + let mut s = session(); + let n = s.doc().unwrap().model.len(); + for (key, bad) in [("justify", json!(1)), ("justify", json!(true)), ("style", json!(2)), ("style", json!(["ROMANS"]))] { + let mut p = json!({"tag": "T", "at": [0, 0]}); + p[key] = bad.clone(); + let err = s.execute("attdef", &p).unwrap_err().to_string(); + assert!(err.contains(key) && err.contains("string"), "{key} = {bad}: {err}"); + } + // Null means absent. + assert!(s.execute("attdef", &json!({"tag": "T", "at": [0, 0], "justify": null, "style": null})).is_ok()); + assert_eq!(s.doc().unwrap().model.len(), n + 1, "only the null one was added"); +} + +/// The definition takes its text style's width factor and oblique angle (#1720). +#[test] +fn the_definition_takes_the_styles_width_factor_and_oblique() { + let mut s = session(); + s.execute("style", &json!({"name": "SLANT", "font": "romans.shx", "widthFactor": 0.7, "oblique": 15, "current": false})).unwrap(); + let a = add(&mut s, json!({"tag": "T", "at": [0, 0], "style": "SLANT"})); + assert!((a.text.width_factor - 0.7).abs() < 1e-12, "width factor {}", a.text.width_factor); + assert!((a.text.oblique - 15f64.to_radians()).abs() < 1e-12, "oblique {}", a.text.oblique); + // The current style, when none is named. + s.execute("style.current", &json!({"name": "SLANT"})).unwrap(); + let a = add(&mut s, json!({"tag": "T", "at": [0, 0]})); + assert!((a.text.width_factor - 0.7).abs() < 1e-12 && (a.text.oblique - 15f64.to_radians()).abs() < 1e-12); + // A plain style keeps 1 and 0. + let a = add(&mut s, json!({"tag": "T", "at": [0, 0], "style": "Standard"})); + assert_eq!((a.text.width_factor, a.text.oblique), (1.0, 0.0)); +} From e65132c77ac293602eac3f314caf4cdf43f6d4f1 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 19:43:43 +1100 Subject: [PATCH 111/531] -ATTDEF: the start-point prompt takes [Justify/Style] (#1720) Typing J or S at the typed -ATTDEF start-point prompt did nothing. The prompt is now 'Specify start point of text or [Justify/Style]' and both options are handled: Justify shares TEXT's option prompt and the JSON form's code check (Align and Fit refused, unknown codes refused), Style takes an existing style name with its width factor and oblique angle and refuses an unknown one the way the JSON form does, each asking again. Tests: the five typed_* and start_point_prompt tests in attdef_justify_style.rs. --- crates/engine/src/cmd/blocks.rs | 80 +++++++++++++++++---- crates/engine/src/cmd/draw.rs | 2 +- crates/engine/src/cmd/draw/text.rs | 9 ++- crates/engine/tests/attdef_justify_style.rs | 79 ++++++++++++++++++++ 4 files changed, 154 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 880ab9aeb..0a88845d9 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -329,6 +329,22 @@ fn current_style_values(s: &Session) -> (String, f64, f64) { style_values(s, &name).ok().flatten().unwrap_or((name, 1.0, 0.0)) } +/// A justification code as `-ATTDEF` takes it, typed or in `justify`. Align and Fit run between +/// two baseline points; `attdef` has one, so it can't express them. +fn attdef_justify(code: &str) -> Result<(HAlign, VAlign)> { + let j = super::draw::justify(code.trim()).ok_or_else(|| bad("attdef", "unknown justification"))?; + if matches!(j.0, HAlign::Aligned | HAlign::Fit) { + return Err(bad("attdef", "Align and Fit need two points, which attdef doesn't take yet; use L, C, R, M or TL … BR")); + } + Ok(j) +} + +/// The named text style with its width factor and oblique angle, or the error both the JSON form +/// and the typed `Style` option give for a style the drawing doesn't have. +fn resolve_style(s: &Session, name: &str) -> Result<(String, f64, f64)> { + style_values(s, name)?.ok_or_else(|| bad("attdef", format!("no text style \"{name}\""))) +} + /// An optional string parameter: absent or null is `None`, a string is `Some`, anything else is /// an error rather than being ignored. fn opt_str_param<'a>(cmd: &str, p: &'a Value, key: &str) -> Result> { @@ -386,13 +402,9 @@ fn run_attdef(s: &mut Session, p: &Value) -> Result { let at = point_req("attdef", p, "at")?; let h = f64_or(p, "height", s.doc()?.header.f64("TEXTSIZE", 0.2)); // Justification and text style as TEXT and MTEXT take them (#1658). - let j = super::draw::justify(opt_str_param("attdef", p, "justify")?.unwrap_or("L")).ok_or_else(|| bad("attdef", "unknown justification"))?; - // Align and Fit run between two baseline points; `attdef` has one, so it can't express them. - if matches!(j.0, HAlign::Aligned | HAlign::Fit) { - return Err(bad("attdef", "Align and Fit need two points, which attdef doesn't take yet; use L, C, R, M or TL … BR")); - } + let j = attdef_justify(opt_str_param("attdef", p, "justify")?.unwrap_or("L"))?; let style = match opt_str_param("attdef", p, "style")? { - Some(n) => style_values(s, n)?.ok_or_else(|| bad("attdef", format!("no text style \"{n}\"")))?, + Some(n) => resolve_style(s, n)?, None => current_style_values(s), }; let (prompt, default) = (str_param(p, "prompt").unwrap_or(tag), str_param(p, "default").unwrap_or("")); @@ -898,26 +910,64 @@ impl Interactive for InsertM { } } -#[derive(Default)] +/// What the start-point prompt of `-ATTDEF` is asking for after a `Justify` or `Style` option. +#[derive(Clone, Copy, PartialEq)] +enum AttdefAsk { + Justify, + Style, +} + struct AttdefM { tag: Option, prompt: Option, default: Option, + justify: (HAlign, VAlign), + /// The text style chosen with the `Style` option; the current one when `None`. + style: Option<(String, f64, f64)>, + asking: Option, +} + +impl Default for AttdefM { + fn default() -> Self { + Self { tag: None, prompt: None, default: None, justify: (HAlign::Left, VAlign::Baseline), style: None, asking: None } + } } impl Interactive for AttdefM { fn name(&self) -> &'static str { "ATTDEF" } - fn prompt(&self, _s: &Session) -> Prompt { + fn prompt(&self, s: &Session) -> Prompt { + match self.asking { + Some(AttdefAsk::Justify) => return super::draw::justify_prompt(), + Some(AttdefAsk::Style) => return Prompt::new("Enter style name", Accept::TEXT).default(current_text_style(s)), + None => {} + } match (&self.tag, &self.prompt, &self.default) { (None, ..) => Prompt::new("Enter attribute tag name", Accept::TEXT), (Some(_), None, _) => Prompt::new("Enter attribute prompt", Accept::TEXT), (Some(_), Some(_), None) => Prompt::new("Enter default attribute value", Accept::TEXT), - _ => Prompt::new("Specify start point of text", Accept::POINT), + _ => Prompt::new("Specify start point of text", Accept::POINT).kw(&["Justify", "Style"]), } } fn input(&mut self, s: &mut Session, i: Input) -> Result { + // The answer to a Justify or Style option; a bad answer is an error and asks again. + if let Some(ask) = self.asking { + let word = match &i { + Input::Keyword(k) | Input::Text(k) => k.clone(), + Input::Enter => String::new(), + _ => return Ok(Step::Continue), + }; + match ask { + AttdefAsk::Justify => self.justify = attdef_justify(&word)?, + AttdefAsk::Style => { + let name = if word.trim().is_empty() { current_text_style(s) } else { word }; + self.style = Some(resolve_style(s, &name)?); + } + } + self.asking = None; + return Ok(Step::Continue); + } let text = match &i { Input::Text(t) => Some(t.clone()), Input::Enter => Some(String::new()), @@ -931,14 +981,18 @@ impl Interactive for AttdefM { } (Some(_), None, _) => self.prompt = text, (Some(_), Some(_), None) => self.default = text, - (Some(tag), Some(pr), Some(def)) => { - if let Input::Point(p) = i { + (Some(tag), Some(pr), Some(def)) => match i { + Input::Keyword(k) if k == "Justify" => self.asking = Some(AttdefAsk::Justify), + Input::Keyword(k) if k == "Style" => self.asking = Some(AttdefAsk::Style), + Input::Point(p) => { let h = s.doc()?.header.f64("TEXTSIZE", 0.2); - let k = attdef_kind(tag, pr, def, p, h, false, (HAlign::Left, VAlign::Baseline), current_style_values(s)); + let style = self.style.clone().unwrap_or_else(|| current_style_values(s)); + let k = attdef_kind(tag, pr, def, p, h, false, self.justify, style); s.add_entity(k)?; return Ok(Step::Done); } - } + _ => {} + }, } Ok(Step::Continue) } diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index 463098679..a30f906ea 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -31,8 +31,8 @@ use line_pline::{LineM, PlineM, run_line, run_pline}; use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray}; use polygon::{PolygonM, run_polygon}; use spline::{SplineM, run_spline}; -pub(crate) use text::justify; use text::{MTextM, TextM, run_mtext, run_text}; +pub(crate) use text::{justify, justify_prompt}; /// Every draw command's spec: JSON parameters, menu path, aliases and the interactive prompt /// machine each command starts. diff --git a/crates/engine/src/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 21962c469..2c190c84e 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -25,6 +25,12 @@ pub(crate) fn justify(j: &str) -> Option<(HAlign, VAlign)> { }) } +/// The prompt for a justification option (TEXT's `Justify`, `-ATTDEF`'s `Justify`). +pub(crate) fn justify_prompt() -> Prompt { + Prompt::new("Enter an option", Accept::TEXT) + .kw(&["Left", "Center", "Right", "Align", "Middle", "Fit", "TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"]) +} + pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind { let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()); let (h, v) = j; @@ -119,8 +125,7 @@ impl Interactive for TextM { fn prompt(&self, s: &Session) -> Prompt { let th = s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2); if self.asking_justify { - return Prompt::new("Enter an option", Accept::TEXT) - .kw(&["Left", "Center", "Right", "Align", "Middle", "Fit", "TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"]); + return justify_prompt(); } match (self.at, self.height, self.rotation) { (None, _, _) => Prompt::new("Specify start point of text", Accept::POINT).kw(&["Justify", "Style"]), diff --git a/crates/engine/tests/attdef_justify_style.rs b/crates/engine/tests/attdef_justify_style.rs index 07f7c5e40..7ce7aefb3 100644 --- a/crates/engine/tests/attdef_justify_style.rs +++ b/crates/engine/tests/attdef_justify_style.rs @@ -135,3 +135,82 @@ fn the_definition_takes_the_styles_width_factor_and_oblique() { let a = add(&mut s, json!({"tag": "T", "at": [0, 0], "style": "Standard"})); assert_eq!((a.text.width_factor, a.text.oblique), (1.0, 0.0)); } + +/// `-ATTDEF` typed at the command line: tag, prompt and default, then the start-point prompt. +fn typed_to_start_point(s: &mut Session) { + s.cmdline("-attdef").unwrap(); + for line in ["TAG", "Prompt", "Default"] { + s.cmdline(line).unwrap(); + } +} + +fn last_attdef(s: &Session) -> Attrib { + let e = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::AttDef(_))).last().unwrap(); + attdef(s, e.handle) +} + +#[test] +fn the_start_point_prompt_offers_justify_and_style() { + let mut s = session(); + typed_to_start_point(&mut s); + assert!(s.prompt_text().contains("Specify start point of text or [Justify/Style]"), "{}", s.prompt_text()); +} + +#[test] +fn typed_justify_then_a_point_justifies_the_definition() { + let mut s = session(); + typed_to_start_point(&mut s); + s.cmdline("J").unwrap(); + assert!(s.prompt_text().contains("Enter an option"), "{}", s.prompt_text()); + s.cmdline("MC").unwrap(); + assert!(s.prompt_text().contains("Specify start point of text"), "{}", s.prompt_text()); + s.cmdline("10,10").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let a = last_attdef(&s); + assert_eq!((a.text.halign, a.text.valign), (HAlign::Center, VAlign::Middle)); + assert_eq!(a.text.align_pt, Some(Vec3::new(10.0, 10.0, 0.0)), "stored as the JSON form does"); +} + +#[test] +fn typed_justify_refuses_align_fit_and_unknown_codes_and_asks_again() { + let mut s = session(); + typed_to_start_point(&mut s); + s.cmdline("J").unwrap(); + for bad in ["A", "Fit", "XX"] { + s.cmdline(bad).unwrap(); + assert!(s.log.iter().any(|l| l.contains("justification") || l.contains("Align and Fit")), "{bad}: {:?}", s.log); + s.log.clear(); + assert!(s.prompt_text().contains("Enter an option"), "{bad}: {}", s.prompt_text()); + } + s.cmdline("TR").unwrap(); + s.cmdline("0,0").unwrap(); + let a = last_attdef(&s); + assert_eq!((a.text.halign, a.text.valign), (HAlign::Right, VAlign::Top)); +} + +#[test] +fn typed_style_then_a_point_takes_the_styles_values() { + let mut s = session(); + s.execute("style", &json!({"name": "SLANT", "font": "romans.shx", "widthFactor": 0.7, "oblique": 15, "current": false})).unwrap(); + typed_to_start_point(&mut s); + s.cmdline("S").unwrap(); + assert!(s.prompt_text().contains("Enter style name"), "{}", s.prompt_text()); + s.cmdline("slant").unwrap(); + s.cmdline("0,0").unwrap(); + let a = last_attdef(&s); + assert_eq!(a.text.style, "SLANT"); + assert!((a.text.width_factor - 0.7).abs() < 1e-12 && (a.text.oblique - 15f64.to_radians()).abs() < 1e-12); +} + +#[test] +fn typed_style_that_does_not_exist_asks_again() { + let mut s = session(); + typed_to_start_point(&mut s); + s.cmdline("S").unwrap(); + s.cmdline("NOPE").unwrap(); + assert!(s.log.iter().any(|l| l.contains("no text style \"NOPE\"")), "{:?}", s.log); + assert!(s.prompt_text().contains("Enter style name"), "{}", s.prompt_text()); + s.cmdline("ROMANS").unwrap(); + s.cmdline("0,0").unwrap(); + assert_eq!(last_attdef(&s).text.style, "ROMANS"); +} From 1a322faa0bc3d9efdbf32908582bd2a2bd344ff7 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:08:20 -0300 Subject: [PATCH 112/531] fix(dwg): scan the bridge header in one pass; leave out proxies of a binary DXF header_value kept an offset for every line up to the first ENDSEC: an input without one cost about 24 bytes per line (0.8 GB for 32 MiB of short lines, some 25 GB at the 1 GiB input limit). It now reads (group code, value) pairs in one pass and stops at 0/ENDSEC, so memory no longer grows with the input (36 MB for the same 32 MiB, the input itself). dxf_class_names doesn't read a binary DXF's CLASSES, so its proxies kept their DXF numbers, which name other classes in the DWG. CADCraft's own bridge is always ASCII; for a binary DXF given to the conversion functions, the proxies are now left out, as a pre-2013 DWG leaves them, instead of naming the wrong classes. Both reported by CodeRabbit on #2471. --- crates/dwg/src/lib.rs | 109 +++++++++++++++++++++++++---------------- crates/io/src/tests.rs | 20 ++++++++ 2 files changed, 88 insertions(+), 41 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index ce4133569..cd260baa4 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -588,22 +588,28 @@ mod native { } /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value - /// line after the group code that follows the `9` group naming it. Only the HEADER section - /// (up to the first `ENDSEC`) is searched; lines may end in `\r\n`. + /// of the group that follows the `9` group naming it. The file is read as (group code, + /// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end + /// of the HEADER section: a large input without one costs time, not memory (a line index of + /// a 32 MiB file used 0.8 GB). Lines may end in `\r\n`. fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> { - let mut lines: Vec<(usize, &[u8])> = Vec::new(); let mut offset = 0usize; - for line in dxf.split(|b| *b == b'\n') { - let trimmed = line.trim_ascii(); - let lead = line.len() - line.trim_ascii_start().len(); - lines.push((offset.saturating_add(lead), trimmed)); + let mut lines = dxf.split(|b| *b == b'\n').map(|line| { + let at = offset.saturating_add(line.len() - line.trim_ascii_start().len()); offset = offset.saturating_add(line.len()).saturating_add(1); - if trimmed == b"ENDSEC" { - break; + (at, line.trim_ascii()) + }); + while let (Some((_, code)), Some((_, value))) = (lines.next(), lines.next()) { + if code == b"0" && value == b"ENDSEC" { + return None; + } + if code == b"9" && value == name { + let (_, code) = lines.next()?; + let (at, value) = lines.next()?; + return (code != b"0" && code != b"9").then_some((at, value)); } } - let at = lines.windows(2).position(|w| w[0].1 == b"9" && w[1].1 == name)?; - lines.get(at.checked_add(3)?).copied() + None } /// The current dimension and text styles' names from their handles: a DWG stores the @@ -642,11 +648,13 @@ mod native { /// The DXF names of an ASCII DXF's CLASS records, in CLASSES order: a proxy's class number /// (group 91) is 500 plus its class's place here (DXF Reference, ACAD_PROXY_OBJECT). Empty for - /// a binary DXF or one without a CLASSES section. - pub(super) fn dxf_class_names(dxf: &[u8]) -> Vec { + /// one without a CLASSES section. `None` for a binary DXF, whose classes this doesn't read: + /// CADCraft's own bridge DXF is always ASCII, and only a binary DXF given to the public + /// conversion functions comes here. + pub(super) fn dxf_class_names(dxf: &[u8]) -> Option> { let mut names = Vec::new(); if dxf.starts_with(b"AutoCAD Binary DXF") { - return names; + return None; } let mut lines = dxf.split(|b| *b == b'\n').map(|l| l.trim_ascii()); let (mut in_classes, mut in_class) = (false, false); @@ -662,7 +670,7 @@ mod native { _ => {} } } - names + Some(names) } /// Proxy objects' and entities' class numbers as the DWG numbers its classes. A DXF proxy @@ -676,28 +684,33 @@ mod native { /// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses /// the file: "No ClassId") or, by its old number, some other class. Such a DWG leaves the /// proxies out instead, as it does other programs' data it can't write (`not_saved` reports - /// the entities). Returns how many proxies were left out. - fn proxy_classes(doc: &mut acadrust::CadDocument, classes: &[String]) -> usize { - if doc.version < acadrust::DxfVersion::AC1027 { - let entities: Vec = doc - .entities() - .filter_map(|e| match e { - acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { - Some(x.common.handle) - } - _ => None, - }) - .collect(); - let objects: Vec = - doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); - for h in &entities { - doc.remove_entity(*h); + /// the entities). So does a DXF whose classes are unknown (`classes` is `None`, a binary + /// DXF): its proxies' numbers can't be mapped, and kept as they are they would name the + /// wrong classes and the ODA would refuse the file. Returns how many proxies were left out. + fn proxy_classes(doc: &mut acadrust::CadDocument, classes: Option<&[String]>) -> usize { + let classes = match classes { + Some(c) if doc.version >= acadrust::DxfVersion::AC1027 => c, + _ => { + let entities: Vec = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { + Some(x.common.handle) + } + _ => None, + }) + .collect(); + let objects: Vec = + doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); + for h in &entities { + doc.remove_entity(*h); + } + for h in &objects { + doc.objects.remove(h); + } + return entities.len() + objects.len(); } - for h in &objects { - doc.objects.remove(h); - } - return entities.len() + objects.len(); - } + }; let number = |id: i32| -> Option { let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) @@ -737,7 +750,6 @@ mod native { 0 } - /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG /// stores the handle of the layer, and the one read with the DXF needn't be the layer's in /// the document, so the drawing reopened with layer "0" current (#2252). @@ -789,7 +801,7 @@ mod native { // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. guarded(AssertUnwindSafe(|| { super::fail_in_test("convert"); - proxy_classes(&mut doc, &classes); + proxy_classes(&mut doc, classes.as_deref()); other_layout_owners(&mut doc); table_style_rows(&mut doc, true); dimension_flags(&mut doc); @@ -1286,6 +1298,21 @@ mod tests { } /// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER` + /// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER` + /// name whose value would come after it, or a file that never ends its HEADER, is no version + /// to replace, and `\r\n` lines keep the value's offset right. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn declare_version_reads_the_header_in_pairs_up_to_endsec() { + let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None); + let endless = vec![b'\n'; 1 << 20]; + assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None); + let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n"; + let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n"); + } + /// are read as they are. #[cfg(not(target_arch = "wasm32"))] #[test] @@ -1338,8 +1365,8 @@ mod tests { #[test] fn dxf_class_names_in_classes_order() { let dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nWIDGETA\r\n 2\r\nAcDbWidgetA\r\n 3\r\nApp\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 2\r\nAcDbWidgetB\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\nNOT_A_CLASS\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; - assert_eq!(native::dxf_class_names(dxf), ["WIDGETA", "WIDGETB"]); - assert!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n").is_empty()); - assert!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0").is_empty()); + assert_eq!(native::dxf_class_names(dxf).unwrap(), ["WIDGETA", "WIDGETB"]); + assert_eq!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n"), Some(Vec::new())); + assert_eq!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0"), None); } } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index ec29cc0fa..7ffd02398 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2858,6 +2858,26 @@ fn proxies_keep_their_class_in_dwg() { } } +/// A binary DXF given to the DWG conversion directly: its CLASSES aren't read, so the proxies' +/// numbers can't be mapped to the DWG's classes. Kept as they were, they named other classes +/// (the ODA refuses such a file), so the DWG leaves them out, as a pre-2013 DWG does, and the +/// rest of the drawing is written. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_binary_dxf_leaves_its_proxies_out_of_the_dwg() { + use acadrust::entities::{EntityType, ExtendedEntityData}; + use acadrust::objects::ObjectType; + let d = read(&proxy_file(), "p.dxf").unwrap(); + let binary = write_with(&d, "p.dxf", &SaveOptions { version: Some(Version::R2018), binary: true }).unwrap(); + assert!(binary.starts_with(b"AutoCAD Binary DXF")); + let dwg = cadcraft_dwg::dxf_to_dwg_as(&binary, "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let proxies = doc.objects.values().filter(|o| matches!(o, ObjectType::ProxyObject(_))).count() + + doc.entities().filter(|e| matches!(e, EntityType::Extended(x) if matches!(x.data, ExtendedEntityData::Proxy(_)))).count(); + assert_eq!(proxies, 0, "no proxy with an unmapped class number"); + assert!(doc.layers.get("0").is_some(), "the drawing itself is written"); +} + /// A name that isn't valid Unicode still picks its format by extension. #[cfg(unix)] #[test] From cef9ee4b10ee899d9561fe985a579b71899e2231 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:42:40 -0300 Subject: [PATCH 113/531] fix(dwg): read kept objects as the file's version on every save, not just the first The bridge took the version of the kept groups from $ACADVER, but SAVEAS writes the saved version there and the kept groups stay as they were read. After a 2018 drawing was saved as a 2004 DWG, the next save read its mental ray render settings as 2004 (class version 2, which the ODA File Converter rejects) and a 2004 field lost its cached value. Foreign now records the $ACADVER of the file the kept data was read from (Foreign::version), and the DWG save passes that. The new declare_version test also moves out of the doc comment it was pasted into. Both reported by austin62jake on #2471. --- crates/doc/src/foreign.rs | 4 +++ crates/dwg/src/lib.rs | 30 ++++++++++----------- crates/io/src/dxf_raw.rs | 1 + crates/io/src/lib.rs | 5 ++-- crates/io/tests/dwg_kept_object_versions.rs | 25 +++++++++++++++++ 5 files changed, 48 insertions(+), 17 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index e0ebb81a4..80ebbc3a3 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -75,6 +75,10 @@ pub struct Foreign { /// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD` /// names its entity with a 320 handle (see [`Foreign::data_store_entities`]). pub data_store: Vec, + /// The `$ACADVER` of the file all this was read from: its groups are in that version's form. + /// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a + /// later save must not take it for this one (#2471). + pub version: Option, } impl Foreign { diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index cd260baa4..3157ea68e 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -1298,21 +1298,6 @@ mod tests { } /// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER` - /// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER` - /// name whose value would come after it, or a file that never ends its HEADER, is no version - /// to replace, and `\r\n` lines keep the value's offset right. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn declare_version_reads_the_header_in_pairs_up_to_endsec() { - let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n"; - assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None); - let endless = vec![b'\n'; 1 << 20]; - assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None); - let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n"; - let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap(); - assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n"); - } - /// are read as they are. #[cfg(not(target_arch = "wasm32"))] #[test] @@ -1328,6 +1313,21 @@ mod tests { assert_eq!(native::declare_version(late, acadrust::DxfVersion::AC1032), None); } + /// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER` + /// name whose value would come after it, or a file that never ends its HEADER, is no version + /// to replace, and `\r\n` lines keep the value's offset right. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn declare_version_reads_the_header_in_pairs_up_to_endsec() { + let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None); + let endless = vec![b'\n'; 1 << 20]; + assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None); + let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n"; + let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n"); + } + /// Declared as 2007 or later, a DXF is UTF-8: code page text is decoded first. Declared as an /// older version, the code page bytes stay as they are. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9b755f80f..9f6718c08 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -452,6 +452,7 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.data_store = ds.tags.iter().take(MAX_DATA_STORE_GROUPS).map(raw).collect(); } if !f.is_empty() { + f.version = d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).map(str::to_string); d.foreign = Arc::new(f); } } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index c643d4b29..9796b49e3 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -102,11 +102,12 @@ pub fn write_with(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Re // one, at least 2004: R2000 DWG has no true colours, transparency, table styles or // gradients, so a drawing from an R2000 DXF doesn't lose them by default. The objects // CADCraft keeps without modelling them are still in the groups of the file they came - // from (`$ACADVER`), and the bridge reads them as that version. + // from (`Foreign::version`, not `$ACADVER`, which SAVEAS changes), and the bridge reads + // them as that version. Some(Format::Dwg) if !opts.binary => { let version = opts.version.unwrap_or_else(|| version.max(Version::R2004)); let bridge = dxf_write::dwg_bridge(d, version); - match d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str) { + match d.foreign.version.as_deref() { Some(kept) => cadcraft_dwg::dxf_to_dwg_kept_as(bridge.as_bytes(), version.code(), kept), None => cadcraft_dwg::dxf_to_dwg_as(bridge.as_bytes(), version.code()), } diff --git a/crates/io/tests/dwg_kept_object_versions.rs b/crates/io/tests/dwg_kept_object_versions.rs index ad07c6952..8d03c1d75 100644 --- a/crates/io/tests/dwg_kept_object_versions.rs +++ b/crates/io/tests/dwg_kept_object_versions.rs @@ -235,6 +235,31 @@ fn kept_objects_survive(version: &str, target: Version) { assert!(wrong.is_empty(), "{version} → {target:?}:\n{}", wrong.join("\n")); } +/// A drawing saved once as an older DWG has that version as its `$ACADVER` (SAVEAS sets it, so a +/// later QSAVE writes it again), but its kept objects are still in the 2018 file's groups. The +/// next save must still read them as 2018: read as the saved version, the mental ray settings +/// came out a class version too high (the ODA refuses the DWG) and a 2004 field lost its cached +/// value. +#[test] +fn kept_groups_keep_their_version_across_saves() { + let dxf = synthetic("AC1032"); + for (first, second) in [(Version::R2004, Version::R2004), (Version::R2010, Version::R2018), (Version::R2018, Version::R2018)] { + let mut source = acadrust::DxfReader::from_reader(Cursor::new(dxf.clone().into_bytes())).unwrap().read().unwrap(); + source.version = acad(second); + let reference = kept(&acadrust::DwgReader::from_stream(Cursor::new(acadrust::DwgWriter::write_to_vec(&source).unwrap())).read().unwrap()); + + let mut d = read(dxf.as_bytes(), "kept.dxf").unwrap(); + write_with(&d, "kept.dwg", &SaveOptions { version: Some(first), binary: false }).unwrap(); + // What SAVEAS does to the drawing after writing it. + d.header.set_str("ACADVER", first.code()); + let dwg = write_with(&d, "kept.dwg", &SaveOptions { version: Some(second), binary: false }).unwrap(); + let written = kept(&acadrust::DwgReader::from_stream(Cursor::new(dwg)).read().unwrap()); + let field = |k: &Kept| k.field.as_ref().map(|f| (f.value.clone(), f.value_string.clone())); + assert_eq!(written.mental_ray, reference.mental_ray, "{first:?} then {second:?}: mental ray render settings"); + assert_eq!(field(&written), field(&reference), "{first:?} then {second:?}: field"); + } +} + #[test] fn a_2018_files_kept_objects_reach_a_2018_dwg() { kept_objects_survive("AC1032", Version::R2018); From 6ae7c156b8736af33b0d41d08df61cc3ab579bc7 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:23:06 -0300 Subject: [PATCH 114/531] fix(io): take the kept groups' version from the file's own HEADER A new drawing starts with $ACADVER AC1032, and the reader applies the file's header over it, so a file without $ACADVER left AC1032 in Foreign::version and the bridge read its kept groups with 2018 rules. The version now comes from the file's HEADER section, and is None when the file has no $ACADVER (the bridge then reads the kept groups as R2000, as before). Reported by CodeRabbit on #2471. --- crates/io/src/dxf_raw.rs | 12 +++++++++++- crates/io/tests/dwg_kept_object_versions.rs | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9f6718c08..7857d3be3 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -452,11 +452,21 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.data_store = ds.tags.iter().take(MAX_DATA_STORE_GROUPS).map(raw).collect(); } if !f.is_empty() { - f.version = d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).map(str::to_string); + f.version = file_version(secs); d.foreign = Arc::new(f); } } +/// The `$ACADVER` the file's own HEADER section declares, if it does. Not the drawing's: a new +/// drawing starts as AC1032, and a file without the variable would leave that default there. +fn file_version(secs: &[Section]) -> Option { + let header = secs.iter().find(|s| s.name.eq_ignore_ascii_case("HEADER"))?; + let at = header.tags.iter().position(|t| t.code == 9 && t.str().trim().eq_ignore_ascii_case("$ACADVER"))?; + let value = header.tags.get(at + 1).filter(|t| t.code != 9)?.str(); + let value = value.trim(); + (!value.is_empty()).then(|| value.to_string()) +} + fn entity_types(drawing: &Drawing) -> HashMap { let mut types = HashMap::new(); for entity in all_entities(drawing) { diff --git a/crates/io/tests/dwg_kept_object_versions.rs b/crates/io/tests/dwg_kept_object_versions.rs index 8d03c1d75..787470705 100644 --- a/crates/io/tests/dwg_kept_object_versions.rs +++ b/crates/io/tests/dwg_kept_object_versions.rs @@ -260,6 +260,20 @@ fn kept_groups_keep_their_version_across_saves() { } } +/// A DXF without `$ACADVER` has no version for its kept groups: the drawing's own `$ACADVER` +/// is then the default a new drawing starts with (AC1032), which says nothing about the file, so +/// the kept groups are read as the bridge's R2000, as before. +#[test] +fn a_file_without_acadver_records_no_version() { + let dxf = synthetic("AC1032").replacen(" 9\r\n$ACADVER\r\n 1\r\nAC1032\r\n", "", 1); + assert!(!dxf.contains("$ACADVER")); + let d = read(dxf.as_bytes(), "kept.dxf").unwrap(); + assert!(!d.foreign.objects.is_empty(), "the render settings and the field are kept"); + assert_eq!(d.foreign.version, None); + let with = read(synthetic("AC1032").as_bytes(), "kept.dxf").unwrap(); + assert_eq!(with.foreign.version.as_deref(), Some("AC1032")); +} + #[test] fn a_2018_files_kept_objects_reach_a_2018_dwg() { kept_objects_survive("AC1032", Version::R2018); From 66f65b763e579502ca61cf8e913d8e2f263487ba Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 31 Oct 2026 04:38:42 +0400 Subject: [PATCH 115/531] docs: list bs beside ka in the supported interface languages Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- docs/control-protocol.md | 2 +- docs/localization.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 51b912b05..5e6ac3f87 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,7 +188,7 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `bs`, `el` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the optional craft-fonts input or the operating system; Georgian needs the `Geor` face from craft-fonts (an installed font does not count). Without a suitable font, the saved choice is diff --git a/docs/localization.md b/docs/localization.md index 8925e21be..3e8090993 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -22,7 +22,7 @@ Automation can select the language through the existing control channel: ``` The `ui.set` method also accepts `{"interfaceLanguage":"cs"}`. Supported values are `auto`, -`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el`, and `ka`; invalid values are rejected without changing the current +`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `bs`, `el`, and `ka`; invalid values are rejected without changing the current selection. Resetting palettes keeps the language choice. ## Translation coverage From 651615e5c2837760e7a2811e50dd1f59b922b7e7 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 31 Oct 2026 05:00:18 +0400 Subject: [PATCH 116/531] docs: Greek and Bosnian in the language lists; Georgian on the web comes with #1971 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- README.md | 2 +- docs/localization-parity.md | 2 +- docs/localization.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1752ac3a4..078c53511 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ numbers): | Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF | | Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit | | Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror | -| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | +| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | | Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) | ## Quick start diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 637a156f2..884cc3389 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -73,7 +73,7 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | -| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | +| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release builds (web builds too once #1971 adds it to the web faces); English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Bosnian | bs | 1,442 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes | Latin: yes (bundled egui fonts) | AI-assisted; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | diff --git a/docs/localization.md b/docs/localization.md index 3e8090993..a916c00e6 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,7 +1,7 @@ # Interface languages Choose **Edit → Interface Language** and select **Auto (system language)**, **English**, -**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), or **ქართული** (Georgian). +**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), **Bosanski** (Bosnian), or **ქართული** (Georgian). The interface updates without restarting, including the native macOS menus. The choice is saved with the other interface preferences (`cadcraft.prefs`, beside the theme): eframe storage on the desktop, browser local storage on the web. Installations without a saved From 5f6dbede5ca24082119edf164286b500519e7cea Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 31 Oct 2026 06:00:43 +0400 Subject: [PATCH 117/531] docs: Georgian row count after the block-editor prompt Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- docs/localization-parity.md | 4 ++-- docs/localization.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 884cc3389..25d66c7bc 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -73,7 +73,7 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | -| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release builds (web builds too once #1971 adds it to the web faces); English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | +| Georgian | ka | 1,384 catalog rows (1,378 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release builds (web builds too once #1971 adds it to the web faces); English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Bosnian | bs | 1,442 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes | Latin: yes (bundled egui fonts) | AI-assisted; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | @@ -92,7 +92,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| | 2026-10-30 | minor | Bosnian (`bs`, Latin, Ijekavian) added: 1,442 rows, one/few/other plurals, `bs-*` locales; AI-assisted, native proofreading pending | -| 2026-10-23 | minor | Georgian (`ka`) added: 1,383 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the embedded craft-fonts `Geor` face loaded when a build has it (the pin is #1971); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; terminology decided by a native speaker | +| 2026-10-23 | minor | Georgian (`ka`) added: 1,384 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the embedded craft-fonts `Geor` face loaded when a build has it (the pin is #1971); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; terminology decided by a native speaker | | 2026-10-22 | minor | Command line IME: enabled while a prompt collects text, composition shown but not saved, commit inserted once; single-line TEXT edits accept CJK input (#1761) | | 2026-10-19 | minor | Brazilian Portuguese: row brought up to date (it still read 0%); native-speaker terminology pass on 69 rows (Bind as Integrar, prompt keywords and SPDX kept in English, Thaw Layer, Snap type, Revolve fixed; snap, viewport, grip, offset, layer on/off and multiline wording made consistent with Brazilian usage) | | 2026-10-15 | minor | Greek (`el`) catalog: 1,330 rows, context/plural/locale/font tests; review pending | diff --git a/docs/localization.md b/docs/localization.md index a916c00e6..f84e7c035 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -120,7 +120,7 @@ follow-up work. ## Georgian (`ka`) interface -Georgian has **1,383 rows**: 1,377 ordinary labels, four contextual menu headings (**ზომების +Georgian has **1,384 rows**: 1,378 ordinary labels, four contextual menu headings (**ზომების დატანა** for the Dimension menu, **ზომა** for the object; **ხატვა** for Draw) and two single-form count templates, since a Georgian noun stays singular after a numeral ("5 კომიტი"). It covers the union of the existing catalogs, and no marked UI literal falls back to English. Commands are verbal From f0c1b4ff290d15d259b2a61c2eb8ddfdca641e6b Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:20:48 +1100 Subject: [PATCH 118/531] -ATTDEF: the Justify prompt leaves out Align and Fit, which it refuses; TEXT keeps them (#1720) -ATTDEF can't take Align or Fit (they need two points), but its Justify prompt listed them because it shared TEXT's prompt. justify_prompt now filters them out of the one shared option list for -ATTDEF; typed A or F is still refused. Test: attdef_justify_prompt_leaves_out_align_and_fit_but_text_keeps_them. --- crates/engine/src/cmd/blocks.rs | 2 +- crates/engine/src/cmd/draw/text.rs | 14 ++++++---- crates/engine/tests/attdef_justify_style.rs | 29 +++++++++++++++++++++ 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 0a88845d9..039753623 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -939,7 +939,7 @@ impl Interactive for AttdefM { } fn prompt(&self, s: &Session) -> Prompt { match self.asking { - Some(AttdefAsk::Justify) => return super::draw::justify_prompt(), + Some(AttdefAsk::Justify) => return super::draw::justify_prompt(false), Some(AttdefAsk::Style) => return Prompt::new("Enter style name", Accept::TEXT).default(current_text_style(s)), None => {} } diff --git a/crates/engine/src/cmd/draw/text.rs b/crates/engine/src/cmd/draw/text.rs index 2c190c84e..24007bc91 100644 --- a/crates/engine/src/cmd/draw/text.rs +++ b/crates/engine/src/cmd/draw/text.rs @@ -25,10 +25,14 @@ pub(crate) fn justify(j: &str) -> Option<(HAlign, VAlign)> { }) } -/// The prompt for a justification option (TEXT's `Justify`, `-ATTDEF`'s `Justify`). -pub(crate) fn justify_prompt() -> Prompt { - Prompt::new("Enter an option", Accept::TEXT) - .kw(&["Left", "Center", "Right", "Align", "Middle", "Fit", "TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"]) +/// The justification options TEXT offers, in prompt order. +const JUSTIFY_OPTIONS: [&str; 15] = ["Left", "Center", "Right", "Align", "Middle", "Fit", "TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"]; + +/// The prompt for a justification option. Align and Fit run between two baseline points, so a +/// command that takes one point (`-ATTDEF`) passes `two_points: false` and doesn't list them. +pub(crate) fn justify_prompt(two_points: bool) -> Prompt { + let options: Vec<&str> = JUSTIFY_OPTIONS.into_iter().filter(|o| two_points || !matches!(*o, "Align" | "Fit")).collect(); + Prompt::new("Enter an option", Accept::TEXT).kw(&options) } pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind { @@ -125,7 +129,7 @@ impl Interactive for TextM { fn prompt(&self, s: &Session) -> Prompt { let th = s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2); if self.asking_justify { - return justify_prompt(); + return justify_prompt(true); } match (self.at, self.height, self.rotation) { (None, _, _) => Prompt::new("Specify start point of text", Accept::POINT).kw(&["Justify", "Style"]), diff --git a/crates/engine/tests/attdef_justify_style.rs b/crates/engine/tests/attdef_justify_style.rs index 7ce7aefb3..e419a95ff 100644 --- a/crates/engine/tests/attdef_justify_style.rs +++ b/crates/engine/tests/attdef_justify_style.rs @@ -214,3 +214,32 @@ fn typed_style_that_does_not_exist_asks_again() { s.cmdline("0,0").unwrap(); assert_eq!(last_attdef(&s).text.style, "ROMANS"); } + +/// The keywords a command's Justify prompt offers, from `[A/B/...]` in its prompt text. +fn justify_options(s: &Session) -> Vec { + let p = s.prompt_text(); + let inner = p.split_once('[').and_then(|(_, r)| r.split_once(']')).map(|(i, _)| i).unwrap_or(""); + inner.split('/').map(str::to_string).collect() +} + +/// `-ATTDEF`'s Justify prompt doesn't list Align and Fit, which it would only refuse (they run +/// between two points), while TEXT's still offers every option (#1720). +#[test] +fn attdef_justify_prompt_leaves_out_align_and_fit_but_text_keeps_them() { + let mut s = session(); + typed_to_start_point(&mut s); + s.cmdline("J").unwrap(); + let opts = justify_options(&s); + assert!(opts.iter().any(|o| o == "Left") && opts.iter().any(|o| o == "MC"), "{opts:?}"); + assert!(!opts.iter().any(|o| o == "Align" || o == "Fit"), "{opts:?}"); + // A typed A or F is still refused. + s.cmdline("A").unwrap(); + assert!(s.log.iter().any(|l| l.contains("Align and Fit")), "{:?}", s.log); + s.cmdline("*Cancel*").ok(); + + let mut t = session(); + t.cmdline("text").unwrap(); + t.cmdline("J").unwrap(); + let opts = justify_options(&t); + assert!(opts.iter().any(|o| o == "Align") && opts.iter().any(|o| o == "Fit"), "{opts:?}"); +} From 38933e7f91808922d81fa5dace021129df25b1b3 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:20:50 +1100 Subject: [PATCH 119/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 53ffffc96..f842c51a9 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,10 +1,10 @@ # Parity checklist -> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-31 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 444 registered commands. +**Menu breadth: 298 / 491 items (61%)** · 446 registered commands. | Menu | Items | Covered | % | |---|---|---|---| From 4caf26ee60346262fedfe269b62e56f21754edd5 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:27:48 +1100 Subject: [PATCH 120/531] OLE2FRAME: draw its frame outline; a DWG save no longer lists it as left out (#2422) The frame is the rectangle from the entity's two corner points (groups 10/20 and 11/21). A DWG write and read-back keeps the OLE data (ole_frame.rs), so the DWG note leaves the type out of notSaved. --- crates/engine/src/cmd/file.rs | 8 ++++- crates/engine/tests/save_reports_not_saved.rs | 13 +++++++ crates/io/tests/it/main.rs | 1 + crates/io/tests/it/ole_frame.rs | 36 +++++++++++++++++++ crates/render/src/draw.rs | 14 ++++++++ crates/render/src/tests.rs | 14 ++++++++ 6 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 crates/io/tests/it/ole_frame.rs diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9aaff4631..bf59d51f1 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -720,6 +720,10 @@ pub fn not_saved(d: &Drawing) -> std::collections::BTreeMap { /// store section, which is written back with the drawing (`Foreign::data_store`). const MODELER_TYPES: [&str; 3] = ["3DSOLID", "REGION", "BODY"]; +/// Types the DWG bridge writes back whole although CADCraft does not model them: a DWG save and +/// read-back keeps their data (`ole_frame.rs`, #2422), so they are not "left out". +const DWG_KEPT_TYPES: [&str; 1] = ["OLE2FRAME"]; + /// [`not_saved`] for a file saved as `version`. From 2013 on, a 3D solid, region or body the data /// store has a record for keeps its geometry and is not counted. pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap { @@ -728,7 +732,9 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)); for e in stores.flat_map(|s| s.iter()) { if let cadcraft_doc::EntityKind::Unknown(u) = &e.kind { - if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&e.handle) { + if DWG_KEPT_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) + || (MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&e.handle)) + { continue; } let n = out.entry(u.dxf_type.clone()).or_insert(0); diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 615028a21..62a4cd41c 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -82,3 +82,16 @@ fn solids_whose_geometry_the_data_store_keeps_are_not_reported_from_2013() { // Before 2013 a file has no data store: every solid loses its geometry. assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2), ("REGION".to_string(), 1)].into_iter().collect()); } + +/// An OLE2FRAME is written back whole by a DWG save, so the DWG note doesn't list it; other +/// unmodelled types are still listed (#2422). +#[test] +fn a_dwg_save_does_not_list_an_ole_frame() { + use cadcraft_engine::cmd::file::{Version, not_saved_as}; + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), unknown("OLE2FRAME")).unwrap(); + d.add(&Space::Model, Common::default(), unknown("MLINE")).unwrap(); + for v in [Version::R2000, Version::R2018] { + assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1)].into_iter().collect(), "{v:?}"); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 7f6ad8f20..ea482d42a 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -44,6 +44,7 @@ mod mtext_columns_roundtrip; mod mtext_embedded_object; mod mtext_line_spacing; mod multiline_attributes; +mod ole_frame; mod paperview_marker; mod passthrough_image_roundtrip; mod pdf_followups; diff --git a/crates/io/tests/it/ole_frame.rs b/crates/io/tests/it/ole_frame.rs new file mode 100644 index 000000000..aa328a895 --- /dev/null +++ b/crates/io/tests/it/ole_frame.rs @@ -0,0 +1,36 @@ +//! An OLE2FRAME is kept as an unknown entity; a DWG save carries it with its data (#2422). + +use cadcraft_doc::EntityKind; +use cadcraft_io::{SaveOptions, Version, read, read_dxf, write_with}; + +/// A 2000 DXF with one OLE2FRAME: corners, the binary data and the end marker (DXF Reference). +fn dxf() -> String { + String::from( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n\ + 0\nOLE2FRAME\n5\n2B\n100\nAcDbEntity\n8\n0\n100\nAcDbOle2Frame\n70\n2\n3\nOLE Object\n\ + 10\n30.14\n20\n-18.99\n30\n0\n11\n35.27\n21\n-22.39\n31\n0\n71\n2\n72\n0\n90\n8\n310\n0102030405060708\n1\nOLE\n\ + 0\nENDSEC\n0\nEOF\n", + ) +} + +fn ole(d: &cadcraft_doc::Drawing) -> Option { + d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) if u.dxf_type == "OLE2FRAME" => Some(u.clone()), + _ => None, + }) +} + +#[test] +fn a_dwg_keeps_an_ole_frame_with_its_data() { + let d = read_dxf(dxf().as_bytes()).unwrap(); + assert!(ole(&d).is_some()); + for v in [Version::R2000, Version::R2010, Version::R2018] { + let dwg = write_with(&d, "x.dwg", &SaveOptions { version: Some(v), binary: false }).unwrap(); + let back = read(&dwg, "x.dwg").unwrap(); + let u = ole(&back).unwrap_or_else(|| panic!("{v:?}: the OLE2FRAME is gone")); + let data: String = u.tags.iter().filter(|t| t.code == 310).map(|t| t.value.to_ascii_uppercase()).collect(); + assert_eq!(data, "0102030405060708", "{v:?}: data"); + // Only the data is compared: with this stand-in blob the DWG round trip returns default + // corners (1,1)/(0,0), which a real object might not do; not verified without a real file. + } +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 7e00b4c8c..e51a1812c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -234,6 +234,12 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { b.polyline(ctx, rgb, lw, l); } } + // An OLE object's content is not drawn; its frame, from its two corner points, is. + EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => { + if let Some(q) = ole_frame(&u.tags) { + b.polyline(ctx, rgb, lw, &q); + } + } kind => { for prim in kind.prims() { match prim { @@ -379,3 +385,11 @@ fn leader_scale(d: &Drawing, st: Option<&cadcraft_doc::DimStyle>) -> f64 { let dimscale = d.header.f64("DIMSCALE", 1.0); st.map(|s| s.effective_scale(dimscale)).unwrap_or_else(|| cadcraft_doc::DimStyle::default().effective_scale(dimscale)) } + +/// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right +/// (groups 11, 21) corners (DXF Reference, OLE2FRAME); `None` when either is missing or not finite. +fn ole_frame(tags: &[cadcraft_doc::RawTag]) -> Option<[Vec2; 5]> { + let get = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()); + let (a, b) = (Vec2::new(get(10)?, get(20)?), Vec2::new(get(11)?, get(21)?)); + Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a]) +} diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ae35f27f9..475488d4a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1122,3 +1122,17 @@ fn raster_hatch_pattern_matches_one_by_one() { assert!(render(&l, &view, &o).unwrap().data() == render_one_by_one(&l, &view, &o).data()); } } + +/// An OLE2FRAME draws its frame, the rectangle from its two corner points (#2422), and nothing +/// when a corner is missing. +#[test] +fn ole_frame_draws_its_outline() { + let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() }; + let frame = |tags: Vec| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap(); + d.add(&Space::Model, Common::default(), frame(vec![tag(10, "1"), tag(20, "2")])).unwrap(); + let l = build(&d, &Space::Model, &Options { tolerance: 0.01, ..Default::default() }); + assert_eq!(l.prims.len(), 1, "only the frame with both corners is drawn"); + assert_eq!(l.prims[0].len, 5, "a closed rectangle: five points"); +} From ada99e613d7535e6ac41752b2a084d04ca13ca55 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:31:00 +1100 Subject: [PATCH 121/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 53ffffc96..f842c51a9 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,10 +1,10 @@ # Parity checklist -> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-31 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 444 registered commands. +**Menu breadth: 298 / 491 items (61%)** · 446 registered commands. | Menu | Items | Covered | % | |---|---|---|---| From 74ddfb377fb2f2b1c093b58d9589b820e32d66be Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:49:13 +1100 Subject: [PATCH 122/531] Test: a DWG keeps an OLE2FRAME's data and frame corners (#2422) The DWG object has no corner fields; the position travels in the start of the OLE data, which the bridge keeps. The test builds that header with known corners and checks them at 2000, 2010 and 2018. --- crates/io/tests/it/ole_frame.rs | 40 +++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/io/tests/it/ole_frame.rs b/crates/io/tests/it/ole_frame.rs index aa328a895..c8c8c73a0 100644 --- a/crates/io/tests/it/ole_frame.rs +++ b/crates/io/tests/it/ole_frame.rs @@ -1,15 +1,40 @@ -//! An OLE2FRAME is kept as an unknown entity; a DWG save carries it with its data (#2422). +//! An OLE2FRAME is kept as an unknown entity; a DWG save carries it with its data and frame +//! position (#2422). A DWG's OLE2FRAME object has no corner fields: the position travels in the +//! start of the OLE data (a 2-byte marker, then the frame's four corners as three little-endian +//! doubles each: upper left, upper right, lower right, lower left), which is how the DXF's +//! groups 10 and 11 come back. That layout is read from the acadrust dependency's decoder. use cadcraft_doc::EntityKind; use cadcraft_io::{SaveOptions, Version, read, read_dxf, write_with}; +const UL: (f64, f64) = (30.14, -18.99); +const LR: (f64, f64) = (35.27, -22.39); + +/// The OLE data: the envelope with the frame's corners. +fn blob() -> Vec { + let mut b = vec![1u8, 0]; + for (x, y) in [UL, (LR.0, UL.1), LR, (UL.0, LR.1)] { + for v in [x, y, 0.0] { + b.extend_from_slice(&v.to_le_bytes()); + } + } + b +} + /// A 2000 DXF with one OLE2FRAME: corners, the binary data and the end marker (DXF Reference). fn dxf() -> String { - String::from( + let data = blob(); + let hex: String = data.iter().map(|b| format!("{b:02X}")).collect(); + format!( "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n\ 0\nOLE2FRAME\n5\n2B\n100\nAcDbEntity\n8\n0\n100\nAcDbOle2Frame\n70\n2\n3\nOLE Object\n\ - 10\n30.14\n20\n-18.99\n30\n0\n11\n35.27\n21\n-22.39\n31\n0\n71\n2\n72\n0\n90\n8\n310\n0102030405060708\n1\nOLE\n\ + 10\n{}\n20\n{}\n30\n0\n11\n{}\n21\n{}\n31\n0\n71\n2\n72\n0\n90\n{}\n310\n{hex}\n1\nOLE\n\ 0\nENDSEC\n0\nEOF\n", + UL.0, + UL.1, + LR.0, + LR.1, + data.len() ) } @@ -21,16 +46,17 @@ fn ole(d: &cadcraft_doc::Drawing) -> Option { } #[test] -fn a_dwg_keeps_an_ole_frame_with_its_data() { +fn a_dwg_keeps_an_ole_frame_with_its_data_and_position() { let d = read_dxf(dxf().as_bytes()).unwrap(); assert!(ole(&d).is_some()); + let want: String = blob().iter().map(|b| format!("{b:02X}")).collect(); for v in [Version::R2000, Version::R2010, Version::R2018] { let dwg = write_with(&d, "x.dwg", &SaveOptions { version: Some(v), binary: false }).unwrap(); let back = read(&dwg, "x.dwg").unwrap(); let u = ole(&back).unwrap_or_else(|| panic!("{v:?}: the OLE2FRAME is gone")); let data: String = u.tags.iter().filter(|t| t.code == 310).map(|t| t.value.to_ascii_uppercase()).collect(); - assert_eq!(data, "0102030405060708", "{v:?}: data"); - // Only the data is compared: with this stand-in blob the DWG round trip returns default - // corners (1,1)/(0,0), which a real object might not do; not verified without a real file. + let corner = |code: i32| u.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()); + assert_eq!(data, want, "{v:?}: data"); + assert_eq!((corner(10), corner(20), corner(11), corner(21)), (Some(UL.0), Some(UL.1), Some(LR.0), Some(LR.1)), "{v:?}: frame corners"); } } From a8d05d689443cedd2b8212d762e4c744b8f36df2 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 15:14:32 +1100 Subject: [PATCH 123/531] CLI: an OLE2FRAME is not reported as undrawn by an image export (#2422) Found end to end: convert to PNG drew the frame outline but still said '1 entity not drawn (OLE2FRAME: 1)'. --- apps/cadcraft-cli/src/output.rs | 5 ++++- apps/cadcraft-cli/tests/it/undrawn_entities.rs | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index d783267dc..d7471e7b1 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -151,7 +151,10 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option, io pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option { let mut types: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); for e in d.model.iter() { - if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind { + // An OLE2FRAME's frame outline is drawn (the OLE content is not), so it isn't reported. + if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind + && !u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") + { let n = types.entry(u.dxf_type.as_str()).or_insert(0); *n = n.saturating_add(1); } diff --git a/apps/cadcraft-cli/tests/it/undrawn_entities.rs b/apps/cadcraft-cli/tests/it/undrawn_entities.rs index 7e7189379..bf626a7d5 100644 --- a/apps/cadcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/cadcraft-cli/tests/it/undrawn_entities.rs @@ -51,3 +51,17 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() { assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); let _ = std::fs::remove_dir_all(&dir); } + +/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it undrawn (#2422). +#[test] +fn an_ole_frame_is_not_reported_as_undrawn() { + let dir = std::env::temp_dir().join(format!("cc-cli-ole-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let input = dir.join("ole.dxf"); + let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n11\n5\n21\n-3\n31\n0\n0\nENDSEC\n0\nEOF\n"; + std::fs::write(&input, ole).unwrap(); + let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]); + assert!(out.status.success()); + assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); + let _ = std::fs::remove_dir_all(&dir); +} From c223550cb355fbe481cd959c35dc42edf58dd64e Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:44:17 +0100 Subject: [PATCH 124/531] feat(ui): Properties palette shows the type's properties for several objects of one type With more than one object selected the palette showed only General. When all selected objects are of one type (line, circle, arc, text, mtext, polyline, hatch, block reference, dimension) it now shows that type's properties, `*VARIES*` where they differ; an edit applies to every selected object. Positions stay read-only, since typing one would move all objects to the same place. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 296 +++++++++++++++++++++++++++++++-- 1 file changed, 284 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 7e01a15d4..63e18c8f9 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -705,6 +705,9 @@ fn properties_header(app: &mut CadApp, ui: &mut egui::Ui) { } } +/// What the palette shows for a property that differs between the selected objects. +const VARIES: &str = "*VARIES*"; + /// Properties palette: the selection's common properties, or the current defaults when nothing is selected; formats lengths per drawing units and dispatches setter commands. pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -874,11 +877,11 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let vals: Vec = sel.iter().filter_map(|h| d.entity(*h)).map(|e| f(e)).collect(); match vals.first() { Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), - _ => "*VARIES*".into(), + _ => VARIES.into(), } }; let selected_color = Some(e.common.color).filter(|c| sel.iter().filter_map(|h| d.entity(*h)).all(|e| e.common.color == *c)); - let color = selected_color.map_or_else(|| "*VARIES*".into(), Color::name); + let color = selected_color.map_or_else(|| VARIES.into(), Color::name); let effective_color = |e: &cadcraft_doc::Entity| { let layer = d.layer(&e.common.layer).map_or(Color::WHITE, |l| l.color); e.common.color.resolve(layer, Color::WHITE) @@ -993,18 +996,18 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); }); + let real = |v: f64| format!("{v:.4}"); + // Rotations show as the drawing measures directions (ANGBASE, ANGDIR). + let angles = app.session.angle_settings(); + let num = |ui: &mut egui::Ui, label: &str, key: &str, shown: String, set: &mut Option, bad: &mut Option, ids: &Vec| { + prop_row(ui, label, |ui| { + if let Some(f) = number(edit_field(ui, ui.scope_id().with((key, ids)), shown), bad) { + *set = Some(json!({ "handles": ids, key: f })); + } + }); + }; if sel.len() == 1 { group(ui, "Geometry"); - let real = |v: f64| format!("{v:.4}"); - // Rotations show as the drawing measures directions (ANGBASE, ANGDIR). - let angles = app.session.angle_settings(); - let num = |ui: &mut egui::Ui, label: &str, key: &str, shown: String, set: &mut Option, bad: &mut Option, ids: &Vec| { - prop_row(ui, label, |ui| { - if let Some(f) = number(edit_field(ui, ui.scope_id().with((key, ids)), shown), bad) { - *set = Some(json!({ "handles": ids, key: f })); - } - }); - }; match &e.kind { EntityKind::Line(l) => { prop_row(ui, "Start X", |ui| { @@ -1159,6 +1162,184 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } _ => {} } + } else if let Some(dims) = sel + .iter() + .map(|h| match d.entity(*h).map(|e| &e.kind) { + Some(EntityKind::Dimension(dm)) => Some(dm), + _ => None, + }) + .collect::>>() + { + // Several dimensions: every property of one dimension, `*VARIES*` where they differ; an + // edit applies to all of them. + group(ui, "Geometry"); + let shared = |f: &dyn Fn(&cadcraft_doc::Dimension, &cadcraft_doc::DimStyle) -> String| -> String { + let vals: Vec = dims + .iter() + .map(|dm| { + let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); + f(dm, &st) + }) + .collect(); + match vals.first() { + Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), + _ => VARIES.into(), + } + }; + let text = shared(&|dm, _| dm.text.clone()); + prop_row(ui, "Text override", |ui| { + if let Some(s) = edit_field(ui, ui.scope_id().with(("dimtxt", &ids)), text.clone()) { + set = Some(json!({ "handles": ids, "textOverride": s })); + } + }); + let style = shared(&|dm, _| dm.style.clone()); + prop_row(ui, "Dim style", |ui| { + if let Some(n) = pick_menu(ui, &style, d.dim_styles.iter().map(|st| st.name.clone())) { + set = Some(json!({ "handles": ids, "dimStyle": n })); + } + }); + let numbers = [ + ("Text height", "textHeight", shared(&|_, st| len(st.text_height))), + ("Arrow size", "arrowSize", shared(&|_, st| len(st.arrow_size))), + ("Dim scale overall", "dimScale", shared(&|_, st| real(st.scale))), + ]; + for (label, key, shown) in numbers { + prop_row(ui, label, |ui| { + if let Some(f) = number(edit_field(ui, ui.scope_id().with((key, &ids)), shown), &mut bad) { + set = Some(json!({ "handles": ids, key: f })); + } + }); + } + let precision = shared(&|_, st| st.decimals.to_string()); + prop_row(ui, "Precision", |ui| { + if let Some(n) = pick_menu(ui, &precision, (0..=8).map(|n: u8| n.to_string())).and_then(|n| n.parse::().ok()) { + set = Some(json!({ "handles": ids, "precision": n })); + } + }); + } else if sel.iter().filter_map(|h| d.entity(*h)).all(|x| std::mem::discriminant(&x.kind) == std::mem::discriminant(&e.kind)) { + // Several objects of one type: the properties of one object, `*VARIES*` where they differ. + // Edits apply to all of them; positions are shown but stay read-only, since typing one + // would move every object to the same place. + group(ui, "Geometry"); + let shared = |f: &dyn Fn(&EntityKind) -> Option| -> String { + let vals: Vec> = sel.iter().filter_map(|h| d.entity(*h)).map(|x| f(&x.kind)).collect(); + match vals.first() { + Some(Some(v0)) if vals.iter().all(|v| v.as_ref() == Some(v0)) => v0.clone(), + _ => VARIES.into(), + } + }; + let deg = |v: f64| real(angles.shown(v).to_degrees()); + match &e.kind { + EntityKind::Line(_) => { + let line = |k: &EntityKind| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None }; + for (label, value) in [ + ("Start X", shared(&|k| line(k).map(|l| len(l.a.x)))), + ("Start Y", shared(&|k| line(k).map(|l| len(l.a.y)))), + ("End X", shared(&|k| line(k).map(|l| len(l.b.x)))), + ("End Y", shared(&|k| line(k).map(|l| len(l.b.y)))), + ("Delta X", shared(&|k| line(k).map(|l| len(l.b.x - l.a.x)))), + ("Delta Y", shared(&|k| line(k).map(|l| len(l.b.y - l.a.y)))), + ] { + prop_row(ui, label, |ui| read_only(ui, &value)); + } + num(ui, "Length", "length", shared(&|k| line(k).map(|l| len((l.b.xy() - l.a.xy()).len()))), &mut set, &mut bad, &ids); + num(ui, "Angle", "angle", shared(&|k| line(k).map(|l| real((l.b.xy() - l.a.xy()).angle().to_degrees()))), &mut set, &mut bad, &ids); + } + EntityKind::Circle(_) => { + let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None }; + prop_row(ui, "Center X", |ui| read_only(ui, &shared(&|k| circle(k).map(|c| len(c.center.x))))); + prop_row(ui, "Center Y", |ui| read_only(ui, &shared(&|k| circle(k).map(|c| len(c.center.y))))); + num(ui, "Radius", "radius", shared(&|k| circle(k).map(|c| len(c.radius))), &mut set, &mut bad, &ids); + num(ui, "Diameter", "diameter", shared(&|k| circle(k).map(|c| len(c.radius * 2.0))), &mut set, &mut bad, &ids); + num( + ui, + "Circumference", + "circumference", + shared(&|k| circle(k).map(|c| len(c.radius * std::f64::consts::TAU))), + &mut set, + &mut bad, + &ids, + ); + num(ui, "Area", "area", shared(&|k| circle(k).map(|c| real(c.radius * c.radius * std::f64::consts::PI))), &mut set, &mut bad, &ids); + } + EntityKind::Arc(_) => { + let arc = |k: &EntityKind| if let EntityKind::Arc(a) = k { Some(a.clone()) } else { None }; + num(ui, "Radius", "radius", shared(&|k| arc(k).map(|a| len(a.radius))), &mut set, &mut bad, &ids); + num(ui, "Start angle", "startAngle", shared(&|k| arc(k).map(|a| real(a.start.to_degrees()))), &mut set, &mut bad, &ids); + num(ui, "End angle", "endAngle", shared(&|k| arc(k).map(|a| real(a.end.to_degrees()))), &mut set, &mut bad, &ids); + } + EntityKind::Text(_) => { + let text = |k: &EntityKind| if let EntityKind::Text(t) = k { Some(t.clone()) } else { None }; + let contents = shared(&|k| text(k).map(|t| t.value)); + prop_row(ui, "Contents", |ui| { + if let Some(s) = edit_field(ui, ui.scope_id().with(("txt", &ids)), contents.clone()) { + set = Some(json!({ "handles": ids, "text": s })); + } + }); + num(ui, "Height", "height", shared(&|k| text(k).map(|t| len(t.height))), &mut set, &mut bad, &ids); + num(ui, "Rotation", "rotation", shared(&|k| text(k).map(|t| deg(t.rotation))), &mut set, &mut bad, &ids); + num(ui, "Width factor", "widthFactor", shared(&|k| text(k).map(|t| real(t.width_factor))), &mut set, &mut bad, &ids); + } + EntityKind::MText(_) => { + let mtext = |k: &EntityKind| if let EntityKind::MText(t) = k { Some(t.clone()) } else { None }; + let contents = shared(&|k| mtext(k).map(|t| t.contents)); + prop_row(ui, "Contents", |ui| { + if let Some(s) = edit_field(ui, ui.scope_id().with(("mtxt", &ids)), contents.clone()) { + set = Some(json!({ "handles": ids, "text": s })); + } + }); + num(ui, "Text height", "height", shared(&|k| mtext(k).map(|t| len(t.height))), &mut set, &mut bad, &ids); + num(ui, "Defined width", "width", shared(&|k| mtext(k).map(|t| len(t.width))), &mut set, &mut bad, &ids); + } + EntityKind::LwPolyline(_) => { + let poly = |k: &EntityKind| { + if let EntityKind::LwPolyline(p) = k { + Some((p.const_width, p.closed, cadcraft_geom::Polyline { vertices: p.vertices.clone(), closed: p.closed })) + } else { + None + } + }; + num(ui, "Global width", "width", shared(&|k| poly(k).map(|(w, ..)| len(w))), &mut set, &mut bad, &ids); + prop_row(ui, "Length", |ui| read_only(ui, &shared(&|k| poly(k).map(|(.., g)| len(g.len()))))); + prop_row(ui, "Area", |ui| { + read_only(ui, &shared(&|k| poly(k).map(|(_, closed, g)| if closed { real(g.area().abs()) } else { String::new() }))) + }); + let closed = shared(&|k| poly(k).map(|(_, c, _)| crate::i18n::t(if c { "Yes" } else { "No" }).to_string())); + prop_row(ui, "Closed", |ui| { + if let Some(n) = pick_menu(ui, &closed, ["Yes", "No"].map(|s| crate::i18n::t(s).to_string())) { + set = Some(json!({ "handles": ids, "closed": n == crate::i18n::t("Yes") })); + } + }); + } + EntityKind::Hatch(_) => { + let hatch = |k: &EntityKind| if let EntityKind::Hatch(h) = k { Some(h.clone()) } else { None }; + let pattern = shared(&|k| hatch(k).map(|h| h.pattern)); + prop_row(ui, "Pattern", |ui| { + ui.menu_button(pattern.clone(), |ui| { + if let Some(name) = patterns::menu(ui, &pattern) { + set = Some(json!({ "handles": ids, "pattern": name })); + ui.close(); + } + }); + }); + num(ui, "Scale", "scale", shared(&|k| hatch(k).map(|h| real(h.scale))), &mut set, &mut bad, &ids); + num(ui, "Angle", "angle", shared(&|k| hatch(k).map(|h| real(h.angle.to_degrees()))), &mut set, &mut bad, &ids); + } + EntityKind::Insert(_) => { + let insert = |k: &EntityKind| if let EntityKind::Insert(i) = k { Some(i.clone()) } else { None }; + for (label, value) in [ + ("Name", shared(&|k| insert(k).map(|i| i.block))), + ("Position X", shared(&|k| insert(k).map(|i| len(i.insert.x)))), + ("Position Y", shared(&|k| insert(k).map(|i| len(i.insert.y)))), + ("Position Z", shared(&|k| insert(k).map(|i| len(i.insert.z)))), + ] { + prop_row(ui, label, |ui| read_only(ui, &value)); + } + num(ui, "Rotation", "rotation", shared(&|k| insert(k).map(|i| deg(i.rotation))), &mut set, &mut bad, &ids); + num(ui, "Scale", "scale", shared(&|k| insert(k).map(|i| real(i.scale.x))), &mut set, &mut bad, &ids); + } + _ => {} + } } if let Some(mut p) = set { // A rotation is typed as shown (from ANGBASE, in the ANGDIR sense); properties.set takes it @@ -1209,4 +1390,95 @@ mod tests { } assert!(painted_blue, "a ByLayer entity on a blue layer needs a blue Properties swatch"); } + + /// The texts of a painted shape, one string per text. + fn collect_text(shape: &Shape, out: &mut Vec) { + match shape { + Shape::Text(t) => out.push(t.galley.text().to_string()), + Shape::Vec(shapes) => shapes.iter().for_each(|s| collect_text(s, out)), + _ => {} + } + } + + /// Everything the Properties palette paints for the current selection, one string per text. + fn painted_texts(app: &mut CadApp, section: fn(&mut CadApp, &mut egui::Ui)) -> Vec { + let ctx = egui::Context::default(); + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 1200.0))), ..Default::default() }; + let mut texts = Vec::new(); + for _ in 0..2 { + app.logic(&ctx); + let mut output = ctx.run_ui(input.clone(), |ui| section(app, ui)); + texts.clear(); + output.shapes.iter().for_each(|s| collect_text(&s.shape, &mut texts)); + output.textures_delta.clear(); + } + texts + } + + /// Several dimensions selected: the Properties palette shows all of a dimension's properties, + /// `*VARIES*` for those that differ, and an edit applies to every dimension. + #[test] + fn several_dimensions_show_every_property_with_varies_for_different_ones() { + let mut app = CadApp::new(Session::default(), Services::default()); + let first = app.run("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap()["handle"].as_str().unwrap().to_string(); + let second = + app.run("dimlinear", json!({ "p1": [0, 0], "p2": [20, 0], "at": [5, 6], "text": "X" })).unwrap()["handle"].as_str().unwrap().to_string(); + app.run("select", json!({ "handles": [first, second] })).unwrap(); + + let texts = painted_texts(&mut app, properties_section); + for want in ["Text override", "Dim style", "Text height", "Arrow size", "Dim scale overall", "Precision"] { + assert!(texts.iter().any(|t| t.as_str() == crate::i18n::t(want)), "the palette shows `{want}`; painted: {texts:?}"); + } + assert!(texts.iter().any(|t| t == VARIES), "the differing text override shows {VARIES}; painted: {texts:?}"); + + app.run("properties.set", json!({ "handles": [first, second], "textHeight": 7 })).unwrap(); + let texts = painted_texts(&mut app, properties_section); + assert!(texts.iter().any(|t| t == "7.0000" || t == "7"), "the common text height is shown; painted: {texts:?}"); + } + + /// Two objects of each type, selected together: the palette shows the type's properties (not + /// just General), `*VARIES*` for the ones that differ, and an edit reaches both objects. + #[test] + fn several_objects_of_one_type_show_their_properties_with_varies() { + let cases: [(&str, [Value; 2], &[&str]); 6] = [ + ("line", [json!({ "points": [[0, 0], [10, 0]] }), json!({ "points": [[0, 5], [20, 5]] })], &["Start X", "Length", "Angle"]), + ("circle", [json!({ "center": [0, 0], "radius": 2 }), json!({ "center": [9, 9], "radius": 5 })], &["Center X", "Radius", "Area"]), + ( + "text", + [json!({ "at": [0, 0], "text": "A", "height": 2 }), json!({ "at": [0, 9], "text": "B", "height": 3 })], + &["Contents", "Height", "Rotation"], + ), + ( + "pline", + [json!({ "vertices": [[0, 0], [4, 0], [4, 4]] }), json!({ "vertices": [[0, 9], [8, 9], [8, 12]] })], + &["Global width", "Length", "Closed"], + ), + ( + "arc", + [json!({ "center": [0, 0], "radius": 3, "start": 0, "end": 90 }), json!({ "center": [9, 0], "radius": 6, "start": 10, "end": 80 })], + &["Radius", "Start angle", "End angle"], + ), + ( + "mtext", + [json!({ "at": [0, 0], "text": "A", "height": 2 }), json!({ "at": [0, 9], "text": "B", "height": 3 })], + &["Contents", "Text height", "Defined width"], + ), + ]; + for (command, params, labels) in cases { + let mut app = CadApp::new(Session::default(), Services::default()); + let handles: Vec = params + .iter() + .map(|p| { + let out = app.run(command, p.clone()).unwrap(); + out["handle"].as_str().map_or_else(|| out["handles"][0].as_str().unwrap().to_string(), str::to_string) + }) + .collect(); + app.run("select", json!({ "handles": handles })).unwrap(); + let texts = painted_texts(&mut app, properties_section); + for want in labels { + assert!(texts.iter().any(|t| t.as_str() == crate::i18n::t(want)), "{command}: the palette shows `{want}`; painted: {texts:?}"); + } + assert!(texts.iter().any(|t| t == VARIES), "{command}: differing values show {VARIES}; painted: {texts:?}"); + } + } } From 6ecabc34511a26e617014fcd8e8192b74ff4b920 Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Wed, 28 Oct 2026 19:50:08 +0100 Subject: [PATCH 125/531] fix(ui): several block references show the dynamic block's name; gaps.md status line The Name row of the several-objects Properties palette used the block's own name, which for a dynamic block is an anonymous `*U..` that differs from one reference to the next. It now resolves each reference's name as the single-object palette does. docs/gaps.md: status line updated for the revision entry. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 63e18c8f9..8ab4508b1 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1327,8 +1327,21 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } EntityKind::Insert(_) => { let insert = |k: &EntityKind| if let EntityKind::Insert(i) = k { Some(i.clone()) } else { None }; + // A dynamic block reference shows its dynamic block's name, as with one reference; + // its anonymous blocks (`*U12`) differ from one reference to the next. + let names: Vec = sel + .iter() + .filter_map(|h| match d.entity(*h).map(|x| &x.kind) { + Some(EntityKind::Insert(i)) => Some(custom_properties(ui, app, *h).map_or_else(|| i.block.clone(), |(n, _)| n)), + _ => None, + }) + .collect(); + let name = match names.first() { + Some(n0) if names.iter().all(|n| n == n0) => n0.clone(), + _ => VARIES.to_string(), + }; for (label, value) in [ - ("Name", shared(&|k| insert(k).map(|i| i.block))), + ("Name", name), ("Position X", shared(&|k| insert(k).map(|i| len(i.insert.x)))), ("Position Y", shared(&|k| insert(k).map(|i| len(i.insert.y)))), ("Position Z", shared(&|k| insert(k).map(|i| len(i.insert.z)))), From f8f0504b9a858a8d264c51d3ba233bfc092116ee Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:15:53 +0100 Subject: [PATCH 126/531] perf(ui): Properties palette keeps the selection's shared values per revision and selection Working out every shared value on each frame made the palette slow with thousands of objects selected. The values (and the selected handles' hex ids) are kept in ui.data until the drawing revision, the selection or the units change. Entity helpers no longer clone whole hatches, texts or polylines for one field. Tests: a value typed in the palette reaches every selected object; the shown values follow revision and selection. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 426 ++++++++++++++++++++++----------- 1 file changed, 286 insertions(+), 140 deletions(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 8ab4508b1..e050a3e2b 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -708,6 +708,60 @@ fn properties_header(app: &mut CadApp, ui: &mut egui::Ui) { /// What the palette shows for a property that differs between the selected objects. const VARIES: &str = "*VARIES*"; +/// What the palette works out from the selection, for one drawing revision and one selection. +#[derive(Default)] +struct SelectionValues { + key: u64, + ids: std::sync::Arc>, + values: std::collections::HashMap<&'static str, Box>, +} + +/// The shared handle to a [`SelectionValues`], kept in `ui.data` between frames. +#[derive(Clone, Default)] +struct SelectionMemo(std::sync::Arc>); + +impl SelectionMemo { + /// The value kept under `key`, worked out by `f` the first time. + fn get(&self, key: &'static str, f: impl FnOnce() -> T) -> T { + let mut m = self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(v) = m.values.get(key).and_then(|v| v.downcast_ref::()) { + return v.clone(); + } + let v = f(); + m.values.insert(key, Box::new(v.clone())); + v + } + + /// The selected handles as hex strings, as `properties.set` takes them. + fn ids(&self) -> std::sync::Arc> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).ids.clone() + } +} + +/// The memo for the current drawing revision and selection; `extra` holds whatever else the shown +/// values depend on (units, angle settings). +fn selection_memo(ui: &egui::Ui, app: &CadApp, sel: &[cadcraft_engine::doc::Handle], extra: impl std::hash::Hash) -> SelectionMemo { + use std::hash::{Hash, Hasher}; + let fresh = || { + let ids = sel.iter().map(|h| h.hex()).collect(); + SelectionMemo(std::sync::Arc::new(std::sync::Mutex::new(SelectionValues { ids: std::sync::Arc::new(ids), ..Default::default() }))) + }; + let Ok(st) = app.session.state() else { return fresh() }; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (st.uid, st.revision, extra, sel).hash(&mut hasher); + let key = hasher.finish(); + let id = egui::Id::unique("properties-selection-memo"); + if let Some(memo) = ui.data(|d| d.get_temp::(id)) + && memo.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).key == key + { + return memo; + } + let memo = fresh(); + memo.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).key = key; + ui.data_mut(|d| d.insert_temp(id, memo.clone())); + memo +} + /// Properties palette: the selection's common properties, or the current defaults when nothing is selected; formats lengths per drawing units and dispatches setter commands. pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -873,33 +927,40 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { // Selected objects: common + geometry for a single object. let first = sel.first().and_then(|h| d.entity(*h)).map(|e| (**e).clone()); let Some(e) = first else { return }; - let same = |f: &dyn Fn(&cadcraft_doc::Entity) -> String| -> String { - let vals: Vec = sel.iter().filter_map(|h| d.entity(*h)).map(|e| f(e)).collect(); - match vals.first() { - Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), - _ => VARIES.into(), - } + // What the palette works out from the selection is kept while the drawing and the selection + // stay as they are: with thousands of objects selected, redoing it every frame is slow. + let memo = + selection_memo(ui, app, &sel, (lu, lp, app.session.angle_settings().shown(0.0).to_bits(), app.session.angle_settings().shown(1.0).to_bits())); + let same = |key: &'static str, f: &dyn Fn(&cadcraft_doc::Entity) -> String| -> String { + memo.get(key, || { + let vals: Vec = sel.iter().filter_map(|h| d.entity(*h)).map(|e| f(e)).collect(); + match vals.first() { + Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), + _ => VARIES.into(), + } + }) }; - let selected_color = Some(e.common.color).filter(|c| sel.iter().filter_map(|h| d.entity(*h)).all(|e| e.common.color == *c)); + let selected_color = memo.get("color", || Some(e.common.color).filter(|c| sel.iter().filter_map(|h| d.entity(*h)).all(|e| e.common.color == *c))); let color = selected_color.map_or_else(|| VARIES.into(), Color::name); let effective_color = |e: &cadcraft_doc::Entity| { let layer = d.layer(&e.common.layer).map_or(Color::WHITE, |l| l.color); e.common.color.resolve(layer, Color::WHITE) }; - let resolved_color = sel - .first() - .and_then(|h| d.entity(*h)) - .map(|e| effective_color(e)) - .filter(|c| sel.iter().filter_map(|h| d.entity(*h)).all(|e| effective_color(e) == *c)) - .unwrap_or(Rgb(255, 255, 255)); - let layer = same(&|e| e.common.layer.clone()); - let linetype = same(&|e| e.common.linetype.clone()); - let lts = same(&|e| format!("{:.4}", e.common.ltscale)); - let lw = same(&|e| e.common.lineweight.name()); - let tr = same(&|e| e.common.transparency.name()); + let resolved_color = memo.get("resolved color", || { + sel.first() + .and_then(|h| d.entity(*h)) + .map(|e| effective_color(e)) + .filter(|c| sel.iter().filter_map(|h| d.entity(*h)).all(|e| effective_color(e) == *c)) + .unwrap_or(Rgb(255, 255, 255)) + }); + let layer = same("layer", &|e| e.common.layer.clone()); + let linetype = same("linetype", &|e| e.common.linetype.clone()); + let lts = same("ltscale", &|e| format!("{:.4}", e.common.ltscale)); + let lw = same("lineweight", &|e| e.common.lineweight.name()); + let tr = same("transparency", &|e| e.common.transparency.name()); let layers: Vec = d.layers.iter().map(|l| l.name.clone()).collect(); let linetypes: Vec = d.linetypes.iter().map(|l| l.name.clone()).collect(); - let ids: Vec = sel.iter().map(|h| h.hex()).collect(); + let ids = &*memo.ids(); let mut set: Option = None; let mut custom_set: Option = None; let group = |ui: &mut egui::Ui, title: &str| { @@ -912,7 +973,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let width = (ui.available_width() - 10.0).max(0.0); if let Some(c) = crate::layers::color_button_resolved( ui, - egui::Id::unique(("properties_color", &ids)), + egui::Id::unique(("properties_color", ids)), selected_color.unwrap_or(Color::ByLayer), resolved_color, &color, @@ -948,7 +1009,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); prop_row(ui, "Linetype scale", |ui| { - if let Some(f) = number(edit_field(ui, ui.scope_id().with(("lts", &ids)), lts.clone()), &mut bad) { + if let Some(f) = number(edit_field(ui, ui.scope_id().with(("lts", ids)), lts.clone()), &mut bad) { set = Some(json!({ "handles": ids, "ltscale": f })); } }); @@ -978,7 +1039,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } ui.separator(); // A fixed percentage, committed when the drag or edit ends. - let tid = egui::Id::unique(("prop_tr", &ids)); + let tid = egui::Id::unique(("prop_tr", ids)); let cur = tr.parse::().ok(); let mut pct = ui.data_mut(|d| d.get_temp::(tid)).or(cur).unwrap_or(0); ui.horizontal(|ui| { @@ -1011,22 +1072,22 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { match &e.kind { EntityKind::Line(l) => { prop_row(ui, "Start X", |ui| { - if let Some(f) = number(edit_field(ui, ui.scope_id().with(("sx", &ids)), len(l.a.x)), &mut bad) { + if let Some(f) = number(edit_field(ui, ui.scope_id().with(("sx", ids)), len(l.a.x)), &mut bad) { set = Some(json!({ "handles": ids, "start": [f, l.a.y] })); } }); prop_row(ui, "Start Y", |ui| { - if let Some(f) = number(edit_field(ui, ui.scope_id().with(("sy", &ids)), len(l.a.y)), &mut bad) { + if let Some(f) = number(edit_field(ui, ui.scope_id().with(("sy", ids)), len(l.a.y)), &mut bad) { set = Some(json!({ "handles": ids, "start": [l.a.x, f] })); } }); prop_row(ui, "End X", |ui| { - if let Some(f) = number(edit_field(ui, ui.scope_id().with(("ex", &ids)), len(l.b.x)), &mut bad) { + if let Some(f) = number(edit_field(ui, ui.scope_id().with(("ex", ids)), len(l.b.x)), &mut bad) { set = Some(json!({ "handles": ids, "end": [f, l.b.y] })); } }); prop_row(ui, "End Y", |ui| { - if let Some(f) = number(edit_field(ui, ui.scope_id().with(("ey", &ids)), len(l.b.y)), &mut bad) { + if let Some(f) = number(edit_field(ui, ui.scope_id().with(("ey", ids)), len(l.b.y)), &mut bad) { set = Some(json!({ "handles": ids, "end": [l.b.x, f] })); } }); @@ -1034,16 +1095,16 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { prop_row(ui, "Delta X", |ui| read_only(ui, &len(dlt.x))); prop_row(ui, "Delta Y", |ui| read_only(ui, &len(dlt.y))); // Length and angle keep the start point and move the end point. - num(ui, "Length", "length", len(dlt.len()), &mut set, &mut bad, &ids); - num(ui, "Angle", "angle", real(dlt.angle().to_degrees()), &mut set, &mut bad, &ids); + num(ui, "Length", "length", len(dlt.len()), &mut set, &mut bad, ids); + num(ui, "Angle", "angle", real(dlt.angle().to_degrees()), &mut set, &mut bad, ids); } EntityKind::Circle(c) => { - num(ui, "Center X", "cx", len(c.center.x), &mut set, &mut bad, &ids); - num(ui, "Center Y", "cy", len(c.center.y), &mut set, &mut bad, &ids); - num(ui, "Radius", "radius", len(c.radius), &mut set, &mut bad, &ids); - num(ui, "Diameter", "diameter", len(c.radius * 2.0), &mut set, &mut bad, &ids); - num(ui, "Circumference", "circumference", len(c.radius * std::f64::consts::TAU), &mut set, &mut bad, &ids); - num(ui, "Area", "area", real(c.radius * c.radius * std::f64::consts::PI), &mut set, &mut bad, &ids); + num(ui, "Center X", "cx", len(c.center.x), &mut set, &mut bad, ids); + num(ui, "Center Y", "cy", len(c.center.y), &mut set, &mut bad, ids); + num(ui, "Radius", "radius", len(c.radius), &mut set, &mut bad, ids); + num(ui, "Diameter", "diameter", len(c.radius * 2.0), &mut set, &mut bad, ids); + num(ui, "Circumference", "circumference", len(c.radius * std::f64::consts::TAU), &mut set, &mut bad, ids); + num(ui, "Area", "area", real(c.radius * c.radius * std::f64::consts::PI), &mut set, &mut bad, ids); if let Some(v) = &mut set && let Some(o) = v.as_object_mut() { @@ -1056,31 +1117,31 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } } EntityKind::Arc(a) => { - num(ui, "Radius", "radius", len(a.radius), &mut set, &mut bad, &ids); - num(ui, "Start angle", "startAngle", real(a.start.to_degrees()), &mut set, &mut bad, &ids); - num(ui, "End angle", "endAngle", real(a.end.to_degrees()), &mut set, &mut bad, &ids); + num(ui, "Radius", "radius", len(a.radius), &mut set, &mut bad, ids); + num(ui, "Start angle", "startAngle", real(a.start.to_degrees()), &mut set, &mut bad, ids); + num(ui, "End angle", "endAngle", real(a.end.to_degrees()), &mut set, &mut bad, ids); } EntityKind::Text(tx) => { prop_row(ui, "Contents", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("txt", &ids)), tx.value.clone()) { + if let Some(s) = edit_field(ui, ui.scope_id().with(("txt", ids)), tx.value.clone()) { set = Some(json!({ "handles": ids, "text": s })); } }); - num(ui, "Height", "height", len(tx.height), &mut set, &mut bad, &ids); - num(ui, "Rotation", "rotation", real(angles.shown(tx.rotation).to_degrees()), &mut set, &mut bad, &ids); - num(ui, "Width factor", "widthFactor", real(tx.width_factor), &mut set, &mut bad, &ids); + num(ui, "Height", "height", len(tx.height), &mut set, &mut bad, ids); + num(ui, "Rotation", "rotation", real(angles.shown(tx.rotation).to_degrees()), &mut set, &mut bad, ids); + num(ui, "Width factor", "widthFactor", real(tx.width_factor), &mut set, &mut bad, ids); } EntityKind::MText(tx) => { prop_row(ui, "Contents", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("mtxt", &ids)), tx.contents.clone()) { + if let Some(s) = edit_field(ui, ui.scope_id().with(("mtxt", ids)), tx.contents.clone()) { set = Some(json!({ "handles": ids, "text": s })); } }); - num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, &ids); - num(ui, "Defined width", "width", len(tx.width), &mut set, &mut bad, &ids); + num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, ids); + num(ui, "Defined width", "width", len(tx.width), &mut set, &mut bad, ids); } EntityKind::LwPolyline(pl) => { - num(ui, "Global width", "width", len(pl.const_width), &mut set, &mut bad, &ids); + num(ui, "Global width", "width", len(pl.const_width), &mut set, &mut bad, ids); let g = cadcraft_geom::Polyline { vertices: pl.vertices.clone(), closed: pl.closed }; prop_row(ui, "Length", |ui| read_only(ui, &len(g.len()))); if pl.closed { @@ -1103,12 +1164,12 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); }); - num(ui, "Scale", "scale", real(hh.scale), &mut set, &mut bad, &ids); - num(ui, "Angle", "angle", real(hh.angle.to_degrees()), &mut set, &mut bad, &ids); + num(ui, "Scale", "scale", real(hh.scale), &mut set, &mut bad, ids); + num(ui, "Angle", "angle", real(hh.angle.to_degrees()), &mut set, &mut bad, ids); } EntityKind::Dimension(dm) => { prop_row(ui, "Text override", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("dimtxt", &ids)), dm.text.clone()) { + if let Some(s) = edit_field(ui, ui.scope_id().with(("dimtxt", ids)), dm.text.clone()) { set = Some(json!({ "handles": ids, "textOverride": s })); } }); @@ -1120,9 +1181,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { // The style's values with this dimension's own overrides; editing one overrides // it for the selected dimensions, as AutoCAD's Properties palette does. let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); - num(ui, "Text height", "textHeight", len(st.text_height), &mut set, &mut bad, &ids); - num(ui, "Arrow size", "arrowSize", len(st.arrow_size), &mut set, &mut bad, &ids); - num(ui, "Dim scale overall", "dimScale", real(st.scale), &mut set, &mut bad, &ids); + num(ui, "Text height", "textHeight", len(st.text_height), &mut set, &mut bad, ids); + num(ui, "Arrow size", "arrowSize", len(st.arrow_size), &mut set, &mut bad, ids); + num(ui, "Dim scale overall", "dimScale", real(st.scale), &mut set, &mut bad, ids); prop_row(ui, "Precision", |ui| { let cur = st.decimals.to_string(); if let Some(n) = pick_menu(ui, &cur, (0..=8).map(|n: u8| n.to_string())).and_then(|n| n.parse::().ok()) { @@ -1139,8 +1200,8 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { prop_row(ui, "Position X", |ui| read_only(ui, &len(i.insert.x))); prop_row(ui, "Position Y", |ui| read_only(ui, &len(i.insert.y))); prop_row(ui, "Position Z", |ui| read_only(ui, &len(i.insert.z))); - num(ui, "Rotation", "rotation", real(angles.shown(i.rotation).to_degrees()), &mut set, &mut bad, &ids); - num(ui, "Scale", "scale", real(i.scale.x), &mut set, &mut bad, &ids); + num(ui, "Rotation", "rotation", real(angles.shown(i.rotation).to_degrees()), &mut set, &mut bad, ids); + num(ui, "Scale", "scale", real(i.scale.x), &mut set, &mut bad, ids); if let Some((_, props)) = custom.filter(|(_, p)| !p.is_empty()) { group(ui, "Custom"); for p in &props { @@ -1173,44 +1234,46 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { // Several dimensions: every property of one dimension, `*VARIES*` where they differ; an // edit applies to all of them. group(ui, "Geometry"); - let shared = |f: &dyn Fn(&cadcraft_doc::Dimension, &cadcraft_doc::DimStyle) -> String| -> String { - let vals: Vec = dims - .iter() - .map(|dm| { - let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); - f(dm, &st) - }) - .collect(); - match vals.first() { - Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), - _ => VARIES.into(), - } + let shared = |key: &'static str, f: &dyn Fn(&cadcraft_doc::Dimension, &cadcraft_doc::DimStyle) -> String| -> String { + memo.get(key, || { + let vals: Vec = dims + .iter() + .map(|dm| { + let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); + f(dm, &st) + }) + .collect(); + match vals.first() { + Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), + _ => VARIES.into(), + } + }) }; - let text = shared(&|dm, _| dm.text.clone()); + let text = shared("dim.text", &|dm, _| dm.text.clone()); prop_row(ui, "Text override", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("dimtxt", &ids)), text.clone()) { + if let Some(s) = edit_field(ui, ui.scope_id().with(("dimtxt", ids)), text.clone()) { set = Some(json!({ "handles": ids, "textOverride": s })); } }); - let style = shared(&|dm, _| dm.style.clone()); + let style = shared("dim.style", &|dm, _| dm.style.clone()); prop_row(ui, "Dim style", |ui| { if let Some(n) = pick_menu(ui, &style, d.dim_styles.iter().map(|st| st.name.clone())) { set = Some(json!({ "handles": ids, "dimStyle": n })); } }); let numbers = [ - ("Text height", "textHeight", shared(&|_, st| len(st.text_height))), - ("Arrow size", "arrowSize", shared(&|_, st| len(st.arrow_size))), - ("Dim scale overall", "dimScale", shared(&|_, st| real(st.scale))), + ("Text height", "textHeight", shared("dim.text_height", &|_, st| len(st.text_height))), + ("Arrow size", "arrowSize", shared("dim.arrow_size", &|_, st| len(st.arrow_size))), + ("Dim scale overall", "dimScale", shared("dim.scale", &|_, st| real(st.scale))), ]; for (label, key, shown) in numbers { prop_row(ui, label, |ui| { - if let Some(f) = number(edit_field(ui, ui.scope_id().with((key, &ids)), shown), &mut bad) { + if let Some(f) = number(edit_field(ui, ui.scope_id().with((key, ids)), shown), &mut bad) { set = Some(json!({ "handles": ids, key: f })); } }); } - let precision = shared(&|_, st| st.decimals.to_string()); + let precision = shared("dim.precision", &|_, st| st.decimals.to_string()); prop_row(ui, "Precision", |ui| { if let Some(n) = pick_menu(ui, &precision, (0..=8).map(|n: u8| n.to_string())).and_then(|n| n.parse::().ok()) { set = Some(json!({ "handles": ids, "precision": n })); @@ -1221,90 +1284,111 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { // Edits apply to all of them; positions are shown but stay read-only, since typing one // would move every object to the same place. group(ui, "Geometry"); - let shared = |f: &dyn Fn(&EntityKind) -> Option| -> String { - let vals: Vec> = sel.iter().filter_map(|h| d.entity(*h)).map(|x| f(&x.kind)).collect(); - match vals.first() { - Some(Some(v0)) if vals.iter().all(|v| v.as_ref() == Some(v0)) => v0.clone(), - _ => VARIES.into(), - } + let shared = |key: &'static str, f: &dyn Fn(&EntityKind) -> Option| -> String { + memo.get(key, || { + let vals: Vec> = sel.iter().filter_map(|h| d.entity(*h)).map(|x| f(&x.kind)).collect(); + match vals.first() { + Some(Some(v0)) if vals.iter().all(|v| v.as_ref() == Some(v0)) => v0.clone(), + _ => VARIES.into(), + } + }) }; let deg = |v: f64| real(angles.shown(v).to_degrees()); match &e.kind { EntityKind::Line(_) => { let line = |k: &EntityKind| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None }; for (label, value) in [ - ("Start X", shared(&|k| line(k).map(|l| len(l.a.x)))), - ("Start Y", shared(&|k| line(k).map(|l| len(l.a.y)))), - ("End X", shared(&|k| line(k).map(|l| len(l.b.x)))), - ("End Y", shared(&|k| line(k).map(|l| len(l.b.y)))), - ("Delta X", shared(&|k| line(k).map(|l| len(l.b.x - l.a.x)))), - ("Delta Y", shared(&|k| line(k).map(|l| len(l.b.y - l.a.y)))), + ("Start X", shared("line.ax", &|k| line(k).map(|l| len(l.a.x)))), + ("Start Y", shared("line.ay", &|k| line(k).map(|l| len(l.a.y)))), + ("End X", shared("line.bx", &|k| line(k).map(|l| len(l.b.x)))), + ("End Y", shared("line.by", &|k| line(k).map(|l| len(l.b.y)))), + ("Delta X", shared("line.dx", &|k| line(k).map(|l| len(l.b.x - l.a.x)))), + ("Delta Y", shared("line.dy", &|k| line(k).map(|l| len(l.b.y - l.a.y)))), ] { prop_row(ui, label, |ui| read_only(ui, &value)); } - num(ui, "Length", "length", shared(&|k| line(k).map(|l| len((l.b.xy() - l.a.xy()).len()))), &mut set, &mut bad, &ids); - num(ui, "Angle", "angle", shared(&|k| line(k).map(|l| real((l.b.xy() - l.a.xy()).angle().to_degrees()))), &mut set, &mut bad, &ids); + num(ui, "Length", "length", shared("line.length", &|k| line(k).map(|l| len((l.b.xy() - l.a.xy()).len()))), &mut set, &mut bad, ids); + num( + ui, + "Angle", + "angle", + shared("line.angle", &|k| line(k).map(|l| real((l.b.xy() - l.a.xy()).angle().to_degrees()))), + &mut set, + &mut bad, + ids, + ); } EntityKind::Circle(_) => { let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None }; - prop_row(ui, "Center X", |ui| read_only(ui, &shared(&|k| circle(k).map(|c| len(c.center.x))))); - prop_row(ui, "Center Y", |ui| read_only(ui, &shared(&|k| circle(k).map(|c| len(c.center.y))))); - num(ui, "Radius", "radius", shared(&|k| circle(k).map(|c| len(c.radius))), &mut set, &mut bad, &ids); - num(ui, "Diameter", "diameter", shared(&|k| circle(k).map(|c| len(c.radius * 2.0))), &mut set, &mut bad, &ids); + prop_row(ui, "Center X", |ui| read_only(ui, &shared("circle.cx", &|k| circle(k).map(|c| len(c.center.x))))); + prop_row(ui, "Center Y", |ui| read_only(ui, &shared("circle.cy", &|k| circle(k).map(|c| len(c.center.y))))); + num(ui, "Radius", "radius", shared("circle.radius", &|k| circle(k).map(|c| len(c.radius))), &mut set, &mut bad, ids); + num(ui, "Diameter", "diameter", shared("circle.diameter", &|k| circle(k).map(|c| len(c.radius * 2.0))), &mut set, &mut bad, ids); num( ui, "Circumference", "circumference", - shared(&|k| circle(k).map(|c| len(c.radius * std::f64::consts::TAU))), + shared("circle.circumference", &|k| circle(k).map(|c| len(c.radius * std::f64::consts::TAU))), &mut set, &mut bad, - &ids, + ids, + ); + num( + ui, + "Area", + "area", + shared("circle.area", &|k| circle(k).map(|c| real(c.radius * c.radius * std::f64::consts::PI))), + &mut set, + &mut bad, + ids, ); - num(ui, "Area", "area", shared(&|k| circle(k).map(|c| real(c.radius * c.radius * std::f64::consts::PI))), &mut set, &mut bad, &ids); } EntityKind::Arc(_) => { let arc = |k: &EntityKind| if let EntityKind::Arc(a) = k { Some(a.clone()) } else { None }; - num(ui, "Radius", "radius", shared(&|k| arc(k).map(|a| len(a.radius))), &mut set, &mut bad, &ids); - num(ui, "Start angle", "startAngle", shared(&|k| arc(k).map(|a| real(a.start.to_degrees()))), &mut set, &mut bad, &ids); - num(ui, "End angle", "endAngle", shared(&|k| arc(k).map(|a| real(a.end.to_degrees()))), &mut set, &mut bad, &ids); + num(ui, "Radius", "radius", shared("arc.radius", &|k| arc(k).map(|a| len(a.radius))), &mut set, &mut bad, ids); + num(ui, "Start angle", "startAngle", shared("arc.start", &|k| arc(k).map(|a| real(a.start.to_degrees()))), &mut set, &mut bad, ids); + num(ui, "End angle", "endAngle", shared("arc.end", &|k| arc(k).map(|a| real(a.end.to_degrees()))), &mut set, &mut bad, ids); } EntityKind::Text(_) => { - let text = |k: &EntityKind| if let EntityKind::Text(t) = k { Some(t.clone()) } else { None }; - let contents = shared(&|k| text(k).map(|t| t.value)); + let contents = shared("text.value", &|k| if let EntityKind::Text(t) = k { Some(t.value.clone()) } else { None }); prop_row(ui, "Contents", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("txt", &ids)), contents.clone()) { + if let Some(s) = edit_field(ui, ui.scope_id().with(("txt", ids)), contents.clone()) { set = Some(json!({ "handles": ids, "text": s })); } }); - num(ui, "Height", "height", shared(&|k| text(k).map(|t| len(t.height))), &mut set, &mut bad, &ids); - num(ui, "Rotation", "rotation", shared(&|k| text(k).map(|t| deg(t.rotation))), &mut set, &mut bad, &ids); - num(ui, "Width factor", "widthFactor", shared(&|k| text(k).map(|t| real(t.width_factor))), &mut set, &mut bad, &ids); + let height = shared("text.height", &|k| if let EntityKind::Text(t) = k { Some(len(t.height)) } else { None }); + num(ui, "Height", "height", height, &mut set, &mut bad, ids); + let rotation = shared("text.rotation", &|k| if let EntityKind::Text(t) = k { Some(deg(t.rotation)) } else { None }); + num(ui, "Rotation", "rotation", rotation, &mut set, &mut bad, ids); + let width_factor = shared("text.width_factor", &|k| if let EntityKind::Text(t) = k { Some(real(t.width_factor)) } else { None }); + num(ui, "Width factor", "widthFactor", width_factor, &mut set, &mut bad, ids); } EntityKind::MText(_) => { - let mtext = |k: &EntityKind| if let EntityKind::MText(t) = k { Some(t.clone()) } else { None }; - let contents = shared(&|k| mtext(k).map(|t| t.contents)); + let contents = shared("mtext.contents", &|k| if let EntityKind::MText(t) = k { Some(t.contents.clone()) } else { None }); prop_row(ui, "Contents", |ui| { - if let Some(s) = edit_field(ui, ui.scope_id().with(("mtxt", &ids)), contents.clone()) { + if let Some(s) = edit_field(ui, ui.scope_id().with(("mtxt", ids)), contents.clone()) { set = Some(json!({ "handles": ids, "text": s })); } }); - num(ui, "Text height", "height", shared(&|k| mtext(k).map(|t| len(t.height))), &mut set, &mut bad, &ids); - num(ui, "Defined width", "width", shared(&|k| mtext(k).map(|t| len(t.width))), &mut set, &mut bad, &ids); + let height = shared("mtext.height", &|k| if let EntityKind::MText(t) = k { Some(len(t.height)) } else { None }); + num(ui, "Text height", "height", height, &mut set, &mut bad, ids); + let width = shared("mtext.width", &|k| if let EntityKind::MText(t) = k { Some(len(t.width)) } else { None }); + num(ui, "Defined width", "width", width, &mut set, &mut bad, ids); } EntityKind::LwPolyline(_) => { - let poly = |k: &EntityKind| { - if let EntityKind::LwPolyline(p) = k { - Some((p.const_width, p.closed, cadcraft_geom::Polyline { vertices: p.vertices.clone(), closed: p.closed })) - } else { - None - } - }; - num(ui, "Global width", "width", shared(&|k| poly(k).map(|(w, ..)| len(w))), &mut set, &mut bad, &ids); - prop_row(ui, "Length", |ui| read_only(ui, &shared(&|k| poly(k).map(|(.., g)| len(g.len()))))); - prop_row(ui, "Area", |ui| { - read_only(ui, &shared(&|k| poly(k).map(|(_, closed, g)| if closed { real(g.area().abs()) } else { String::new() }))) + // Only Length and Area need the vertices; the other rows read one field. + let geom = |p: &cadcraft_doc::LwPolyline| cadcraft_geom::Polyline { vertices: p.vertices.clone(), closed: p.closed }; + let width = shared("poly.width", &|k| if let EntityKind::LwPolyline(p) = k { Some(len(p.const_width)) } else { None }); + num(ui, "Global width", "width", width, &mut set, &mut bad, ids); + let length = shared("poly.length", &|k| if let EntityKind::LwPolyline(p) = k { Some(len(geom(p).len())) } else { None }); + prop_row(ui, "Length", |ui| read_only(ui, &length)); + let area = shared("poly.area", &|k| { + if let EntityKind::LwPolyline(p) = k { Some(if p.closed { real(geom(p).area().abs()) } else { String::new() }) } else { None } + }); + prop_row(ui, "Area", |ui| read_only(ui, &area)); + let closed = shared("poly.closed", &|k| { + if let EntityKind::LwPolyline(p) = k { Some(crate::i18n::t(if p.closed { "Yes" } else { "No" }).to_string()) } else { None } }); - let closed = shared(&|k| poly(k).map(|(_, c, _)| crate::i18n::t(if c { "Yes" } else { "No" }).to_string())); prop_row(ui, "Closed", |ui| { if let Some(n) = pick_menu(ui, &closed, ["Yes", "No"].map(|s| crate::i18n::t(s).to_string())) { set = Some(json!({ "handles": ids, "closed": n == crate::i18n::t("Yes") })); @@ -1312,8 +1396,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); } EntityKind::Hatch(_) => { - let hatch = |k: &EntityKind| if let EntityKind::Hatch(h) = k { Some(h.clone()) } else { None }; - let pattern = shared(&|k| hatch(k).map(|h| h.pattern)); + let pattern = shared("hatch.pattern", &|k| if let EntityKind::Hatch(h) = k { Some(h.pattern.clone()) } else { None }); prop_row(ui, "Pattern", |ui| { ui.menu_button(pattern.clone(), |ui| { if let Some(name) = patterns::menu(ui, &pattern) { @@ -1322,34 +1405,42 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); }); - num(ui, "Scale", "scale", shared(&|k| hatch(k).map(|h| real(h.scale))), &mut set, &mut bad, &ids); - num(ui, "Angle", "angle", shared(&|k| hatch(k).map(|h| real(h.angle.to_degrees()))), &mut set, &mut bad, &ids); + let scale = shared("hatch.scale", &|k| if let EntityKind::Hatch(h) = k { Some(real(h.scale)) } else { None }); + num(ui, "Scale", "scale", scale, &mut set, &mut bad, ids); + let angle = shared("hatch.angle", &|k| if let EntityKind::Hatch(h) = k { Some(real(h.angle.to_degrees())) } else { None }); + num(ui, "Angle", "angle", angle, &mut set, &mut bad, ids); } EntityKind::Insert(_) => { - let insert = |k: &EntityKind| if let EntityKind::Insert(i) = k { Some(i.clone()) } else { None }; // A dynamic block reference shows its dynamic block's name, as with one reference; // its anonymous blocks (`*U12`) differ from one reference to the next. - let names: Vec = sel - .iter() - .filter_map(|h| match d.entity(*h).map(|x| &x.kind) { - Some(EntityKind::Insert(i)) => Some(custom_properties(ui, app, *h).map_or_else(|| i.block.clone(), |(n, _)| n)), - _ => None, - }) - .collect(); - let name = match names.first() { - Some(n0) if names.iter().all(|n| n == n0) => n0.clone(), - _ => VARIES.to_string(), + let name = memo.get("insert.name", || { + let names: Vec = sel + .iter() + .filter_map(|h| match d.entity(*h).map(|x| &x.kind) { + Some(EntityKind::Insert(i)) => Some(custom_properties(ui, app, *h).map_or_else(|| i.block.clone(), |(n, _)| n)), + _ => None, + }) + .collect(); + match names.first() { + Some(n0) if names.iter().all(|n| n == n0) => n0.clone(), + _ => VARIES.to_string(), + } + }); + let position = |key: &'static str, f: fn(&cadcraft_doc::Insert) -> f64| { + shared(key, &|k| if let EntityKind::Insert(i) = k { Some(len(f(i))) } else { None }) }; for (label, value) in [ ("Name", name), - ("Position X", shared(&|k| insert(k).map(|i| len(i.insert.x)))), - ("Position Y", shared(&|k| insert(k).map(|i| len(i.insert.y)))), - ("Position Z", shared(&|k| insert(k).map(|i| len(i.insert.z)))), + ("Position X", position("insert.x", |i| i.insert.x)), + ("Position Y", position("insert.y", |i| i.insert.y)), + ("Position Z", position("insert.z", |i| i.insert.z)), ] { prop_row(ui, label, |ui| read_only(ui, &value)); } - num(ui, "Rotation", "rotation", shared(&|k| insert(k).map(|i| deg(i.rotation))), &mut set, &mut bad, &ids); - num(ui, "Scale", "scale", shared(&|k| insert(k).map(|i| real(i.scale.x))), &mut set, &mut bad, &ids); + let rotation = shared("insert.rotation", &|k| if let EntityKind::Insert(i) = k { Some(deg(i.rotation)) } else { None }); + num(ui, "Rotation", "rotation", rotation, &mut set, &mut bad, ids); + let scale = shared("insert.scale", &|k| if let EntityKind::Insert(i) = k { Some(real(i.scale.x)) } else { None }); + num(ui, "Scale", "scale", scale, &mut set, &mut bad, ids); } _ => {} } @@ -1376,6 +1467,7 @@ mod tests { use crate::Services; use cadcraft_engine::Session; use egui::{Color32, Shape}; + use egui_kittest::kittest::Queryable; fn contains_swatch(shape: &Shape, color: Color32) -> bool { match shape { @@ -1494,4 +1586,58 @@ mod tests { assert!(texts.iter().any(|t| t == VARIES), "{command}: differing values show {VARIES}; painted: {texts:?}"); } } + + /// The radius of every selected circle. + fn selected_radii(app: &CadApp) -> Vec { + let d = app.session.doc().unwrap(); + app.session + .selection() + .iter() + .filter_map(|h| d.entity(*h)) + .filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }) + .collect() + } + + /// A value typed into the palette goes to every selected object, not just the first. + #[test] + fn typing_a_shared_value_changes_every_selected_object() { + let mut app = CadApp::new(Session::default(), Services::default()); + let handles: Vec = + [2, 5, 9].map(|r| app.run("circle", json!({ "center": [0, 0], "radius": r })).unwrap()["handle"].as_str().unwrap().to_string()).to_vec(); + app.run("select", json!({ "handles": handles })).unwrap(); + let mut h = + egui_kittest::Harness::builder().with_size(vec2(400.0, 1200.0)).build_ui_state(|ui, app: &mut CadApp| properties_section(app, ui), app); + h.run_steps(3); + // The first `*VARIES*` field is the Radius: its row comes first. + let radius = h.get_all_by_value(VARIES).next().unwrap(); + radius.focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(2); + h.get_all_by_value(VARIES).next().unwrap().type_text("7"); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(selected_radii(h.state()), vec![7.0, 7.0, 7.0], "all three circles take the typed radius"); + } + + /// The values the palette works out are kept for a drawing revision and a selection, and + /// worked out again when either changes. + #[test] + fn shared_values_follow_the_drawing_and_the_selection() { + let mut app = CadApp::new(Session::default(), Services::default()); + let handles: Vec = + [2, 5].map(|r| app.run("circle", json!({ "center": [0, 0], "radius": r })).unwrap()["handle"].as_str().unwrap().to_string()).to_vec(); + app.run("select", json!({ "handles": handles.clone() })).unwrap(); + let mut h = + egui_kittest::Harness::builder().with_size(vec2(400.0, 1200.0)).build_ui_state(|ui, app: &mut CadApp| properties_section(app, ui), app); + h.run_steps(3); + assert!(h.query_all_by_value(VARIES).count() > 0, "two different radii show {VARIES}"); + h.state_mut().run("properties.set", json!({ "handles": handles, "radius": 4.0 })).unwrap(); + h.run_steps(3); + assert!(h.query_all_by_value(VARIES).count() == 0, "after both radii are 4 nothing varies"); + h.state_mut().run("select", json!({ "handles": [handles[0].clone()] })).unwrap(); + h.run_steps(3); + assert!(h.query_all_by_value("4.0000").count() > 0, "one circle alone shows its radius"); + } } From 50bc6c11583c0f1509bd3f8c69cc0a0e2cb01b5a Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:54:10 +0100 Subject: [PATCH 127/531] fix(ui): Properties palette keeps the polyline Closed value untranslated in its memo Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index e050a3e2b..4bb363d67 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1387,8 +1387,10 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); prop_row(ui, "Area", |ui| read_only(ui, &area)); let closed = shared("poly.closed", &|k| { - if let EntityKind::LwPolyline(p) = k { Some(crate::i18n::t(if p.closed { "Yes" } else { "No" }).to_string()) } else { None } + if let EntityKind::LwPolyline(p) = k { Some(if p.closed { "Yes" } else { "No" }.to_string()) } else { None } }); + // Kept untranslated, so a change of language does not show stale text. + let closed = if closed == VARIES { closed } else { crate::i18n::t(&closed).to_string() }; prop_row(ui, "Closed", |ui| { if let Some(n) = pick_menu(ui, &closed, ["Yes", "No"].map(|s| crate::i18n::t(s).to_string())) { set = Some(json!({ "handles": ids, "closed": n == crate::i18n::t("Yes") })); From 156d117dd8c1a20510f8295ec56f7b19974cfc1a Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:34:08 +0700 Subject: [PATCH 128/531] fix(modify): BREAK and TRIM keep the object's handle, as AutoCAD does BREAK, BREAKATPOINT and TRIM erased the object and added every piece as a new object. AutoCAD 2024 changes the object itself: the piece holding its start (or the only piece left: a circle becomes an arc, a closed polyline is opened) keeps its handle, drawing-order place, groups and extended data; the other pieces are new objects added at the end. Associative dimensions follow the measured rule: an attachment still at a point of the object stays, one on a new piece moves to it, any other follows the object's new end. Constraints on the object are removed, as before. New pieces go to the object's own space. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/assoc.rs | 85 +++- crates/engine/src/cmd/modify.rs | 6 +- crates/engine/src/cmd/modify/break_join.rs | 16 +- crates/engine/src/cmd/modify/trim.rs | 44 +- crates/engine/src/cmd/trimextend.rs | 6 +- .../tests/it/break_join_locked_layers.rs | 3 +- .../engine/tests/it/break_trim_keep_handle.rs | 444 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 8 files changed, 566 insertions(+), 39 deletions(-) create mode 100644 crates/engine/tests/it/break_trim_keep_handle.rs diff --git a/crates/engine/src/assoc.rs b/crates/engine/src/assoc.rs index f17cd1e80..389745dcc 100644 --- a/crates/engine/src/assoc.rs +++ b/crates/engine/src/assoc.rs @@ -40,8 +40,12 @@ fn arc_geom(a: &cadcraft_doc::Arc) -> cadcraft_geom::Arc { /// Where a snap sits on an object now. pub fn snap_point(d: &Drawing, a: &DimAssoc) -> Option { - let e = d.entity(a.handle)?; - match (&e.kind, &a.snap) { + snap_on(d, &d.entity(a.handle)?.kind, &a.snap) +} + +/// Where `snap` sits on an object of kind `kind` (an intersection finds its other line in `d`). +fn snap_on(d: &Drawing, kind: &EntityKind, snap: &AssocSnap) -> Option { + match (kind, snap) { (EntityKind::Line(l), AssocSnap::Start) => Some(l.a.xy()), (EntityKind::Line(l), AssocSnap::End) => Some(l.b.xy()), (EntityKind::Line(l), AssocSnap::Mid) => Some(l.a.xy().mid(l.b.xy())), @@ -88,6 +92,61 @@ fn candidates(kind: &EntityKind) -> Vec<(AssocSnap, Vec2)> { } } +/// Whether two snaps are the same kind of object point: an endpoint or vertex, a centre, or a +/// midpoint. +fn same_kind(a: &AssocSnap, b: &AssocSnap) -> bool { + matches!( + (a, b), + (AssocSnap::Start | AssocSnap::End | AssocSnap::Vertex { .. }, AssocSnap::Start | AssocSnap::End | AssocSnap::Vertex { .. }) + | (AssocSnap::Center, AssocSnap::Center) + | (AssocSnap::Mid, AssocSnap::Mid) + ) +} + +/// BREAK or TRIM reshaped the object `pieces[0]` (which was `old`) and added the other pieces: +/// move the dimension attachments on it as AutoCAD 2024 does. An attachment whose point is still +/// a point of the same kind on the object stays there (a closed polyline opened by BREAK numbers +/// its vertices from the break); one whose point is on a new piece moves to that piece, so a +/// dimension across a line broken in its middle stays where it was; any other is left as it was, +/// so the dimension follows the object's new end when that end was cut off. Attachments at an +/// angle on a circle or arc and at an intersection stay on the object. [`update`] moves the +/// definition points after the command. +pub fn follow_pieces(d: &mut Drawing, old: &EntityKind, pieces: &[Handle]) { + let Some(&h) = pieces.first() else { return }; + let mut changes: Vec<(Handle, Vec)> = Vec::new(); + for store in std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)) { + for e in store.iter() { + let EntityKind::Dimension(dm) = &e.kind else { continue }; + if !dm.assoc.iter().any(|a| a.handle == h) { + continue; + } + let assoc: Vec = dm.assoc.iter().map(|a| on_piece(d, old, pieces, a).unwrap_or_else(|| a.clone())).collect(); + if assoc != dm.assoc { + changes.push((e.handle, assoc)); + } + } + } + for (dh, assoc) in changes { + let _ = d.modify_entity(dh, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.assoc = assoc; + } + }); + } +} + +/// The piece attachment `a` moves to when its object became `pieces` (see [`follow_pieces`]). +fn on_piece(d: &Drawing, old: &EntityKind, pieces: &[Handle], a: &DimAssoc) -> Option { + if pieces.first() != Some(&a.handle) || matches!(a.snap, AssocSnap::OnCircle { .. } | AssocSnap::Intersection { .. }) { + return None; + } + let p = snap_on(d, old, &a.snap)?; + pieces.iter().find_map(|&ph| { + let (snap, _) = candidates(&d.entity(ph)?.kind).into_iter().find(|(s, q)| same_kind(&a.snap, s) && close(p, *q))?; + Some(DimAssoc { point: a.point.clone(), handle: ph, snap }) + }) +} + /// An object point exactly at `p` (an endpoint, vertex, centre or midpoint) to attach to. pub fn find_snap(d: &Drawing, space: &Space, p: Vec2) -> Option<(Handle, AssocSnap)> { if !p.is_finite() { @@ -244,8 +303,10 @@ pub fn recompute(dm: &Dimension, prev: Option<&Dimension>, before: &Drawing, aft let was = prev.unwrap_or(dm); nd.assoc.retain(|a| { let Some(old) = def_point(was, &a.point) else { return false }; - // Only follow if the point sat on the object before the change. - if let Some(prev) = snap_point(before, a) + // Only follow if the point sat on the object before the change, as attached then (BREAK + // and TRIM may have moved the attachment to a piece of the object since). + let held = was.assoc.iter().find(|o| o.point == a.point).unwrap_or(a); + if let Some(prev) = snap_point(before, held) && !close(prev, old.xy()) { return false; @@ -304,16 +365,20 @@ pub fn update(after: &mut Arc, before: &Drawing) -> usize { if dm.assoc.is_empty() { continue; } - let touched = dm.assoc.iter().any(|a| { - src_changed(before, d, a.handle) || matches!(a.snap, AssocSnap::Intersection { other } if src_changed(before, d, other)) - }); - if !touched { - continue; - } let prev = match before.entity(e.handle).map(|x| &x.kind) { Some(EntityKind::Dimension(p)) => Some(p), _ => None, }; + // Its objects changed, or the command moved an attachment (BREAK and TRIM move them + // to new pieces, which a later pick of the same TRIM may reshape again). + let touched = dm.assoc.iter().any(|a| { + src_changed(before, d, a.handle) + || matches!(a.snap, AssocSnap::Intersection { other } if src_changed(before, d, other)) + || prev.is_some_and(|p| !p.assoc.contains(a)) + }); + if !touched { + continue; + } let nd = recompute(dm, prev, before, d); if nd != *dm { changes.push((e.handle, nd)); diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index bbcd25267..8b26270da 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { .menu(&["Modify", "Trim"]) .alias(&["tr"]) .params( - "{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"}", + "{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)", ) .interactive(|_| Ok(Box::new(TrimM::new(false)))), CommandSpec::new("extend", "Extend", trimextend::run_extend) @@ -108,9 +108,9 @@ pub fn specs() -> Vec { CommandSpec::new("break", "Break", run_break) .menu(&["Modify", "Break"]) .alias(&["br"]) - .params("{handle, p1, p2}") + .params("{handle, p1, p2} → {handles: the object (kept, reshaped) then the new pieces; none when nothing is left}") .interactive(|_| Ok(Box::new(BreakM::default()))), - CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at}"), + CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}"), CommandSpec::new("join", "Join", run_join) .menu(&["Modify", "Join"]) .alias(&["j"]) diff --git a/crates/engine/src/cmd/modify/break_join.rs b/crates/engine/src/cmd/modify/break_join.rs index 74fd482a2..0309fe972 100644 --- a/crates/engine/src/cmd/modify/break_join.rs +++ b/crates/engine/src/cmd/modify/break_join.rs @@ -1,4 +1,4 @@ -use super::trim::{param_on, sub_polyline}; +use super::trim::{param_on, replace_with_pieces, sub_polyline}; use super::{ Accept, Arc, EngineError, Entity, EntityKind, Handle, Input, Interactive, Line, PolyVertex, Polyline, Prompt, Result, Segment, Session, Step, Value, Vec2, arc, bad, json, lwpoly, norm_angle, point_param, point_req, targets, @@ -105,19 +105,7 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re } _ => return Err(EngineError::Other("Cannot break that object.".into())), }; - let common = e.common.clone(); - let space = s.space(); - let d = s.doc_mut()?; - d.remove_entity(h); - let mut out = Vec::new(); - for k in pieces { - let nh = d.new_handle(); - if let Some(st) = d.space_mut(&space) { - st.push(Entity { handle: nh, common: common.clone(), kind: k }); - out.push(nh); - } - } - Ok(out) + replace_with_pieces(s, h, pieces) } pub(super) fn run_break(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 66eab0be8..b61c5b0d2 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -170,18 +170,46 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?, k => crate::cmd::modify2::trim_other(k, &cut, pick)?, }; - let common = e.common.clone(); - let space = s.space(); + replace_with_pieces(s, h, pieces) +} + +/// Put `pieces` in place of object `h` as AutoCAD 2024's BREAK and TRIM leave them: the first +/// piece (the one holding the object's start, or the only piece of a circle or closed polyline) +/// is the object itself, keeping its handle, its place in the drawing order, its groups and its +/// extended data; the others are new objects with its properties, added at the end of its space +/// (`entlast`); with no pieces the object is erased. Returns the pieces' handles. (A line broken +/// in its middle keeps its handle on the piece from its start point, the piece to its end point is +/// new; a circle broken or trimmed becomes an arc with the circle's handle.) +/// +/// Dimensions attached to the object follow [`crate::assoc::follow_pieces`]. Its parametric +/// constraints are removed: its new shape no longer meets them, and solving them again would move +/// the objects they tie it to. +pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec) -> Result> { let d = s.doc_mut()?; - d.remove_entity(h); - let mut out = Vec::new(); - for k in pieces { - let nh = d.new_handle(); + let mut pieces = pieces.into_iter(); + let Some(first) = pieces.next() else { + d.remove_entity(h); + return Ok(Vec::new()); + }; + let (Some(space), Some(old)) = (d.space_of(h), d.entity(h).cloned()) else { + return Err(EngineError::Other("no such object".into())); + }; + d.modify_entity(h, |e| e.kind = first)?; + let mut out = vec![h]; + for kind in pieces { + let handle = d.new_handle(); if let Some(st) = d.space_mut(&space) { - st.push(Entity { handle: nh, common: common.clone(), kind: k }); - out.push(nh); + st.push(Entity { handle, common: old.common.clone(), kind }); + out.push(handle); } } + crate::assoc::follow_pieces(d, &old.kind, &out); + let n = d.constraints.len(); + d.constraints.retain(|c| c.refs.iter().all(|r| r.handle != h)); + let removed = n - d.constraints.len(); + if removed > 0 { + s.echo(format!("{removed} constraint(s) of the broken or trimmed object removed.")); + } Ok(out) } diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index ab03d5c31..eab957589 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -36,7 +36,7 @@ fn misses_edges(e: &EngineError) -> bool { } /// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses -/// erases it. Returns the handles that replace `h` (none when it was erased). +/// erases it. Returns what `h` became: its pieces, `h` itself first (none when it was erased). fn apply(s: &mut Session, h: Handle, at: Vec2, extending: bool, edges: Edges, quick: bool) -> Result> { if extending { extend(s, h, at, edges)?; @@ -118,8 +118,8 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu run_picks(s, work, extending, edges, quick, tol) } -/// Trim (or extend) each object at its pick points. A trim replaces the object with pieces, so -/// later picks go to the piece within `tol` of the point (none: that part is already gone). +/// Trim (or extend) each object at its pick points. A trim leaves the object in pieces, so later +/// picks go to the piece within `tol` of the point (none: that part is already gone). fn run_picks(s: &mut Session, work: Vec<(Handle, Vec)>, extending: bool, edges: Edges, quick: bool, tol: f64) -> Result { let mut n = 0; let mut last_err = None; diff --git a/crates/engine/tests/it/break_join_locked_layers.rs b/crates/engine/tests/it/break_join_locked_layers.rs index 0a1f6e707..4162ca9ee 100644 --- a/crates/engine/tests/it/break_join_locked_layers.rs +++ b/crates/engine/tests/it/break_join_locked_layers.rs @@ -45,7 +45,8 @@ fn break_and_breakatpoint_refuse_a_locked_line() { let unlocked = snapshot(&s); let r = s.execute("break", &json!({"handle": a, "p1": [3, 0], "p2": [7, 0]})).unwrap(); assert_eq!(r["handles"].as_array().unwrap().len(), 2); - assert!(s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&a).unwrap()).is_none()); + // The line keeps its handle as the piece from its start. + assert_eq!(r["handles"][0].as_str(), Some(a.as_str())); assert!(s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&control).unwrap()).is_some()); let broken = snapshot(&s); s.execute("undo", &json!({})).unwrap(); diff --git a/crates/engine/tests/it/break_trim_keep_handle.rs b/crates/engine/tests/it/break_trim_keep_handle.rs new file mode 100644 index 000000000..0fc5a1fc3 --- /dev/null +++ b/crates/engine/tests/it/break_trim_keep_handle.rs @@ -0,0 +1,444 @@ +//! BREAK, BREAKATPOINT and TRIM change the object itself, as AutoCAD 2024 does: the piece from +//! the object's start, or the only piece left, keeps its handle and its place in the drawing +//! order, and the other pieces are new objects added at the end (`entlast`). Groups keep the +//! object, an associative hatch whose boundary no longer closes keeps its shape and its link +//! ends, and a dimension attached to the object stays on the point it measured, or follows the +//! object's new end where that point was cut off. +//! +//! The two chains, the group, the two hatches and the three dimensions on a line were measured in +//! AutoCAD 2024 (accoreconsole) on the same drawings: the objects in database order (`entnext`) +//! after each chain, a new handle marked `+`, and the dimensions' DIMASSOC references. The other +//! cases follow from those rules, or say what they check. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{AssocSnap, Common, DimAssoc, Dimension, EntityKind, Handle, Hatch, Line, Space}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +fn first_handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +/// Adds the object `cmd` makes from `p`, on layer `name`. +fn add(s: &mut Session, name: &str, cmd: &str, p: Value) -> Handle { + let h = first_handle(&s.execute(cmd, &p).unwrap()); + s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": name })).unwrap(); + h +} + +fn line(s: &mut Session, name: &str, a: [f64; 2], b: [f64; 2]) -> Handle { + add(s, name, "line", json!({ "points": [a, b] })) +} + +fn arc(s: &mut Session, name: &str, c: [f64; 2], start: f64, end: f64) -> Handle { + add(s, name, "arc", json!({ "center": c, "radius": 10, "start": start, "end": end })) +} + +fn pline(s: &mut Session, name: &str, vertices: Value, closed: bool) -> Handle { + add(s, name, "pline", json!({ "vertices": vertices, "closed": closed })) +} + +/// The drawing the chains were measured on, each object on a layer named after it, made in this +/// order. +fn drawing() -> Session { + let mut s = Session::new(); + line(&mut s, "LA", [0.0, 50.0], [100.0, 50.0]); + line(&mut s, "LB", [50.0, 0.0], [50.0, 100.0]); + pline(&mut s, "LP", json!([[0, 200], [20, 200], [20, 220]]), false); + line(&mut s, "LE", [200.0, 0.0], [210.0, 0.0]); + line(&mut s, "LF", [210.0, 0.0], [220.0, 0.0]); + line(&mut s, "LC", [0.0, 0.0], [100.0, 100.0]); + line(&mut s, "LD", [0.0, 100.0], [100.0, 0.0]); + arc(&mut s, "LR", [300.0, 0.0], 0.0, 180.0); + add(&mut s, "LO", "circle", json!({ "center": [400, 0], "radius": 10 })); + pline(&mut s, "LK", json!([[500, 0], [520, 0], [520, 20], [500, 20]]), true); + line(&mut s, "LG", [600.0, 0.0], [600.0, 100.0]); + line(&mut s, "LH", [590.0, 40.0], [610.0, 40.0]); + line(&mut s, "LI", [590.0, 60.0], [610.0, 60.0]); + line(&mut s, "LT", [650.0, 0.0], [650.0, 100.0]); + line(&mut s, "LU", [640.0, 40.0], [660.0, 40.0]); + line(&mut s, "LW", [395.0, -20.0], [395.0, 20.0]); + line(&mut s, "LX", [10.0, 190.0], [10.0, 210.0]); + line(&mut s, "LY", [15.0, 190.0], [15.0, 210.0]); + arc(&mut s, "LJ", [700.0, 0.0], 0.0, 90.0); + arc(&mut s, "LL", [700.0, 0.0], 90.0, 360.0); + line(&mut s, "LM", [800.0, 0.0], [810.0, 0.0]); + arc(&mut s, "LN", [810.0, 10.0], 270.0, 360.0); + pline(&mut s, "LQ", json!([[900, 0], [910, 0]]), false); + line(&mut s, "LS", [910.0, 0.0], [910.0, 10.0]); + line(&mut s, "LZ", [1000.0, 0.0], [1010.0, 0.0]); + s +} + +/// `v` to `places` decimals without trailing zeros, as `rtos` printed the measurements. +fn num(v: f64, places: usize) -> String { + let t = format!("{v:.places$}"); + let t = if t.contains('.') { t.trim_end_matches('0').trim_end_matches('.') } else { &t }; + if t == "-0" { "0".into() } else { t.into() } +} + +fn pt(p: Vec2) -> String { + format!("{},{}", num(p.x, 4), num(p.y, 4)) +} + +/// An angle in degrees in [0, 360). +fn deg(a: f64) -> String { + let d = a.to_degrees().rem_euclid(360.0); + num(if d >= 360.0 - 5e-4 { 0.0 } else { d }, 3) +} + +/// The model space objects in order as `layer[+]:TYPE:shape`, `+` marking a handle that wasn't in +/// `original`. +fn table(s: &Session, original: &[Handle]) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .map(|e| { + let shape = match &e.kind { + EntityKind::Line(l) => format!("LINE:{}>{}", pt(l.a.xy()), pt(l.b.xy())), + EntityKind::Arc(a) => format!("ARC:c{}r{}a{}>{}", pt(a.center.xy()), num(a.radius, 4), deg(a.start), deg(a.end)), + EntityKind::Circle(c) => format!("CIRCLE:c{}r{}", pt(c.center.xy()), num(c.radius, 4)), + EntityKind::LwPolyline(p) => { + format!("LWPOLYLINE:f{}{}", u8::from(p.closed), p.vertices.iter().map(|v| format!(";{}", pt(v.p))).collect::()) + } + k => format!("{k:?}"), + }; + let new = if original.contains(&e.handle) { "" } else { "+" }; + format!("{}{new}:{shape}", e.common.layer) + }) + .collect() +} + +fn handles(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.handle).collect() +} + +/// The object on layer `name` that was there first. +fn named(s: &Session, name: &str) -> Handle { + s.doc().unwrap().model.iter().find(|e| e.common.layer == name).unwrap().handle +} + +/// Runs `commands` on the command line one by one, each to its end. +fn run(s: &mut Session, commands: &[&str]) { + for c in commands { + s.script(&format!("{c}\n")).unwrap(); + assert!(s.running.is_none(), "{c}: {}", s.prompt_text()); + } +} + +/// The objects AutoCAD leaves untouched in the middle of both tables. +const UNTOUCHED: [&str; 8] = [ + "LG:LINE:600,0>600,100", + "LH:LINE:590,40>610,40", + "LI:LINE:590,60>610,60", + "LT:LINE:650,0>650,100", + "LU:LINE:640,40>660,40", + "LW:LINE:395,-20>395,20", + "LX:LINE:10,190>10,210", + "LY:LINE:15,190>15,210", +]; + +/// The measured `entnext` table after the chain of breaks below. (LL and LN end at 360°, written +/// 0° here.) +fn after_breaks() -> Vec<&'static str> { + let mut v = vec![ + "LA:LINE:10,50>100,50", + "LB:LINE:50,0>50,20", + "LP:LWPOLYLINE:f0;0,200;10,200", + "LE:LINE:200,0>210,0", + "LF:LINE:210,0>220,0", + "LC:LINE:0,0>100,100", + "LD:LINE:0,100>100,0", + "LR:ARC:c300,0r10a0>45", + "LO:ARC:c400,0r10a90>0", + "LK:LWPOLYLINE:f0;520,10;520,20;500,20;500,0;510,0", + ]; + v.extend(UNTOUCHED); + v.extend([ + "LJ:ARC:c700,0r10a0>45", + "LL:ARC:c700,0r10a90>0", + "LM:LINE:800,0>810,0", + "LN:ARC:c810,10r10a270>0", + "LQ:LWPOLYLINE:f0;900,0;910,0", + "LS:LINE:910,0>910,10", + "LZ:LINE:1000,0>1005,0", + "LB+:LINE:50,30>50,100", + "LR+:ARC:c300,0r10a135>180", + "LP+:LWPOLYLINE:f0;20,210;20,220", + "LZ+:LINE:1005,0>1010,0", + "LJ+:ARC:c700,0r10a45>90", + ]); + v +} + +#[test] +fn a_chain_of_breaks_leaves_the_objects_in_autocads_order() { + let mut s = drawing(); + let original = handles(&s); + run( + &mut s, + &[ + // A line picked nearer its end: the piece from its start still keeps the handle. + "BREAK 50,30 50,20", + // Off the start: one piece, the line itself. + "BREAK 10,50 -10,50", + "BREAK 307.0710678,7.0710678 292.9289322,7.0710678", + // A circle becomes an arc with its handle. + "BREAK 410,0 400,10", + "BREAK 5,200 F 10,200 20,210", + // A closed polyline opens with its handle. + "BREAK 510,0 520,10", + ], + ); + // BREAKATPOINT, picking each object at the point it is broken at. + for (name, at) in [("LZ", [1005.0, 0.0]), ("LJ", [707.0710678, 7.0710678])] { + s.execute("breakatpoint", &json!({ "handle": named(&s, name).hex(), "at": at })).unwrap(); + } + assert_eq!(table(&s, &original), after_breaks()); +} + +#[test] +fn a_chain_of_trims_leaves_the_objects_in_autocads_order() { + let mut s = drawing(); + let original = handles(&s); + // Quick mode: every object cuts. Each pick is between the measured cutting edges. + run(&mut s, &["TRIM 600,50\n", "TRIM 650,80\n", "TRIM 50,10\n", "TRIM 390,0\n", "TRIM 12,200\n"]); + let mut want = vec![ + "LA:LINE:0,50>100,50", + "LB:LINE:50,50>50,100", + "LP:LWPOLYLINE:f0;0,200;10,200", + "LE:LINE:200,0>210,0", + "LF:LINE:210,0>220,0", + "LC:LINE:0,0>100,100", + "LD:LINE:0,100>100,0", + "LR:ARC:c300,0r10a0>180", + "LO:ARC:c400,0r10a240>120", + "LK:LWPOLYLINE:f1;500,0;520,0;520,20;500,20", + "LG:LINE:600,0>600,40", + ]; + want.extend(&UNTOUCHED[1..3]); + want.push("LT:LINE:650,0>650,40"); + want.extend(&UNTOUCHED[4..]); + want.extend([ + "LJ:ARC:c700,0r10a0>90", + "LL:ARC:c700,0r10a90>0", + "LM:LINE:800,0>810,0", + "LN:ARC:c810,10r10a270>0", + "LQ:LWPOLYLINE:f0;900,0;910,0", + "LS:LINE:910,0>910,10", + "LZ:LINE:1000,0>1010,0", + "LG+:LINE:600,60>600,100", + "LP+:LWPOLYLINE:f0;15,200;20,200;20,220", + ]); + assert_eq!(table(&s, &original), want); +} + +#[test] +fn the_json_forms_return_the_kept_object_first() { + let mut s = Session::new(); + let l = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + let r = s.execute("break", &json!({ "handle": l.hex(), "p1": [20, 0], "p2": [30, 0] })).unwrap(); + let hs = r["handles"].as_array().unwrap(); + assert_eq!(hs.len(), 2); + assert_eq!(hs[0], l.hex()); + assert_eq!(handles(&s), vec![l, Handle::parse_hex(hs[1].as_str().unwrap()).unwrap()]); + let r = s.execute("breakatpoint", &json!({ "handle": l.hex(), "at": [10, 0] })).unwrap(); + assert_eq!(r["handles"][0], l.hex()); + // Undo puts the line back, whole, under its own handle. + s.execute("u", &json!({})).unwrap(); + s.execute("u", &json!({})).unwrap(); + assert_eq!(table(&s, &[l]), ["0:LINE:0,0>100,0"]); +} + +#[test] +fn the_new_piece_goes_to_the_space_of_the_object() { + // A paper space line broken through the JSON form while model space is current. + let mut s = Session::new(); + let paper = Space::Paper("Layout1".into()); + let line = EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(100.0, 0.0, 0.0) }); + let l = s.doc_mut().unwrap().add(&paper, Common::default(), line).unwrap(); + s.execute("break", &json!({ "handle": l.hex(), "p1": [20, 0], "p2": [30, 0] })).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.model.iter().count(), 0); + let pieces: Vec = d.space(&paper).unwrap().iter().map(|e| e.handle).collect(); + assert_eq!(pieces.len(), 2); + assert_eq!(pieces[0], l); +} + +#[test] +fn a_group_keeps_the_broken_object_and_not_the_new_piece() { + let mut s = Session::new(); + let a = first_handle(&s.execute("line", &json!({ "points": [[0, 50], [100, 50]] })).unwrap()); + let b = first_handle(&s.execute("line", &json!({ "points": [[50, 0], [50, 100]] })).unwrap()); + s.execute("group", &json!({ "name": "G1", "handles": [a.hex(), b.hex()] })).unwrap(); + s.execute("break", &json!({ "handle": b.hex(), "p1": [50, 20], "p2": [50, 30] })).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.model.iter().count(), 3); + assert_eq!(d.groups.iter().find(|g| g.name == "G1").unwrap().members, vec![a, b]); +} + +fn hatch(s: &Session, h: Handle) -> Hatch { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Hatch(x) => x.clone(), + k => panic!("not a hatch: {k:?}"), + } +} + +fn loop_points(h: &Hatch) -> Vec> { + h.loops.iter().map(|l| l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()).collect() +} + +#[test] +fn a_hatch_whose_polyline_is_broken_open_keeps_its_shape_and_loses_its_link() { + let mut s = Session::new(); + let k = first_handle(&s.execute("pline", &json!({ "vertices": [[500, 0], [520, 0], [520, 20], [500, 20]], "closed": true })).unwrap()); + let h = first_handle(&s.execute("hatch", &json!({ "handles": [k.hex()] })).unwrap()); + assert!(hatch(&s, h).associative); + let square = loop_points(&hatch(&s, h)); + s.execute("break", &json!({ "handle": k.hex(), "p1": [510, 0], "p2": [520, 10] })).unwrap(); + assert!(matches!(&s.doc().unwrap().entity(k).unwrap().kind, EntityKind::LwPolyline(p) if !p.closed)); + let after = hatch(&s, h); + assert!(!after.associative); + assert_eq!(loop_points(&after), square); + s.execute("u", &json!({})).unwrap(); + assert!(hatch(&s, h).associative); +} + +#[test] +fn a_hatch_whose_boundary_line_is_trimmed_keeps_its_shape_and_loses_its_link() { + let mut s = Session::new(); + let sides = [ + line(&mut s, "0", [500.0, 0.0], [520.0, 0.0]), + line(&mut s, "0", [520.0, 0.0], [520.0, 20.0]), + line(&mut s, "0", [520.0, 20.0], [500.0, 20.0]), + line(&mut s, "0", [500.0, 20.0], [500.0, 0.0]), + ]; + let h = first_handle(&s.execute("hatch", &json!({ "points": [[510, 10]] })).unwrap()); + assert!(hatch(&s, h).associative); + let square = loop_points(&hatch(&s, h)); + let k1 = line(&mut s, "0", [505.0, -5.0], [505.0, 5.0]); + let k2 = line(&mut s, "0", [515.0, -5.0], [515.0, 5.0]); + let before = handles(&s); + s.execute("trim", &json!({ "handle": sides[0].hex(), "pick": [510, 0], "edges": [k1.hex(), k2.hex()] })).unwrap(); + let after = handles(&s); + assert_eq!(after[..before.len()], before[..]); + assert_eq!(after.len(), before.len() + 1); + let hh = hatch(&s, h); + assert!(!hh.associative); + assert_eq!(loop_points(&hh), square); +} + +fn dim(s: &Session, h: Handle) -> Dimension { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Dimension(d) => d.clone(), + k => panic!("not a dimension: {k:?}"), + } +} + +fn attachments(d: &Dimension) -> Vec<(String, Handle, AssocSnap)> { + let mut v: Vec<(String, Handle, AssocSnap)> = d.assoc.iter().map(|a: &DimAssoc| (a.point.clone(), a.handle, a.snap.clone())).collect(); + v.sort_by(|a, b| a.0.cmp(&b.0)); + v +} + +fn origins(d: &Dimension) -> [(f64, f64); 2] { + [(d.p13.x, d.p13.y), (d.p14.x, d.p14.y)] +} + +/// A vertical line from (x, 0) to (x, 100) with a linear dimension attached to both its ends. +fn dimensioned_line(s: &mut Session, x: f64) -> (Handle, Handle) { + let l = first_handle(&s.execute("line", &json!({ "points": [[x, 0], [x, 100]] })).unwrap()); + let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [x, 0], "p2": [x, 100], "at": [x + 20.0, 50] })).unwrap()); + assert_eq!(attachments(&dim(s, d)), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); + (l, d) +} + +#[test] +fn a_dimension_across_a_line_broken_in_its_middle_stays_on_both_ends() { + // Measured: the reference to the line's end moves to the new piece, the dimension is unchanged. + let mut s = Session::new(); + let (l, d) = dimensioned_line(&mut s, 50.0); + run(&mut s, &["BREAK 50,20 50,30"]); + let piece = *handles(&s).last().unwrap(); + assert!(piece != l && piece != d); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), piece, AssocSnap::End)]); + assert_eq!(origins(&dm), [(50.0, 0.0), (50.0, 100.0)]); + s.execute("u", &json!({})).unwrap(); + assert_eq!(attachments(&dim(&s, d)), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); +} + +#[test] +fn a_dimension_on_a_trimmed_off_end_follows_the_new_end() { + // Measured: the references stay on the line, the dimension measures 40 instead of 100. + let mut s = Session::new(); + let (l, d) = dimensioned_line(&mut s, 650.0); + let edge = first_handle(&s.execute("line", &json!({ "points": [[640, 40], [660, 40]] })).unwrap()); + s.execute("trim", &json!({ "handle": l.hex(), "pick": [650, 80], "edges": [edge.hex()] })).unwrap(); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); + assert_eq!(origins(&dm), [(650.0, 0.0), (650.0, 40.0)]); +} + +#[test] +fn a_dimension_on_a_broken_off_start_follows_the_new_start() { + // Measured: BREAK from the start to (650, 20); the dimension starts at (650, 20). + let mut s = Session::new(); + let (l, d) = dimensioned_line(&mut s, 650.0); + run(&mut s, &["BREAK 650,10 F 650,0 650,20"]); + assert_eq!(handles(&s), [l, d]); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]); + assert_eq!(origins(&dm), [(650.0, 20.0), (650.0, 100.0)]); +} + +#[test] +fn a_dimension_follows_a_piece_a_later_pick_of_the_same_trim_shortens() { + // The measured rules pick by pick: the first pick moves the reference to the line's end onto + // the new piece, the second cuts that end off, so the dimension ends at the piece's new end. + let mut s = Session::new(); + let other = first_handle(&s.execute("line", &json!({ "points": [[0, 20], [0, 30]] })).unwrap()); + let l = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + for x in [40, 60, 80] { + s.execute("line", &json!({ "points": [[x, -5], [x, 5]] })).unwrap(); + } + let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [0, 30], "p2": [100, 0], "at": [50, 60] })).unwrap()); + assert_eq!(attachments(&dim(&s, d)), [("p13".into(), other, AssocSnap::End), ("p14".into(), l, AssocSnap::End)]); + s.script("TRIM 50,0 90,0\n\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let piece = *handles(&s).last().unwrap(); + assert_eq!(table(&s, &[l]).last().unwrap(), "0+:LINE:60,0>80,0"); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), other, AssocSnap::End), ("p14".into(), piece, AssocSnap::End)]); + assert_eq!(origins(&dm), [(0.0, 30.0), (80.0, 0.0)]); +} + +#[test] +fn a_dimension_on_a_closed_polyline_opened_by_break_keeps_its_vertices() { + // The vertices it measured are still vertices of the polyline, numbered from the break. + let mut s = Session::new(); + let k = first_handle(&s.execute("pline", &json!({ "vertices": [[500, 0], [520, 0], [520, 20], [500, 20]], "closed": true })).unwrap()); + let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [500, 20], "p2": [520, 20], "at": [510, 40] })).unwrap()); + assert_eq!(attachments(&dim(&s, d)), [("p13".into(), k, AssocSnap::Vertex { index: 3 }), ("p14".into(), k, AssocSnap::Vertex { index: 2 })]); + s.execute("break", &json!({ "handle": k.hex(), "p1": [510, 0], "p2": [520, 10] })).unwrap(); + let dm = dim(&s, d); + assert_eq!(attachments(&dm), [("p13".into(), k, AssocSnap::Vertex { index: 2 }), ("p14".into(), k, AssocSnap::Vertex { index: 1 })]); + assert_eq!(origins(&dm), [(500.0, 20.0), (520.0, 20.0)]); + // Still attached: moving the polyline takes the dimension along. + s.execute("move", &json!({ "handles": [k.hex()], "delta": [0, 10] })).unwrap(); + assert_eq!(origins(&dim(&s, d)), [(500.0, 30.0), (520.0, 30.0)]); +} + +#[test] +fn constraints_on_a_broken_object_go_and_leave_the_others_where_they_are() { + let mut s = Session::new(); + let a = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + let b = first_handle(&s.execute("line", &json!({ "points": [[100, 0], [100, 50]] })).unwrap()); + s.execute("geomconstraint", &json!({ "type": "coincident", "h1": a.hex(), "p1": "end", "h2": b.hex(), "p2": "start" })).unwrap(); + s.execute("break", &json!({ "handle": a.hex(), "p1": [40, 0], "p2": [60, 0] })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.constraints.is_empty()); + let original = [a, b]; + assert_eq!(table(&s, &original), ["0:LINE:0,0>40,0", "0:LINE:100,0>100,50", "0+:LINE:60,0>100,0"]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 5c0a37f45..a4c72a878 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -18,6 +18,7 @@ mod blockreplace; mod break_closed_polyline; mod break_join_locked_layers; mod break_keeps_z; +mod break_trim_keep_handle; mod burst; mod chprop_command; mod compare_export; From 4c875d949e7762b2126f312154e8ac929a570b53 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:12:08 +0700 Subject: [PATCH 129/531] fix(modify): BREAK and TRIM on closed and self-cutting polylines, keeping Z BREAK on a closed polyline removes the stretch between the two points that doesn't run through the start vertex, whichever point comes first; at one point (or BREAKATPOINT) it splits the polyline in two, and at the start vertex leaves it closed. In Standard mode, or when picked as an edge, a polyline that is one of the cutting edges is also cut at its own vertices and crossings. Pieces keep a line's Z, an arc's centre Z and a polyline's elevation, constant width and linetype generation, for TRIM as for BREAK. All measured in AutoCAD 2024 except Quick mode's implicit edges, which keep leaving the polyline out. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/break_join.rs | 42 ++- crates/engine/src/cmd/modify/trim.rs | 100 ++++++- crates/engine/src/cmd/trimextend.rs | 4 +- .../engine/tests/it/break_closed_polyline.rs | 14 +- .../tests/it/break_trim_polyline_rules.rs | 247 ++++++++++++++++++ crates/engine/tests/it/main.rs | 2 + .../engine/tests/it/trim_keeps_z_and_width.rs | 102 ++++++++ 8 files changed, 473 insertions(+), 40 deletions(-) create mode 100644 crates/engine/tests/it/break_trim_polyline_rules.rs create mode 100644 crates/engine/tests/it/trim_keeps_z_and_width.rs diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 8b26270da..02a9ab770 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -82,7 +82,7 @@ pub fn specs() -> Vec { .menu(&["Modify", "Trim"]) .alias(&["tr"]) .params( - "{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)", + "{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex] (default: every object; a polyline that is one of them, or every object in Standard mode, also cuts itself at its vertices and crossings), edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)", ) .interactive(|_| Ok(Box::new(TrimM::new(false)))), CommandSpec::new("extend", "Extend", trimextend::run_extend) diff --git a/crates/engine/src/cmd/modify/break_join.rs b/crates/engine/src/cmd/modify/break_join.rs index 0309fe972..1aefa2c05 100644 --- a/crates/engine/src/cmd/modify/break_join.rs +++ b/crates/engine/src/cmd/modify/break_join.rs @@ -4,16 +4,6 @@ use super::{ Value, Vec2, arc, bad, json, lwpoly, norm_angle, point_param, point_req, targets, }; -/// Gives a rebuilt arc piece its source centre Z, or a rebuilt polyline piece its source elevation. -fn with_z(mut k: EntityKind, z: f64) -> EntityKind { - match &mut k { - EntityKind::Arc(a) => a.center.z = z, - EntityKind::LwPolyline(p) => p.elevation = z, - _ => {} - } - k -} - /// Break `h` between two points (or at one point when p1 == p2). pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result> { if crate::cmd::curves::is_locked(s, h) { @@ -44,7 +34,7 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re let a1 = c.center.xy().angle_to(p1); let a2 = c.center.xy().angle_to(p2); // AutoCAD removes the CCW portion from the first to the second point. - vec![with_z(arc(&Arc::new(c.center.xy(), c.radius, a2, a1)), c.center.z)] + vec![arc(&Arc::new(c.center.xy(), c.radius, a2, a1))] } EntityKind::Arc(a) => { let ga = Arc::new(a.center.xy(), a.radius, a.start, a.end); @@ -55,10 +45,10 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re } let mut v = Vec::new(); if t1 > 1e-12 { - v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1)), a.center.z)); + v.push(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1))); } if t2 < ga.sweep() - 1e-12 { - v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end)), a.center.z)); + v.push(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end))); } v } @@ -81,24 +71,32 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re }; let (mut t1, mut t2) = (lp(p1), lp(p2)); if p.closed { - if (t1 - t2).abs() < 1e-9 { - return Err(EngineError::Other("Cannot break a closed polyline at a single point.".into())); + let (lo, hi) = if t1 <= t2 { (t1, t2) } else { (t2, t1) }; + let tol = 1e-9 * (1.0 + total); + if hi - lo < tol { + // One point: the outline opens at its start vertex and splits at the point; + // at the start vertex itself it stays whole and closed. + if lo < tol || lo > total - tol { + return Ok(vec![h]); + } + vec![lwpoly(sub_polyline(&segs, 0.0, lo), false), lwpoly(sub_polyline(&segs, lo, total), false)] + } else { + // The stretch between the points that doesn't run through the start vertex + // goes, whichever point came first; what is left runs from the later point + // round through the start vertex to the earlier one. + let doubled: Vec = segs.iter().chain(segs.iter()).copied().collect(); + vec![lwpoly(sub_polyline(&doubled, hi, lo + total), false)] } - // Like a circle: the stretch from the first point to the second, along the - // vertices, goes; what is left runs from the second point round to the first. - let doubled: Vec = segs.iter().chain(segs.iter()).copied().collect(); - let end = if t1 > t2 { t1 } else { t1 + total }; - vec![with_z(lwpoly(sub_polyline(&doubled, t2, end), false), p.elevation)] } else { if t1 > t2 { std::mem::swap(&mut t1, &mut t2); } let mut v = Vec::new(); if t1 > 1e-12 { - v.push(with_z(lwpoly(sub_polyline(&segs, 0.0, t1), false), p.elevation)); + v.push(lwpoly(sub_polyline(&segs, 0.0, t1), false)); } if t2 < total - 1e-12 { - v.push(with_z(lwpoly(sub_polyline(&segs, t2, total), false), p.elevation)); + v.push(lwpoly(sub_polyline(&segs, t2, total), false)); } v } diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index b61c5b0d2..ede201ff9 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -13,6 +13,10 @@ pub(crate) struct Edges<'a> { /// Implied edges (EDGEMODE 1): lines and the end segments of open polylines count as running /// on without end, arcs as whole circles. pub implied: bool, + /// Quick mode (TRIMEXTENDMODE 1), where `only: None` means every object but the one trimmed. + /// A trimmed polyline that is one of the edges cuts itself too: picked as one, or with every + /// object in Standard mode. + pub quick: bool, } /// All primitives of the cutting edges (excluding `exclude`). @@ -91,13 +95,15 @@ fn prim_to_segments(p: &Prim) -> Vec { } } -/// Trim `h` at the piece containing `pick`. Returns the handles that replace it. +/// Trim `h` at the piece containing `pick`. Returns what it became: its pieces, `h` first +/// ([`replace_with_pieces`]). pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result> { if crate::cmd::curves::is_locked(s, h) { return Err(EngineError::Other("The object is on a locked layer.".into())); } let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let cut = edge_segments(s, edges, h)?; + let itself = edges.only.map_or(!edges.quick, |o| o.contains(&h)); let pieces: Vec = match &e.kind { EntityKind::Line(l) => { let ln = Line::new(l.a.xy(), l.b.xy()); @@ -167,7 +173,7 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu } keep.into_iter().collect() } - EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?, + EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick, itself)?, k => crate::cmd::modify2::trim_other(k, &cut, pick)?, }; replace_with_pieces(s, h, pieces) @@ -181,19 +187,20 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu /// in its middle keeps its handle on the piece from its start point, the piece to its end point is /// new; a circle broken or trimmed becomes an arc with the circle's handle.) /// -/// Dimensions attached to the object follow [`crate::assoc::follow_pieces`]. Its parametric -/// constraints are removed: its new shape no longer meets them, and solving them again would move -/// the objects they tie it to. +/// Each piece keeps what the object had beyond its outline ([`inherit`]). Dimensions attached to +/// the object follow [`crate::assoc::follow_pieces`]. Its parametric constraints are removed: its +/// new shape no longer meets them, and solving them again would move the objects they tie it to. pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec) -> Result> { let d = s.doc_mut()?; - let mut pieces = pieces.into_iter(); - let Some(first) = pieces.next() else { + if pieces.is_empty() { d.remove_entity(h); return Ok(Vec::new()); - }; + } let (Some(space), Some(old)) = (d.space_of(h), d.entity(h).cloned()) else { return Err(EngineError::Other("no such object".into())); }; + let mut pieces = pieces.into_iter().map(|k| inherit(&old.kind, k)); + let Some(first) = pieces.next() else { return Ok(Vec::new()) }; d.modify_entity(h, |e| e.kind = first)?; let mut out = vec![h]; for kind in pieces { @@ -213,6 +220,31 @@ pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec EntityKind { + match (source, &mut piece) { + (EntityKind::Line(s), EntityKind::Line(p)) => { + let ln = Line::new(s.a.xy(), s.b.xy()); + if ln.len() > 0.0 { + let z = |t: f64| s.a.z + (s.b.z - s.a.z) * t; + p.a.z = z(ln.param_of(p.a.xy())); + p.b.z = z(ln.param_of(p.b.xy())); + } + } + (EntityKind::Arc(s), EntityKind::Arc(p)) => p.center.z = s.center.z, + (EntityKind::Circle(s), EntityKind::Arc(p)) => p.center.z = s.center.z, + (EntityKind::LwPolyline(s), EntityKind::LwPolyline(p)) => { + p.elevation = s.elevation; + p.const_width = s.const_width; + p.plinegen = s.plinegen; + } + _ => {} + } + piece +} + /// Sub-polyline between length parameters `a` and `b` (open polylines). pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec { let mut out: Vec = Vec::new(); @@ -245,7 +277,53 @@ pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec out } -fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> Result> { +/// Upper bounds on the segments of a polyline searched for crossings with itself (the pairs grow +/// with the square) and on the crossings kept (hostile files); a longer polyline still cuts itself +/// at its vertices. +const MAX_SELF_CROSSING_SEGMENTS: usize = 2048; +const MAX_SELF_CROSSINGS: usize = 10_000; + +/// Where a polyline cuts itself, as lengths along it: the vertices between its segments (every +/// vertex of a closed one, its start included) and the points where two of its segments cross. +/// AutoCAD 2024 trims a polyline that is one of the cutting edges at these. +fn self_cuts(segs: &[Segment], closed: bool) -> Vec { + let mut starts = Vec::with_capacity(segs.len()); + let mut acc = 0.0; + for s in segs { + starts.push(acc); + acc += s.len(); + } + let mut ts: Vec = starts.iter().copied().skip(usize::from(!closed)).collect(); + if segs.len() > MAX_SELF_CROSSING_SEGMENTS { + return ts; + } + let inside = |t: f64| t > 1e-9 && t < 1.0 - 1e-9; + let parts: Vec<_> = segs.iter().zip(starts).map(|(s, t0)| (s, s.bounds(), t0)).collect(); + let mut crossings = 0; + for (i, (a, box_a, a0)) in parts.iter().enumerate() { + for (b, box_b, b0) in parts.iter().skip(i + 1) { + if !box_a.intersects(box_b) { + continue; + } + for x in intersect_ext(a, b, false) { + let (ta, tb) = (param_on(a, x), param_on(b, x)); + if inside(ta) && inside(tb) { + ts.push(a0 + ta * a.len()); + ts.push(b0 + tb * b.len()); + crossings += 1; + if crossings >= MAX_SELF_CROSSINGS { + return ts; + } + } + } + } + } + ts +} + +/// Trim a polyline at the piece containing `pick`, between the cuts by `cut` and, when it is one +/// of the cutting edges (`itself`), by its own vertices and crossings ([`self_cuts`]). +fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result> { let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; let segs = pl.segments(); let total: f64 = segs.iter().map(Segment::len).sum(); @@ -266,6 +344,10 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> R acc += len; } ts.retain(|t| *t > 1e-9 && *t < total - 1e-9); + if itself { + // A closed polyline also cuts itself at its start vertex. + ts.extend(self_cuts(&segs, p.closed).into_iter().filter(|t| (*t > 1e-9 || p.closed) && *t < total - 1e-9)); + } ts.sort_by(f64::total_cmp); if ts.is_empty() { return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index eab957589..922d28dd6 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -173,7 +173,6 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result { let cmd = if extending { "extend" } else { "trim" }; let only: Option> = p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().and_then(Handle::parse_hex)).collect()); - let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? }; let quick = match p.get("mode") { None | Some(Value::Null) => false, Some(v) => match v.as_str().map(|m| m.trim().to_ascii_lowercase()).as_deref() { @@ -182,6 +181,7 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result { _ => return Err(bad(cmd, "`mode` must be \"quick\" or \"standard\"")), }, }; + let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)?, quick }; let key = if extending { "extended" } else { "trimmed" }; if p.get("fence").is_some_and(|v| !v.is_null()) { let pts = points_param(p, "fence") @@ -243,7 +243,7 @@ impl TrimM { TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new() } } fn edges(&self, quick: bool, implied: bool) -> Edges<'_> { - Edges { only: self.edges.as_deref(), implied: !quick && implied } + Edges { only: self.edges.as_deref(), implied: !quick && implied, quick } } fn select_edges(&mut self, s: &mut Session) { s.echo(if self.extend { "Select boundary edges ..." } else { "Select cutting edges ..." }); diff --git a/crates/engine/tests/it/break_closed_polyline.rs b/crates/engine/tests/it/break_closed_polyline.rs index fabfb5305..46a36299e 100644 --- a/crates/engine/tests/it/break_closed_polyline.rs +++ b/crates/engine/tests/it/break_closed_polyline.rs @@ -1,5 +1,6 @@ -//! BREAK on a closed polyline removes the stretch from the first to the second point along the -//! vertex direction and leaves one open polyline (#1173). +//! BREAK on a closed polyline removes the stretch between the two points that doesn't run +//! through its start vertex, whichever point comes first, and leaves one open polyline from the +//! later point round to the earlier one (#1173; AutoCAD 2024, accoreconsole). use cadcraft_doc::{EntityKind, LwPolyline}; use cadcraft_engine::Session; @@ -38,14 +39,15 @@ fn break_opens_a_closed_polyline_at_the_command_line() { } #[test] -fn break_json_on_a_closed_polyline_follows_the_order_of_the_points() { +fn break_json_on_a_closed_polyline_ignores_the_order_of_the_points() { let mut s = Session::new(); let r = closed_rect(&mut s); - // Second point before the first along the vertices: the long way round goes, the short - // stretch between them stays. + // Second point before the first along the vertices: the same stretch goes as with the points + // the other way round (measured with the first point after the second, and both ways on a + // 100 x 10 rectangle broken at (10, 0) and (10, 10), where the long stretch went). s.execute("break", &json!({ "handle": r["handle"], "p1": [100, 30], "p2": [50, 0] })).unwrap(); let ps = polys(&s); assert_eq!(ps.len(), 1); assert!(!ps[0].closed); - assert_eq!(pts(&ps[0]), vec![(50.0, 0.0), (100.0, 0.0), (100.0, 30.0)]); + assert_eq!(pts(&ps[0]), vec![(100.0, 30.0), (100.0, 60.0), (0.0, 60.0), (0.0, 0.0), (50.0, 0.0)]); } diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs new file mode 100644 index 000000000..519a24664 --- /dev/null +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -0,0 +1,247 @@ +//! BREAK on a closed polyline and TRIM of a polyline that is one of its own cutting edges, as +//! AutoCAD 2024 does them (measured with accoreconsole on these drawings): +//! +//! - BREAK between two points of a closed polyline removes the stretch between them that doesn't +//! run through its start vertex, whichever point comes first; BREAK or BREAKATPOINT at one point +//! splits it there into two open polylines, and at its start vertex leaves it closed. +//! - In Standard mode, a polyline that is one of the cutting edges (picked, or with every object) +//! is also cut at its own vertices and where it crosses itself. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle}; +use serde_json::{Value, json}; + +type Vertex = (f64, f64, f64); + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle { + handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap()) +} + +fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle { + handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap()) +} + +/// Every polyline in model space in order: its handle, closed flag and vertices with bulges. +fn polys(s: &Session) -> Vec<(Handle, bool, Vec)> { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::LwPolyline(p) => Some((e.handle, p.closed, p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect())), + _ => None, + }) + .collect() +} + +fn same(got: &[Vertex], want: &[Vertex]) -> bool { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-9) +} + +/// The polylines are `want` in order, (`kept`, closed, vertices): `kept` is whether it has the +/// handle `h`. +fn expect(s: &Session, h: Handle, want: &[(bool, bool, &[Vertex])]) { + let got = polys(s); + assert_eq!(got.len(), want.len(), "{got:?}"); + for ((gh, gc, gv), (kept, closed, wv)) in got.iter().zip(want) { + assert_eq!((*gh == h, *gc), (*kept, *closed), "{got:?}"); + assert!(same(gv, wv), "{gv:?} != {wv:?}"); + } +} + +fn run(s: &mut Session, script: &str) { + s.script(script).unwrap(); + assert!(s.running.is_none(), "{script}: {}", s.prompt_text()); +} + +// ---------------- BREAK on a closed polyline ---------------- + +#[test] +fn break_removes_the_stretch_between_the_points_that_misses_the_start_vertex() { + // 100 x 10 rectangle broken at (10, 0) and (10, 10): the 190-unit stretch between them goes, + // the 20 units across the start vertex stay, with the points either way round. + for script in ["BREAK 10,0 10,10\n", "BREAK 10,10 10,0\n"] { + let mut s = Session::new(); + let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true); + run(&mut s, script); + expect(&s, r, &[(true, false, &[(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]); + } +} + +#[test] +fn break_with_the_first_point_after_the_second_keeps_the_run_through_the_start() { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], { "p": [40, 0], "bulge": 0.5 }, [60, 0], [60, 30], [0, 30]]), true); + run(&mut s, "BREAK 60,20 10,0\n"); + expect(&s, p, &[(true, false, &[(60.0, 20.0, 0.0), (60.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]); +} + +const SQUARE: [[f64; 2]; 4] = [[250.0, 0.0], [270.0, 0.0], [270.0, 20.0], [250.0, 20.0]]; + +#[test] +fn break_at_one_point_splits_a_closed_polyline_in_two() { + let first: &[Vertex] = &[(250.0, 0.0, 0.0), (260.0, 0.0, 0.0)]; + let second: &[Vertex] = &[(260.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)]; + let mut s = Session::new(); + let p = pline(&mut s, json!(SQUARE), true); + run(&mut s, "BREAK 260,0 260,0\n"); + expect(&s, p, &[(true, false, first), (false, false, second)]); + // BREAKATPOINT does the same. + let mut s = Session::new(); + let p = pline(&mut s, json!(SQUARE), true); + let r = s.execute("breakatpoint", &json!({ "handle": p.hex(), "at": [260, 0] })).unwrap(); + assert_eq!(r["handles"].as_array().unwrap().len(), 2); + expect(&s, p, &[(true, false, first), (false, false, second)]); +} + +#[test] +fn break_at_a_vertex_splits_there_and_at_the_start_vertex_changes_nothing() { + let mut s = Session::new(); + let p = pline(&mut s, json!(SQUARE), true); + run(&mut s, "BREAK 270,20 270,20\n"); + expect( + &s, + p, + &[ + (true, false, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0)]), + (false, false, &[(270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)]), + ], + ); + let mut s = Session::new(); + let p = pline(&mut s, json!(SQUARE), true); + run(&mut s, "BREAK 250,0 250,0\n"); + expect(&s, p, &[(true, true, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0)])]); +} + +// ---------------- TRIM of a polyline that cuts itself ---------------- + +/// A polyline with an arc, and vertical lines at x = 20 and x = 60 crossing it. +fn arc_polyline(s: &mut Session) -> (Handle, Handle, Handle) { + let p = pline(s, json!([[0, 0], { "p": [40, 0], "bulge": 0.4 }, [70, 0], [90, 30]]), false); + let b = line(s, [20.0, -10.0], [20.0, 40.0]); + let c = line(s, [60.0, -20.0], [60.0, 40.0]); + (p, b, c) +} + +/// The piece from the x = 60 cut on the arc to the end, as measured. +const FROM_C: [Vertex; 3] = [(60.0, -5.417486860749438, 0.1330399827453447), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)]; + +fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: Option<&[Handle]>) { + let mut p = json!({ "handle": h.hex(), "pick": pick }); + if let Some(es) = edges { + p["edges"] = json!(es.iter().map(|e| e.hex()).collect::>()); + } + s.execute("trim", &p).unwrap(); +} + +#[test] +fn with_every_object_cutting_a_polyline_trims_to_its_own_vertex() { + let mut s = Session::new(); + let (p, ..) = arc_polyline(&mut s); + trim(&mut s, p, [55.0, -6.0], None); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]); +} + +#[test] +fn edges_that_leave_the_polyline_out_cut_only_where_they_cross_it() { + let mut s = Session::new(); + let (p, b, c) = arc_polyline(&mut s); + trim(&mut s, p, [55.0, -6.0], Some(&[b, c])); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 0.0, 0.0)]), (false, false, &FROM_C)]); +} + +#[test] +fn a_polyline_that_is_its_only_edge_loses_the_whole_segment_picked() { + let mut s = Session::new(); + let (p, ..) = arc_polyline(&mut s); + trim(&mut s, p, [55.0, -6.0], Some(&[p])); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &[(70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]); + // The first segment: one piece left, the polyline itself. + let mut s = Session::new(); + let (p, ..) = arc_polyline(&mut s); + trim(&mut s, p, [10.0, 0.0], Some(&[p])); + expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.4), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]); +} + +#[test] +fn a_closed_polyline_that_is_its_only_edge_opens_without_the_segment_picked() { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [40, 0], [40, 30], [0, 30]]), true); + trim(&mut s, p, [20.0, 0.0], Some(&[p])); + expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.0), (40.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0)])]); +} + +#[test] +fn a_polyline_crossing_itself_is_cut_at_the_crossing() { + let x = json!([[0, 0], [40, 20], [40, 0], [0, 20]]); + let mut s = Session::new(); + let p = pline(&mut s, x.clone(), false); + trim(&mut s, p, [10.0, 5.0], Some(&[p])); + expect(&s, p, &[(true, false, &[(20.0, 10.0, 0.0), (40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]); + // Every object (the polyline alone): cut between the crossing and the next vertex. + let mut s = Session::new(); + let p = pline(&mut s, x, false); + trim(&mut s, p, [30.0, 15.0], None); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 10.0, 0.0)]), (false, false, &[(40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]); +} + +#[test] +fn a_closed_polyline_at_survey_coordinates_trims_to_its_own_vertex() { + let mut s = Session::new(); + let p = pline( + &mut s, + json!([[612345.678, 2398765.432], { "p": [612385.678, 2398765.432], "bulge": 0.4 }, [612415.678, 2398765.432], [612415.678, 2398795.432], [612345.678, 2398795.432]]), + true, + ); + let b = line(&mut s, [612365.678, 2398755.432], [612365.678, 2398805.432]); + let c = line(&mut s, [612405.678, 2398745.432], [612405.678, 2398805.432]); + trim(&mut s, p, [612400.678, 2398759.432], Some(&[p, b, c])); + let got = polys(&s); + assert_eq!(got.len(), 1); + let (h, closed, vs) = &got[0]; + assert!(*h == p && !closed); + let want: [Vertex; 6] = [ + (612405.678, 2398760.014513139, 0.1330399827461127), + (612415.678, 2398765.432, 0.0), + (612415.678, 2398795.432, 0.0), + (612345.678, 2398795.432, 0.0), + (612345.678, 2398765.432, 0.0), + (612385.678, 2398765.432, 0.0), + ]; + // Survey coordinates: a micrometre on the points, the bulge to 1e-9. + assert_eq!(vs.len(), want.len()); + for (g, w) in vs.iter().zip(&want) { + assert!((g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-9, "{g:?} != {w:?}"); + } +} + +#[test] +fn standard_mode_at_the_command_line_with_every_object_cuts_at_the_polyline_vertex() { + let mut s = Session::new(); + let (p, ..) = arc_polyline(&mut s); + // Mode Standard, Enter: every object is a cutting edge. + run(&mut s, "TRIM O S\n\n55,-6\n\n"); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]); +} + +#[test] +fn a_polyline_picked_as_an_edge_in_quick_mode_cuts_itself_too() { + // Quick mode with the edges given (its cuTting edges option): picked is picked. + let mut s = Session::new(); + let (p, _, c) = arc_polyline(&mut s); + s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick", "edges": [p.hex(), c.hex()] })).unwrap(); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]); +} + +#[test] +fn quick_mode_still_cuts_only_at_other_objects() { + // Not measured: AutoCAD's scripted TRIM runs Standard mode only. + let mut s = Session::new(); + let (p, ..) = arc_polyline(&mut s); + s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick" })).unwrap(); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 0.0, 0.0)]), (false, false, &FROM_C)]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index a4c72a878..58c38b5f0 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -19,6 +19,7 @@ mod break_closed_polyline; mod break_join_locked_layers; mod break_keeps_z; mod break_trim_keep_handle; +mod break_trim_polyline_rules; mod burst; mod chprop_command; mod compare_export; @@ -143,6 +144,7 @@ mod tolerance; mod transparent; mod trim_closed_polyline; mod trim_extend_options; +mod trim_keeps_z_and_width; mod undo_count; mod undo_layout_tab; mod viewport_clip; diff --git a/crates/engine/tests/it/trim_keeps_z_and_width.rs b/crates/engine/tests/it/trim_keeps_z_and_width.rs new file mode 100644 index 000000000..1efea9194 --- /dev/null +++ b/crates/engine/tests/it/trim_keeps_z_and_width.rs @@ -0,0 +1,102 @@ +//! TRIM keeps what the object has beyond its outline, as BREAK does: a line's Z, an arc's centre +//! Z (a circle trimmed into an arc), a polyline's elevation, and a polyline's constant width on +//! every piece. The Z cases and the width on BREAK were measured in AutoCAD 2024 (accoreconsole) +//! on these drawings. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Circle, Common, Entity, EntityKind, Handle, Line, LwPolyline}; +use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3}; +use serde_json::json; + +fn add(s: &mut Session, kind: EntityKind, thickness: f64) -> Handle { + let space = s.space(); + let d = s.doc_mut().unwrap(); + let handle = d.new_handle(); + d.space_mut(&space).unwrap().push(Entity { handle, common: Common { thickness, ..Common::default() }, kind }); + handle +} + +fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle { + let v = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap() +} + +fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edge: Handle) { + s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": [edge.hex()] })).unwrap(); +} + +fn kind(s: &Session, h: Handle) -> EntityKind { + s.doc().unwrap().entity(h).unwrap().kind.clone() +} + +fn polyline(vertices: &[(f64, f64, f64)], const_width: f64, elevation: f64, plinegen: bool) -> EntityKind { + let vertices = vertices.iter().map(|&(x, y, bulge)| PolyVertex { bulge, ..PolyVertex::new(Vec2::new(x, y)) }).collect(); + EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width, elevation, plinegen }) +} + +fn near(a: Vec3, b: Vec3, tol: f64) -> bool { + (a.x - b.x).abs() < tol && (a.y - b.y).abs() < tol && (a.z - b.z).abs() < tol +} + +#[test] +fn trim_keeps_a_lines_z() { + let mut s = Session::new(); + let a = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.5, 0.25, 0.007), b: Vec3::new(0.54, 0.25, 0.007) }), 0.0); + let b = line(&mut s, [0.52, 0.24], [0.52, 0.26]); + trim(&mut s, a, [0.53, 0.25], b); + let EntityKind::Line(l) = kind(&s, a) else { panic!("not a line") }; + assert!(near(l.a, Vec3::new(0.5, 0.25, 0.007), 1e-12) && near(l.b, Vec3::new(0.52, 0.25, 0.007), 1e-12), "{l:?}"); +} + +#[test] +fn trim_keeps_the_centre_z_of_a_circle_made_an_arc() { + // At survey coordinates, with a thickness of 2. + let mut s = Session::new(); + let c = add(&mut s, EntityKind::Circle(Circle { center: Vec3::new(612345.678, 2398765.432, 5.0), radius: 10.0 }), 2.0); + let b = line(&mut s, [612350.678, 2398745.432], [612350.678, 2398785.432]); + trim(&mut s, c, [612335.678, 2398765.432], b); + let e = s.doc().unwrap().entity(c).unwrap().clone(); + let EntityKind::Arc(a) = &e.kind else { panic!("not an arc: {:?}", e.kind) }; + assert!(near(a.center, Vec3::new(612345.678, 2398765.432, 5.0), 1e-9), "{a:?}"); + assert!((a.start - 5.235987755978257).abs() < 1e-9 && (a.end - 1.047197551201328).abs() < 1e-9, "{a:?}"); + assert_eq!(e.common.thickness, 2.0); +} + +#[test] +fn trim_keeps_a_polylines_elevation() { + let mut s = Session::new(); + let p = add(&mut s, polyline(&[(0.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)], 0.0, 12.5, false), 1.0); + let b = line(&mut s, [10.0, -10.0], [10.0, 30.0]); + trim(&mut s, p, [5.0, 0.0], b); + let EntityKind::LwPolyline(l) = kind(&s, p) else { panic!("not a polyline") }; + assert_eq!(l.elevation, 12.5); + let want = [(10.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)]; + assert_eq!(l.vertices.len(), want.len()); + for (v, w) in l.vertices.iter().zip(want) { + assert!(near(Vec3::new(v.p.x, v.p.y, v.bulge), Vec3::new(w.0, w.1, w.2), 1e-12), "{v:?} != {w:?}"); + } +} + +#[test] +fn break_and_trim_keep_a_polylines_constant_width_on_every_piece() { + // Measured for BREAK: a width-2 polyline broken from (705, 0) to (735, 0) leaves two width-2 + // pieces. TRIM leaves its pieces the same way. Linetype generation is the polyline's setting + // too, so the pieces keep it (not measured). + let shape = [(700.0, 0.0, 0.0), (720.0, 0.0, 0.0), (740.0, 0.0, 0.0)]; + let mut s = Session::new(); + let p = add(&mut s, polyline(&shape, 2.0, 0.0, true), 0.0); + let r = s.execute("break", &json!({ "handle": p.hex(), "p1": [705, 0], "p2": [735, 0] })).unwrap(); + let mut s2 = Session::new(); + let q = add(&mut s2, polyline(&shape, 2.0, 0.0, true), 0.0); + let k1 = line(&mut s2, [705.0, -5.0], [705.0, 5.0]); + let k2 = line(&mut s2, [735.0, -5.0], [735.0, 5.0]); + let t = s2.execute("trim", &json!({ "handle": q.hex(), "pick": [720, 0], "edges": [k1.hex(), k2.hex()] })).unwrap(); + for (s, r) in [(&s, &r), (&s2, &t)] { + let hs = r["handles"].as_array().unwrap(); + assert_eq!(hs.len(), 2); + for h in hs { + let EntityKind::LwPolyline(l) = kind(s, Handle::parse_hex(h.as_str().unwrap()).unwrap()) else { panic!("not a polyline") }; + assert_eq!((l.const_width, l.plinegen), (2.0, true)); + } + } +} From 032a5dc3c782b03e81bd225d36c1a9641a174eae Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:19:01 +0700 Subject: [PATCH 130/531] feat(modify): BREAKATPOINT at the command line, as AutoCAD does BREAKATPOINT gets AutoCAD 2024's prompts ("Select object:", then "Specify break point:") and splits the object there; before, it only had its JSON form, so typing it, a script or the menu failed. BREAK and BREAKATPOINT now end the command when the break can't be made ("Arc cannot be full 360 degrees", no full stop, as measured), refuse an object on a locked layer when it is picked, and leave nothing selected after Enter. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify.rs | 7 +- crates/engine/src/cmd/modify/break_join.rs | 87 ++++++++++-- .../tests/it/breakatpoint_command_line.rs | 128 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 4 files changed, 209 insertions(+), 14 deletions(-) create mode 100644 crates/engine/tests/it/breakatpoint_command_line.rs diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 02a9ab770..c579e170a 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -25,7 +25,7 @@ mod stretch; mod transform; mod trim; -use break_join::{BreakM, run_break, run_breakat, run_join}; +use break_join::{BreakAtPointM, BreakM, run_break, run_breakat, run_join}; use explode::run_explode; pub(crate) use explode::{explode_kind, explode_with}; use fillet::{FilletM, run_chamfer, run_fillet}; @@ -110,7 +110,10 @@ pub fn specs() -> Vec { .alias(&["br"]) .params("{handle, p1, p2} → {handles: the object (kept, reshaped) then the new pieces; none when nothing is left}") .interactive(|_| Ok(Box::new(BreakM::default()))), - CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}"), + CommandSpec::new("breakatpoint", "Break At Point", run_breakat) + .menu(&["Modify", "Break At Point"]) + .params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}") + .interactive(|_| Ok(Box::new(BreakAtPointM::default()))), CommandSpec::new("join", "Join", run_join) .menu(&["Modify", "Join"]) .alias(&["j"]) diff --git a/crates/engine/src/cmd/modify/break_join.rs b/crates/engine/src/cmd/modify/break_join.rs index 1aefa2c05..fa49e4368 100644 --- a/crates/engine/src/cmd/modify/break_join.rs +++ b/crates/engine/src/cmd/modify/break_join.rs @@ -29,7 +29,7 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re } EntityKind::Circle(c) => { if p1.near(p2, 1e-12) { - return Err(EngineError::Other("Arc cannot be full 360 degrees.".into())); + return Err(EngineError::Other("Arc cannot be full 360 degrees".into())); } let a1 = c.center.xy().angle_to(p1); let a2 = c.center.xy().angle_to(p2); @@ -213,6 +213,41 @@ pub(super) fn run_join(s: &mut Session, p: &Value) -> Result { Ok(json!({ "handle": r.map(|h| h.hex()) })) } +/// The object picked at `p` for BREAK and BREAKATPOINT ("*Invalid selection*" when there is none). +/// One on a locked layer is refused there, and the command asks for an object again, as AutoCAD +/// 2024 does; the pick doesn't fall through to an object under it. +fn pick_to_break(s: &mut Session, p: Vec2) -> Result> { + let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; + let space = s.space(); + match s.pick_object(&space, p, ap)? { + Some(h) if crate::cmd::curves::is_locked(s, h) => { + s.echo("The object is on a locked layer."); + Ok(None) + } + Some(h) => { + s.set_selection(vec![h]); + Ok(Some(h)) + } + None => { + s.echo("*Invalid selection*"); + Ok(None) + } + } +} + +/// Break `h` from `p1` to `p2` and end the command. As in AutoCAD 2024, a break that can't be made +/// (a whole circle at one point: "Arc cannot be full 360 degrees") is reported and ends the +/// command too, leaving the object as it was. +fn break_and_end(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result { + match break_entity(s, h, p1, p2) { + Ok(_) => {} + Err(EngineError::Other(m)) => s.echo(m), + Err(e) => return Err(e), + } + s.set_selection(Vec::new()); + Ok(Step::Done) +} + #[derive(Default)] pub(super) struct BreakM { obj: Option<(Handle, Vec2)>, @@ -234,14 +269,8 @@ impl Interactive for BreakM { fn input(&mut self, s: &mut Session, i: Input) -> Result { match (self.obj, i) { (None, Input::Point(p)) => { - let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; - let space = s.space(); - match s.pick_object(&space, p, ap)? { - Some(h) => { - self.obj = Some((h, p)); - s.set_selection(vec![h]); - } - None => s.echo("*Invalid selection*"), + if let Some(h) = pick_to_break(s, p)? { + self.obj = Some((h, p)); } Ok(Step::Continue) } @@ -254,12 +283,46 @@ impl Interactive for BreakM { self.first_point = false; Ok(Step::Continue) } - (Some((h, p1)), Input::Point(p2)) => { - break_entity(s, h, p1, p2)?; + (Some((h, p1)), Input::Point(p2)) => break_and_end(s, h, p1, p2), + (Some(_), Input::Enter) => { s.set_selection(Vec::new()); Ok(Step::Done) } - (_, Input::Enter) => Ok(Step::Done), + (None, Input::Enter) => Ok(Step::Done), + _ => Ok(Step::Continue), + } + } +} + +/// BREAKATPOINT at the command line, with AutoCAD 2024's prompts: "Select object:", then "Specify +/// break point:"; the object is split there with no gap (the point projects onto it). +#[derive(Default)] +pub(super) struct BreakAtPointM { + obj: Option, +} + +impl Interactive for BreakAtPointM { + fn name(&self) -> &'static str { + "BREAKATPOINT" + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.obj { + None => Prompt::new("Select object", Accept::POINT), + Some(_) => Prompt::new("Specify break point", Accept::POINT), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match (self.obj, i) { + (None, Input::Point(p)) => { + self.obj = pick_to_break(s, p)?; + Ok(Step::Continue) + } + (Some(h), Input::Point(p)) => break_and_end(s, h, p, p), + (Some(_), Input::Enter) => { + s.set_selection(Vec::new()); + Ok(Step::Done) + } + (None, Input::Enter) => Ok(Step::Done), _ => Ok(Step::Continue), } } diff --git a/crates/engine/tests/it/breakatpoint_command_line.rs b/crates/engine/tests/it/breakatpoint_command_line.rs new file mode 100644 index 000000000..ff0bd47d3 --- /dev/null +++ b/crates/engine/tests/it/breakatpoint_command_line.rs @@ -0,0 +1,128 @@ +//! BREAKATPOINT at the command line and from a script, with AutoCAD 2024's prompts ("Select +//! object:", then "Specify break point:"); BREAK and BREAKATPOINT end the command when a circle +//! can't be broken at one point, and refuse an object on a locked layer when it is picked. Measured +//! in AutoCAD 2024 (accoreconsole) on these drawings. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle}; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +/// The model space objects in order: handle and kind. +fn objects(s: &Session) -> Vec<(Handle, EntityKind)> { + s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect() +} + +fn line_ends(k: &EntityKind) -> ((f64, f64), (f64, f64)) { + let EntityKind::Line(l) = k else { panic!("not a line: {k:?}") }; + ((l.a.x, l.a.y), (l.b.x, l.b.y)) +} + +#[test] +fn breakatpoint_asks_for_the_object_then_the_point_and_splits_the_line_there() { + let mut s = Session::new(); + let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap()); + s.cmdline("BREAKATPOINT").unwrap(); + assert!(s.prompt_text().ends_with("Select object:"), "{}", s.prompt_text()); + s.cmdline("1002,0").unwrap(); + assert!(s.prompt_text().ends_with("Specify break point:"), "{}", s.prompt_text()); + // Off the line: the point projects onto it. + s.cmdline("1005,3").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let objs = objects(&s); + assert_eq!(objs.len(), 2); + assert_eq!(objs[0].0, l); + assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0))); + assert_eq!(line_ends(&objs[1].1), ((1005.0, 0.0), (1010.0, 0.0))); +} + +#[test] +fn breakatpoint_from_a_script_splits_an_arc_and_a_closed_polyline() { + let mut s = Session::new(); + let a = handle(&s.execute("arc", &json!({ "center": [700, 0], "radius": 10, "start": 0, "end": 90 })).unwrap()); + let p = handle(&s.execute("pline", &json!({ "vertices": [[250, 0], [270, 0], [270, 20], [250, 20]], "closed": true })).unwrap()); + s.script("BREAKATPOINT 707.0710678,7.0710678 707.0710678,7.0710678\nBREAKATPOINT 260,0 260,0\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let objs = objects(&s); + assert_eq!(objs.iter().map(|o| o.0).take(2).collect::>(), [a, p]); + let EntityKind::Arc(arc) = &objs[0].1 else { panic!("not an arc") }; + assert!((arc.start - 0.0).abs() < 1e-9 && (arc.end.to_degrees() - 45.0).abs() < 1e-6, "{arc:?}"); + let EntityKind::Arc(rest) = &objs[2].1 else { panic!("not an arc") }; + assert!((rest.start.to_degrees() - 45.0).abs() < 1e-6 && (rest.end.to_degrees() - 90.0).abs() < 1e-9, "{rest:?}"); + let pts = |k: &EntityKind| match k { + EntityKind::LwPolyline(l) => (l.closed, l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect::>()), + k => panic!("not a polyline: {k:?}"), + }; + assert_eq!(pts(&objs[1].1), (false, vec![(250.0, 0.0), (260.0, 0.0)])); + assert_eq!(pts(&objs[3].1), (false, vec![(260.0, 0.0), (270.0, 0.0), (270.0, 20.0), (250.0, 20.0), (250.0, 0.0)])); +} + +#[test] +fn breakatpoint_and_break_at_one_point_of_a_circle_report_it_and_end() { + for script in ["BREAKATPOINT 1300,10 1300,10\n", "BREAK 1300,10 1300,10\n"] { + let mut s = Session::new(); + let c = handle(&s.execute("circle", &json!({ "center": [1300, 0], "radius": 10 })).unwrap()); + s.script(script).unwrap(); + assert!(s.running.is_none(), "{script}: {}", s.prompt_text()); + assert!(s.log.iter().any(|l| l == "Arc cannot be full 360 degrees"), "{script}: {:?}", s.log); + let objs = objects(&s); + assert_eq!(objs.len(), 1); + assert!(objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}"); + } +} + +#[test] +fn enter_ends_breakatpoint_and_leaves_nothing_selected() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + s.script("BREAKATPOINT\n\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + // Enter at the break point after picking: the line is not left selected. + s.script("BREAKATPOINT 5,0\n\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert!(s.selection().is_empty()); + assert_eq!(objects(&s).len(), 1); +} + +#[test] +fn an_object_on_a_locked_layer_is_refused_when_picked() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + s.execute("layer.set", &json!({ "name": "0", "locked": true })).unwrap(); + for cmd in ["BREAKATPOINT", "BREAK"] { + s.cmdline(cmd).unwrap(); + s.cmdline("5,0").unwrap(); + assert!(s.prompt_text().ends_with("Select object:"), "{cmd}: {}", s.prompt_text()); + assert!(s.log.iter().any(|l| l == "The object is on a locked layer."), "{cmd}: {:?}", s.log); + s.cmdline("").unwrap(); + assert!(s.running.is_none(), "{cmd}: {}", s.prompt_text()); + } + assert_eq!(objects(&s).len(), 1); +} + +#[test] +fn breakatpoint_from_lisp_with_a_bare_entity_name() { + let mut s = Session::new(); + let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap()); + s.cmdline("(command \"_.BREAKATPOINT\" (entlast) '(1004.0 0.0))").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let objs = objects(&s); + assert_eq!(objs.len(), 2); + assert_eq!(objs[0].0, l); + assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1004.0, 0.0))); +} + +#[test] +fn breakatpoint_from_lisp_with_an_entity_and_point() { + let mut s = Session::new(); + let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap()); + s.cmdline("(command \"_.BREAKATPOINT\" (list (entlast) '(1005.0 0.0)) '(1005.0 0.0))").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let objs = objects(&s); + assert_eq!(objs.len(), 2); + assert_eq!(objs[0].0, l); + assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0))); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 58c38b5f0..cda13decd 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -20,6 +20,7 @@ mod break_join_locked_layers; mod break_keeps_z; mod break_trim_keep_handle; mod break_trim_polyline_rules; +mod breakatpoint_command_line; mod burst; mod chprop_command; mod compare_export; From a84de561834f97c4b76e185335b2bdc97a1c2503 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Legrand?= Date: Sat, 31 Oct 2026 15:31:08 +0100 Subject: [PATCH 131/531] refactor(color): satisfy Clippy pedantic lints --- crates/color/src/lib.rs | 64 +++++++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index e99f8d269..ea58d63ab 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -1,5 +1,5 @@ //! CAD colours: the 256-entry colour index (ACI), 24-bit true colour, and the logical -//! ByLayer / ByBlock values. The index palette is generated from its well-known structure +//! `ByLayer` / `ByBlock` values. The index palette is generated from its well-known structure //! (24 hues × 5 values × 2 saturations, plus primaries and greys), not copied from any file. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -11,12 +11,15 @@ use serde::{Deserialize, Serialize}; pub struct Rgb(pub u8, pub u8, pub u8); impl Rgb { + #[must_use] pub fn to_u32(self) -> u32 { (u32::from(self.0) << 16) | (u32::from(self.1) << 8) | u32::from(self.2) } + #[must_use] pub fn from_u32(v: u32) -> Rgb { Rgb(((v >> 16) & 0xff) as u8, ((v >> 8) & 0xff) as u8, (v & 0xff) as u8) } + #[must_use] pub fn hex(self) -> String { format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2) } @@ -29,6 +32,7 @@ impl Rgb { u32::from_str_radix(s, 16).ok().map(Rgb::from_u32) } /// Relative luminance (0..1) for contrast decisions. + #[must_use] pub fn luma(self) -> f64 { (0.2126 * f64::from(self.0) + 0.7152 * f64::from(self.1) + 0.0722 * f64::from(self.2)) / 255.0 } @@ -48,7 +52,8 @@ pub enum Color { impl Color { pub const WHITE: Color = Color::Index(7); - /// DXF group 62 value: 0 = ByBlock, 256 = ByLayer. + /// DXF group 62 value: 0 = `ByBlock`, 256 = `ByLayer`. + #[must_use] pub fn to_aci(self) -> i16 { match self { Color::ByLayer => 256, @@ -57,14 +62,16 @@ impl Color { Color::True(rgb) => i16::from(nearest_aci(rgb)), } } + #[must_use] pub fn from_aci(v: i16) -> Color { match v { 0 => Color::ByBlock, - 1..=255 => Color::Index(v as u8), + 1..=255 => u8::try_from(v).map_or(Color::ByLayer, Color::Index), _ => Color::ByLayer, } } /// Resolve to RGB given the layer and block colours. + #[must_use] pub fn resolve(self, layer: Color, block: Color) -> Rgb { match self { Color::ByLayer => match layer { @@ -79,7 +86,8 @@ impl Color { Color::True(c) => c, } } - /// Short display name like AutoCAD's Properties palette ("ByLayer", "Red", "Color 34", "255,128,0"). + /// Short display name like `AutoCAD`'s Properties palette ("`ByLayer`", "Red", "Color 34", "255,128,0"). + #[must_use] pub fn name(self) -> String { match self { Color::ByLayer => "ByLayer".into(), @@ -102,7 +110,7 @@ impl Color { let t = s.trim().to_ascii_lowercase(); let named = ["", "red", "yellow", "green", "cyan", "blue", "magenta", "white"]; if let Some(i) = named.iter().position(|n| !n.is_empty() && *n == t) { - return Some(Color::Index(i as u8)); + return u8::try_from(i).ok().map(Color::Index); } match t.as_str() { "bylayer" => return Some(Color::ByLayer), @@ -117,7 +125,7 @@ impl Color { return match i { 0 => Some(Color::ByBlock), 256 => Some(Color::ByLayer), - 1..=255 => Some(Color::Index(i as u8)), + 1..=255 => u8::try_from(i).ok().map(Color::Index), _ => None, }; } @@ -145,11 +153,16 @@ pub fn aci_rgb(i: u8) -> Rgb { PALETTE.get(usize::from(i)).copied().unwrap_or(Rgb(255, 255, 255)) } -/// The palette as a 256-entry table (entry 0 = ByBlock placeholder = black). +/// The palette as a 256-entry table (entry 0 = `ByBlock` placeholder = black). pub static PALETTE: std::sync::LazyLock<[Rgb; 256]> = std::sync::LazyLock::new(build_palette); +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "Palette channels are finite and clamped to the u8 range before conversion." +)] fn build_palette() -> [Rgb; 256] { - let mut p = [Rgb(0, 0, 0); 256]; + let mut palette = [Rgb(0, 0, 0); 256]; let base = [ Rgb(0, 0, 0), Rgb(255, 0, 0), @@ -162,34 +175,35 @@ fn build_palette() -> [Rgb; 256] { Rgb(128, 128, 128), Rgb(192, 192, 192), ]; - for (slot, c) in p.iter_mut().zip(base) { - *slot = c; + for (slot, colour) in palette.iter_mut().zip(base) { + *slot = colour; } let values = [255.0, 204.0, 153.0, 127.0, 76.0]; - for i in 10..250usize { - let hue = (i - 10) / 10; // 0..24, 15° each - let sub = i % 10; - let v: f64 = values.get(sub / 2).copied().unwrap_or(255.0); + for index in 10..250usize { + let hue = (index - 10) / 10; // 0..24, 15° each + let sub = index % 10; + let value: f64 = values.get(sub / 2).copied().unwrap_or(255.0); let half = sub % 2 == 1; - let (r, g, b) = hue_fractions(hue); - let ch = |f: f64| -> u8 { - let f = if half { 0.5 + 0.5 * f } else { f }; - (v * f).floor().clamp(0.0, 255.0) as u8 + let (red, green, blue) = hue_fractions(hue); + let channel = |fraction: f64| -> u8 { + let fraction = if half { 0.5 + 0.5 * fraction } else { fraction }; + (value * fraction).floor().clamp(0.0, 255.0) as u8 }; - if let Some(slot) = p.get_mut(i) { - *slot = Rgb(ch(r), ch(g), ch(b)); + if let Some(slot) = palette.get_mut(index) { + *slot = Rgb(channel(red), channel(green), channel(blue)); } } let greys = [51u8, 91, 132, 173, 214, 255]; - for (k, g) in greys.iter().enumerate() { - if let Some(slot) = p.get_mut(250 + k) { - *slot = Rgb(*g, *g, *g); + for (offset, shade) in greys.iter().enumerate() { + if let Some(slot) = palette.get_mut(250 + offset) { + *slot = Rgb(*shade, *shade, *shade); } } - p + palette } /// Channel fractions for hue step 0..24 (red → yellow → green → cyan → blue → magenta → red). +#[expect(clippy::cast_precision_loss, reason = "Only the four hue offsets 0..=3 are converted; they are exact in f64.")] fn hue_fractions(h: usize) -> (f64, f64, f64) { let seg = h / 4; let t = (h % 4) as f64 / 4.0; @@ -204,6 +218,7 @@ fn hue_fractions(h: usize) -> (f64, f64, f64) { } /// The closest index colour to an RGB value (1..=255). +#[must_use] pub fn nearest_aci(c: Rgb) -> u8 { let mut best = (u32::MAX, 7u8); for i in 1..=255u8 { @@ -220,6 +235,7 @@ pub fn nearest_aci(c: Rgb) -> u8 { /// Display colour of `c` on `background`. Colour 7 (`aci7`) flips to contrast with the /// background, white on dark and black on light (paper), as CAD programs draw it; every other /// colour, including a true-colour or index white or black, keeps its RGB. +#[must_use] pub fn display_rgb(c: Rgb, aci7: bool, background: Rgb) -> Rgb { if !aci7 { c From cc1914d84e2402b76c92492b928ad6c8fe1a0588 Mon Sep 17 00:00:00 2001 From: WillPastor <47420496+WillPastor@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:27:11 -0400 Subject: [PATCH 132/531] Avoid repeated alias scans during PGP imports Accumulate PGP definitions directly in the alias map while preserving validation, warning order and capacity behavior. Add compatibility coverage for alias imports and reloads. Addresses the PGP import performance finding in #1933. --- crates/engine/src/cmd/file/pgp.rs | 12 +-- crates/engine/tests/aliases.rs | 138 +++++++++++++++++++++++++++++- 2 files changed, 140 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/file/pgp.rs b/crates/engine/src/cmd/file/pgp.rs index 515feac7f..acf68eb79 100644 --- a/crates/engine/src/cmd/file/pgp.rs +++ b/crates/engine/src/cmd/file/pgp.rs @@ -63,8 +63,8 @@ pub fn alias_name(a: &str) -> std::result::Result { } /// The aliases of a `.pgp` file's text, and its problems. -fn parse(text: &str) -> (Vec<(String, String)>, Vec) { - let mut out: Vec<(String, String)> = Vec::new(); +fn parse(text: &str) -> (BTreeMap, Vec) { + let mut out = BTreeMap::new(); let mut warnings = Vec::new(); let mut warn = |no: usize, msg: String| { if warnings.len() < MAX_WARNINGS { @@ -100,13 +100,13 @@ fn parse(text: &str) -> (Vec<(String, String)>, Vec) { warn(no, format!("{}: unknown command {}; skipped", alias.trim(), target.trim())); continue; }; + // Once full, stop at the next valid definition, even if it repeats an alias. if out.len() >= MAX_ALIASES { warn(no, format!("more than {MAX_ALIASES} aliases; the rest are skipped")); break; } - // A later line for the same alias wins, as it would when typed into the file twice. - out.retain(|(a, _)| *a != name); - out.push((name, id)); + // A later definition wins without scanning all the aliases accumulated so far. + out.insert(name, id); } (out, warnings) } @@ -120,7 +120,7 @@ fn listing(warnings: &[String], added: usize) -> Value { fn load(text: &str, path: Option) -> (usize, Vec) { let (aliases, warnings) = parse(text); let mut st = store(); - st.map = aliases.into_iter().collect(); + st.map = aliases; if path.is_some() { st.file = path; } diff --git a/crates/engine/tests/aliases.rs b/crates/engine/tests/aliases.rs index d1b39bb81..b3c0bdde3 100644 --- a/crates/engine/tests/aliases.rs +++ b/crates/engine/tests/aliases.rs @@ -5,6 +5,7 @@ use std::sync::Mutex; use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::MAX_ALIASES; use cadcraft_engine::cmd::resolve_alias; use serde_json::json; @@ -26,6 +27,10 @@ ZZBAD, *NOSUCHCOMMAND LINE, *CIRCLE "; +fn alias_prefix(count: usize) -> String { + (0..count).map(|i| format!("ZZP{i:05},*LINE\n")).collect() +} + #[test] fn an_alias_file_adds_and_overrides_aliases() { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); @@ -61,17 +66,142 @@ fn an_alias_file_adds_and_overrides_aliases() { fn reinit_reads_the_alias_file_again() { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let dir = TempDir::new("aliases"); - let file = dir.file("mine.pgp", "ZZR, *RECTANG\n"); + let file = dir.file("mine.pgp", "ZZR, *LINE\nzzr, *RECTANG\n"); let mut s = Session::new(); - s.execute("aliasedit", &json!({ "file": file })).unwrap(); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + let r = s.execute("aliasedit", &json!({ "file": file })).unwrap(); + assert_eq!(r["loaded"], json!(1)); + assert_eq!(r["file"], json!(file)); + assert_eq!(r["warnings"], json!([])); assert_eq!(resolve_alias("zzr"), "rectang"); - std::fs::write(&file, "ZZR, *CIRCLE\n").unwrap(); + std::fs::write(&file, "ZZR, *MOVE\nzzr, *CIRCLE\n").unwrap(); s.cmdline("reinit").unwrap(); assert_eq!(resolve_alias("zzr"), "circle"); assert!(s.log.iter().any(|l| l.contains("1 command alias")), "{:?}", s.log); - let r = s.execute("reinit", &json!({ "text": "ZZS, *SCALE\n" })).unwrap(); + let r = s.execute("aliasedit", &json!({})).unwrap(); + assert_eq!(r["file"], json!(file)); + assert_eq!(r["aliases"], json!({ "zzr": "circle" })); + let r = s.execute("reinit", &json!({ "text": "ZZS, *LINE\nzzs, *SCALE\n" })).unwrap(); assert_eq!(r["aliases"], json!({ "zzs": "scale" })); + assert_eq!(r["loaded"], json!(1)); + assert_eq!(r["warnings"], json!([])); + assert_eq!(r["file"], json!(file), "reloading text keeps the remembered file"); + let r = s.execute("reinit", &json!({})).unwrap(); + assert_eq!(r["aliases"], json!({ "zzr": "circle" })); + assert_eq!(r["loaded"], json!(1)); + assert_eq!(r["file"], json!(file)); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); +} + +#[test] +fn valid_redefinitions_win_and_the_listing_stays_sorted() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + let text = "ZZZ,*LINE\nZza,*LINE\nzzz,*CIRCLE\nZZA,*NO_SUCH_1933\nLINE,*CIRCLE\n"; + let r = s.execute("aliasedit", &json!({ "text": text })).unwrap(); + let aliases = json!({ "zza": "line", "zzz": "circle" }); + assert_eq!(r["aliases"], aliases); + assert_eq!(r["loaded"], json!(2), "loaded counts unique aliases, not definitions"); + assert_eq!(r["file"], json!(null)); + assert_eq!( + r["warnings"], + json!(["line 4: ZZA: unknown command *NO_SUCH_1933; skipped", "line 5: LINE is a command name; it stays the command; skipped"]) + ); + assert_eq!(resolve_alias("ZZZ"), "circle"); + assert_eq!(resolve_alias("zza"), "line", "an invalid redefinition keeps the previous target"); + assert_eq!(resolve_alias("line"), "line"); + assert_eq!(serde_json::to_string(&r["aliases"]).unwrap(), r#"{"zza":"line","zzz":"circle"}"#); + let listing = s.execute("aliasedit", &json!({})).unwrap(); + assert_eq!(listing, json!({ "aliases": aliases, "file": null, "loaded": 0, "warnings": [] })); + + let empty = s.execute("aliasedit", &json!({ "text": "" })).unwrap(); + assert_eq!(empty, json!({ "aliases": {}, "file": null, "loaded": 0, "warnings": [] })); + assert_eq!(resolve_alias("zza"), "zza", "an empty import replaces the old set"); + assert_eq!(resolve_alias("zzz"), "zzz"); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); +} + +#[test] +fn duplicates_below_the_limit_leave_room_for_another_alias() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + let mut text = alias_prefix(MAX_ALIASES - 1); + for _ in 0..16 { + text.push_str("ZZP00000,*MOVE\nzzp00001,*CIRCLE\n"); + } + let r = s.execute("aliasedit", &json!({ "text": text })).unwrap(); + assert_eq!(r["loaded"], json!(MAX_ALIASES - 1)); + assert_eq!(r["aliases"].as_object().unwrap().len(), MAX_ALIASES - 1); + assert_eq!(r["warnings"], json!([])); + for i in 0..MAX_ALIASES - 1 { + let expected = match i { + 0 => "move", + 1 => "circle", + _ => "line", + }; + assert_eq!(r["aliases"][format!("zzp{i:05}")], json!(expected)); + } + + text.push_str("ZZNEW,*PLINE\n"); + let r = s.execute("aliasedit", &json!({ "text": text })).unwrap(); + assert_eq!(r["loaded"], json!(MAX_ALIASES)); + assert_eq!(r["aliases"].as_object().unwrap().len(), MAX_ALIASES); + assert_eq!(r["aliases"]["zznew"], json!("pline")); + assert_eq!(r["aliases"]["zzp00000"], json!("move")); + assert_eq!(r["aliases"]["zzp00001"], json!("circle")); + assert_eq!(r["warnings"], json!([]), "duplicate definitions do not use up the alias limit"); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); +} + +#[test] +fn a_full_file_validates_lines_before_stopping_at_the_next_valid_definition() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + let mut text = alias_prefix(MAX_ALIASES); + text.push_str("; comment\nZZP00000,*NO_SUCH_1933\nLINE,*CIRCLE\nZZEXTERNAL, START NOTHING\nmalformed\nZZP00000,*MOVE\nZZAFTER,*CIRCLE\nanother malformed sentinel\n"); + let r = s.execute("aliasedit", &json!({ "text": text })).unwrap(); + assert_eq!(r["loaded"], json!(MAX_ALIASES)); + assert_eq!(r["aliases"].as_object().unwrap().len(), MAX_ALIASES); + assert_eq!(r["aliases"]["zzp00000"], json!("line"), "the cap stops even a valid duplicate replacement"); + assert!(r["aliases"].get("zzafter").is_none(), "the remainder of the file is skipped"); + assert_eq!( + r["warnings"], + json!([ + format!("line {}: ZZP00000: unknown command *NO_SUCH_1933; skipped", MAX_ALIASES + 2), + format!("line {}: LINE is a command name; it stays the command; skipped", MAX_ALIASES + 3), + format!("line {}: ZZEXTERNAL is an external command; CADCraft doesn't run programs from alias files", MAX_ALIASES + 4), + format!("line {}: `malformed` is not ALIAS, *COMMAND; skipped", MAX_ALIASES + 5), + format!("line {}: more than {MAX_ALIASES} aliases; the rest are skipped", MAX_ALIASES + 6) + ]) + ); + + // Setting one existing alias through JSON has a different rule from importing a full file. + let r = s.execute("aliasedit", &json!({ "set": { "ZZP00000": "move" } })).unwrap(); + assert_eq!(r["aliases"]["zzp00000"], json!("move")); + assert_eq!(r["loaded"], json!(1)); + assert!(s.execute("aliasedit", &json!({ "set": { "ZZNEW": "line" } })).is_err()); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); +} + +#[test] +fn the_warning_limit_does_not_stop_a_later_valid_redefinition() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + let mut text = String::from("ZZW,*LINE\n"); + for _ in 0..101 { + text.push_str("ZZW,*NO_SUCH_1933\n"); + } + text.push_str("zzw,*CIRCLE\n"); + let r = s.execute("aliasedit", &json!({ "text": text })).unwrap(); + assert_eq!(r["aliases"], json!({ "zzw": "circle" })); + assert_eq!(r["loaded"], json!(1)); + let warnings: Vec<_> = (2..=101).map(|no| format!("line {no}: ZZW: unknown command *NO_SUCH_1933; skipped")).collect(); + assert_eq!(r["warnings"], json!(warnings), "only the first 100 warnings are returned"); s.execute("aliasedit", &json!({ "clear": true })).unwrap(); } From 62e70432e7f5f46a6d7f88373d70877c0426c487 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 11:05:33 +1100 Subject: [PATCH 133/531] Plot: choose the output format from the path extension (#2556) plot ignored the extension of `path` and wrote PDF unless a device said otherwise. Without a device, png/svg/pdf is now taken from the extension (any case), like export; a device that writes another format is refused, and the reply carries `format`. Tests plot_format.rs check magic bytes, the mismatch error and the reply format. --- crates/engine/src/cmd/layout.rs | 7 +-- crates/engine/src/cmd/plotters.rs | 22 +++++++++- crates/engine/tests/plot_format.rs | 68 ++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 crates/engine/tests/plot_format.rs diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index a538d73b5..94fd11c59 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -833,6 +833,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { None => space.tab_name().to_string(), }; let pages = sheets.as_ref().map_or(1, Vec::len); + let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into()); match str_param(p, "path") { Some(_path) => { #[cfg(not(target_arch = "wasm32"))] @@ -841,15 +842,15 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { // Exclusively create a fresh temporary file and rename it into place so a planted // `.cadcraft-tmp` symlink cannot redirect the plot write (CWE-59). crate::atomic_write::write_atomic(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - Ok(json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages })) + Ok(json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })) } #[cfg(target_arch = "wasm32")] { super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?; - Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages })) + Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })) } } - None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages })), + None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })), } } diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 903ef1bc4..521b67cf9 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -267,6 +267,11 @@ pub fn page_device(cmd: &str, p: &Value, page: &mut PageSetup) -> Result { Ok(false) } +/// The output a path's extension (any case) asks for: png, svg or pdf; other extensions ask for none. +fn path_output(path: &str) -> Option { + PlotOutput::parse(&std::path::Path::new(path).extension()?.to_string_lossy()) +} + /// The options PLOT / EXPORTPDF hand the plotter with `device` and the device's papers /// resolved: `device` (else the layout's page setup device) picks the output (`output`: pdf, /// png or svg; EXPORTPDF always writes PDF) and `resolution`; a paper of the device becomes @@ -288,9 +293,22 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { None => layout.as_ref().and_then(|pg| find_device(&pg.device)), }; let mut out = if p.is_object() { p.clone() } else { json!({}) }; - let (Some(dev), Some(o)) = (dev, out.as_object_mut()) else { return Ok(out) }; + // The path's extension names the format, like EXPORT, unless a device is given; a given + // device that writes another format is refused. EXPORTPDF always writes PDF. + let by_path = if cmd == "exportpdf" { None } else { str_param(p, "path").and_then(path_output) }; + if let (Some(want), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty())) + && dev.output != want + { + return Err(bad(cmd, format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str()))); + } + let (Some(dev), Some(o)) = (dev, out.as_object_mut()) else { + if let (Some(want), Some(o)) = (by_path, out.as_object_mut()) { + o.insert("output".into(), json!(want.as_str())); + } + return Ok(out); + }; o.remove("device"); - let output = if cmd == "exportpdf" { PlotOutput::Pdf } else { dev.output }; + let output = if cmd == "exportpdf" { PlotOutput::Pdf } else { by_path.unwrap_or(dev.output) }; o.insert("output".into(), json!(output.as_str())); o.insert("resolution".into(), json!(dev.resolution)); let paper = match str_param(p, "paper") { diff --git a/crates/engine/tests/plot_format.rs b/crates/engine/tests/plot_format.rs new file mode 100644 index 000000000..1f4509c8c --- /dev/null +++ b/crates/engine/tests/plot_format.rs @@ -0,0 +1,68 @@ +//! PLOT chooses the output format from the extension of `path` when no device is named (#2556), +//! like EXPORT does; a device that writes another format is refused. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::cmd::plotters::{PlotterStore, set_plotter_store}; +use serde_json::json; + +fn session() -> Session { + set_plotter_store(PlotterStore::memory()); + set_io(IoHooks { + read: |_, _| Err("no reader in this test".into()), + write: |_, _| Err("no writer in this test".into()), + plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), + }); + let mut s = Session::new(); + s.cmdline("line 0,0 100,0").unwrap(); + s.cmdline("").unwrap(); + s +} + +fn magic(path: &std::path::Path) -> Vec { + std::fs::read(path).unwrap().into_iter().take(5).collect() +} + +#[test] +fn the_extension_picks_png_svg_or_pdf() { + let mut s = session(); + let dir = std::env::temp_dir().join(format!("cadcraft-plot-format-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cases: [(&str, &[u8], &str); 4] = + [("a.png", b"\x89PNG\r", "png"), ("b.svg", b" Date: Sun, 1 Nov 2026 11:08:06 +1100 Subject: [PATCH 134/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 53ffffc96..a91ee2f25 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,10 +1,10 @@ # Parity checklist -> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 444 registered commands. +**Menu breadth: 298 / 491 items (61%)** · 449 registered commands. | Menu | Items | Covered | % | |---|---|---|---| From d19df49fcf29976ea5ea416eb4236201808e4a5b Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sat, 31 Oct 2026 19:01:28 -0600 Subject: [PATCH 135/531] HATCH and LWPOLYLINE in a tilted plane are read as seen from above (#1886) Their boundary and vertices are in the object's plane (OCS). Only a mirrored plane (0,0,-1) was handled, by flipping x; a tilted plane whose normal points down was taken for a mirror too, and one pointing up kept its plane coordinates, so each face landed turned about the origin by its own angle. A tilted one is now mapped to the WCS and drawn as seen from above at its mean height: bulged edges are flattened (they are elliptical there), and a hatch's pattern direction and origin follow. Its extrusion becomes Z, since its points are plan coordinates now. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/common.rs | 32 ++++++++++++++++++++- crates/io/src/dxf_read/entities.rs | 46 ++++++++++++++++++++++++++---- crates/io/src/tests.rs | 41 ++++++++++++++++++++++++++ docs/file-format-parity.md | 5 ++-- 4 files changed, 115 insertions(+), 9 deletions(-) diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index e46f3c09d..37f53beb2 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -1,4 +1,4 @@ -use super::{Color, Common, Lineweight, Rgb, Tag, Transparency, Vec2, Vec3}; +use super::{Color, Common, Lineweight, PolyVertex, Rgb, Tag, Transparency, Vec2, Vec3}; /// Value lookup helpers over an entity's tags. pub(super) struct T<'a>(pub(super) &'a [Tag]); @@ -105,3 +105,33 @@ pub(super) fn ocs(c: &Common, p: Vec3) -> Vec3 { pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 { if (n.z - 1.0).abs() < 1e-12 && n.x.abs() < 1e-12 && n.y.abs() < 1e-12 { p } else { cadcraft_geom::Mat4::ocs(n).apply(p) } } + +/// Whether an extrusion tilts an object's plane off the XY plane (neither the Z axis nor the Z +/// axis turned over, as MIRROR leaves it, allowing for noise in x and y like INSERT does). +pub(super) fn tilted(n: Vec3) -> bool { + n.is_finite() && n.x.hypot(n.y) > 1e-3 * n.z.abs() +} + +/// A run of OCS vertices at `elevation` in the plane of `n` as seen from above in the WCS. A +/// tilted arc is an elliptical arc there, so bulged edges are flattened (within a thousandth of +/// the run's size); straight runs keep their vertices. Also gives the mean WCS Z, the elevation +/// the flattened run takes. +pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], closed: bool) -> (Vec, f64) { + let m = cadcraft_geom::Mat4::ocs(n); + let pts: Vec = if vertices.iter().all(|v| v.bulge == 0.0) { + vertices.iter().map(|v| v.p).collect() + } else { + let pl = cadcraft_geom::Polyline { vertices: vertices.to_vec(), closed }; + let b = pl.bounds(); + let size = (b.max - b.min).len(); + let tol = if size.is_finite() && size > 0.0 { size * 1e-3 } else { 1e-6 }; + let mut pts = pl.tessellate(tol); + if closed && pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + pts + }; + let world: Vec = pts.iter().map(|p| m.apply(Vec3::new(p.x, p.y, elevation))).collect(); + let z = if world.is_empty() { elevation } else { world.iter().map(|p| p.z).sum::() / world.len() as f64 }; + (world.iter().map(|p| PolyVertex::new(p.xy())).collect(), z) +} diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 12abae7da..92e6aef4c 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -1,4 +1,4 @@ -use super::common::{T, common, ocs}; +use super::common::{T, common, ocs, plan_of_tilted, tilted}; use super::hatch::hatch; use super::text::{attdef, attrib_modes, attrib_props, mtext_from, multiline_attrib, split_embedded, text_from}; use super::{ @@ -81,13 +81,17 @@ fn lwpolyline(tags: &[Tag], c: &Common, t: &T) -> Option { } verts.extend(cur); let flags = t.i(70).unwrap_or(0); - if c.extrusion.z < 0.0 { + let mut elevation = t.fd(38, 0.0); + if tilted(c.extrusion) { + // In a tilted plane: drawn as seen from above, at the vertices' mean height. + (verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0); + } else if c.extrusion.z < 0.0 { for v in &mut verts { v.p.x = -v.p.x; v.bulge = -v.bulge; } } - let pl = LwPolyline { vertices: verts, closed: flags & 1 != 0, const_width: t.fd(43, 0.0), elevation: t.fd(38, 0.0), plinegen: flags & 128 != 0 }; + let pl = LwPolyline { vertices: verts, closed: flags & 1 != 0, const_width: t.fd(43, 0.0), elevation, plinegen: flags & 128 != 0 }; // A region CADCraft wrote as polylines (`dxf_region`). crate::dxf_region::from_polyline(tags, pl) } @@ -121,14 +125,21 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef return None; } let t = T(tags); - let c = common(&t); + let mut c = common(&t); let k = match kind { "LINE" => EntityKind::Line(Line { a: t.p(10), b: t.p(11) }), "POINT" => EntityKind::Point(Point { p: t.p(10), angle: t.fd(50, 0.0).to_radians() }), "CIRCLE" => EntityKind::Circle(Circle { center: ocs(&c, t.p(10)), radius: t.fd(40, 1.0).abs() }), "ARC" => EntityKind::Arc(arc(&c, &t)), "ELLIPSE" => EntityKind::Ellipse(ellipse(&c, &t)), - "LWPOLYLINE" => lwpolyline(tags, &c, &t)?, + "LWPOLYLINE" => { + let k = lwpolyline(tags, &c, &t)?; + if tilted(c.extrusion) { + // Its vertices are now WCS, seen from above (`lwpolyline`). + c.extrusion = Vec3::Z; + } + k + } "SPLINE" => EntityKind::Spline(spline(&t)), "HELIX" => EntityKind::Helix(helix(tags)), "RAY" => EntityKind::Ray(RayLine { base: t.p(10), dir: t.p(11) }), @@ -227,7 +238,30 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef "3DFACE" => EntityKind::Face3d(Face3d { corners: [t.p(10), t.p(11), t.p(12), t.p(13)], hidden_edges: t.i(70).unwrap_or(0) as u8 }), "HATCH" => { let mut k = hatch(tags, &t)?; - if c.extrusion.z < 0.0 + if tilted(c.extrusion) + && let EntityKind::Hatch(h) = &mut k + { + // In a tilted plane (a terrain face, a slope): the boundary as seen from above, + // at its mean height, and the pattern direction and origin projected the same way. + let n = c.extrusion; + let m = cadcraft_geom::Mat4::ocs(n); + let (mut sum, mut count) = (0.0, 0usize); + for l in &mut h.loops { + let (v, z) = plan_of_tilted(n, h.elevation, &l.vertices, true); + sum += z * v.len() as f64; + count += v.len(); + l.vertices = v; + } + let dir = m.apply(Vec3::new(h.angle.cos(), h.angle.sin(), 0.0)).xy(); + if dir.len() > 1e-9 { + h.angle = cadcraft_geom::norm_angle(dir.y.atan2(dir.x)); + } + h.origin = m.apply(Vec3::new(h.origin.x, h.origin.y, h.elevation)).xy(); + if count > 0 { + h.elevation = sum / count as f64; + } + c.extrusion = Vec3::Z; + } else if c.extrusion.z < 0.0 && let EntityKind::Hatch(h) = &mut k { // Boundary in the mirrored OCS, like LWPOLYLINE; the pattern direction mirrors too. diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 977a7c184..f81122eda 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2109,6 +2109,47 @@ fn mirrored_hatch_extrusion_flips_boundary() { } } +/// Issue #1886: a HATCH in a tilted plane (a terrain face) is drawn as seen from above, not turned +/// about the origin. With extrusion (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and +/// y = (0, √3/2, 1/2): the square (1,0)..(3,2) lies over (-3,0)..(-1,√3), from z 0 up to z 1. +/// Before, the negative Z counted as a plain mirror and only x was flipped. +#[test] +fn tilted_hatch_is_drawn_as_seen_from_above() { + let text = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n2\nSOLID\n70\n1\n71\n0\n91\n1\n\ + 92\n2\n72\n0\n73\n1\n93\n4\n10\n1\n20\n0\n10\n3\n20\n0\n10\n3\n20\n2\n10\n1\n20\n2\n97\n0\n75\n0\n76\n1\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "h.dxf").unwrap(); + let b = d.extents(&Space::Model); + for (got, want) in [(b.min.x, -3.0), (b.min.y, 0.0), (b.max.x, -1.0), (b.max.y, 3f64.sqrt())] { + assert!((got - want).abs() < 1e-9, "extents {b:?}"); + } + let e = d.model.iter().next().unwrap(); + assert_eq!(e.common.extrusion, Vec3::Z, "its points are plan coordinates now"); + let EntityKind::Hatch(h) = &e.kind else { panic!("not a hatch") }; + assert!((h.elevation - 0.5).abs() < 1e-9, "the mean height of its corners: {}", h.elevation); +} + +/// Issue #1886: a LWPOLYLINE circle (two half-circle bulges) in the same tilted plane is the +/// ellipse it looks like from above, flattened; a plain one keeps its bulges. +#[test] +fn tilted_lwpolyline_is_drawn_as_seen_from_above() { + let circle = |n: &str| { + format!("0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n1\n{n}10\n1\n20\n0\n42\n1\n10\n-1\n20\n0\n42\n1\n0\nENDSEC\n0\nEOF\n") + }; + let d = read(circle("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap(); + let b = d.extents(&Space::Model); + let ry = 3f64.sqrt() / 2.0; + for (got, want) in [(b.min.x, -1.0), (b.min.y, -ry), (b.max.x, 1.0), (b.max.y, ry)] { + assert!((got - want).abs() < 5e-3, "extents {b:?}"); + } + let e = d.model.iter().next().unwrap(); + assert_eq!(e.common.extrusion, Vec3::Z); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert!(p.vertices.len() > 8 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len()); + let plain = read(circle("").as_bytes(), "p.dxf").unwrap(); + let p = first(&plain, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::>(), vec![1.0, 1.0]); +} + /// The model extents of a one-loop solid HATCH whose edge boundary is `edges` (group 72 onwards). fn hatch_edge_extents(edges: &str) -> Bounds2 { let n = edges.matches("72\n").count(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d85415123..d6e2b9680 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -73,7 +73,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Content | Read | Write | Notes | |---|---|---|---| -| LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | +| LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes; a LWPOLYLINE in a tilted plane is read as seen from above (arcs flattened, #1886) | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | | TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement; a justified TEXT's insertion point (group 10, which AutoCAD takes from a DWG as it is) is computed as AutoCAD computes it: Middle (M) centred on the string's own extents, bottom justifications at a TrueType face's descent (#2229) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | @@ -81,7 +81,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | | LEADER | yes | yes | | | MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides and annotative scale contexts not kept | -| HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD) | | +| HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD); a hatch in a tilted plane is read as seen from above (#1886) | | | HATCH gradient | yes | yes (#162, fixes #80) | | | SOLID, TRACE, 3DFACE | yes | yes | | | ACAD_TABLE | yes | yes (entity + block) | | @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | HATCH and LWPOLYLINE in a tilted plane (extrusion off the Z axis) are read as seen from above at their mean height, instead of keeping plane coordinates that turned them about the origin (#1886) | | 2026-10-29 | minor | R2000 DXF: CLASS records written without group 91 (instance count), which came with the 2004 format; AutoCAD LT 2026 stopped responding on every R2000 DXF CADCraft saved (checked black-box in AutoCAD LT 2026) | | 2026-10-26 | minor | CC-046: ATTEDIT and -ATTEDIT value changes invalidate derived justified baselines before DXF/DWG export; preserve alignment anchors, unchanged values and Aligned/Fit endpoints. Review follow-up: baseline recomputation preserves insertion elevation independently of alignment elevation. The shared writer correction also applies to justified TEXT. Independent of attribute editor UI; reverting the follow-up restores elevation loss on recomputation, while reverting the value setter restores stale XY baselines. | | 2026-10-25 | minor | LAYOUT SAveas (`layout.saveas`) writes a layout as a drawing template: its page setup and paper space objects, no model space objects or other layouts, and only the named objects they use | From 33dc795c5f68aa3029246004583f1252876dd5f3 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:48:11 +0300 Subject: [PATCH 136/531] ui: the options reset brings a hidden menu bar and tool bar back --- crates/ui-egui/src/lib.rs | 17 +++++++++++++++++ crates/ui-egui/src/options.rs | 13 +++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 97ab2faf4..834767d3c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1183,4 +1183,21 @@ mod tests { let ui: UiState = serde_json::from_value(json!({ "saveFormat": "dwg" })).unwrap_or_default(); assert_eq!(ui.save_format, SaveFormat::Dwg); } + + #[test] + fn options_reset_brings_the_interface_back() { + // Hiding the interface (View/Window toggles) can leave no way back — on Windows the + // in-window menu bar is the only menu there is. Options > Reset must restore it (#1240). + let mut a = app(); + a.run("ui.toggle.toolbar", json!({ "on": false })).unwrap(); + a.run("ui.toggle.menubar", json!({ "on": cfg!(target_os = "macos") })).unwrap(); + a.start("ui.hidepalettes"); + assert!(!a.ui.show_toolbar && !a.ui.show_palettes && !a.ui.show_toolsets); + assert_eq!(a.ui.in_window_menu, cfg!(target_os = "macos"), "the test did not hide the menu bar"); + a.run("options", json!({ "reset": true })).unwrap(); + assert!(a.ui.show_toolbar, "the tool bar is still hidden"); + assert!(a.ui.show_palettes, "the palettes are still hidden"); + assert!(a.ui.show_toolsets); + assert_eq!(a.ui.in_window_menu, !cfg!(target_os = "macos"), "the menu bar did not come back"); + } } diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index 27f778735..1fc880275 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -315,13 +315,14 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result { /// The interface preferences back to their defaults (the interface language stays). fn reset_ui(app: &mut CadApp) { - let d = crate::UiState::default(); - app.ui.theme = d.theme; - app.ui.animations = d.animations; - app.ui.save_format = d.save_format; - app.ui.save_version = d.save_version; + // Everything interface, back to its defaults: a hidden menu bar, tool bar, palettes or + // panels and a rearranged panel layout come back — once the menu bar is hidden there may be + // no other way to reach the toggles (#1240). The interface language stays; the open dialog, + // the start tab and the recent files are state, not preferences, and stay too. + let (language, dialog, start_tab) = (app.ui.interface_language, app.ui.dialog.take(), app.ui.start_tab); + let recent_files = std::mem::take(&mut app.ui.recent_files); + app.ui = crate::UiState { interface_language: language, dialog, start_tab, recent_files, ..Default::default() }; app.ui.system_cursor = app.system_cursor_default; - app.ui.history_lines = d.history_lines; app.options = UiOptions::default(); } From c22700d3aff6c3f8939e337404abc7ef2f6e5e60 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 15:27:09 +1100 Subject: [PATCH 137/531] Plot: refuse several layouts for PNG and SVG output (review on #2585) An image holds one sheet, so layouts with more than one entry now report a clear error instead of pages:N with one render. --- crates/engine/src/cmd/layout.rs | 5 +++++ crates/engine/src/cmd/layout/tests.rs | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 94fd11c59..f253456b3 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -827,6 +827,11 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { None => o.remove("plotTransparency"), }; } + // A PNG or SVG holds one render: several sheets would report `pages: N` but write only one. + let image = opts.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg")); + if image && sheets.as_ref().is_some_and(|names| names.len() > 1) { + return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately")); + } let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?; let layout = match &sheets { Some(names) => names.first().cloned().unwrap_or_default(), diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 03356b892..df548fc7d 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -230,6 +230,13 @@ fn plot_goes_through_the_hook() { assert!(s.execute("plot", &json!({"layout": "Model", "plotArea": "window"})).is_err(), "window needs corners"); assert!(s.execute("plot", &json!({"layout": "Layout1", "plotArea": "display"})).is_err(), "layouts plot their sheet"); assert!(s.execute("plot", &json!({"layout": "Model", "scale": -1})).is_err()); + // Image output holds one sheet: several `layouts` would report pages:N but write one render. + for out in ["x.png", "x.svg"] { + let e = s.execute("plot", &json!({"path": out, "layouts": ["Layout1", "Layout2"]})).unwrap_err(); + assert!(e.to_string().contains("layouts"), "{e}"); + } + assert!(s.execute("plot", &json!({"output": "png", "layouts": ["Layout1", "Layout2"]})).is_err()); + assert!(s.execute("plot", &json!({"output": "png", "layouts": ["Layout1"]})).is_ok(), "one sheet still fine as an image"); #[cfg(not(target_arch = "wasm32"))] { let path = std::env::temp_dir().join(format!("cadcraft-plot-test-{}.pdf", std::process::id())); From 756946c4d617fd0a6d602e3a8b3a57fa3e2601e6 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sat, 31 Oct 2026 22:29:03 -0600 Subject: [PATCH 138/531] Tilted LWPOLYLINE keeps its widths; a tilted hatch's gradient turns too Straight runs carry each vertex's widths onto its projected vertex (flattened arcs still have none). The gradient direction is projected like the pattern's. A pattern keeps the spacing and dashes of its plane, noted in the parity doc. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/common.rs | 14 ++++++++++---- crates/io/src/dxf_read/entities.rs | 11 ++++++++--- crates/io/src/tests.rs | 25 +++++++++++++++++++++++++ docs/file-format-parity.md | 2 +- 4 files changed, 44 insertions(+), 8 deletions(-) diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 37f53beb2..7abb19c18 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -114,11 +114,12 @@ pub(super) fn tilted(n: Vec3) -> bool { /// A run of OCS vertices at `elevation` in the plane of `n` as seen from above in the WCS. A /// tilted arc is an elliptical arc there, so bulged edges are flattened (within a thousandth of -/// the run's size); straight runs keep their vertices. Also gives the mean WCS Z, the elevation -/// the flattened run takes. +/// the run's size, without widths); straight runs keep their vertices and widths. Also gives +/// the mean WCS Z, the elevation the flattened run takes. pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], closed: bool) -> (Vec, f64) { let m = cadcraft_geom::Mat4::ocs(n); - let pts: Vec = if vertices.iter().all(|v| v.bulge == 0.0) { + let straight = vertices.iter().all(|v| v.bulge == 0.0); + let pts: Vec = if straight { vertices.iter().map(|v| v.p).collect() } else { let pl = cadcraft_geom::Polyline { vertices: vertices.to_vec(), closed }; @@ -133,5 +134,10 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c }; let world: Vec = pts.iter().map(|p| m.apply(Vec3::new(p.x, p.y, elevation))).collect(); let z = if world.is_empty() { elevation } else { world.iter().map(|p| p.z).sum::() / world.len() as f64 }; - (world.iter().map(|p| PolyVertex::new(p.xy())).collect(), z) + let out = if straight { + world.iter().zip(vertices).map(|(p, v)| PolyVertex { p: p.xy(), ..*v }).collect() + } else { + world.iter().map(|p| PolyVertex::new(p.xy())).collect() + }; + (out, z) } diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 92e6aef4c..90c68604b 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -252,9 +252,14 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef count += v.len(); l.vertices = v; } - let dir = m.apply(Vec3::new(h.angle.cos(), h.angle.sin(), 0.0)).xy(); - if dir.len() > 1e-9 { - h.angle = cadcraft_geom::norm_angle(dir.y.atan2(dir.x)); + // The pattern keeps the spacing and dashes of its plane: only its direction turns. + let plan_angle = |a: f64| { + let dir = m.apply(Vec3::new(a.cos(), a.sin(), 0.0)).xy(); + if dir.len() > 1e-9 { cadcraft_geom::norm_angle(dir.y.atan2(dir.x)) } else { a } + }; + h.angle = plan_angle(h.angle); + if let Some(g) = h.gradient.as_mut() { + g.angle = plan_angle(g.angle); } h.origin = m.apply(Vec3::new(h.origin.x, h.origin.y, h.elevation)).xy(); if count > 0 { diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index f81122eda..d1c317e18 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2128,6 +2128,31 @@ fn tilted_hatch_is_drawn_as_seen_from_above() { assert!((h.elevation - 0.5).abs() < 1e-9, "the mean height of its corners: {}", h.elevation); } +/// A tilted gradient hatch turns its gradient's direction with its boundary: in that plane OCS +X +/// is plan -X, so a gradient at 0 runs at 180°. +#[test] +fn tilted_hatch_turns_its_gradient() { + let text = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n8\n0\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n2\nSOLID\n70\n1\n71\n0\n91\n1\n\ + 92\n2\n72\n0\n73\n1\n93\n4\n10\n1\n20\n0\n10\n3\n20\n0\n10\n3\n20\n2\n10\n1\n20\n2\n97\n0\n75\n0\n76\n1\n\ + 450\n1\n451\n0\n452\n0\n453\n2\n460\n0\n461\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "h.dxf").unwrap(); + let h = first(&d, |k| if let EntityKind::Hatch(h) = k { Some(h.clone()) } else { None }); + let g = h.gradient.expect("a gradient"); + assert!((g.angle - std::f64::consts::PI).abs() < 1e-9, "gradient angle {}", g.angle); +} + +/// A straight tilted LWPOLYLINE keeps its vertex widths (groups 40/41) on the projected vertices. +#[test] +fn tilted_straight_lwpolyline_keeps_its_widths() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n1\n20\n0\n40\n0.5\n41\n1\n10\n3\n20\n2\n40\n1\n41\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let got: Vec<(f64, f64)> = p.vertices.iter().map(|v| (v.start_width, v.end_width)).collect(); + assert_eq!(got, vec![(0.5, 1.0), (1.0, 0.0)]); + assert!((p.vertices[1].p.x + 3.0).abs() < 1e-9 && (p.vertices[1].p.y - 3f64.sqrt()).abs() < 1e-9, "{:?}", p.vertices[1].p); +} + /// Issue #1886: a LWPOLYLINE circle (two half-circle bulges) in the same tilted plane is the /// ellipse it looks like from above, flattened; a plain one keeps its bulges. #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d6e2b9680..afaef75a9 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -81,7 +81,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | | LEADER | yes | yes | | | MULTILEADER | yes (#459) | yes, native MULTILEADER with MLEADERSTYLE (#459) | several landings per multileader are folded into one; per-object overrides and annotative scale contexts not kept | -| HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD); a hatch in a tilted plane is read as seen from above (#1886) | | +| HATCH pattern / solid | yes | yes; associative hatches keep their boundary objects in blocks too, and the boundary carries the hatch reactor (stretched dynamic blocks drag the fill in AutoCAD); a hatch in a tilted plane is read as seen from above (#1886), its pattern and gradient turned with it; a pattern keeps the line spacing and dashes of its plane | | | HATCH gradient | yes | yes (#162, fixes #80) | | | SOLID, TRACE, 3DFACE | yes | yes | | | ACAD_TABLE | yes | yes (entity + block) | | From ad609fab0235dca742108e336925f0a116001472 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 15:38:48 +1100 Subject: [PATCH 139/531] OLE2FRAME: the frame counts in the drawing extents; CLI test uses a self-cleaning dir (review on #2587) bounds_in now takes the frame from its corner tags (shared ole_frame in the doc crate), so zoom extents shows a frame outside other geometry. The undrawn_entities tests clean up on drop. --- .../cadcraft-cli/tests/it/undrawn_entities.rs | 29 +++++++++++++++---- crates/doc/src/extents.rs | 25 ++++++++++++++++ crates/doc/src/lib.rs | 2 +- crates/render/src/draw.rs | 10 +------ 4 files changed, 50 insertions(+), 16 deletions(-) diff --git a/apps/cadcraft-cli/tests/it/undrawn_entities.rs b/apps/cadcraft-cli/tests/it/undrawn_entities.rs index bf626a7d5..ca5338c2f 100644 --- a/apps/cadcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/cadcraft-cli/tests/it/undrawn_entities.rs @@ -7,6 +7,25 @@ fn cli(args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap() } +/// A fresh scratch directory that is removed on drop, also when an assertion fails. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id())); + // A directory left behind by an earlier run with the same process id must not leak in. + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).expect("create scratch dir"); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + /// A line, two foreign REGIONs and a PDF underlay: the last three are kept as unknown entities. const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\ 0\nLINE\n8\n0\n10\n0\n20\n0\n11\n5\n21\n5\n\ @@ -17,8 +36,8 @@ const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\ #[test] fn convert_to_an_image_warns_about_entities_it_cannot_draw() { - let dir = std::env::temp_dir().join(format!("cc-cli-undrawn-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let scratch = Scratch::new("undrawn"); + let dir = scratch.0.clone(); let input = dir.join("proxies.dxf"); std::fs::write(&input, PROXIES).unwrap(); let input = input.to_str().unwrap(); @@ -49,19 +68,17 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() { let out = cli(&["convert", sample.to_str().unwrap(), dir.join("sample.svg").to_str().unwrap()]); assert!(out.status.success()); assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); - let _ = std::fs::remove_dir_all(&dir); } /// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it undrawn (#2422). #[test] fn an_ole_frame_is_not_reported_as_undrawn() { - let dir = std::env::temp_dir().join(format!("cc-cli-ole-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let scratch = Scratch::new("ole"); + let dir = scratch.0.clone(); let input = dir.join("ole.dxf"); let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n11\n5\n21\n-3\n31\n0\n0\nENDSEC\n0\nEOF\n"; std::fs::write(&input, ole).unwrap(); let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]); assert!(out.status.success()); assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); - let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 353a42b53..55e3e5d24 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -9,6 +9,14 @@ use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim}; /// Nested block references deeper than this are ignored (cyclic or hostile files). pub const MAX_BLOCK_DEPTH: usize = 16; +/// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right +/// (groups 11, 21) corners (DXF Reference, OLE2FRAME); `None` when either is missing or not finite. +pub fn ole_frame(tags: &[crate::RawTag]) -> Option<[Vec2; 5]> { + let get = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()); + let (a, b) = (Vec2::new(get(10)?, get(20)?), Vec2::new(get(11)?, get(21)?)); + Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a]) +} + /// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification /// the same way the renderer places it (the stroke font is about 0.88 of the height per character). fn text_box(t: &crate::Text, len: usize) -> Bounds2 { @@ -244,6 +252,10 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< Bounds2::from_points([o, o + u, o + v, o + u + v]) } EntityKind::LwPolyline(p) => lwpolyline_bounds(p), + // An OLE object's content is not drawn, but its frame is, so the frame counts (#2422). + EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => { + ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points) + } kind => { let mut b = Bounds2::EMPTY; for p in kind.prims() { @@ -438,4 +450,17 @@ mod tests { empty.text = Some(crate::MText { contents: " ".into(), ..mtext }); assert!(bounds(EntityKind::MLeader(empty)).max.x < 26.0); } + + /// An OLE2FRAME counts in the extents through its corner tags (#2422); a missing or + /// non-finite corner counts as nothing. + #[test] + fn ole_frame_counts_in_extents() { + let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() }; + let frame = |tags: Vec| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])); + assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0))); + assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame"); + assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty()); + assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty()); + } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index e07a08609..55169219f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -27,7 +27,7 @@ pub use cadcraft_color as color; pub use cadcraft_geom as geom; pub use constraint::*; pub use entity::*; -pub use extents::{MAX_BLOCK_DEPTH, entity_bounds, extent_bounds}; +pub use extents::{MAX_BLOCK_DEPTH, entity_bounds, extent_bounds, ole_frame}; pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index e51a1812c..0ff9515ed 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -236,7 +236,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { } // An OLE object's content is not drawn; its frame, from its two corner points, is. EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => { - if let Some(q) = ole_frame(&u.tags) { + if let Some(q) = cadcraft_doc::ole_frame(&u.tags) { b.polyline(ctx, rgb, lw, &q); } } @@ -385,11 +385,3 @@ fn leader_scale(d: &Drawing, st: Option<&cadcraft_doc::DimStyle>) -> f64 { let dimscale = d.header.f64("DIMSCALE", 1.0); st.map(|s| s.effective_scale(dimscale)).unwrap_or_else(|| cadcraft_doc::DimStyle::default().effective_scale(dimscale)) } - -/// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right -/// (groups 11, 21) corners (DXF Reference, OLE2FRAME); `None` when either is missing or not finite. -fn ole_frame(tags: &[cadcraft_doc::RawTag]) -> Option<[Vec2; 5]> { - let get = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()); - let (a, b) = (Vec2::new(get(10)?, get(20)?), Vec2::new(get(11)?, get(21)?)); - Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a]) -} From a49e4ff941d8857d4a7230f7992d79e172f0e639 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sat, 31 Oct 2026 22:45:35 -0600 Subject: [PATCH 140/531] Tilted LWPOLYLINE: straight edges keep their widths next to flattened arcs Only bulged edges are flattened now, each on its own; the vertices that start straight edges keep their widths. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/common.rs | 51 +++++++++++++++++--------------- crates/io/src/tests.rs | 15 ++++++++++ 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 7abb19c18..1ca00706f 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -113,31 +113,34 @@ pub(super) fn tilted(n: Vec3) -> bool { } /// A run of OCS vertices at `elevation` in the plane of `n` as seen from above in the WCS. A -/// tilted arc is an elliptical arc there, so bulged edges are flattened (within a thousandth of -/// the run's size, without widths); straight runs keep their vertices and widths. Also gives -/// the mean WCS Z, the elevation the flattened run takes. +/// tilted arc is an elliptical arc there, so each bulged edge is flattened (within a thousandth +/// of the run's size), its points without widths; vertices that start straight edges keep their +/// widths. Also gives the mean WCS Z, the elevation the flattened run takes. pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], closed: bool) -> (Vec, f64) { let m = cadcraft_geom::Mat4::ocs(n); - let straight = vertices.iter().all(|v| v.bulge == 0.0); - let pts: Vec = if straight { - vertices.iter().map(|v| v.p).collect() - } else { - let pl = cadcraft_geom::Polyline { vertices: vertices.to_vec(), closed }; - let b = pl.bounds(); - let size = (b.max - b.min).len(); - let tol = if size.is_finite() && size > 0.0 { size * 1e-3 } else { 1e-6 }; - let mut pts = pl.tessellate(tol); - if closed && pts.len() > 1 && pts.first() == pts.last() { - pts.pop(); + let b = cadcraft_geom::Polyline { vertices: vertices.to_vec(), closed }.bounds(); + let size = (b.max - b.min).len(); + let tol = if size.is_finite() && size > 0.0 { size * 1e-3 } else { 1e-6 }; + let mut local: Vec = Vec::with_capacity(vertices.len()); + for (i, v) in vertices.iter().enumerate() { + let next = if i + 1 < vertices.len() { + vertices.get(i + 1) + } else if closed { + vertices.first() + } else { + None + }; + match next { + Some(w) if v.bulge != 0.0 => { + local.push(PolyVertex::new(v.p)); + let edge = cadcraft_geom::Polyline { vertices: vec![*v, PolyVertex::new(w.p)], closed: false }.tessellate(tol); + // The edge's own ends are this vertex and the next one. + local.extend(edge.iter().skip(1).take(edge.len().saturating_sub(2)).map(|p| PolyVertex::new(*p))); + } + _ => local.push(PolyVertex { bulge: 0.0, ..*v }), } - pts - }; - let world: Vec = pts.iter().map(|p| m.apply(Vec3::new(p.x, p.y, elevation))).collect(); - let z = if world.is_empty() { elevation } else { world.iter().map(|p| p.z).sum::() / world.len() as f64 }; - let out = if straight { - world.iter().zip(vertices).map(|(p, v)| PolyVertex { p: p.xy(), ..*v }).collect() - } else { - world.iter().map(|p| PolyVertex::new(p.xy())).collect() - }; - (out, z) + } + let to_plan = |p: Vec2| m.apply(Vec3::new(p.x, p.y, elevation)); + let z = if local.is_empty() { elevation } else { local.iter().map(|v| to_plan(v.p).z).sum::() / local.len() as f64 }; + (local.into_iter().map(|v| PolyVertex { p: to_plan(v.p).xy(), ..v }).collect(), z) } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index d1c317e18..674570c65 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2153,6 +2153,21 @@ fn tilted_straight_lwpolyline_keeps_its_widths() { assert!((p.vertices[1].p.x + 3.0).abs() < 1e-9 && (p.vertices[1].p.y - 3f64.sqrt()).abs() < 1e-9, "{:?}", p.vertices[1].p); } +/// A tilted LWPOLYLINE mixing straight and bulged edges keeps the widths of its straight edges; +/// only the points of the flattened arc have none. +#[test] +fn tilted_mixed_lwpolyline_keeps_its_straight_widths() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n3\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n0\n20\n0\n40\n0.5\n41\n1\n10\n2\n20\n0\n42\n1\n10\n4\n20\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let v = &p.vertices; + assert!(v.len() > 4 && v.iter().all(|v| v.bulge == 0.0), "{} vertices", v.len()); + assert_eq!((v[0].start_width, v[0].end_width), (0.5, 1.0), "the straight edge keeps its widths"); + assert!(v[1..].iter().all(|v| v.start_width == 0.0 && v.end_width == 0.0), "the flattened arc has none"); + assert!((v[1].p.x + 2.0).abs() < 1e-9 && (v[v.len() - 1].p.x + 4.0).abs() < 1e-9, "{:?} {:?}", v[1].p, v[v.len() - 1].p); +} + /// Issue #1886: a LWPOLYLINE circle (two half-circle bulges) in the same tilted plane is the /// ellipse it looks like from above, flattened; a plain one keeps its bulges. #[test] From b51318003be6e74e276bddccfc693168b5cb5664 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 16:21:24 +1100 Subject: [PATCH 141/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index f842c51a9..5fb179f5a 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Parity checklist -> **Generated:** 2026-10-31 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. From 8dc927e01c8b8c860b09c1fd6d7d82f2b2daf4cc Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 16:57:17 +1100 Subject: [PATCH 142/531] Format: rustfmt after the clippy fix (review on #2587) --- crates/doc/src/extents.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 55e3e5d24..fbbb4824a 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -253,9 +253,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } EntityKind::LwPolyline(p) => lwpolyline_bounds(p), // An OLE object's content is not drawn, but its frame is, so the frame counts (#2422). - EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => { - ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points) - } + EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points), kind => { let mut b = Bounds2::EMPTY; for p in kind.prims() { From 12ce66889eb8a417e8aa913b4ae8882293ba60c2 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 18:06:41 +1100 Subject: [PATCH 143/531] Plot: a single layouts entry picks the sheet for PNG and SVG (review on #2585) run_plot rendered the session space for image output while the reply named the layout. The one-entry list now resolves to the render space, as the PDF path does. Test: plot_goes_through_the_hook. --- crates/engine/src/cmd/layout.rs | 17 ++++++++++++++--- crates/engine/src/cmd/layout/tests.rs | 5 ++++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f253456b3..ae4c1de0b 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -785,10 +785,22 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { // Checked here for a clear error; the plotter resolves the names the same way. let sheets = p.get("layouts").map(|v| plot_sheets(cmd, s.doc()?, v)).transpose()?; + let is_image = p.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg")); let space = match str_param(p, "layout") { Some(n) if n.eq_ignore_ascii_case("model") => Space::Model, Some(n) => Space::Paper(layout_name(cmd, s.doc()?, n)?), - None => s.space(), + // A PNG or SVG holds one render: a single `layouts` entry names the sheet to draw (the PDF + // path resolves `layouts` itself), not whatever space the session happens to show. + None => match sheets.as_deref() { + Some([only]) if is_image => { + if only.eq_ignore_ascii_case("model") { + Space::Model + } else { + Space::Paper(only.clone()) + } + } + _ => s.space(), + }, }; let mut opts = if p.is_object() { p.clone() } else { json!({}) }; if let Some(raw) = p.get("offset") { @@ -828,8 +840,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { }; } // A PNG or SVG holds one render: several sheets would report `pages: N` but write only one. - let image = opts.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg")); - if image && sheets.as_ref().is_some_and(|names| names.len() > 1) { + if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) { return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately")); } let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?; diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index df548fc7d..9bb73f5fc 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -236,7 +236,10 @@ fn plot_goes_through_the_hook() { assert!(e.to_string().contains("layouts"), "{e}"); } assert!(s.execute("plot", &json!({"output": "png", "layouts": ["Layout1", "Layout2"]})).is_err()); - assert!(s.execute("plot", &json!({"output": "png", "layouts": ["Layout1"]})).is_ok(), "one sheet still fine as an image"); + let one = s.execute("plot", &json!({"output": "png", "layouts": ["Layout1"]})).unwrap(); + assert_eq!(one["layout"], "Layout1"); + let text = String::from_utf8(super::super::file::base64_decode(one["data"].as_str().unwrap()).unwrap()).unwrap(); + assert!(text.contains("Paper(\"Layout1\")"), "one sheet renders that layout, not the session space: {text}"); #[cfg(not(target_arch = "wasm32"))] { let path = std::env::temp_dir().join(format!("cadcraft-plot-test-{}.pdf", std::process::id())); From 87f3c087b2d9412f1b9b282ecf782b4b2262da35 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 18:12:57 +1100 Subject: [PATCH 144/531] OLE2FRAME: corners skip application groups; MOVE/COPY carry the frame, rotate/scale/mirror refuse it (review on #2587) ole_frame read 10/20 and 11/21 from inside 102 groups; it now skips them as the DXF reader does. A window-selected OLE2FRAME was left in place by MOVE/COPY. A DWG save writes the position from the corner groups (checked by write + read-back), so MOVE/COPY now shift them; transforms that would not keep it axis aligned return an error before anything changes. --- crates/doc/src/entity.rs | 1 + crates/doc/src/extents.rs | 75 +++++++++++++++++++++- crates/doc/src/lib.rs | 2 +- crates/engine/src/cmd/modify/transform.rs | 11 ++++ crates/engine/tests/ole_frame_transform.rs | 57 ++++++++++++++++ crates/io/tests/it/ole_frame.rs | 15 +++++ 6 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 crates/engine/tests/ole_frame_transform.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index d13b82722..a32fb820a 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -461,6 +461,7 @@ impl EntityKind { let a = if mirror { t.rotation() } else { t.rotation() + rot }; t.dir = Vec2::from_angle(cadcraft_geom::norm_angle(a)).to3(0.0); } + EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => crate::ole_frame_transform(&mut u.tags, m), EntityKind::Unknown(_) => {} } } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index fbbb4824a..4bbdf3cf9 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -9,14 +9,63 @@ use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim}; /// Nested block references deeper than this are ignored (cyclic or hostile files). pub const MAX_BLOCK_DEPTH: usize = 16; +/// Positions in `tags` of the groups outside application-defined `102 {` .. `102 }` groups, whose +/// codes are the application's own and not the entity's. +fn outside_app(tags: &[crate::RawTag]) -> Vec { + let mut in_app = false; + let mut out = Vec::new(); + for (i, t) in tags.iter().enumerate() { + if t.code == 102 { + in_app = t.value.starts_with('{'); + } else if !in_app { + out.push(i); + } + } + out +} + +/// The positions of the frame's corner groups 10, 20, 11, 21 (in that order) and their values. +fn ole_corner_groups(tags: &[crate::RawTag]) -> Option<[(usize, f64); 4]> { + let own = outside_app(tags); + let find = |code: i32| { + let i = own.iter().copied().find(|&i| tags.get(i).is_some_and(|t| t.code == code))?; + let v = tags.get(i)?.value.trim().parse::().ok().filter(|v| v.is_finite())?; + Some((i, v)) + }; + Some([find(10)?, find(20)?, find(11)?, find(21)?]) +} + /// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right /// (groups 11, 21) corners (DXF Reference, OLE2FRAME); `None` when either is missing or not finite. pub fn ole_frame(tags: &[crate::RawTag]) -> Option<[Vec2; 5]> { - let get = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()); - let (a, b) = (Vec2::new(get(10)?, get(20)?), Vec2::new(get(11)?, get(21)?)); + let [(_, x1), (_, y1), (_, x2), (_, y2)] = ole_corner_groups(tags)?; + let (a, b) = (Vec2::new(x1, y1), Vec2::new(x2, y2)); Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a]) } +/// Move an OLE2FRAME by `m`, a translation: its two corners are mapped through `m` (a DWG save +/// writes the frame's position from these groups). Other transforms do not keep a frame axis +/// aligned, so callers refuse them (see [`ole_frame_accepts`]). A frame with no usable corners is +/// left alone. +pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { + let Some([(ix1, x1), (iy1, y1), (ix2, x2), (iy2, y2)]) = ole_corner_groups(tags) else { return }; + let (a, b) = (m.apply(Vec2::new(x1, y1)), m.apply(Vec2::new(x2, y2))); + if !(a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { + return; + } + for (i, v) in [(ix1, a.x), (iy1, a.y), (ix2, b.x), (iy2, b.y)] { + if let Some(t) = tags.get_mut(i) { + t.value = v.to_string(); + } + } +} + +/// Whether `m` can move an OLE2FRAME: only a translation (move, copy, stretch of the whole frame). +pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool { + const T: f64 = 1e-12; + (m.a - 1.0).abs() < T && m.b.abs() < T && m.c.abs() < T && (m.d - 1.0).abs() < T +} + /// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification /// the same way the renderer places it (the stroke font is about 0.88 of the height per character). fn text_box(t: &crate::Text, len: usize) -> Bounds2 { @@ -461,4 +510,26 @@ mod tests { assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty()); assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty()); } + + /// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not + /// to the frame: the real corners come after it (review on #2587). + #[test] + fn ole_frame_skips_application_groups() { + let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() }; + let tags = vec![ + tag(102, "{ACAD_REACTORS"), + tag(10, "900"), + tag(20, "900"), + tag(11, "901"), + tag(21, "901"), + tag(102, "}"), + tag(10, "30"), + tag(20, "-19"), + tag(11, "35"), + tag(21, "-22"), + ]; + let q = ole_frame(&tags).expect("frame"); + assert_eq!((q[0], q[2]), (Vec2::new(30.0, -19.0), Vec2::new(35.0, -22.0))); + assert!(ole_frame(&tags[..6]).is_none(), "corners only inside the group are not a frame"); + } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 55169219f..748f2c9e8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -27,7 +27,7 @@ pub use cadcraft_color as color; pub use cadcraft_geom as geom; pub use constraint::*; pub use entity::*; -pub use extents::{MAX_BLOCK_DEPTH, entity_bounds, extent_bounds, ole_frame}; +pub use extents::{MAX_BLOCK_DEPTH, entity_bounds, extent_bounds, ole_frame, ole_frame_accepts, ole_frame_transform}; pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 5a86d9e07..c4a507262 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -4,6 +4,17 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, f6 pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { let d = s.doc_mut()?; + // An OLE2FRAME only translates (its corners stay axis aligned); refuse the rest before anything + // changes, instead of reporting success and leaving the frame where it was. + if !cadcraft_doc::ole_frame_accepts(m) + && hs.iter().any(|h| { + d.entity(*h).is_some_and(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME"))) + }) + { + return Err(crate::EngineError::Other( + "An OLE object can only be moved or copied; rotating, scaling and mirroring it are not supported.".into(), + )); + } let mut out = Vec::new(); for h in hs { let Some(sp) = d.space_of(*h) else { continue }; diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs new file mode 100644 index 000000000..0c0fade22 --- /dev/null +++ b/crates/engine/tests/ole_frame_transform.rs @@ -0,0 +1,57 @@ +//! An OLE2FRAME is window-selectable (it counts in the extents, #2422): MOVE and COPY carry it by +//! the offset, and the transforms that would not keep it axis aligned are refused before anything +//! reports success (review on #2587). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Common, Drawing, EntityKind, RawTag, Space, Unknown}; +use serde_json::json; + +fn session() -> (Session, String) { + let tag = |code: i32, v: &str| RawTag { code, value: v.into() }; + let mut d = Drawing::new_imperial(); + let kind = + EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] }); + let h = d.add(&Space::Model, Common::default(), kind).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "ole.dxf", None); + (s, h.hex()) +} + +fn corners(s: &Session) -> Vec<(i32, String)> { + let d = s.doc().unwrap(); + d.model + .iter() + .filter_map(|e| { + if let EntityKind::Unknown(u) = &e.kind { Some(u.tags.iter().map(|t| (t.code, t.value.clone())).collect::>()) } else { None } + }) + .flatten() + .collect() +} + +#[test] +fn move_and_copy_carry_an_ole_frame() { + let (mut s, h) = session(); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let want: Vec<(i32, String)> = [(10, "40"), (20, "-14"), (11, "45"), (21, "-17")].iter().map(|(c, v)| (*c, v.to_string())).collect(); + assert_eq!(corners(&s), want); + s.execute("copy", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let all = corners(&s); + assert_eq!(all.len(), 8); + assert_eq!(all[4..].iter().map(|(_, v)| v.as_str()).collect::>(), ["50", "-9", "55", "-12"]); +} + +#[test] +fn rotate_scale_and_mirror_refuse_an_ole_frame() { + let (mut s, h) = session(); + let before = corners(&s); + for (cmd, p) in [ + ("rotate", json!({ "handles": [h], "base": [0, 0], "angle": 30 })), + ("scale", json!({ "handles": [h], "base": [0, 0], "factor": 2 })), + ("mirror", json!({ "handles": [h], "p1": [0, 0], "p2": [1, 0] })), + ] { + let e = s.execute(cmd, &p).expect_err(cmd); + assert!(e.to_string().contains("OLE object"), "{cmd}: {e}"); + } + assert_eq!(corners(&s), before); + assert_eq!(s.doc().unwrap().model.len(), 1, "nothing was copied"); +} diff --git a/crates/io/tests/it/ole_frame.rs b/crates/io/tests/it/ole_frame.rs index c8c8c73a0..0ca0bc23e 100644 --- a/crates/io/tests/it/ole_frame.rs +++ b/crates/io/tests/it/ole_frame.rs @@ -60,3 +60,18 @@ fn a_dwg_keeps_an_ole_frame_with_its_data_and_position() { assert_eq!((corner(10), corner(20), corner(11), corner(21)), (Some(UL.0), Some(UL.1), Some(LR.0), Some(LR.1)), "{v:?}: frame corners"); } } + +/// A frame moved through its corner tags (what MOVE does) keeps the new position in a DWG save +/// and read-back (review on #2587). +#[test] +fn a_moved_ole_frame_keeps_its_position_in_a_dwg() { + let mut d = read_dxf(dxf().as_bytes()).unwrap(); + for h in d.model.handles() { + d.model.modify(h, |e| e.kind.transform(&cadcraft_geom::Mat3::translate(cadcraft_geom::Vec2::new(100.0, -50.0)))); + } + let dwg = write_with(&d, "x.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap(); + let u = ole(&read(&dwg, "x.dwg").unwrap()).unwrap(); + let c = |code: i32| u.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + assert!(near(c(10), UL.0 + 100.0) && near(c(20), UL.1 - 50.0) && near(c(11), LR.0 + 100.0) && near(c(21), LR.1 - 50.0), "{:?}", u.tags); +} From 09b5fb9328fbf706aa58aec54ba0277facf4aad2 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 18:40:45 +1100 Subject: [PATCH 145/531] Plot: refuse a path whose extension names no format (review on #2585) A path like x.txt (or one with no extension) wrote a PDF under that name. Like EXPORT, PLOT now refuses it unless output or a device says what to write. Test: plot_path_extension_picks_the_format_like_export. --- crates/engine/src/cmd/layout/tests.rs | 33 +++++++++++++++++++++++++++ crates/engine/src/cmd/plotters.rs | 13 +++++++++++ crates/engine/tests/plot_format.rs | 7 +++--- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 9bb73f5fc..2cb9b0c2e 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -303,3 +303,36 @@ fn mspace_edits_model_through_viewport() { s.execute("layout.set", &json!({"name": "Model"})).unwrap(); assert!(s.state().unwrap().mspace.is_none()); } + +/// The path's extension picks the plot format as EXPORT does, in any case; one that names no +/// format (or none) is refused instead of writing a PDF under that name, and a device that writes +/// another format is refused. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn plot_path_extension_picks_the_format_like_export() { + super::super::file::set_io(super::super::file::IoHooks { + read: |_, _| Err("no reader in tests".into()), + write: |_, _| Err("no writer in tests".into()), + plot: Some(fake_plot), + }); + if io().and_then(|h| h.plot).is_none() { + return; // another test installed hooks without a plotter first + } + let mut s = session_with_model(); + let dir = std::env::temp_dir().join(format!("cadcraft-plot-ext-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = |n: &str| dir.join(n).to_string_lossy().to_string(); + let upper = s.execute("plot", &json!({"path": path("X.PNG")})).unwrap(); + assert_eq!(upper["format"], "png", "an upper-case extension still picks png"); + let e = s.execute("plot", &json!({"path": path("x.txt")})).unwrap_err().to_string(); + assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}"); + assert!(!dir.join("x.txt").exists(), "nothing written under an unknown extension"); + let e = s.execute("plot", &json!({"path": path("noext")})).unwrap_err().to_string(); + assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}"); + assert!(!dir.join("noext").exists()); + let e = s.execute("plot", &json!({"path": path("y.png"), "device": "CADCraft PDF"})).unwrap_err().to_string(); + assert!(e.contains("writes pdf") && e.contains("png"), "{e}"); + // An explicit output still decides for an odd name. + assert_eq!(s.execute("plot", &json!({"path": path("z.txt"), "output": "pdf"})).unwrap()["format"], "pdf"); + std::fs::remove_dir_all(&dir).ok(); +} diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 521b67cf9..d9aed574f 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -296,6 +296,19 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { // The path's extension names the format, like EXPORT, unless a device is given; a given // device that writes another format is refused. EXPORTPDF always writes PDF. let by_path = if cmd == "exportpdf" { None } else { str_param(p, "path").and_then(path_output) }; + // A path whose extension names no format (or has none) would hold a PDF under that name: + // refuse it, as EXPORT does, unless `output` or a device says what to write. + if cmd == "plot" + && by_path.is_none() + && p.get("output").is_none() + && !given.is_some_and(|n| !n.is_empty()) + && let Some(path) = str_param(p, "path") + { + return Err(bad( + cmd, + format!("can't tell the format of `{path}`: give a path ending in .png, .svg or .pdf, or set `output` to png, svg or pdf"), + )); + } if let (Some(want), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty())) && dev.output != want { diff --git a/crates/engine/tests/plot_format.rs b/crates/engine/tests/plot_format.rs index 1f4509c8c..48a4306bb 100644 --- a/crates/engine/tests/plot_format.rs +++ b/crates/engine/tests/plot_format.rs @@ -36,11 +36,12 @@ fn the_extension_picks_png_svg_or_pdf() { assert_eq!(r["format"], format, "{name}: the reply names the format"); assert_eq!(magic(&out), head, "{name}: the file holds that format"); } - // No path, or an extension that names no format: PDF as before. + // No path: PDF data as before. An extension that names no format is refused, like EXPORT. assert_eq!(s.execute("plot", &json!({ "layout": "Model" })).unwrap()["format"], "pdf"); let other = dir.join("e.plt"); - assert_eq!(s.execute("plot", &json!({ "path": other.to_string_lossy(), "layout": "Model" })).unwrap()["format"], "pdf"); - assert_eq!(magic(&other), b"%PDF-"); + let e = s.execute("plot", &json!({ "path": other.to_string_lossy(), "layout": "Model" })).unwrap_err().to_string(); + assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}"); + assert!(!other.exists(), "nothing is written under a name that is not a format"); // EXPORTPDF always writes PDF. let pdf = dir.join("f.png"); s.execute("exportpdf", &json!({ "path": pdf.to_string_lossy(), "layout": "Model" })).unwrap(); From b1bab3043c236a6bfae7e9effd60368e551ac2f4 Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:46:57 +0100 Subject: [PATCH 146/531] test(ui): Properties palette with several objects: undo, mixed types, one object Covers the cases a reviewer asked for: one undo restores every edited object, a mixed selection shows General only (no Radius row), and one object shows its own value with nothing varying. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 97 ++++++++++++++++++++++++++++------ 1 file changed, 82 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 4bb363d67..2485e8a60 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1600,29 +1600,96 @@ mod tests { .collect() } + /// The radius of each circle in `handles`, selected or not. + fn radii_of(app: &CadApp, handles: &[String]) -> Vec { + let d = app.session.doc().unwrap(); + handles + .iter() + .filter_map(|h| d.entity(cadcraft_doc::Handle::parse_hex(h)?)) + .filter_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }) + .collect() + } + + /// A palette showing `app`'s selection, a few frames in. + fn palette(app: CadApp) -> egui_kittest::Harness<'static, CadApp> { + let mut h = + egui_kittest::Harness::builder().with_size(vec2(400.0, 1200.0)).build_ui_state(|ui, app: &mut CadApp| properties_section(app, ui), app); + h.run_steps(3); + h + } + + /// Types `text` into the first `*VARIES*` field (the Radius, whose row comes first) and commits it. + fn type_into_first_varies(h: &mut egui_kittest::Harness<'static, CadApp>, text: &str) { + let field = h.get_all_by_value(VARIES).next().unwrap(); + field.focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(2); + h.get_all_by_value(VARIES).next().unwrap().type_text(text); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + } + + fn circles(app: &mut CadApp, radii: &[i32], extra: Value) -> Vec { + radii + .iter() + .map(|r| { + let mut p = json!({ "center": [0, 0], "radius": r }); + if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) { + o.extend(e.clone()); + } + app.run("circle", p).unwrap()["handle"].as_str().unwrap().to_string() + }) + .collect() + } + /// A value typed into the palette goes to every selected object, not just the first. #[test] fn typing_a_shared_value_changes_every_selected_object() { let mut app = CadApp::new(Session::default(), Services::default()); - let handles: Vec = - [2, 5, 9].map(|r| app.run("circle", json!({ "center": [0, 0], "radius": r })).unwrap()["handle"].as_str().unwrap().to_string()).to_vec(); + let handles = circles(&mut app, &[2, 5, 9], json!({})); app.run("select", json!({ "handles": handles })).unwrap(); - let mut h = - egui_kittest::Harness::builder().with_size(vec2(400.0, 1200.0)).build_ui_state(|ui, app: &mut CadApp| properties_section(app, ui), app); - h.run_steps(3); - // The first `*VARIES*` field is the Radius: its row comes first. - let radius = h.get_all_by_value(VARIES).next().unwrap(); - radius.focus(); - h.run_steps(2); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(2); - h.get_all_by_value(VARIES).next().unwrap().type_text("7"); - h.run_steps(2); - h.key_press(egui::Key::Enter); - h.run_steps(3); + let mut h = palette(app); + type_into_first_varies(&mut h, "7"); assert_eq!(selected_radii(h.state()), vec![7.0, 7.0, 7.0], "all three circles take the typed radius"); } + /// The edit to several objects is one undo step. + #[test] + fn editing_several_objects_is_one_undo_step() { + let mut app = CadApp::new(Session::default(), Services::default()); + let handles = circles(&mut app, &[2, 5, 9], json!({})); + app.run("select", json!({ "handles": handles.clone() })).unwrap(); + let mut h = palette(app); + type_into_first_varies(&mut h, "7"); + assert_eq!(radii_of(h.state(), &handles), vec![7.0, 7.0, 7.0], "the edit reached all three"); + h.state_mut().run("undo", json!({})).unwrap(); + assert_eq!(radii_of(h.state(), &handles), vec![2.0, 5.0, 9.0], "one undo puts back all three radii"); + } + + /// A mixed selection has no type to show: only the properties every object has (General), so + /// no Radius row, however different the circles' radii are. One object is unchanged: its own + /// values, nothing varies. + #[test] + fn mixed_types_show_general_only_and_one_object_is_unchanged() { + let mut app = CadApp::new(Session::default(), Services::default()); + let mut handles = circles(&mut app, &[2, 5], json!({})); + let line = app.run("line", json!({ "points": [[0, 0], [10, 0]] })).unwrap()["handles"][0].as_str().unwrap().to_string(); + let circles_only = handles.clone(); + handles.push(line); + app.run("select", json!({ "handles": handles })).unwrap(); + let mut h = palette(app); + assert_eq!(h.query_all_by_value(VARIES).count(), 0, "two circles and a line show no Radius to vary"); + h.state_mut().run("select", json!({ "handles": circles_only.clone() })).unwrap(); + h.run_steps(3); + assert!(h.query_all_by_value(VARIES).count() > 0, "the two circles alone do show it"); + h.state_mut().run("select", json!({ "handles": [circles_only[0].clone()] })).unwrap(); + h.run_steps(3); + assert_eq!(h.query_all_by_value(VARIES).count(), 0, "one circle shows its own radius"); + assert!(h.query_all_by_value("2.0000").count() > 0); + } + /// The values the palette works out are kept for a drawing revision and a selection, and /// worked out again when either changes. #[test] From c1b88a6cbcb76744f97d58ca71795c39b61d96b3 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 19:21:22 +1100 Subject: [PATCH 147/531] OLE2FRAME: an image export notes that the OLE content is not drawn (review on #2587) --- apps/cadcraft-cli/src/output.rs | 27 ++++++++++++------- .../cadcraft-cli/tests/it/undrawn_entities.rs | 10 ++++--- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index d7471e7b1..8a8f7d97c 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -150,22 +150,31 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option, io /// as unknown objects, `Proxy` in `info`), or `None` when there are none. pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option { let mut types: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + let mut ole = 0usize; for e in d.model.iter() { - // An OLE2FRAME's frame outline is drawn (the OLE content is not), so it isn't reported. - if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind - && !u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") - { + // An OLE2FRAME's frame outline is drawn, so it isn't an undrawn entity; its content is + // not, which gets a note of its own. + if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind { + if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") { + ole = ole.saturating_add(1); + continue; + } let n = types.entry(u.dxf_type.as_str()).or_insert(0); *n = n.saturating_add(1); } } let n = types.values().fold(0usize, |a, n| a.saturating_add(*n)); - if n == 0 { - return None; + let mut lines = Vec::new(); + if n > 0 { + let list: Vec = types.iter().map(|(t, n)| format!("{t}: {n}")).collect(); + let entities = if n == 1 { "entity" } else { "entities" }; + lines.push(format!("{path}: {n} {entities} not drawn ({})", list.join(", "))); } - let list: Vec = types.iter().map(|(t, n)| format!("{t}: {n}")).collect(); - let entities = if n == 1 { "entity" } else { "entities" }; - Some(format!("{path}: {n} {entities} not drawn ({})", list.join(", "))) + if ole > 0 { + let objects = if ole == 1 { "object" } else { "objects" }; + lines.push(format!("{path}: {ole} OLE {objects} shown as the frame only (the OLE content is not drawn)")); + } + if lines.is_empty() { None } else { Some(lines.join("\n")) } } /// The warning for the records of `path` the reader could not place, or `None` when there are none. diff --git a/apps/cadcraft-cli/tests/it/undrawn_entities.rs b/apps/cadcraft-cli/tests/it/undrawn_entities.rs index ca5338c2f..8b176cbbc 100644 --- a/apps/cadcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/cadcraft-cli/tests/it/undrawn_entities.rs @@ -70,9 +70,10 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() { assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); } -/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it undrawn (#2422). +/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it +/// says once that the OLE content inside the frame is not drawn (review on #2587). #[test] -fn an_ole_frame_is_not_reported_as_undrawn() { +fn an_ole_frame_is_noted_as_frame_only() { let scratch = Scratch::new("ole"); let dir = scratch.0.clone(); let input = dir.join("ole.dxf"); @@ -80,5 +81,8 @@ fn an_ole_frame_is_not_reported_as_undrawn() { std::fs::write(&input, ole).unwrap(); let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]); assert!(out.status.success()); - assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!err.contains("entity not drawn") && !err.contains("entities not drawn"), "{err}"); + let notes: Vec<&str> = err.lines().filter(|l| l.contains("OLE")).collect(); + assert_eq!(notes, [format!("{}: 1 OLE object shown as the frame only (the OLE content is not drawn)", input.display())], "{err}"); } From afb24ee6e5da70bec7bb85f2814c33d7a01844f9 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 21:08:47 +1100 Subject: [PATCH 148/531] OLE2FRAME: MOVE also moves the corners inside the OLE data (review on #2587) The OLE data (310 groups) starts with the frame's four corners. MOVE shifted groups 10/20/11/21 only, so a DXF save wrote new corner groups beside a data header with the old position. The transform now rewrites those doubles (x, y; z kept) in the decoded hex, keeping each chunk's length; malformed or short data is left untouched. --- crates/doc/src/extents.rs | 57 +++++++++++++++++- crates/engine/tests/ole_frame_transform.rs | 69 ++++++++++++++++++++++ crates/io/tests/it/ole_frame.rs | 19 ++++++ 3 files changed, 144 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 4bbdf3cf9..4aff09d8b 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -43,8 +43,62 @@ pub fn ole_frame(tags: &[crate::RawTag]) -> Option<[Vec2; 5]> { Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a]) } +/// The bytes of the OLE data before its corners: a 2-byte marker. +const OLE_HEADER: usize = 2; +/// The corners in the OLE data: four of x, y, z as little-endian doubles (upper left, upper right, +/// lower right, lower left). +const OLE_CORNERS: usize = 12; + +/// Move the four corners at the start of the OLE data (the 310 groups' hex, in order) by `m`, +/// keeping z and every tag's length. Data that is not valid hex or is too short is left alone. +fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { + let idx: Vec = outside_app(tags).into_iter().filter(|&i| tags.get(i).is_some_and(|t| t.code == 310)).collect(); + let mut bytes: Vec = Vec::new(); + let mut lens: Vec = Vec::new(); + for &i in &idx { + let Some(t) = tags.get(i) else { return }; + let s = t.value.trim(); + if s.len() % 2 != 0 || !s.is_ascii() { + return; + } + for k in (0..s.len()).step_by(2) { + let Some(b) = s.get(k..k + 2).and_then(|h| u8::from_str_radix(h, 16).ok()) else { return }; + bytes.push(b); + } + lens.push(s.len() / 2); + } + let end = OLE_HEADER + OLE_CORNERS * 8; + if bytes.len() < end { + return; + } + let mut out = bytes.clone(); + for c in 0..4 { + let at = OLE_HEADER + c * 24; + let rd = |o: usize| out.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).filter(|v| v.is_finite()); + let (Some(x), Some(y)) = (rd(at), rd(at + 8)) else { return }; + let p = m.apply(Vec2::new(x, y)); + if !(p.x.is_finite() && p.y.is_finite()) { + return; + } + if let Some(s) = out.get_mut(at..at + 8) { + s.copy_from_slice(&p.x.to_le_bytes()); + } + if let Some(s) = out.get_mut(at + 8..at + 16) { + s.copy_from_slice(&p.y.to_le_bytes()); + } + } + let mut pos = 0; + for (&i, &n) in idx.iter().zip(&lens) { + let (Some(t), Some(chunk)) = (tags.get_mut(i), out.get(pos..pos + n)) else { return }; + let lower = t.value.bytes().any(|b| b.is_ascii_lowercase()); + t.value = chunk.iter().map(|b| if lower { format!("{b:02x}") } else { format!("{b:02X}") }).collect(); + pos += n; + } +} + /// Move an OLE2FRAME by `m`, a translation: its two corners are mapped through `m` (a DWG save -/// writes the frame's position from these groups). Other transforms do not keep a frame axis +/// writes the frame's position from these groups), and so are the corners at the start of its OLE +/// data (310 groups), which a reader of the saved file may trust instead. Other transforms do not keep a frame axis /// aligned, so callers refuse them (see [`ole_frame_accepts`]). A frame with no usable corners is /// left alone. pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { @@ -58,6 +112,7 @@ pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) t.value = v.to_string(); } } + ole_data_transform(tags, m); } /// Whether `m` can move an OLE2FRAME: only a translation (move, copy, stretch of the whole frame). diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index 0c0fade22..50ecc1f2f 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -55,3 +55,72 @@ fn rotate_scale_and_mirror_refuse_an_ole_frame() { assert_eq!(corners(&s), before); assert_eq!(s.doc().unwrap().model.len(), 1, "nothing was copied"); } + +/// The OLE data's marker and four corners (x, y, z doubles each), as hex split into chunks. +fn data_session(chunks: &[usize], hex_override: Option<&str>) -> (Session, String) { + let tag = |code: i32, v: &str| RawTag { code, value: v.into() }; + let mut blob = vec![1u8, 0]; + for (x, y) in [(30.0f64, -19.0f64), (35.0, -19.0), (35.0, -22.0), (30.0, -22.0)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let hex: String = hex_override.map(str::to_string).unwrap_or_else(|| blob.iter().map(|b| format!("{b:02X}")).collect()); + let mut tags = vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]; + let mut at = 0; + for &n in chunks { + let end = (at + n).min(hex.len()); + tags.push(tag(310, &hex[at..end])); + at = end; + } + if at < hex.len() { + tags.push(tag(310, &hex[at..])); + } + let mut d = Drawing::new_imperial(); + let h = d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags })).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "ole.dxf", None); + (s, h.hex()) +} + +fn data_tags(s: &Session) -> Vec { + let d = s.doc().unwrap(); + d.model + .iter() + .filter_map(|e| { + if let EntityKind::Unknown(u) = &e.kind { + Some(u.tags.iter().filter(|t| t.code == 310).map(|t| t.value.clone()).collect::>()) + } else { + None + } + }) + .flatten() + .collect() +} + +#[test] +fn move_also_moves_the_corners_in_the_ole_data() { + let (mut s, h) = data_session(&[10, 100, 40], None); + let before = data_tags(&s); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let after = data_tags(&s); + assert_eq!(after.iter().map(String::len).collect::>(), before.iter().map(String::len).collect::>(), "chunk lengths are kept"); + let hex: String = after.concat(); + let bytes: Vec = (0..hex.len() / 2).map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()).collect(); + let f = |o: usize| f64::from_le_bytes(bytes[o..o + 8].try_into().unwrap()); + let want = [(40.0, -14.0), (45.0, -14.0), (45.0, -17.0), (40.0, -17.0)]; + for (c, (x, y)) in want.iter().enumerate() { + assert_eq!((f(2 + c * 24), f(10 + c * 24), f(18 + c * 24)), (*x, *y, 7.0), "corner {c}"); + } +} + +#[test] +fn move_leaves_malformed_or_short_ole_data_alone() { + for (chunks, hex) in [(vec![4], "0100"), (vec![3, 3], "ABCDE"), (vec![10], "ZZ0100ZZ0100"), (vec![2], "é")] { + let (mut s, h) = data_session(&chunks, Some(hex)); + let before = data_tags(&s); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + assert_eq!(data_tags(&s), before, "{hex}"); + assert_eq!(corners(&s)[0].1, "40", "the corner groups still move"); + } +} diff --git a/crates/io/tests/it/ole_frame.rs b/crates/io/tests/it/ole_frame.rs index 0ca0bc23e..188987db5 100644 --- a/crates/io/tests/it/ole_frame.rs +++ b/crates/io/tests/it/ole_frame.rs @@ -75,3 +75,22 @@ fn a_moved_ole_frame_keeps_its_position_in_a_dwg() { let near = |a: f64, b: f64| (a - b).abs() < 1e-9; assert!(near(c(10), UL.0 + 100.0) && near(c(20), UL.1 - 50.0) && near(c(11), LR.0 + 100.0) && near(c(21), LR.1 - 50.0), "{:?}", u.tags); } + +/// After a move, a DXF save and read-back carries the moved corners both in groups 10/11 and in +/// the OLE data header (review on #2587). +#[test] +fn a_moved_ole_frame_keeps_its_data_header_in_a_dxf() { + let mut d = read_dxf(dxf().as_bytes()).unwrap(); + for h in d.model.handles() { + d.model.modify(h, |e| e.kind.transform(&cadcraft_geom::Mat3::translate(cadcraft_geom::Vec2::new(100.0, -50.0)))); + } + let bytes = write_with(&d, "x.dxf", &SaveOptions { version: None, binary: false }).unwrap(); + let u = ole(&read_dxf(&bytes).unwrap()).unwrap(); + let hex: String = u.tags.iter().filter(|t| t.code == 310).map(|t| t.value.clone()).collect(); + let b: Vec = (0..hex.len() / 2).map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()).collect(); + let f = |o: usize| f64::from_le_bytes(b[o..o + 8].try_into().unwrap()); + let near = |a: f64, c: f64| (a - c).abs() < 1e-9; + assert!(near(f(2), UL.0 + 100.0) && near(f(10), UL.1 - 50.0) && near(f(2 + 48), LR.0 + 100.0) && near(f(10 + 48), LR.1 - 50.0)); + let g = |code: i32| u.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).unwrap(); + assert!(near(g(10), UL.0 + 100.0) && near(g(21), LR.1 - 50.0)); +} From 63bc5381134ad73ead4263e87ce1d3e261100639 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 22:09:49 +1100 Subject: [PATCH 149/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 5fb179f5a..a91ee2f25 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -4,7 +4,7 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 446 registered commands. +**Menu breadth: 298 / 491 items (61%)** · 449 registered commands. | Menu | Items | Covered | % | |---|---|---|---| From 0e871873e7fadc01a62a4a5301fb097ea5f0f8b0 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 22:20:09 +1100 Subject: [PATCH 150/531] Plot: refuse layout and layouts that name different sheets (review on #2585) layout picked the rendered space while layouts filled the reply, so a request could render Model and report Layout1. Both selectors must now agree, for every output. Test: plot_goes_through_the_hook. --- crates/engine/src/cmd/layout.rs | 6 ++++++ crates/engine/src/cmd/layout/tests.rs | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index ae4c1de0b..d2a6155db 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -785,6 +785,12 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { // Checked here for a clear error; the plotter resolves the names the same way. let sheets = p.get("layouts").map(|v| plot_sheets(cmd, s.doc()?, v)).transpose()?; + // `layout` and `layouts` must name the same sheet(s), or the reply would name one sheet and the render another. + if let (Some(n), Some(names)) = (str_param(p, "layout"), sheets.as_deref()) + && !matches!(names, [only] if only.eq_ignore_ascii_case(n)) + { + return Err(bad(cmd, "`layout` and `layouts` name different sheets; give only one of them")); + } let is_image = p.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg")); let space = match str_param(p, "layout") { Some(n) if n.eq_ignore_ascii_case("model") => Space::Model, diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 2cb9b0c2e..75489a8a7 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -236,6 +236,14 @@ fn plot_goes_through_the_hook() { assert!(e.to_string().contains("layouts"), "{e}"); } assert!(s.execute("plot", &json!({"output": "png", "layouts": ["Layout1", "Layout2"]})).is_err()); + // `layout` and `layouts` naming different sheets are refused (the reply would name one sheet and the render another); agreeing ones pass. + for p in + [json!({"output": "png", "layout": "Model", "layouts": ["Layout1"]}), json!({"output": "pdf", "layout": "Layout1", "layouts": ["Model"]})] + { + let e = s.execute("plot", &p).unwrap_err().to_string(); + assert!(e.contains("different"), "{e}"); + } + assert_eq!(s.execute("plot", &json!({"output": "png", "layout": "layout1", "layouts": ["Layout1"]})).unwrap()["layout"], "Layout1"); let one = s.execute("plot", &json!({"output": "png", "layouts": ["Layout1"]})).unwrap(); assert_eq!(one["layout"], "Layout1"); let text = String::from_utf8(super::super::file::base64_decode(one["data"].as_str().unwrap()).unwrap()).unwrap(); From d6555e5bdf2c92182c65e79c8a935e7b62699adb Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 22:20:10 +1100 Subject: [PATCH 151/531] Plot: an unknown extension needs a real format selector (review on #2585) device None and a null or unknown output no longer bypass the refusal and write a PDF under the odd name; only a recognised output or a device that resolves does. Test: plot_path_extension_picks_the_format_like_export. --- crates/engine/src/cmd/layout/tests.rs | 10 ++++++++++ crates/engine/src/cmd/plotters.rs | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 75489a8a7..d4c82e17d 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -340,6 +340,16 @@ fn plot_path_extension_picks_the_format_like_export() { assert!(!dir.join("noext").exists()); let e = s.execute("plot", &json!({"path": path("y.png"), "device": "CADCraft PDF"})).unwrap_err().to_string(); assert!(e.contains("writes pdf") && e.contains("png"), "{e}"); + // A device that resolves to none, or a null/unknown `output`, names no format: the refusal stands. + for p in [ + json!({"path": path("x.txt"), "device": "None"}), + json!({"path": path("x.txt"), "output": null}), + json!({"path": path("x.txt"), "output": "bogus"}), + ] { + let e = s.execute("plot", &p).unwrap_err().to_string(); + assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}"); + assert!(!dir.join("x.txt").exists(), "nothing written under an unknown extension"); + } // An explicit output still decides for an odd name. assert_eq!(s.execute("plot", &json!({"path": path("z.txt"), "output": "pdf"})).unwrap()["format"], "pdf"); std::fs::remove_dir_all(&dir).ok(); diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index d9aed574f..a8ac31818 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -300,8 +300,8 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { // refuse it, as EXPORT does, unless `output` or a device says what to write. if cmd == "plot" && by_path.is_none() - && p.get("output").is_none() - && !given.is_some_and(|n| !n.is_empty()) + && !p.get("output").and_then(Value::as_str).is_some_and(|o| PlotOutput::parse(o).is_some()) + && !(dev.is_some() && given.is_some_and(|n| !n.is_empty())) && let Some(path) = str_param(p, "path") { return Err(bad( From 0c486e337a880dee0f218d4b0692978637f9892f Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 22:25:36 +1100 Subject: [PATCH 152/531] Engine: refuse rotating, scaling or mirroring an OLE frame on main's transform paths (#2587) Main moved the edit loop into edit_entities and gave SCALE its own scale_entities, so the merged check no longer compiled (CI: m not in scope). The refusal is now one helper that transform_entities and scale_entities call before anything changes. --- crates/engine/src/cmd/modify/transform.rs | 31 +++++++++++++++-------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index e3765713c..b3b897847 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -5,6 +5,7 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, f6 // ---------------- core operations ---------------- pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { + refuse_ole_frames(s, hs, m)?; edit_entities(s, hs, copy, |e| e.kind.transform(m)) } @@ -12,6 +13,7 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: /// and every height of the objects about its Z, their thickness too. pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result> { let m = Mat3::scale_about(base.xy(), f); + refuse_ole_frames(s, hs, &m)?; edit_entities(s, hs, copy, |e| { e.kind.transform(&m); e.kind.scale_heights(base.z, f); @@ -19,6 +21,24 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, }) } +/// An OLE2FRAME only translates (its corners stay axis aligned): refuse any other `m` before anything +/// changes, instead of reporting success and leaving the frame where it was. +fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3) -> Result<()> { + if cadcraft_doc::ole_frame_accepts(m) { + return Ok(()); + } + let d = s.doc()?; + let ole = |h: &Handle| { + d.entity(*h).is_some_and(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME"))) + }; + if hs.iter().any(ole) { + return Err(crate::EngineError::Other( + "An OLE object can only be moved or copied; rotating, scaling and mirroring it are not supported.".into(), + )); + } + Ok(()) +} + /// `p` at the current elevation (ELEVATION), the Z AutoCAD gives a point entered without one. pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 { let z = s.doc().map(|d| d.header.f64("ELEVATION", 0.0)).ok().filter(|z| z.is_finite()); @@ -29,17 +49,6 @@ pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 { /// on a locked layer is left alone unless it is copied. The handles edited or made. fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut Entity)) -> Result> { let d = s.doc_mut()?; - // An OLE2FRAME only translates (its corners stay axis aligned); refuse the rest before anything - // changes, instead of reporting success and leaving the frame where it was. - if !cadcraft_doc::ole_frame_accepts(m) - && hs.iter().any(|h| { - d.entity(*h).is_some_and(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME"))) - }) - { - return Err(crate::EngineError::Other( - "An OLE object can only be moved or copied; rotating, scaling and mirroring it are not supported.".into(), - )); - } let mut out = Vec::new(); for h in hs { let Some(sp) = d.space_of(*h) else { continue }; From b8efe39acc5f4e2b8d6aefbc481ed722a08b6ff2 Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:42:12 +0100 Subject: [PATCH 153/531] fix(ui): Properties palette tells values apart that the display rounds alike The shared values of several objects were compared as the text each row shows, so a text height of 7 and one of 7.000001 (both "7.0000") read as one common value. Numeric rows now carry the number they were formatted from and compare it to 12 significant digits, which separates anything the display could show at 8 decimals and ignores float noise. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 111 +++++++++++++++++++++++---------- 1 file changed, 78 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 2485e8a60..f6ef6e5a5 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -762,6 +762,22 @@ fn selection_memo(ui: &egui::Ui, app: &CadApp, sel: &[cadcraft_engine::doc::Hand memo } +/// Separates what a numeric row shows from the value it was worked out from, so that two objects +/// whose values differ by less than the display shows still count as different. The value is +/// compared to 12 significant digits, which keeps float noise (a length that comes out as +/// 5.000000000000001) from reading as a difference. +const EXACT_SEP: char = '\u{1f}'; + +/// `shown`, tagged with the number `v` it was formatted from. +fn exact(shown: String, v: f64) -> String { + format!("{shown}{EXACT_SEP}{:.11e}", v + 0.0) +} + +/// What a row shows of a value that [`exact`] tagged (a plain string is shown as it is). +fn shown_part(s: &str) -> String { + s.split(EXACT_SEP).next().unwrap_or_default().to_string() +} + /// Properties palette: the selection's common properties, or the current defaults when nothing is selected; formats lengths per drawing units and dispatches setter commands. pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -773,6 +789,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { // Lengths are shown as the drawing's units say (UNITS), and read back in any format. let (lu, lp) = (h.i64("LUNITS", 2), h.i64("LUPREC", 4)); let len = |v: f64| cadcraft_engine::units::format_distance(v, lu, lp); + let lenx = |v: f64| exact(len(v), v); let mut bad: Option = None; if sel.is_empty() { // Current properties for new objects; each row runs the command that sets it. @@ -1058,6 +1075,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); let real = |v: f64| format!("{v:.4}"); + let realx = |v: f64| exact(real(v), v); // Rotations show as the drawing measures directions (ANGBASE, ANGDIR). let angles = app.session.angle_settings(); let num = |ui: &mut egui::Ui, label: &str, key: &str, shown: String, set: &mut Option, bad: &mut Option, ids: &Vec| { @@ -1244,7 +1262,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }) .collect(); match vals.first() { - Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), + Some(v0) if vals.iter().all(|v| v == v0) => shown_part(v0), _ => VARIES.into(), } }) @@ -1262,9 +1280,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); let numbers = [ - ("Text height", "textHeight", shared("dim.text_height", &|_, st| len(st.text_height))), - ("Arrow size", "arrowSize", shared("dim.arrow_size", &|_, st| len(st.arrow_size))), - ("Dim scale overall", "dimScale", shared("dim.scale", &|_, st| real(st.scale))), + ("Text height", "textHeight", shared("dim.text_height", &|_, st| lenx(st.text_height))), + ("Arrow size", "arrowSize", shared("dim.arrow_size", &|_, st| lenx(st.arrow_size))), + ("Dim scale overall", "dimScale", shared("dim.scale", &|_, st| realx(st.scale))), ]; for (label, key, shown) in numbers { prop_row(ui, label, |ui| { @@ -1288,31 +1306,32 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { memo.get(key, || { let vals: Vec> = sel.iter().filter_map(|h| d.entity(*h)).map(|x| f(&x.kind)).collect(); match vals.first() { - Some(Some(v0)) if vals.iter().all(|v| v.as_ref() == Some(v0)) => v0.clone(), + Some(Some(v0)) if vals.iter().all(|v| v.as_ref() == Some(v0)) => shown_part(v0), _ => VARIES.into(), } }) }; let deg = |v: f64| real(angles.shown(v).to_degrees()); + let degx = |v: f64| exact(deg(v), angles.shown(v).to_degrees()); match &e.kind { EntityKind::Line(_) => { let line = |k: &EntityKind| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None }; for (label, value) in [ - ("Start X", shared("line.ax", &|k| line(k).map(|l| len(l.a.x)))), - ("Start Y", shared("line.ay", &|k| line(k).map(|l| len(l.a.y)))), - ("End X", shared("line.bx", &|k| line(k).map(|l| len(l.b.x)))), - ("End Y", shared("line.by", &|k| line(k).map(|l| len(l.b.y)))), - ("Delta X", shared("line.dx", &|k| line(k).map(|l| len(l.b.x - l.a.x)))), - ("Delta Y", shared("line.dy", &|k| line(k).map(|l| len(l.b.y - l.a.y)))), + ("Start X", shared("line.ax", &|k| line(k).map(|l| lenx(l.a.x)))), + ("Start Y", shared("line.ay", &|k| line(k).map(|l| lenx(l.a.y)))), + ("End X", shared("line.bx", &|k| line(k).map(|l| lenx(l.b.x)))), + ("End Y", shared("line.by", &|k| line(k).map(|l| lenx(l.b.y)))), + ("Delta X", shared("line.dx", &|k| line(k).map(|l| lenx(l.b.x - l.a.x)))), + ("Delta Y", shared("line.dy", &|k| line(k).map(|l| lenx(l.b.y - l.a.y)))), ] { prop_row(ui, label, |ui| read_only(ui, &value)); } - num(ui, "Length", "length", shared("line.length", &|k| line(k).map(|l| len((l.b.xy() - l.a.xy()).len()))), &mut set, &mut bad, ids); + num(ui, "Length", "length", shared("line.length", &|k| line(k).map(|l| lenx((l.b.xy() - l.a.xy()).len()))), &mut set, &mut bad, ids); num( ui, "Angle", "angle", - shared("line.angle", &|k| line(k).map(|l| real((l.b.xy() - l.a.xy()).angle().to_degrees()))), + shared("line.angle", &|k| line(k).map(|l| realx((l.b.xy() - l.a.xy()).angle().to_degrees()))), &mut set, &mut bad, ids, @@ -1320,15 +1339,15 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } EntityKind::Circle(_) => { let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None }; - prop_row(ui, "Center X", |ui| read_only(ui, &shared("circle.cx", &|k| circle(k).map(|c| len(c.center.x))))); - prop_row(ui, "Center Y", |ui| read_only(ui, &shared("circle.cy", &|k| circle(k).map(|c| len(c.center.y))))); - num(ui, "Radius", "radius", shared("circle.radius", &|k| circle(k).map(|c| len(c.radius))), &mut set, &mut bad, ids); - num(ui, "Diameter", "diameter", shared("circle.diameter", &|k| circle(k).map(|c| len(c.radius * 2.0))), &mut set, &mut bad, ids); + prop_row(ui, "Center X", |ui| read_only(ui, &shared("circle.cx", &|k| circle(k).map(|c| lenx(c.center.x))))); + prop_row(ui, "Center Y", |ui| read_only(ui, &shared("circle.cy", &|k| circle(k).map(|c| lenx(c.center.y))))); + num(ui, "Radius", "radius", shared("circle.radius", &|k| circle(k).map(|c| lenx(c.radius))), &mut set, &mut bad, ids); + num(ui, "Diameter", "diameter", shared("circle.diameter", &|k| circle(k).map(|c| lenx(c.radius * 2.0))), &mut set, &mut bad, ids); num( ui, "Circumference", "circumference", - shared("circle.circumference", &|k| circle(k).map(|c| len(c.radius * std::f64::consts::TAU))), + shared("circle.circumference", &|k| circle(k).map(|c| lenx(c.radius * std::f64::consts::TAU))), &mut set, &mut bad, ids, @@ -1337,7 +1356,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { ui, "Area", "area", - shared("circle.area", &|k| circle(k).map(|c| real(c.radius * c.radius * std::f64::consts::PI))), + shared("circle.area", &|k| circle(k).map(|c| realx(c.radius * c.radius * std::f64::consts::PI))), &mut set, &mut bad, ids, @@ -1345,9 +1364,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } EntityKind::Arc(_) => { let arc = |k: &EntityKind| if let EntityKind::Arc(a) = k { Some(a.clone()) } else { None }; - num(ui, "Radius", "radius", shared("arc.radius", &|k| arc(k).map(|a| len(a.radius))), &mut set, &mut bad, ids); - num(ui, "Start angle", "startAngle", shared("arc.start", &|k| arc(k).map(|a| real(a.start.to_degrees()))), &mut set, &mut bad, ids); - num(ui, "End angle", "endAngle", shared("arc.end", &|k| arc(k).map(|a| real(a.end.to_degrees()))), &mut set, &mut bad, ids); + num(ui, "Radius", "radius", shared("arc.radius", &|k| arc(k).map(|a| lenx(a.radius))), &mut set, &mut bad, ids); + num(ui, "Start angle", "startAngle", shared("arc.start", &|k| arc(k).map(|a| realx(a.start.to_degrees()))), &mut set, &mut bad, ids); + num(ui, "End angle", "endAngle", shared("arc.end", &|k| arc(k).map(|a| realx(a.end.to_degrees()))), &mut set, &mut bad, ids); } EntityKind::Text(_) => { let contents = shared("text.value", &|k| if let EntityKind::Text(t) = k { Some(t.value.clone()) } else { None }); @@ -1356,11 +1375,11 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { set = Some(json!({ "handles": ids, "text": s })); } }); - let height = shared("text.height", &|k| if let EntityKind::Text(t) = k { Some(len(t.height)) } else { None }); + let height = shared("text.height", &|k| if let EntityKind::Text(t) = k { Some(lenx(t.height)) } else { None }); num(ui, "Height", "height", height, &mut set, &mut bad, ids); - let rotation = shared("text.rotation", &|k| if let EntityKind::Text(t) = k { Some(deg(t.rotation)) } else { None }); + let rotation = shared("text.rotation", &|k| if let EntityKind::Text(t) = k { Some(degx(t.rotation)) } else { None }); num(ui, "Rotation", "rotation", rotation, &mut set, &mut bad, ids); - let width_factor = shared("text.width_factor", &|k| if let EntityKind::Text(t) = k { Some(real(t.width_factor)) } else { None }); + let width_factor = shared("text.width_factor", &|k| if let EntityKind::Text(t) = k { Some(realx(t.width_factor)) } else { None }); num(ui, "Width factor", "widthFactor", width_factor, &mut set, &mut bad, ids); } EntityKind::MText(_) => { @@ -1370,17 +1389,17 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { set = Some(json!({ "handles": ids, "text": s })); } }); - let height = shared("mtext.height", &|k| if let EntityKind::MText(t) = k { Some(len(t.height)) } else { None }); + let height = shared("mtext.height", &|k| if let EntityKind::MText(t) = k { Some(lenx(t.height)) } else { None }); num(ui, "Text height", "height", height, &mut set, &mut bad, ids); - let width = shared("mtext.width", &|k| if let EntityKind::MText(t) = k { Some(len(t.width)) } else { None }); + let width = shared("mtext.width", &|k| if let EntityKind::MText(t) = k { Some(lenx(t.width)) } else { None }); num(ui, "Defined width", "width", width, &mut set, &mut bad, ids); } EntityKind::LwPolyline(_) => { // Only Length and Area need the vertices; the other rows read one field. let geom = |p: &cadcraft_doc::LwPolyline| cadcraft_geom::Polyline { vertices: p.vertices.clone(), closed: p.closed }; - let width = shared("poly.width", &|k| if let EntityKind::LwPolyline(p) = k { Some(len(p.const_width)) } else { None }); + let width = shared("poly.width", &|k| if let EntityKind::LwPolyline(p) = k { Some(lenx(p.const_width)) } else { None }); num(ui, "Global width", "width", width, &mut set, &mut bad, ids); - let length = shared("poly.length", &|k| if let EntityKind::LwPolyline(p) = k { Some(len(geom(p).len())) } else { None }); + let length = shared("poly.length", &|k| if let EntityKind::LwPolyline(p) = k { Some(lenx(geom(p).len())) } else { None }); prop_row(ui, "Length", |ui| read_only(ui, &length)); let area = shared("poly.area", &|k| { if let EntityKind::LwPolyline(p) = k { Some(if p.closed { real(geom(p).area().abs()) } else { String::new() }) } else { None } @@ -1407,9 +1426,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); }); - let scale = shared("hatch.scale", &|k| if let EntityKind::Hatch(h) = k { Some(real(h.scale)) } else { None }); + let scale = shared("hatch.scale", &|k| if let EntityKind::Hatch(h) = k { Some(realx(h.scale)) } else { None }); num(ui, "Scale", "scale", scale, &mut set, &mut bad, ids); - let angle = shared("hatch.angle", &|k| if let EntityKind::Hatch(h) = k { Some(real(h.angle.to_degrees())) } else { None }); + let angle = shared("hatch.angle", &|k| if let EntityKind::Hatch(h) = k { Some(realx(h.angle.to_degrees())) } else { None }); num(ui, "Angle", "angle", angle, &mut set, &mut bad, ids); } EntityKind::Insert(_) => { @@ -1439,9 +1458,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { ] { prop_row(ui, label, |ui| read_only(ui, &value)); } - let rotation = shared("insert.rotation", &|k| if let EntityKind::Insert(i) = k { Some(deg(i.rotation)) } else { None }); + let rotation = shared("insert.rotation", &|k| if let EntityKind::Insert(i) = k { Some(degx(i.rotation)) } else { None }); num(ui, "Rotation", "rotation", rotation, &mut set, &mut bad, ids); - let scale = shared("insert.scale", &|k| if let EntityKind::Insert(i) = k { Some(real(i.scale.x)) } else { None }); + let scale = shared("insert.scale", &|k| if let EntityKind::Insert(i) = k { Some(realx(i.scale.x)) } else { None }); num(ui, "Scale", "scale", scale, &mut set, &mut bad, ids); } _ => {} @@ -1543,6 +1562,32 @@ mod tests { assert!(texts.iter().any(|t| t == "7.0000" || t == "7"), "the common text height is shown; painted: {texts:?}"); } + /// Values the display rounds alike still count as different: two dimensions whose text heights + /// differ by a millionth show `*VARIES*`, as do two circles whose radii do. Float noise (a + /// ten-trillionth) is not a difference. + #[test] + fn values_that_differ_below_the_display_precision_still_vary() { + let mut app = CadApp::new(Session::default(), Services::default()); + let dims: Vec = [10, 20] + .map(|x| app.run("dimlinear", json!({ "p1": [0, 0], "p2": [x, 0], "at": [5, 3] })).unwrap()["handle"].as_str().unwrap().to_string()) + .to_vec(); + app.run("select", json!({ "handles": dims.clone() })).unwrap(); + app.run("properties.set", json!({ "handles": [dims[0].clone()], "textHeight": 7.0 })).unwrap(); + app.run("properties.set", json!({ "handles": [dims[1].clone()], "textHeight": 7.0 + 1e-13 })).unwrap(); + let texts = painted_texts(&mut app, properties_section); + assert!(!texts.iter().any(|t| t == VARIES), "noise below 12 digits is not a difference; painted: {texts:?}"); + app.run("properties.set", json!({ "handles": [dims[1].clone()], "textHeight": 7.000001 })).unwrap(); + let texts = painted_texts(&mut app, properties_section); + assert!(texts.iter().any(|t| t == VARIES), "7 and 7.000001 differ although both show as 7.0000; painted: {texts:?}"); + + let mut app = CadApp::new(Session::default(), Services::default()); + let circles = circles(&mut app, &[2, 2], json!({})); + app.run("select", json!({ "handles": circles.clone() })).unwrap(); + app.run("properties.set", json!({ "handles": [circles[1].clone()], "radius": 2.000001 })).unwrap(); + let h = palette(app); + assert!(h.query_all_by_value(VARIES).count() > 0, "radii 2 and 2.000001 vary"); + } + /// Two objects of each type, selected together: the palette shows the type's properties (not /// just General), `*VARIES*` for the ones that differ, and an edit reaches both objects. #[test] From 90806a74769ba0b3002bf69ea9407810afbecf5a Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sun, 1 Nov 2026 06:25:21 -0600 Subject: [PATCH 154/531] Tilted LWPOLYLINE: flatten each arc within a tolerance from its own size A long edge elsewhere in the run made the tolerance larger than a small arc, which then flattened to its chord. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/common.rs | 11 ++++++----- crates/io/src/tests.rs | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 1ca00706f..f59fe4687 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -114,13 +114,10 @@ pub(super) fn tilted(n: Vec3) -> bool { /// A run of OCS vertices at `elevation` in the plane of `n` as seen from above in the WCS. A /// tilted arc is an elliptical arc there, so each bulged edge is flattened (within a thousandth -/// of the run's size), its points without widths; vertices that start straight edges keep their +/// of the edge's own size), its points without widths; vertices that start straight edges keep their /// widths. Also gives the mean WCS Z, the elevation the flattened run takes. pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], closed: bool) -> (Vec, f64) { let m = cadcraft_geom::Mat4::ocs(n); - let b = cadcraft_geom::Polyline { vertices: vertices.to_vec(), closed }.bounds(); - let size = (b.max - b.min).len(); - let tol = if size.is_finite() && size > 0.0 { size * 1e-3 } else { 1e-6 }; let mut local: Vec = Vec::with_capacity(vertices.len()); for (i, v) in vertices.iter().enumerate() { let next = if i + 1 < vertices.len() { @@ -133,7 +130,11 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c match next { Some(w) if v.bulge != 0.0 => { local.push(PolyVertex::new(v.p)); - let edge = cadcraft_geom::Polyline { vertices: vec![*v, PolyVertex::new(w.p)], closed: false }.tessellate(tol); + let arc = cadcraft_geom::Polyline { vertices: vec![*v, PolyVertex::new(w.p)], closed: false }; + // From the edge's own size, so a long edge elsewhere can't flatten a small arc away. + let b = arc.bounds(); + let size = (b.max - b.min).len(); + let edge = arc.tessellate(if size.is_finite() && size > 0.0 { size * 1e-3 } else { 1e-6 }); // The edge's own ends are this vertex and the next one. local.extend(edge.iter().skip(1).take(edge.len().saturating_sub(2)).map(|p| PolyVertex::new(*p))); } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 674570c65..c3beb387b 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2168,6 +2168,20 @@ fn tilted_mixed_lwpolyline_keeps_its_straight_widths() { assert!((v[1].p.x + 2.0).abs() < 1e-9 && (v[v.len() - 1].p.x + 4.0).abs() < 1e-9, "{:?} {:?}", v[1].p, v[v.len() - 1].p); } +/// A small arc next to a long straight edge stays an arc: its flattening tolerance comes from +/// its own size. The half circle of radius 1 bulges a whole unit off its chord. +#[test] +fn tilted_small_arc_beside_a_long_edge_stays_curved() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n3\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n0\n20\n0\n10\n10000\n20\n0\n42\n1\n10\n10002\n20\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert!(p.vertices.len() > 8, "{} vertices", p.vertices.len()); + // OCS y maps to plan y times √3/2: the arc's far point is about 0.866 off the chord. + let off = p.vertices.iter().map(|v| v.p.y.abs()).fold(0.0, f64::max); + assert!((off - 3f64.sqrt() / 2.0).abs() < 1e-2, "the arc reaches {off} off its chord"); +} + /// Issue #1886: a LWPOLYLINE circle (two half-circle bulges) in the same tilted plane is the /// ellipse it looks like from above, flattened; a plain one keeps its bulges. #[test] From 7fdda542d359dd7d47163fba7e177dace53c3de0 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 23:32:58 +1100 Subject: [PATCH 155/531] OLE2FRAME: MOVE rewrites the corners in the OLE data only when they are the frame's corners (review on #2587) The data layout is only known when its corners match the frame's groups; any other header is left byte-identical while the tags still move. Test: move_leaves_ole_data_that_is_not_the_frames_corners_alone. --- crates/doc/src/extents.rs | 18 ++++++++++++++++-- crates/engine/tests/ole_frame_transform.rs | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 4aff09d8b..651ac4b05 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -51,7 +51,7 @@ const OLE_CORNERS: usize = 12; /// Move the four corners at the start of the OLE data (the 310 groups' hex, in order) by `m`, /// keeping z and every tag's length. Data that is not valid hex or is too short is left alone. -fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { +fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3, frame: [f64; 4]) { let idx: Vec = outside_app(tags).into_iter().filter(|&i| tags.get(i).is_some_and(|t| t.code == 310)).collect(); let mut bytes: Vec = Vec::new(); let mut lens: Vec = Vec::new(); @@ -71,6 +71,19 @@ fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { if bytes.len() < end { return; } + // Only data whose corners are this frame's corners (UL, UR, LR, LL) has the layout above; any + // other header is not ours to rewrite. + let [x1, y1, x2, y2] = frame; + let want = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]; + let near = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0); + for (c, (wx, wy)) in want.iter().enumerate() { + let at = OLE_HEADER + c * 24; + let rd = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes); + let (Some(x), Some(y)) = (rd(at), rd(at + 8)) else { return }; + if !(near(x, *wx) && near(y, *wy)) { + return; + } + } let mut out = bytes.clone(); for c in 0..4 { let at = OLE_HEADER + c * 24; @@ -103,6 +116,7 @@ fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { /// left alone. pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { let Some([(ix1, x1), (iy1, y1), (ix2, x2), (iy2, y2)]) = ole_corner_groups(tags) else { return }; + let frame = [x1, y1, x2, y2]; let (a, b) = (m.apply(Vec2::new(x1, y1)), m.apply(Vec2::new(x2, y2))); if !(a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { return; @@ -112,7 +126,7 @@ pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) t.value = v.to_string(); } } - ole_data_transform(tags, m); + ole_data_transform(tags, m, frame); } /// Whether `m` can move an OLE2FRAME: only a translation (move, copy, stretch of the whole frame). diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index 50ecc1f2f..22d88075a 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -124,3 +124,21 @@ fn move_leaves_malformed_or_short_ole_data_alone() { assert_eq!(corners(&s)[0].1, "40", "the corner groups still move"); } } + +/// OLE data whose bytes are not this frame's corners (an unknown header, so the layout does not +/// apply) is not rewritten by MOVE; the frame's own corner groups still move (review on #2587). +#[test] +fn move_leaves_ole_data_that_is_not_the_frames_corners_alone() { + let mut blob = vec![9u8, 9]; + for (x, y) in [(1.0f64, 2.0f64), (3.0, 2.0), (3.0, 4.0), (1.0, 4.0)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let hex: String = blob.iter().map(|b| format!("{b:02X}")).collect(); + let (mut s, h) = data_session(&[40, 100], Some(&hex)); + let before = data_tags(&s); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + assert_eq!(data_tags(&s), before); + assert_eq!(corners(&s)[0].1, "40", "the corner groups still move"); +} From c9ffc3e3943b75499b5ca6e063860bd0d32e9187 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 23:32:58 +1100 Subject: [PATCH 156/531] OLE2FRAME: a frame without usable corners counts as not drawn in an image export (review on #2587) The renderer draws nothing for it, so it is no longer reported as shown as the frame only. Test: an_ole_frame_without_corners_is_counted_as_not_drawn. --- apps/cadcraft-cli/src/output.rs | 2 +- apps/cadcraft-cli/tests/it/undrawn_entities.rs | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index 8a8f7d97c..c810ede20 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -155,7 +155,7 @@ pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> // An OLE2FRAME's frame outline is drawn, so it isn't an undrawn entity; its content is // not, which gets a note of its own. if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind { - if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") { + if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") && cadcraft_engine::doc::ole_frame(&u.tags).is_some() { ole = ole.saturating_add(1); continue; } diff --git a/apps/cadcraft-cli/tests/it/undrawn_entities.rs b/apps/cadcraft-cli/tests/it/undrawn_entities.rs index 8b176cbbc..59762d283 100644 --- a/apps/cadcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/cadcraft-cli/tests/it/undrawn_entities.rs @@ -86,3 +86,19 @@ fn an_ole_frame_is_noted_as_frame_only() { let notes: Vec<&str> = err.lines().filter(|l| l.contains("OLE")).collect(); assert_eq!(notes, [format!("{}: 1 OLE object shown as the frame only (the OLE content is not drawn)", input.display())], "{err}"); } + +/// An OLE2FRAME without usable corners (here group 11/21 missing) has no outline to draw, so it is +/// an undrawn entity, not "shown as the frame only" (review on #2587). +#[test] +fn an_ole_frame_without_corners_is_counted_as_not_drawn() { + let scratch = Scratch::new("ole-nocorner"); + let dir = scratch.0.clone(); + let input = dir.join("ole.dxf"); + let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n0\nENDSEC\n0\nEOF\n"; + std::fs::write(&input, ole).unwrap(); + let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]); + assert!(out.status.success()); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains(&format!("{}: 1 entity not drawn (OLE2FRAME: 1)", input.display())), "{err}"); + assert!(!err.contains("frame only"), "{err}"); +} From b54adc597625ad647dac55b587d8a48af1298f7c Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 23:32:59 +1100 Subject: [PATCH 157/531] OLE2FRAME: MOCORO checks before it changes anything; a locked frame doesn't block in-place edits (review on #2587) MOCORO refuses a rotate or scale step on an OLE frame up front, before an earlier move or copy is applied. refuse_ole_frames ignores a frame on a locked layer for in-place edits, as edit_entities does. Tests: mocoro_refuses_before_it_changes_anything, a_locked_ole_frame_does_not_block_an_in_place_rotation. --- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/transform.rs | 12 ++++--- crates/engine/src/cmd/modify2/mocoro.rs | 11 ++++++- crates/engine/tests/ole_frame_transform.rs | 38 ++++++++++++++++++++++ 4 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 22126f900..ad138348d 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -32,7 +32,7 @@ use fillet::{FilletM, run_chamfer, run_fillet}; use offset::{OffsetM, run_offset}; use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; -pub(crate) use transform::transform_entities; +pub(crate) use transform::{refuse_ole_frames, transform_entities}; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; pub(crate) use trim::{Edges, extend, trim}; diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index b3b897847..9737afb8f 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -5,7 +5,7 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, f6 // ---------------- core operations ---------------- pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { - refuse_ole_frames(s, hs, m)?; + refuse_ole_frames(s, hs, m, copy)?; edit_entities(s, hs, copy, |e| e.kind.transform(m)) } @@ -13,7 +13,7 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: /// and every height of the objects about its Z, their thickness too. pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result> { let m = Mat3::scale_about(base.xy(), f); - refuse_ole_frames(s, hs, &m)?; + refuse_ole_frames(s, hs, &m, copy)?; edit_entities(s, hs, copy, |e| { e.kind.transform(&m); e.kind.scale_heights(base.z, f); @@ -23,13 +23,17 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, /// An OLE2FRAME only translates (its corners stay axis aligned): refuse any other `m` before anything /// changes, instead of reporting success and leaving the frame where it was. -fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3) -> Result<()> { +pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<()> { if cadcraft_doc::ole_frame_accepts(m) { return Ok(()); } let d = s.doc()?; let ole = |h: &Handle| { - d.entity(*h).is_some_and(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME"))) + d.entity(*h).is_some_and(|e| { + // An in-place edit skips an object on a locked layer (see edit_entities), so it cannot be refused. + let locked = !copy && d.layer(&e.common.layer).is_some_and(|l| l.locked); + !locked && matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME")) + }) }; if hs.iter().any(ole) { return Err(crate::EngineError::Other( diff --git a/crates/engine/src/cmd/modify2/mocoro.rs b/crates/engine/src/cmd/modify2/mocoro.rs index c701e24ae..93732a7cf 100644 --- a/crates/engine/src/cmd/modify2/mocoro.rs +++ b/crates/engine/src/cmd/modify2/mocoro.rs @@ -16,7 +16,7 @@ use super::other; use crate::cmd::curves::KW; use crate::cmd::helpers::line; use crate::cmd::machines::{SelOutcome, SelectPhase, number}; -use crate::cmd::modify::transform_entities; +use crate::cmd::modify::{refuse_ole_frames, transform_entities}; use crate::cmd::{bad, point_req, point_value, targets}; use crate::prompt::Drag; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; @@ -108,6 +108,15 @@ pub(super) fn run_mocoro(s: &mut Session, p: &Value) -> Result { } // Every option is checked before the drawing changes. let ops = list.iter().enumerate().map(|(i, v)| parse_op(i, v)).collect::>>()?; + // An OLE frame only translates: a rotate or scale step that would refuse it must do so before an + // earlier move or copy changes the drawing (a refused command is not rolled back). + for op in &ops { + match *op { + Op::Rotate(a) => refuse_ole_frames(s, &objs, &Mat3::rotate_about(base, a), false)?, + Op::Scale(f) => refuse_ole_frames(s, &objs, &Mat3::scale_about(base, f), false)?, + _ => {} + } + } let mut copies = Vec::new(); for op in ops { copies.extend(apply(s, &objs, &mut base, op)?); diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index 22d88075a..653d9f017 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -142,3 +142,41 @@ fn move_leaves_ole_data_that_is_not_the_frames_corners_alone() { assert_eq!(data_tags(&s), before); assert_eq!(corners(&s)[0].1, "40", "the corner groups still move"); } + +#[test] +fn mocoro_refuses_before_it_changes_anything() { + let (mut s, h) = session(); + let before = corners(&s); + let undo = s.state().unwrap().undo.len(); + let ops = json!([{ "move": [10, 5] }, { "copy": [20, 0] }, { "rotate": 30 }]); + let e = s.execute("mocoro", &json!({ "handles": [h], "base": [0, 0], "ops": ops })).expect_err("rotate"); + assert!(e.to_string().contains("OLE object"), "{e}"); + assert_eq!(corners(&s), before, "the earlier move and copy were not applied"); + assert_eq!(s.doc().unwrap().model.len(), 1); + assert_eq!(s.state().unwrap().undo.len(), undo); +} + +#[test] +fn a_locked_ole_frame_does_not_block_an_in_place_rotation() { + let tag = |code: i32, v: &str| RawTag { code, value: v.into() }; + let mut d = Drawing::new_imperial(); + d.ensure_layer("L"); + let common = Common { layer: "L".into(), ..Common::default() }; + let kind = + EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] }); + let ole = d.add(&Space::Model, common, kind).unwrap(); + if let Some(l) = d.layer_mut("L") { + l.locked = true; + } + let mut s = Session::empty(); + s.open_drawing(d, "ole.dxf", None); + let ln = s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + let ln = ln["handle"].as_str().or_else(|| ln["handles"][0].as_str()).unwrap().to_string(); + let before = corners(&s); + s.execute("rotate", &json!({ "handles": [ln.clone(), ole.hex()], "base": [0, 0], "angle": 90 })).unwrap(); + assert_eq!(corners(&s), before, "the locked frame is left alone"); + let d = s.doc().unwrap(); + let e = d.entity(cadcraft_engine::doc::Handle::parse_hex(&ln).unwrap()).unwrap(); + let cadcraft_engine::doc::EntityKind::Line(l) = &e.kind else { panic!("line") }; + assert!((l.b.y - 10.0).abs() < 1e-9 && l.b.x.abs() < 1e-9, "{l:?}"); +} From 9735b232273290fe448eef2b213652a75f0a2c88 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sun, 1 Nov 2026 06:41:10 -0600 Subject: [PATCH 158/531] Tilted planes: decide by how far points would move; spread arc widths An object counts as tilted when drawing its OCS points as plan coordinates would put some of them off their place seen from above by more than a billionth of its size and distance from the origin, sampled along its arcs too. A slight tilt far from the origin is now projected, and noise in a plan normal still leaves the object (and its arcs) alone. A flattened tilted arc spreads its start and end widths evenly over its segments, as a tapered segment does. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/common.rs | 65 +++++++++++++++++++++++++----- crates/io/src/dxf_read/entities.rs | 23 +++++------ crates/io/src/tests.rs | 34 ++++++++++++++++ 3 files changed, 99 insertions(+), 23 deletions(-) diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index f59fe4687..30e70e6f8 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -106,16 +106,56 @@ pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 { if (n.z - 1.0).abs() < 1e-12 && n.x.abs() < 1e-12 && n.y.abs() < 1e-12 { p } else { cadcraft_geom::Mat4::ocs(n).apply(p) } } -/// Whether an extrusion tilts an object's plane off the XY plane (neither the Z axis nor the Z -/// axis turned over, as MIRROR leaves it, allowing for noise in x and y like INSERT does). -pub(super) fn tilted(n: Vec3) -> bool { - n.is_finite() && n.x.hypot(n.y) > 1e-3 * n.z.abs() +/// Whether an object with OCS points `pts` (x, y and elevation) lies in a plane tilted off the +/// XY plane: drawing its points as plan coordinates (x flipped for a mirrored plane, as the +/// readers do) would put some of them off their place seen from above by more than a +/// billionth of the object's size and distance from the origin. A normal that is the Z axis +/// or the Z axis turned over moves nothing, and noise in one moves points by a negligible +/// amount, so those objects keep their arcs; however small the tilt, an object far enough from +/// the origin to be moved visibly is projected. +pub(super) fn tilted(n: Vec3, pts: impl IntoIterator) -> bool { + if !n.is_finite() || n.len() < 1e-12 { + return false; + } + let m = cadcraft_geom::Mat4::ocs(n); + let flip = if n.z < 0.0 { -1.0 } else { 1.0 }; + let (mut moved, mut reach) = (0.0f64, 1.0f64); + for p in pts.into_iter().filter(|p| p.is_finite()) { + let shown = Vec2::new(flip * p.x, p.y); + moved = moved.max((m.apply(p).xy() - shown).len()); + reach = reach.max(p.x.abs()).max(p.y.abs()).max(p.z.abs()); + } + moved > 1e-9 * reach +} + +/// Points along a run of OCS vertices at `elevation`, for [`tilted`]: its vertices and, on its +/// arcs, points between them (an arc can bulge where its ends don't move). +pub(super) fn run_points(vertices: &[PolyVertex], elevation: f64, closed: bool) -> Vec { + let mut pts = Vec::with_capacity(vertices.len()); + for (i, v) in vertices.iter().enumerate() { + pts.push(v.p); + let next = if i + 1 < vertices.len() { + vertices.get(i + 1) + } else if closed { + vertices.first() + } else { + None + }; + if let Some(w) = next.filter(|_| v.bulge != 0.0) { + // Each arc sampled from its own size, so a small one next to a long edge counts too. + let arc = cadcraft_geom::Polyline { vertices: vec![*v, PolyVertex::new(w.p)], closed: false }; + let b = arc.bounds(); + let size = (b.max - b.min).len(); + pts.extend(arc.tessellate(if size.is_finite() && size > 0.0 { size * 0.05 } else { 1e-6 })); + } + } + pts.into_iter().map(|p| p.to3(elevation)).collect() } /// A run of OCS vertices at `elevation` in the plane of `n` as seen from above in the WCS. A /// tilted arc is an elliptical arc there, so each bulged edge is flattened (within a thousandth -/// of the edge's own size), its points without widths; vertices that start straight edges keep their -/// widths. Also gives the mean WCS Z, the elevation the flattened run takes. +/// of the edge's own size), its width spread evenly along it; vertices that start straight +/// edges keep their widths. Also gives the mean WCS Z, the elevation the flattened run takes. pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], closed: bool) -> (Vec, f64) { let m = cadcraft_geom::Mat4::ocs(n); let mut local: Vec = Vec::with_capacity(vertices.len()); @@ -129,14 +169,21 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c }; match next { Some(w) if v.bulge != 0.0 => { - local.push(PolyVertex::new(v.p)); let arc = cadcraft_geom::Polyline { vertices: vec![*v, PolyVertex::new(w.p)], closed: false }; // From the edge's own size, so a long edge elsewhere can't flatten a small arc away. let b = arc.bounds(); let size = (b.max - b.min).len(); let edge = arc.tessellate(if size.is_finite() && size > 0.0 { size * 1e-3 } else { 1e-6 }); - // The edge's own ends are this vertex and the next one. - local.extend(edge.iter().skip(1).take(edge.len().saturating_sub(2)).map(|p| PolyVertex::new(*p))); + // The edge runs from this vertex to the next one in equal turns of its arc; its + // width changes evenly along it, as a tapered segment's does. + let steps = edge.len().saturating_sub(1).max(1); + let width = |k: usize| v.start_width + (v.end_width - v.start_width) * k as f64 / steps as f64; + local.extend(edge.iter().take(steps).enumerate().map(|(k, p)| PolyVertex { + p: *p, + bulge: 0.0, + start_width: width(k), + end_width: width(k + 1), + })); } _ => local.push(PolyVertex { bulge: 0.0, ..*v }), } diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 90c68604b..3636d32a9 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -1,4 +1,4 @@ -use super::common::{T, common, ocs, plan_of_tilted, tilted}; +use super::common::{T, common, ocs, plan_of_tilted, run_points, tilted}; use super::hatch::hatch; use super::text::{attdef, attrib_modes, attrib_props, mtext_from, multiline_attrib, split_embedded, text_from}; use super::{ @@ -45,7 +45,7 @@ fn ellipse(c: &Common, t: &T) -> Ellipse { } /// A LWPOLYLINE, or the region CADCraft wrote as one. -fn lwpolyline(tags: &[Tag], c: &Common, t: &T) -> Option { +fn lwpolyline(tags: &[Tag], c: &mut Common, t: &T) -> Option { let mut verts = Vec::new(); let mut cur: Option = None; for tg in tags { @@ -82,9 +82,11 @@ fn lwpolyline(tags: &[Tag], c: &Common, t: &T) -> Option { verts.extend(cur); let flags = t.i(70).unwrap_or(0); let mut elevation = t.fd(38, 0.0); - if tilted(c.extrusion) { - // In a tilted plane: drawn as seen from above, at the vertices' mean height. + if tilted(c.extrusion, run_points(&verts, elevation, flags & 1 != 0)) { + // In a tilted plane: drawn as seen from above, at the vertices' mean height, its + // vertices now plan coordinates. (verts, elevation) = plan_of_tilted(c.extrusion, elevation, &verts, flags & 1 != 0); + c.extrusion = Vec3::Z; } else if c.extrusion.z < 0.0 { for v in &mut verts { v.p.x = -v.p.x; @@ -132,14 +134,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef "CIRCLE" => EntityKind::Circle(Circle { center: ocs(&c, t.p(10)), radius: t.fd(40, 1.0).abs() }), "ARC" => EntityKind::Arc(arc(&c, &t)), "ELLIPSE" => EntityKind::Ellipse(ellipse(&c, &t)), - "LWPOLYLINE" => { - let k = lwpolyline(tags, &c, &t)?; - if tilted(c.extrusion) { - // Its vertices are now WCS, seen from above (`lwpolyline`). - c.extrusion = Vec3::Z; - } - k - } + "LWPOLYLINE" => lwpolyline(tags, &mut c, &t)?, "SPLINE" => EntityKind::Spline(spline(&t)), "HELIX" => EntityKind::Helix(helix(tags)), "RAY" => EntityKind::Ray(RayLine { base: t.p(10), dir: t.p(11) }), @@ -238,8 +233,8 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef "3DFACE" => EntityKind::Face3d(Face3d { corners: [t.p(10), t.p(11), t.p(12), t.p(13)], hidden_edges: t.i(70).unwrap_or(0) as u8 }), "HATCH" => { let mut k = hatch(tags, &t)?; - if tilted(c.extrusion) - && let EntityKind::Hatch(h) = &mut k + if let EntityKind::Hatch(h) = &mut k + && tilted(c.extrusion, h.loops.iter().flat_map(|l| run_points(&l.vertices, h.elevation, true))) { // In a tilted plane (a terrain face, a slope): the boundary as seen from above, // at its mean height, and the pattern direction and origin projected the same way. diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index c3beb387b..2f5206971 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2182,6 +2182,40 @@ fn tilted_small_arc_beside_a_long_edge_stays_curved() { assert!((off - 3f64.sqrt() / 2.0).abs() < 1e-2, "the arc reaches {off} off its chord"); } +/// A tilted tapered arc spreads its width evenly over its flattened segments: from 1 at its +/// start to 3 at its end, each segment starting where the last one ended. +#[test] +fn tilted_tapered_arc_spreads_its_width() { + let text = "0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 10\n0\n20\n0\n40\n1\n41\n3\n42\n1\n10\n2\n20\n0\n0\nENDSEC\n0\nEOF\n"; + let d = read(text.as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let v = &p.vertices; + assert!(v.len() > 4, "{} vertices", v.len()); + let arc = &v[..v.len() - 1]; + assert_eq!(arc.first().map(|v| v.start_width), Some(1.0)); + assert!(arc.last().is_some_and(|v| (v.end_width - 3.0).abs() < 1e-9), "{:?}", arc.last()); + assert!(arc.windows(2).all(|w| (w[0].end_width - w[1].start_width).abs() < 1e-9 && w[0].start_width < w[1].start_width)); +} + +/// Far from the origin even a tilt under a thousandth moves an object visibly, so it is +/// projected: with normal (0, 0.0009, 1) a polyline at elevation 1,000,000 lies about 900 units +/// up from its OCS y. Noise in a plan normal moves nothing visible and keeps the arcs. +#[test] +fn a_slight_tilt_far_away_is_projected_and_noise_is_not() { + let poly = |n: &str, more: &str| { + format!("0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n2\n70\n0\n38\n1000000\n{n}10\n0\n20\n0\n{more}10\n1\n20\n0\n0\nENDSEC\n0\nEOF\n") + }; + let d = read(poly("210\n0\n220\n0.0009\n230\n1\n", "").as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + let ny = 0.0009 / (1.0f64 + 0.0009 * 0.0009).sqrt(); + assert!((p.vertices[0].p.y - ny * 1.0e6).abs() < 1e-6, "{:?}", p.vertices[0].p); + assert_eq!(d.model.iter().next().unwrap().common.extrusion, Vec3::Z); + let d = read(poly("210\n0\n220\n1e-15\n230\n1\n", "42\n1\n").as_bytes(), "p.dxf").unwrap(); + let p = first(&d, |k| if let EntityKind::LwPolyline(p) = k { Some(p.clone()) } else { None }); + assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::>(), vec![1.0, 0.0], "a plan polyline keeps its arc"); +} + /// Issue #1886: a LWPOLYLINE circle (two half-circle bulges) in the same tilted plane is the /// ellipse it looks like from above, flattened; a plain one keeps its bulges. #[test] From b3af16c62112a04c30aacd365636ff85300ae785 Mon Sep 17 00:00:00 2001 From: WillPastor <47420496+WillPastor@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:14:16 -0500 Subject: [PATCH 159/531] Check full-capacity PGP import responsiveness Measure the existing 10,000-alias import after parameter preparation and assert a generous five-second budget after validation and cleanup. Preserve the duplicate, ordering and capacity compatibility checks. Addresses the PGP import performance finding in #1933. --- crates/engine/tests/aliases.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/aliases.rs b/crates/engine/tests/aliases.rs index b3c0bdde3..70f705de8 100644 --- a/crates/engine/tests/aliases.rs +++ b/crates/engine/tests/aliases.rs @@ -3,6 +3,7 @@ //! process-wide, so these tests run one at a time. use std::sync::Mutex; +use std::time::{Duration, Instant}; use cadcraft_engine::Session; use cadcraft_engine::cmd::file::MAX_ALIASES; @@ -163,7 +164,11 @@ fn a_full_file_validates_lines_before_stopping_at_the_next_valid_definition() { s.execute("aliasedit", &json!({ "clear": true })).unwrap(); let mut text = alias_prefix(MAX_ALIASES); text.push_str("; comment\nZZP00000,*NO_SUCH_1933\nLINE,*CIRCLE\nZZEXTERNAL, START NOTHING\nmalformed\nZZP00000,*MOVE\nZZAFTER,*CIRCLE\nanother malformed sentinel\n"); - let r = s.execute("aliasedit", &json!({ "text": text })).unwrap(); + let params = json!({ "text": text }); + let start = Instant::now(); + let result = s.execute("aliasedit", ¶ms); + let elapsed = start.elapsed(); + let r = result.unwrap(); assert_eq!(r["loaded"], json!(MAX_ALIASES)); assert_eq!(r["aliases"].as_object().unwrap().len(), MAX_ALIASES); assert_eq!(r["aliases"]["zzp00000"], json!("line"), "the cap stops even a valid duplicate replacement"); @@ -185,6 +190,8 @@ fn a_full_file_validates_lines_before_stopping_at_the_next_valid_definition() { assert_eq!(r["loaded"], json!(1)); assert!(s.execute("aliasedit", &json!({ "set": { "ZZNEW": "line" } })).is_err()); s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + // A generous responsiveness guard, not a benchmark or a timeout for a hung import. + assert!(elapsed < Duration::from_secs(5), "importing {MAX_ALIASES} aliases took {elapsed:?}"); } #[test] From 6b707c89e4c7d3d118524c9084bac43f6b0a67cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=81=E4=BC=AA?= <56018602+r4x2t7@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:14:16 +0800 Subject: [PATCH 160/531] TEXTEDIT: edit text in a window, from a double-click TEXTEDIT took over the command line: the caret left the drawing, the prompt asked for a point, and the text was edited where you could no longer see it. The shortcut menu offered Edit Text on text, mtext and attribute definitions, and that is exactly where a user expects to type. A double-click on one of those objects now opens a small window holding the object's text, its type and its handle, with OK and Cancel. Ctrl+Enter applies. Text that has not changed sends no command, so the undo stack stays clean. The TEXTEDIT command itself is untouched: scripts, LISP and the command line still drive it as before, and the window is a second surface on the same edit. --- crates/ui-egui/src/canvas/pick.rs | 22 +++--- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/ar.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/pt_br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh.tsv | 2 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/textdlg.rs | 116 ++++++++++++++++++++++++++++++ 22 files changed, 164 insertions(+), 12 deletions(-) create mode 100644 crates/ui-egui/src/textdlg.rs diff --git a/crates/ui-egui/src/canvas/pick.rs b/crates/ui-egui/src/canvas/pick.rs index 3bd28b017..112740d06 100644 --- a/crates/ui-egui/src/canvas/pick.rs +++ b/crates/ui-egui/src/canvas/pick.rs @@ -1,4 +1,4 @@ -use super::{CadApp, Handle, Input, Vec2}; +use super::{CadApp, Handle, Vec2}; /// The vertical wheel scroll this frame that zooms, in points, read from the raw wheel events so /// each notch zooms by its whole step at once, as in standard CAD (#660). egui's smoothed delta @@ -26,20 +26,18 @@ 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 or attribute definition at `p` (the objects its shortcut menu -/// offers Edit Text for); false when there is none. +/// Open Edit Text on the text, mtext or attribute definition at `p` (the objects the 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| { - app.session.doc().ok()?.entity(h).map(|e| matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_))) + let hit = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { + let e = app.session.doc().ok()?.entity(h)?; + matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)).then_some(h) }); - if is_text != Some(true) { - return false; - } - app.start("textedit"); - if let Err(e) = app.session.input(Input::Point(p)) { - app.session.echo(e.to_string()); - } + let Some(h) = hit else { return false }; + // The window edits the object in place of the command line, which used to take the caret and + // hide the drawing behind it. + app.ui.dialog = Some(format!("textedit:{}", h.hex())); true } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index acdddb552..0c2210bbd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -31,6 +31,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), o if o == "options" || o.starts_with("options:") => crate::options::dialog(app, ctx, o, &mut open), + o if o.starts_with("textedit:") => crate::textdlg::dialog(app, ctx, o, &mut open), other => crate::managers::dialog(app, ctx, other, &mut open), } // A dialog that closed by opening another (Plot Preview back to Plot) keeps the new one. diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 40e14cdb5..d40d401e1 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -1242,3 +1242,5 @@ menu View عرض Check for Updates… التحقق من وجود تحديثات… CADCraft is up to date. CADCraft محدّث. Could not check for updates. تعذّر التحقق من وجود تحديثات. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 14565ce2f..f191c6650 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1447,3 +1447,5 @@ menu Modify Izmijeni Save changes to block "{name}"? Sačuvati promjene u bloku „{name}”? Layouts Rasporedi Associate Poveži + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index c979cd786..9adc82cdb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1227,3 +1227,5 @@ menu Modify Modifikace Check for Updates… Zkontrolovat aktualizace… CADCraft is up to date. CADCraft je aktuální. Could not check for updates. Aktualizace se nepodařilo zkontrolovat. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 84b944529..99cd29664 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1044,3 +1044,5 @@ Check for Updates… Nach Updates suchen… CADCraft is up to date. CADCraft ist auf dem neuesten Stand. Could not check for updates. Die Suche nach Updates ist fehlgeschlagen. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2825e8fd2..6be929370 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1338,3 +1338,5 @@ menu View Προβολή Check for Updates… Έλεγχος για ενημερώσεις… CADCraft is up to date. Το CADCraft είναι ενημερωμένο. Could not check for updates. Δεν ήταν δυνατός ο έλεγχος για ενημερώσεις. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b24970979..14450f4be 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1258,3 +1258,5 @@ Check for Updates… Buscar actualizaciones… CADCraft is up to date. CADCraft está actualizado. Could not check for updates. No se pudo buscar actualizaciones. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 42ad7ee48..adb6f3842 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1017,3 +1017,5 @@ Check for Updates… Rechercher des mises à jour… CADCraft is up to date. CADCraft est à jour. Could not check for updates. Impossible de rechercher les mises à jour. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fc27bd7ce..6eadaa28b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1349,3 +1349,5 @@ menu View Nézet Check for Updates… Frissítések keresése… CADCraft is up to date. A CADCraft naprakész. Could not check for updates. A frissítések keresése nem sikerült. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 634249093..d4b3a7a26 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1367,3 +1367,5 @@ menu Modify Edita Check for Updates… Verifica aggiornamenti… CADCraft is up to date. CADCraft è aggiornato. Could not check for updates. Impossibile verificare gli aggiornamenti. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 1bd7e0fd5..761bd4316 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1247,3 +1247,5 @@ menu Modify 수정 Check for Updates… 업데이트 확인… CADCraft is up to date. CADCraft가 최신 버전입니다. Could not check for updates. 업데이트를 확인하지 못했습니다. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 8f6533d51..56a65c4eb 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -1256,3 +1256,5 @@ Check for Updates… Verificar atualizações… CADCraft is up to date. O CADCraft está atualizado. Could not check for updates. Não foi possível verificar atualizações. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b8f97bf73..1c7088ec7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1018,3 +1018,5 @@ Check for Updates… Проверить обновления… CADCraft is up to date. У вас последняя версия CADCraft. Could not check for updates. Не удалось проверить обновления. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6bea4c3da..cb4d7e21c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1451,3 +1451,5 @@ menu Modify Ändra Check for Updates… Sök efter uppdateringar… CADCraft is up to date. CADCraft är uppdaterat. Could not check for updates. Det gick inte att söka efter uppdateringar. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 034f261e1..b1cf211dd 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -102,6 +102,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "quick", "vpscale", "options/dialog", + "textdlg", ]; let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut files = Vec::new(); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2bf979f85..fd2f284e7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1352,3 +1352,5 @@ menu View Görünüm Check for Updates… Güncellemeleri denetle… CADCraft is up to date. CADCraft güncel. Could not check for updates. Güncellemeler denetlenemedi. + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 714ce6c4c..f9fbaf747 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1376,3 +1376,5 @@ CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9b1493031..9ed3db625 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1451,3 +1451,5 @@ menu Modify Hiệu chỉnh Change Properties Đổi thuộc tính Font Phông chữ Save Layout as Template Lưu layout thành mẫu + Ctrl+Enter to apply Ctrl+Enter to apply + Edit Text Edit Text diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 2663105a2..1912b43a6 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1380,3 +1380,5 @@ Save Layout as Template 将布局另存为样板 Set Dynamic Property 设置动态特性 Units 单位 + Ctrl+Enter to apply Ctrl+Enter 应用 + Edit Text 编辑文字 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 97ab2faf4..876eb12c8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -37,6 +37,8 @@ mod mtext_editor; mod panel_state; pub mod spacemouse; pub mod switch; +// The Edit Text window, opened by a double-click on a text object. +pub mod textdlg; // The External References palette. pub mod xrefs; diff --git a/crates/ui-egui/src/textdlg.rs b/crates/ui-egui/src/textdlg.rs new file mode 100644 index 000000000..b3d13ae9f --- /dev/null +++ b/crates/ui-egui/src/textdlg.rs @@ -0,0 +1,116 @@ +//! Edit Text: the window a double-click on a text object opens. +//! +//! TEXTEDIT already existed, but only as a command line: double-clicking a single-line text put +//! the caret in the command bar, one line, no context, and the text under the cursor was out of +//! sight. The window shows the same edit over the drawing: the object's own text, its type and +//! handle, and OK/Cancel. The engine call is unchanged (`textedit` with a handle and the new +//! text), so undo, locked layers and the DXF round trip behave exactly as before. + +use egui::RichText; +use serde_json::json; + +use crate::CadApp; +use crate::theme::Tokens; +use cadcraft_engine::doc::EntityKind; + +/// The text the window starts with, in the form the user edits: MText line breaks are `\P` in +/// the drawing and a newline here, and an empty dimension text means the measured value, shown +/// as `<>` the way the dimension itself does. +fn text_of(k: &EntityKind) -> Option { + match k { + EntityKind::Text(t) => Some(t.value.clone()), + EntityKind::AttDef(a) => Some(a.text.value.clone()), + EntityKind::MText(t) => Some(t.contents.replace("\\P", "\n")), + EntityKind::Dimension(d) => Some(if d.text.is_empty() { "<>".to_string() } else { d.text.clone() }), + _ => None, + } +} + +#[derive(Default, Clone)] +struct State { + handle: String, + kind: String, + text: String, + /// What the drawing holds now, to tell an edit from a no-op. + original: String, + message: String, +} + +/// Read the object the window is for. A handle that no longer exists, or an object that is not +/// text, leaves the window empty instead of failing: the drawing may have changed under it. +fn initial(app: &CadApp, hex: &str) -> State { + let mut st = State { handle: hex.to_string(), ..Default::default() }; + let Some(h) = cadcraft_doc::Handle::parse_hex(hex) else { return st }; + let Ok(d) = app.session.doc() else { return st }; + let Some(e) = d.entity(h) else { return st }; + st.kind = e.kind.type_name().to_string(); + st.text = text_of(&e.kind).unwrap_or_default(); + st.original = st.text.clone(); + st +} + +/// The Edit Text window for `spec`, which is `textedit:` so the handle survives the +/// dialog dispatch without a new field in the saved UI state. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, spec: &str, open: &mut bool) { + let t = Tokens::get(); + let hex = spec.strip_prefix("textedit:").unwrap_or_default().to_string(); + let sid = egui::Id::unique("textedit_state").with(&hex); + let cached: Option = ctx.data_mut(|d| d.get_temp(sid)); + let mut st = match cached { + Some(s) => s, + None => initial(app, &hex), + }; + // The window's own close button and the two buttons below all decide the same thing, so the + // decision stays in a local until the window is gone: `open` is borrowed for the title bar. + let mut keep = *open; + let mut commit = false; + let mut cancel = false; + egui::Window::new(crate::tl!("Edit Text")) + .id(egui::Id::unique("Edit Text")) + .open(&mut keep) + .collapsible(false) + .resizable(true) + .default_width(440.0) + .show(ctx, |ui| { + let head = format!("{} · {}", crate::i18n::t(&st.kind), st.handle); + ui.label(RichText::new(head).color(t.text_faint).small()); + let r = ui.add(egui::TextEdit::multiline(&mut st.text).desired_width(f32::INFINITY).desired_rows(3).hint_text(crate::tl!("Text"))); + // Ctrl+Enter commits from inside the field, so a multiline text can keep plain Enter. + if r.has_focus() && ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Enter)) { + commit = true; + } + ui.horizontal(|ui| { + if ui.button(crate::tl!("OK")).clicked() { + commit = true; + } + if ui.button(crate::tl!("Cancel")).clicked() { + cancel = true; + } + ui.label(RichText::new(crate::tl!("Ctrl+Enter to apply")).color(t.text_faint).small()); + }); + if !st.message.is_empty() { + ui.label(RichText::new(st.message.as_str()).color(t.warn).small()); + } + }); + if cancel { + keep = false; + } + if commit { + // Typing and undoing back to the same text is not an edit: closing without a command + // keeps the undo stack honest. + if st.text == st.original { + keep = false; + } else { + let params = json!({ "handles": [st.handle.clone()], "text": st.text }); + match app.run("textedit", params) { + Ok(_) => { + st.original = st.text.clone(); + keep = false; + } + Err(e) => st.message = e, + } + } + } + *open = keep; + ctx.data_mut(|d| d.insert_temp(sid, st)); +} From 60c4f0d4399387d495af40b5a10fd6dbe8fc51a0 Mon Sep 17 00:00:00 2001 From: filforce95 <49290121+filforce95@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:01:57 +0100 Subject: [PATCH 161/531] docs: leave ui-parity.md to the maintainers PRs no longer edit the progress docs (CLAUDE.md, Roadmap); the affected row is named in the PR description instead. Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 66d74bfe1..3522b5091 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (clicks count on press, even while the mouse moves) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (WIPEOUT closure-aware grips) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How CADCraft's interaction compares with AutoCAD's: point entry, object snaps, tracking, dynamic input, grips, selection, the command line, chrome and navigation. A drafter's speed in AutoCAD @@ -127,7 +127,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. |---|---|---| | Pick, implied window (left→right) and crossing (right→left) | yes | yes, coloured and dashed rectangles (`lib.rs:576-589`, `canvas.rs:823-836`), filled as SELECTIONAREA, WINDOWAREACOLOR, CROSSINGAREACOLOR and SELECTIONAREAOPACITY say (Visual Effect Settings) | | Keywords W, C, WP, CP, F, BOX, AU, SI, M, G (group), CL (class) | yes | yes except CLass: W, C, F, WP, CP (#226); BOX, AUto, SIngle, Multiple, Group, Add, Remove, Undo (#428); ALL, Last, Previous | -| Press-drag selection windows (PICKDRAG) | yes | clicks or drag (2, default), or two clicks only (0); Options ▸ Selection ▸ Select using two clicks only, saved in the profile; drag-only mode (1) is unavailable. Clicks count when the button goes down, even while the mouse moves, and a press held after the pointer leaves a 6-point tolerance for 0.25 s is a drag; a press on an object picks it, and a drag from it does not open a window (#1001) | +| Press-drag selection windows (PICKDRAG) | yes | clicks or drag (2, default), or two clicks only (0); Options ▸ Selection ▸ Select using two clicks only, saved in the profile; drag-only mode (1) is unavailable | | Lasso | yes | **no** | | Selection cycling (SELECTIONCYCLING) | yes | yes (#1143): SELECTIONCYCLING 2 lists the objects under a click (type, layer; the row under the pointer highlights its object), 1 the badge; Shift+Space steps the highlight through them (#1145); no Ctrl+W | | Selection preview, hover highlight | yes | selected and hovered objects redrawn in the selection colour, fills half see-through (SELECTIONEFFECT 1; 0 dashed), selection effect color; HIGHLIGHT (not saved), SELECTIONPREVIEW, PREVIEWEFFECT, PREVIEWFILTER (Visual Effect Settings) | @@ -214,7 +214,6 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | 2026-10-16 | minor | ALIASEDIT opens the Command Aliases dialog (#1381) | | 2026-10-18 | minor | In-window menu bar: once a menu is open, pointing at another title closes it and opens that one (#1567) | | 2026-10-13 | minor | Options ▸ Selection adds Select using two clicks only; PICKDRAG 0 disables drag-window creation/completion, 2 preserves clicks or drag, and the preference survives restart; UI pointer and profile regressions | -| 2026-10-23 | minor | Clicks on the drawing count when the button goes down, at that spot, even while the mouse moves: points (base points too), object picks, both corners of a click-click window and polygon points; holding the button after the pointer leaves a 6-point tolerance for 0.25 s drags a window (PICKDRAG 2); a press on an object picks it, and a drag from it no longer opens a window; selection cycling opens and picks on the press too (#1001) | | 2026-10-12 | minor | Selected and hovered objects redrawn in the selection colour (text and arrowheads included); Options ▸ Selection laid out as AutoCAD's: Object grouping, Show grips, grip object limit, selection preview, Visual Effect Settings (selection area, preview filter) | | 2026-10-12 | minor | Animation effects (dialog and menu fades, smoothed wheel scrolling and ⌘/Ctrl+wheel zoom) follow the operating system's setting; View ▸ Accessibility ▸ Animation Effects chooses System, On or Off | | 2026-10-12 | minor | Hatch and Gradient / Hatch Edit dialogs (HATCH, GRADIENT, HATCHEDIT, double-click a hatch; HPDLGMODE) | From 0dcdf8d7a9b8ee5995643b550f05c04f25d446b9 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 12:02:37 -0500 Subject: [PATCH 162/531] properties.set leaves objects on locked layers out and says how many The Properties palette, Quick Properties and CHPROP's JSON form all edit through properties.set, which changed objects on locked layers. It now leaves them out and changes the rest, as CHPROP, MATCHPROP, MOVE and CUTCLIP already do. During REFEDIT, objects outside the working set are left out too, instead of the whole edit being refused. The result gains `locked`, and a `message`, which app.run shows at the command line, says how many were left out. When every object is left out, the drawing doesn't change and no undo step is added. CHPROP's JSON form was properties.set on the unlocked objects; it is now properties.set itself. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 68 +++++++++++- crates/engine/src/cmd/props/chprop.rs | 28 ----- crates/engine/tests/it/main.rs | 1 + .../engine/tests/it/properties_set_locked.rs | 104 ++++++++++++++++++ 4 files changed, 169 insertions(+), 32 deletions(-) create mode 100644 crates/engine/tests/it/properties_set_locked.rs diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 8afaddb3d..ea2b1405b 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -10,7 +10,7 @@ mod rename; pub use matchprop::MatchProps; use cadcraft_color::Color; -use cadcraft_doc::{EntityKind, Lineweight, Transparency}; +use cadcraft_doc::{EntityKind, Handle, Lineweight, Transparency}; use cadcraft_geom::Vec3; use serde_json::{Value, json}; @@ -21,8 +21,8 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)}"), - CommandSpec::new("chprop", "Change Properties", chprop::run_chprop) + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)} → {changed, locked, message?}: objects on locked layers (and, during REFEDIT, outside the working set) are left out, and `message` says how many"), + CommandSpec::new("chprop", "Change Properties", run_set) .params("as properties.set, leaving out objects on locked layers → {changed, locked} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)") .interactive(|_| Ok(Box::new(chprop::ChpropM::new()))), CommandSpec::new("change", "Change", change::run_change) @@ -196,11 +196,67 @@ fn set_xy(p: &mut Vec3, v: &Value) { } } +/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked +/// layers and, while a reference is edited in place, those outside the working set. +#[derive(Default)] +struct LeftOut { + locked: usize, + outside: usize, +} + +impl LeftOut { + /// `hs` without the objects that can't be edited, and how many those were. + fn split(s: &Session, hs: Vec) -> Result<(Vec, LeftOut)> { + let d = s.doc()?; + let mut out = LeftOut::default(); + let hs = hs + .into_iter() + .filter(|h| { + if super::blocks::refedit::locked(d, *h) { + out.outside += 1; + } else if super::curves::is_locked(s, *h) { + out.locked += 1; + } else { + return true; + } + false + }) + .collect(); + Ok((hs, out)) + } + + /// `{changed, locked}`, and a message saying how many were left out when any were. + fn result(&self, changed: usize) -> Value { + let mut notes = Vec::new(); + match self.locked { + 0 => {} + 1 => notes.push("1 object was on a locked layer.".to_string()), + n => notes.push(format!("{n} objects were on a locked layer.")), + } + match self.outside { + 0 => {} + 1 => notes.push("1 object was not in the working set.".to_string()), + n => notes.push(format!("{n} objects were not in the working set.")), + } + if changed == 0 && !notes.is_empty() { + notes.push("Nothing was changed.".to_string()); + } + let mut r = json!({ "changed": changed, "locked": self.locked + self.outside }); + if !notes.is_empty() + && let Some(o) = r.as_object_mut() + { + o.insert("message".into(), json!(notes.join(" "))); + } + r + } +} + fn run_set(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; if hs.is_empty() { return Err(bad("properties.set", "nothing selected")); } + let (hs, left_out) = LeftOut::split(s, hs)?; let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?; let transparency = p .get("transparency") @@ -211,6 +267,10 @@ fn run_set(s: &mut Session, p: &Value) -> Result { .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) .transpose()?; let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; + if hs.is_empty() { + // Every object was left out: the drawing stays as it was, with no undo step. + return Ok(left_out.result(0)); + } let d = s.doc_mut()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). let linetype = str_param(p, "linetype") @@ -237,7 +297,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { apply_kind_properties(e, p, dim_style.as_ref(), &dim_over); })?; } - Ok(json!({ "changed": hs.len() })) + Ok(left_out.result(hs.len())) } fn apply_kind_properties( diff --git a/crates/engine/src/cmd/props/chprop.rs b/crates/engine/src/cmd/props/chprop.rs index fac500ecd..66488f02d 100644 --- a/crates/engine/src/cmd/props/chprop.rs +++ b/crates/engine/src/cmd/props/chprop.rs @@ -23,7 +23,6 @@ use serde_json::{Value, json}; use super::super::curves::{KW, is_locked}; use super::super::machines::{SelOutcome, SelectPhase, number}; -use super::super::targets; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; const PROPERTIES: [&str; 7] = ["Color", "LAyer", "LType", "ltScale", "LWeight", "Thickness", "TRansparency"]; @@ -237,33 +236,6 @@ pub(super) fn feed_unlocked(select: &mut SelectPhase, s: &mut Session, i: Input) Ok(outcome) } -/// CHPROP's JSON form: `properties.set` on the objects that are not on locked layers, which the -/// command leaves out too; "locked" says how many were. -pub(super) fn run_chprop(s: &mut Session, p: &Value) -> Result { - let hs = targets(s, p)?; - let locked = locked(s, &hs); - if locked.is_empty() { - return super::run_set(s, p).map(|r| with_locked(r, 0)); - } - let free: Vec = hs.into_iter().filter(|h| !locked.contains(h)).collect(); - let r = if free.is_empty() { - json!({ "changed": 0 }) - } else { - let mut q = p.as_object().cloned().unwrap_or_default(); - q.insert("handles".into(), json!(free.iter().map(|h| h.hex()).collect::>())); - super::run_set(s, &Value::Object(q))? - }; - Ok(with_locked(r, locked.len())) -} - -/// `r` with how many objects were left out on locked layers. -fn with_locked(mut r: Value, n: usize) -> Value { - if let Some(o) = r.as_object_mut() { - o.insert("locked".into(), json!(n)); - } - r -} - /// A colour typed at CHPROP: 1–255, a name, BYLAYER or BYBLOCK (not 0 or 256, which COLOR takes). fn color(t: &str) -> Option { if t.bytes().all(|b| b.is_ascii_digit()) { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 0763ee6eb..0e1fb0a5b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -102,6 +102,7 @@ mod plot_styles; mod point_modifiers; mod post_command_passes; mod prompt_keywords; +mod properties_set_locked; mod props_bad_lineweight; mod props_insert_scale_attribs; mod purge_mlinestyles; diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs new file mode 100644 index 000000000..11fd75830 --- /dev/null +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -0,0 +1,104 @@ +//! `properties.set`, which the Properties palette, Quick Properties and CHPROP edit through, leaves +//! objects on locked layers alone as CHPROP, MATCHPROP and MOVE do, and says how many it left out. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::color::Color; +use cadcraft_engine::doc::{Common, EntityKind, Handle, Insert, Space}; +use cadcraft_engine::geom::Vec3; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +fn line(s: &mut Session, y: f64) -> Handle { + handle(&s.execute("line", &json!({ "points": [[0, y], [50, y]] })).unwrap()) +} + +/// Line a on layer 0 and lines b and c on the locked layer L1; their handles. +fn locked_drawing() -> (Session, [Handle; 3]) { + let mut s = Session::new(); + let hs = [line(&mut s, 0.0), line(&mut s, 20.0), line(&mut s, 40.0)]; + s.execute("properties.set", &json!({ "handles": [hs[1].hex(), hs[2].hex()], "layer": "L1" })).unwrap(); + s.execute("layer.set", &json!({ "name": "L1", "locked": true })).unwrap(); + (s, hs) +} + +fn counts(r: &Value) -> (Option, Option) { + (r["changed"].as_u64(), r["locked"].as_u64()) +} + +fn colors(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.common.color).collect() +} + +fn layers(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.common.layer.clone()).collect() +} + +#[test] +fn objects_on_locked_layers_are_left_out() { + let (mut s, [a, b, c]) = locked_drawing(); + let r = s.execute("properties.set", &json!({ "handles": [a.hex()], "color": 2 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(0)), "{r}"); + assert!(r.get("message").is_none(), "{r}"); + let r = s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex()], "color": 3 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer."); + assert_eq!(colors(&s), [Color::Index(3), Color::ByLayer, Color::ByLayer]); + // The selection when no handles are given; a new layer leaves them on theirs. + s.set_selection(vec![a, b, c]); + let r = s.execute("properties.set", &json!({ "layer": "L2" })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(2)), "{r}"); + assert_eq!(r["message"], "2 objects were on a locked layer."); + assert_eq!(layers(&s), ["L2", "L1", "L1"]); +} + +#[test] +fn with_every_object_locked_nothing_changes() { + let (mut s, [_, b, c]) = locked_drawing(); + let undo = s.state().unwrap().undo.len(); + let r = s.execute("properties.set", &json!({ "handles": [b.hex(), c.hex()], "layer": "NEW", "color": 4 })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(2)), "{r}"); + assert_eq!(r["message"], "2 objects were on a locked layer. Nothing was changed."); + assert_eq!(colors(&s), [Color::ByLayer; 3]); + assert!(s.doc().unwrap().layer("NEW").is_none(), "no layer is made"); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); + // A bad value is still refused. + assert!(s.execute("properties.set", &json!({ "handles": [b.hex()], "color": "nonsense" })).is_err()); + // CHPROP's JSON form is properties.set. + let r = s.execute("chprop", &json!({ "handles": [b.hex()], "color": 4 })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer. Nothing was changed."); +} + +/// While a reference is edited in place, only its working set changes; before, an edit that +/// reached outside it was refused whole. +#[test] +fn during_refedit_objects_outside_the_working_set_are_left_out() { + let mut s = Session::new(); + let l = line(&mut s, 0.0); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [l.hex()], "keep": "delete" })).unwrap(); + let kind = EntityKind::Insert(Insert { + block: "B".into(), + insert: Vec3::new(100.0, 0.0, 0.0), + 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, + }); + let a = s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap(); + let other = line(&mut s, 20.0); + let r = s.execute("refedit", &json!({ "handle": a.hex() })).unwrap(); + let copy = handle(&json!({ "handle": r["working"][0] })); + let r = s.execute("properties.set", &json!({ "handles": [copy.hex(), other.hex()], "color": 5 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was not in the working set."); + let d = s.doc().unwrap(); + assert_eq!(d.entity(copy).unwrap().common.color, Color::Index(5)); + assert_eq!(d.entity(other).unwrap().common.color, Color::ByLayer); + assert!(d.refedit.is_some(), "the edit goes on"); +} From 5787b3634f7d663330af1855fc6a806c77de43f9 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 13:06:16 -0500 Subject: [PATCH 163/531] Review fix: properties.set checks every value before leaving all objects out With every object on a locked layer, properties.set returned before it checked the linetype, the dimension style and the dimension overrides, so it accepted bad values there. They're now checked first, reading the drawing without writing to it; the drawing is taken for writing, and a new layer made, only when there are objects to change. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 17 +++++++++-------- crates/engine/tests/it/properties_set_locked.rs | 14 ++++++++++++-- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index ea2b1405b..0a1081c18 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -267,11 +267,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) .transpose()?; let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; - if hs.is_empty() { - // Every object was left out: the drawing stays as it was, with no undo step. - return Ok(left_out.result(0)); - } - let d = s.doc_mut()?; + let d = s.doc()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). let linetype = str_param(p, "linetype") .map(|n| { @@ -282,13 +278,18 @@ fn run_set(s: &mut Session, p: &Value) -> Result { } }) .transpose()?; - if let Some(l) = str_param(p, "layer") { - d.ensure_layer(l); - } let dim_style = str_param(p, "dimStyle") .map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found")))) .transpose()?; let dim_over = dim_overrides(p)?; + if hs.is_empty() { + // Every object was left out: the drawing stays as it was, with no undo step. + return Ok(left_out.result(0)); + } + let d = s.doc_mut()?; + if let Some(l) = str_param(p, "layer") { + d.ensure_layer(l); + } let anno_scale = d.current_anno_scale(); let common = CommonEntityProperties { anno_scale: &anno_scale, color, linetype: linetype.as_deref(), lineweight: lw, transparency, thickness }; for h in &hs { diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index 11fd75830..267727a4f 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -64,8 +64,18 @@ fn with_every_object_locked_nothing_changes() { assert_eq!(colors(&s), [Color::ByLayer; 3]); assert!(s.doc().unwrap().layer("NEW").is_none(), "no layer is made"); assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); - // A bad value is still refused. - assert!(s.execute("properties.set", &json!({ "handles": [b.hex()], "color": "nonsense" })).is_err()); + // A bad value is still refused, whichever it is. + for bad in [ + json!({ "color": "nonsense" }), + json!({ "linetype": "NOT_LOADED" }), + json!({ "dimStyle": "Missing" }), + json!({ "textHeight": -1 }), + json!({ "precision": 9 }), + ] { + let mut p = bad.clone(); + p["handles"] = json!([b.hex()]); + assert!(s.execute("properties.set", &p).is_err(), "{bad}"); + } // CHPROP's JSON form is properties.set. let r = s.execute("chprop", &json!({ "handles": [b.hex()], "color": 4 })).unwrap(); assert_eq!(counts(&r), (Some(0), Some(1)), "{r}"); From c311ec6b77be2b600505a1d1f42e2e5bb526a019 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 13:38:01 -0500 Subject: [PATCH 164/531] Review fix: CHPROP's parameter text says what properties.set now returns CHPROP's JSON form is properties.set, so its description now names the REFEDIT working set too and lists `message` in the result. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 0a1081c18..7297afad9 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)} → {changed, locked, message?}: objects on locked layers (and, during REFEDIT, outside the working set) are left out, and `message` says how many"), CommandSpec::new("chprop", "Change Properties", run_set) - .params("as properties.set, leaving out objects on locked layers → {changed, locked} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)") + .params("as properties.set, leaving out objects on locked layers (and, during REFEDIT, outside the working set) → {changed, locked, message?} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)") .interactive(|_| Ok(Box::new(chprop::ChpropM::new()))), CommandSpec::new("change", "Change", change::run_change) .alias(&["-ch"]) From e82dede24af47a504575152d334dd1ad8fcff493 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 13:48:18 -0500 Subject: [PATCH 165/531] Review fix: properties.set counts each object once and refuses missing ones first `targets` keeps a handle listed twice, so it was counted twice as left out. During REFEDIT, a handle that names no object counted as outside the working set instead of being refused. properties.set now takes each object once, and refuses a handle that names no object before anything changes; before, the objects ahead of it in the list had already been changed when the error came. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 35 +++++++++++-------- .../engine/tests/it/properties_set_locked.rs | 17 +++++++++ 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 7297afad9..8f8aa454a 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -205,24 +205,29 @@ struct LeftOut { } impl LeftOut { - /// `hs` without the objects that can't be edited, and how many those were. + /// `hs` without the objects that can't be edited, each object once, and how many those were. A + /// handle that names no object is an error, before anything changes. fn split(s: &Session, hs: Vec) -> Result<(Vec, LeftOut)> { let d = s.doc()?; + let mut seen = std::collections::HashSet::new(); let mut out = LeftOut::default(); - let hs = hs - .into_iter() - .filter(|h| { - if super::blocks::refedit::locked(d, *h) { - out.outside += 1; - } else if super::curves::is_locked(s, *h) { - out.locked += 1; - } else { - return true; - } - false - }) - .collect(); - Ok((hs, out)) + let mut free = Vec::new(); + for h in hs { + if d.entity(h).is_none() { + return Err(cadcraft_doc::DocError::NoEntity(h).into()); + } + if !seen.insert(h) { + continue; + } + if super::blocks::refedit::locked(d, h) { + out.outside += 1; + } else if super::curves::is_locked(s, h) { + out.locked += 1; + } else { + free.push(h); + } + } + Ok((free, out)) } /// `{changed, locked}`, and a message saying how many were left out when any were. diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index 267727a4f..258294d79 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -52,6 +52,20 @@ fn objects_on_locked_layers_are_left_out() { assert_eq!(counts(&r), (Some(1), Some(2)), "{r}"); assert_eq!(r["message"], "2 objects were on a locked layer."); assert_eq!(layers(&s), ["L2", "L1", "L1"]); + // An object listed twice counts once. + let r = s.execute("properties.set", &json!({ "handles": [a.hex(), a.hex(), b.hex(), b.hex()], "color": 6 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer."); +} + +/// A handle that names no object is refused before anything changes. +#[test] +fn a_missing_object_is_refused_before_any_change() { + let (mut s, [a, b, _]) = locked_drawing(); + let undo = s.state().unwrap().undo.len(); + assert!(s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex(), "FFFFF"], "color": 7 })).is_err()); + assert_eq!(colors(&s), [Color::ByLayer; 3]); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); } #[test] @@ -111,4 +125,7 @@ fn during_refedit_objects_outside_the_working_set_are_left_out() { assert_eq!(d.entity(copy).unwrap().common.color, Color::Index(5)); assert_eq!(d.entity(other).unwrap().common.color, Color::ByLayer); assert!(d.refedit.is_some(), "the edit goes on"); + // A handle that names no object isn't counted as outside the working set: it's refused. + assert!(s.execute("properties.set", &json!({ "handles": [copy.hex(), "FFFFF"], "color": 6 })).is_err()); + assert_eq!(s.doc().unwrap().entity(copy).unwrap().common.color, Color::Index(5)); } From 8b91646795aa3a3e135cf79c076eefa7b85fbb74 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 14:10:07 -0500 Subject: [PATCH 166/531] Review fix: CHPROP says what it left out; the working set is read once Interactive CHPROP threw away properties.set's message, so an edit to an object it had just moved onto a locked layer was left out without a word. It now shows the message. properties.set looked each object up in REFEDIT's working set, a list, twice; it now builds the set once and checks the layer directly. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 10 ++++++---- crates/engine/src/cmd/props/chprop.rs | 9 +++++++-- crates/engine/tests/it/properties_set_locked.rs | 14 ++++++++++++++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 8f8aa454a..5c7a349b2 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -209,19 +209,21 @@ impl LeftOut { /// handle that names no object is an error, before anything changes. fn split(s: &Session, hs: Vec) -> Result<(Vec, LeftOut)> { let d = s.doc()?; + // The working set, once: `RefEdit::is_working` searches a list. + let working: Option> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect()); let mut seen = std::collections::HashSet::new(); let mut out = LeftOut::default(); let mut free = Vec::new(); for h in hs { - if d.entity(h).is_none() { + let Some(e) = d.entity(h) else { return Err(cadcraft_doc::DocError::NoEntity(h).into()); - } + }; if !seen.insert(h) { continue; } - if super::blocks::refedit::locked(d, h) { + if working.as_ref().is_some_and(|w| !w.contains(&h)) { out.outside += 1; - } else if super::curves::is_locked(s, h) { + } else if d.layer(&e.common.layer).is_some_and(|l| l.locked) { out.locked += 1; } else { free.push(h); diff --git a/crates/engine/src/cmd/props/chprop.rs b/crates/engine/src/cmd/props/chprop.rs index 66488f02d..50fb94597 100644 --- a/crates/engine/src/cmd/props/chprop.rs +++ b/crates/engine/src/cmd/props/chprop.rs @@ -89,13 +89,18 @@ impl ChpropM { if vals.all(|v| v == first) { first } else { "varies".into() } } - /// Apply `props` to the selection through `properties.set`. + /// Apply `props` to the selection through `properties.set`, saying what it left out: objects + /// this command moved onto a locked layer, say. fn apply(&self, s: &mut Session, props: Value) -> Result<()> { let mut p = json!({ "handles": self.handles.iter().map(|h| h.hex()).collect::>() }); if let (Some(p), Value::Object(props)) = (p.as_object_mut(), props) { p.extend(props); } - super::run_set(s, &p).map(|_| ()) + let r = super::run_set(s, &p)?; + if let Some(m) = r.get("message").and_then(Value::as_str) { + s.echo(m.to_string()); + } + Ok(()) } /// Take an answer to `ask`; `false` when it was refused (the prompt comes again). diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index 258294d79..b8356a504 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -58,6 +58,20 @@ fn objects_on_locked_layers_are_left_out() { assert_eq!(r["message"], "1 object was on a locked layer."); } +/// CHPROP says so when it leaves an edit out: an object it moved onto a locked layer keeps its +/// color. +#[test] +fn chprop_says_when_it_leaves_an_object_it_moved_onto_a_locked_layer_alone() { + let (mut s, _) = locked_drawing(); + let d = line(&mut s, 60.0); + s.cmdline("(setq d (entlast))").unwrap(); + s.log.clear(); + s.cmdline("(command \"_.CHPROP\" d \"\" \"_LA\" \"L1\" \"_C\" 3 \"\")").unwrap(); + let e = s.doc().unwrap().entity(d).unwrap().common.clone(); + assert_eq!((e.layer.as_str(), e.color), ("L1", Color::ByLayer)); + assert!(s.log.iter().any(|l| l == "1 object was on a locked layer. Nothing was changed."), "{:?}", s.log); +} + /// A handle that names no object is refused before anything changes. #[test] fn a_missing_object_is_refused_before_any_change() { From 7e386a2cc4761eeee217c8190c5d3d752765cf77 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 14:38:15 -0500 Subject: [PATCH 167/531] Review fix: test that an edit only outside the working set changes nothing Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/it/properties_set_locked.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index b8356a504..5277f48bd 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -139,6 +139,14 @@ fn during_refedit_objects_outside_the_working_set_are_left_out() { assert_eq!(d.entity(copy).unwrap().common.color, Color::Index(5)); assert_eq!(d.entity(other).unwrap().common.color, Color::ByLayer); assert!(d.refedit.is_some(), "the edit goes on"); + // With only objects outside the working set, nothing changes: no layer, no undo step. + let undo = s.state().unwrap().undo.len(); + let r = s.execute("properties.set", &json!({ "handles": [other.hex()], "color": 6, "layer": "NEW" })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was not in the working set. Nothing was changed."); + assert_eq!(s.doc().unwrap().entity(other).unwrap().common.color, Color::ByLayer); + assert!(s.doc().unwrap().layer("NEW").is_none(), "no layer is made"); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); // A handle that names no object isn't counted as outside the working set: it's refused. assert!(s.execute("properties.set", &json!({ "handles": [copy.hex(), "FFFFF"], "color": 6 })).is_err()); assert_eq!(s.doc().unwrap().entity(copy).unwrap().common.color, Color::Index(5)); From df26fc51975cbbcefae2f04e25b97ef56769d1d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=81=E4=BC=AA?= <56018602+r4x2t7@users.noreply.github.com> Date: Mon, 2 Nov 2026 06:34:15 +0800 Subject: [PATCH 168/531] TEXTEDIT: the window opens from the shortcut menu; the double-click keeps its in-place editing The double-click on a text object goes back to starting the in-place TEXTEDIT (#842), which the text_double_click tests guard. The window is what the shortcut menu's Edit Text entry opens for a single selected text, mtext or attribute definition; with several objects selected the command line still runs. The window records the drawing it was opened for and refuses to commit into another one, and its state now lives exactly as long as the window does, so a cancelled edit cannot resurface. --- crates/ui-egui/src/canvas/pick.rs | 22 +++++++++++--------- crates/ui-egui/src/context_menu.rs | 33 ++++++++++++++++++++++++++++-- crates/ui-egui/src/i18n/ar.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/pt_br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh.tsv | 1 + crates/ui-egui/src/textdlg.rs | 32 +++++++++++++++++++++-------- 20 files changed, 84 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/canvas/pick.rs b/crates/ui-egui/src/canvas/pick.rs index 112740d06..3bd28b017 100644 --- a/crates/ui-egui/src/canvas/pick.rs +++ b/crates/ui-egui/src/canvas/pick.rs @@ -1,4 +1,4 @@ -use super::{CadApp, Handle, Vec2}; +use super::{CadApp, Handle, Input, Vec2}; /// The vertical wheel scroll this frame that zooms, in points, read from the raw wheel events so /// each notch zooms by its whole step at once, as in standard CAD (#660). egui's smoothed delta @@ -26,18 +26,20 @@ 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`. -/// Open Edit Text on the text, mtext or attribute definition at `p` (the objects the shortcut -/// menu offers Edit Text for); 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 hit = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { - let e = app.session.doc().ok()?.entity(h)?; - matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)).then_some(h) + let is_text = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { + app.session.doc().ok()?.entity(h).map(|e| matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_))) }); - let Some(h) = hit else { return false }; - // The window edits the object in place of the command line, which used to take the caret and - // hide the drawing behind it. - app.ui.dialog = Some(format!("textedit:{}", h.hex())); + if is_text != Some(true) { + return false; + } + app.start("textedit"); + if let Err(e) = app.session.input(Input::Point(p)) { + app.session.echo(e.to_string()); + } true } diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbaf48df3..0b00d933c 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -153,9 +153,35 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { } } -/// [`object_commands`] that are registered, as menu items. +/// [`object_commands`] that are registered, as menu items. The Edit Text entry of a single +/// selected text, mtext or attribute definition opens the Edit Text window instead of the +/// TEXTEDIT command line; the double-click keeps its in-place editing (#842), and several +/// selected texts still take the command line. pub fn object_entries(app: &CadApp) -> Vec { - object_commands(app).into_iter().filter_map(|(id, label)| item(app, id, label)).collect() + object_commands(app) + .into_iter() + .filter_map(|(id, label)| { + if id == "textedit" { + edit_text_window_entry(app).or_else(|| item(app, id, label)) + } else { + item(app, id, label) + } + }) + .collect() +} + +/// The Edit Text entry as the `textedit:` dialog id, for a single selected text, mtext +/// or attribute definition; `None` otherwise, so the command line entry stands in. +fn edit_text_window_entry(app: &CadApp) -> Option { + use cadcraft_engine::doc::EntityKind; + let sel = app.session.selection(); + if sel.len() != 1 { + return None; + } + let h = *sel.first()?; + let d = app.session.doc().ok()?; + d.entity(h).filter(|e| matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)))?; + Some(Entry::Item { label: "Edit Text".into(), id: format!("textedit:{}", h.hex()), shortcut: None, enabled: true }) } /// The command menu while a command runs (`None` when none does): Enter and Cancel, Recent Input, @@ -213,6 +239,9 @@ pub fn choose(app: &mut CadApp, id: &str) { } } else if let Some(s) = id.strip_prefix(SNAP) { choose_snap(app, s); + } else if id.starts_with("textedit:") { + // The Edit Text window of the single selected text object; the id carries the handle. + app.ui.dialog = Some(id.to_string()); } else { activate(app, id); } diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 657ec3fd1..75538130a 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -1374,3 +1374,4 @@ menu View عرض {command} is an unknown command. {command} أمر غير معروف. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. تغيّر الرسم. أغلق النافذة وافتحها مرة أخرى. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 508fd7422..f2ee28566 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1450,3 +1450,4 @@ menu Modify Izmijeni Associate Poveži Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Crtež se promijenio. Zatvorite prozor i otvorite ga ponovo. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1d5db0700..422b0a1b7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1230,3 +1230,4 @@ menu Modify Modifikace Could not check for updates. Aktualizace se nepodařilo zkontrolovat. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Výkres se změnil. Zavřete okno a otevřete jej znovu. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 213aa4f5a..cf1be2ca0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1047,3 +1047,4 @@ Could not check for updates. Die Suche nach Updates ist fehlgeschlagen. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Die Zeichnung hat sich geändert. Schließen Sie das Fenster und öffnen Sie es erneut. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9a1b0784d..981a3054f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1341,3 +1341,4 @@ menu View Προβολή Could not check for updates. Δεν ήταν δυνατός ο έλεγχος για ενημερώσεις. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Το σχέδιο άλλαξε. Κλείστε το παράθυρο και ανοίξτε το ξανά. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e02790314..16e8ce57d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1261,3 +1261,4 @@ Could not check for updates. No se pudo buscar actualizaciones. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. El dibujo cambió. Cierre la ventana y ábrala de nuevo. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 031519a07..d53fbd216 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1020,3 +1020,4 @@ Could not check for updates. Impossible de rechercher les mises à jour. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Le dessin a changé. Fermez la fenêtre et rouvrez-la. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cd47b5ca6..c40c4b898 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1352,3 +1352,4 @@ menu View Nézet Could not check for updates. A frissítések keresése nem sikerült. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. A rajz megváltozott. Zárja be az ablakot, és nyissa meg újra. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 550e3aeae..485790efa 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1370,3 +1370,4 @@ menu Modify Edita Could not check for updates. Impossibile verificare gli aggiornamenti. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Il disegno è cambiato. Chiudere la finestra e riaprirla. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 847c78149..166e42c4f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1250,3 +1250,4 @@ menu Modify 수정 Could not check for updates. 업데이트를 확인하지 못했습니다. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. 도면이 변경되었습니다. 창을 닫고 다시 여십시오. diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 0e272cced..6fa9d6b45 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -1259,3 +1259,4 @@ Could not check for updates. Não foi possível verificar atualizações. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. O desenho mudou. Feche a janela e abra-a novamente. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3bcdb5aa7..4407bb82e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1021,3 +1021,4 @@ Could not check for updates. Не удалось проверить обновления. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Чертёж изменился. Закройте окно и откройте его снова. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index bd5b8d59e..54c609d64 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1454,3 +1454,4 @@ menu Modify Ändra Could not check for updates. Det gick inte att söka efter uppdateringar. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Ritningen har ändrats. Stäng fönstret och öppna det igen. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2ad0e4a72..c002c60ba 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1355,3 +1355,4 @@ menu View Görünüm Could not check for updates. Güncellemeler denetlenemedi. Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Çizim değişti. Pencereyi kapatıp yeniden açın. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 10edda9a5..8c9d18b57 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1379,3 +1379,4 @@ Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Креслення змінилося. Закрийте вікно та відкрийте його знову. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 195616277..8908bb7ad 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1454,3 +1454,4 @@ menu Modify Hiệu chỉnh Save Layout as Template Lưu layout thành mẫu Ctrl+Enter to apply Ctrl+Enter to apply Edit Text Edit Text + The drawing changed. Close the window and open it again. Bản vẽ đã thay đổi. Đóng cửa sổ và mở lại. diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 8656cd4cf..d410b37de 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1383,3 +1383,4 @@ Units 单位 Ctrl+Enter to apply Ctrl+Enter 应用 Edit Text 编辑文字 + The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。 diff --git a/crates/ui-egui/src/textdlg.rs b/crates/ui-egui/src/textdlg.rs index b3d13ae9f..c9a279660 100644 --- a/crates/ui-egui/src/textdlg.rs +++ b/crates/ui-egui/src/textdlg.rs @@ -1,10 +1,11 @@ -//! Edit Text: the window a double-click on a text object opens. +//! Edit Text: the window behind the shortcut menu's Edit Text entry. //! -//! TEXTEDIT already existed, but only as a command line: double-clicking a single-line text put -//! the caret in the command bar, one line, no context, and the text under the cursor was out of -//! sight. The window shows the same edit over the drawing: the object's own text, its type and -//! handle, and OK/Cancel. The engine call is unchanged (`textedit` with a handle and the new -//! text), so undo, locked layers and the DXF round trip behave exactly as before. +//! TEXTEDIT already existed, but only as a command line: it put the caret in the command bar, +//! one line, no context, and the text under the cursor was out of sight. The window shows the +//! same edit over the drawing: the object's own text, its type and handle, and OK/Cancel. The +//! engine call is unchanged (`textedit` with a handle and the new text), so undo, locked layers +//! and the DXF round trip behave exactly as before. The double-click keeps its in-place editing +//! (#842); the window is the shortcut menu's way in. use egui::RichText; use serde_json::json; @@ -33,13 +34,17 @@ struct State { text: String, /// What the drawing holds now, to tell an edit from a no-op. original: String, + /// The drawing the window was opened for: a handle means nothing once another drawing is + /// active, and committing to it would edit an object the user never saw. + uid: u64, message: String, } /// Read the object the window is for. A handle that no longer exists, or an object that is not /// text, leaves the window empty instead of failing: the drawing may have changed under it. fn initial(app: &CadApp, hex: &str) -> State { - let mut st = State { handle: hex.to_string(), ..Default::default() }; + let uid = app.session.state().map(|s| s.uid).unwrap_or_default(); + let mut st = State { handle: hex.to_string(), uid, ..Default::default() }; let Some(h) = cadcraft_doc::Handle::parse_hex(hex) else { return st }; let Ok(d) = app.session.doc() else { return st }; let Some(e) = d.entity(h) else { return st }; @@ -100,6 +105,11 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, spec: &str, open: &mut bool // keeps the undo stack honest. if st.text == st.original { keep = false; + } else if app.session.state().map(|s| s.uid).ok() != Some(st.uid) { + // The drawing switched while the window sat open: the handle now names another + // drawing's object, so the commit is refused and the user reopens on the drawing + // they meant to edit. + st.message = crate::tl!("The drawing changed. Close the window and open it again.").to_string(); } else { let params = json!({ "handles": [st.handle.clone()], "text": st.text }); match app.run("textedit", params) { @@ -112,5 +122,11 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, spec: &str, open: &mut bool } } *open = keep; - ctx.data_mut(|d| d.insert_temp(sid, st)); + // The state lives exactly as long as the window does: a closed window leaves nothing + // behind, so reopening it reads the drawing's text instead of an edit the user cancelled. + if keep { + ctx.data_mut(|d| d.insert_temp(sid, st)); + } else { + ctx.data_mut(|d| d.remove_temp::(sid)); + } } From 44950708baacb6a85e73a559c8cfdf69887d50f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=81=E4=BC=AA?= <56018602+r4x2t7@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:23:09 +0800 Subject: [PATCH 169/531] TEXTEDIT: the context-menu test follows the window entry, several texts keep the command --- crates/ui-egui/src/context_menu.rs | 8 +------ crates/ui-egui/tests/it/context_menus.rs | 28 ++++++++++++++++++------ 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 0b00d933c..3f1c98ebf 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -160,13 +160,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { pub fn object_entries(app: &CadApp) -> Vec { object_commands(app) .into_iter() - .filter_map(|(id, label)| { - if id == "textedit" { - edit_text_window_entry(app).or_else(|| item(app, id, label)) - } else { - item(app, id, label) - } - }) + .filter_map(|(id, label)| if id == "textedit" { edit_text_window_entry(app).or_else(|| item(app, id, label)) } else { item(app, id, label) }) .collect() } diff --git a/crates/ui-egui/tests/it/context_menus.rs b/crates/ui-egui/tests/it/context_menus.rs index 3134b8d3c..fbd39f930 100644 --- a/crates/ui-egui/tests/it/context_menus.rs +++ b/crates/ui-egui/tests/it/context_menus.rs @@ -133,7 +133,8 @@ fn idle_menu_lists_recent_commands_and_selection_commands() { #[test] fn selection_menu_has_the_object_types_edit_commands() { let cases = [ - ("text", json!({ "at": [0, 0], "text": "hi" }), "textedit"), + // A single text's Edit Text opens the Edit Text window: the id carries the handle. + ("text", json!({ "at": [0, 0], "text": "hi" }), "textedit:"), ("pline", json!({ "vertices": [[0, 0], [10, 0], [10, 5]] }), "pedit"), ("spline", json!({ "fit": [[0, 0], [5, 5], [10, 0]] }), "splinedit"), ]; @@ -142,14 +143,27 @@ fn selection_menu_has_the_object_types_edit_commands() { app.run(cmd, params).unwrap(); select_all(&mut app); let g = vec![context_menu::object_entries(&app)]; - assert!(ids(&g).iter().any(|i| i == edit), "{cmd}: {edit} missing from {:?}", labels(&g)); - assert!(ids(&context_menu::entries(&app)).iter().any(|i| i == edit)); + let hit = ids(&g).iter().find(|i| i.starts_with(edit)).cloned(); + assert!(hit.is_some(), "{cmd}: {edit} missing from {:?}", labels(&g)); + assert!(ids(&context_menu::entries(&app)).iter().any(|i| i.starts_with(edit))); + // Choosing the window's entry opens the dialog on the object; the double-click keeps its + // in-place editing (#842). + if let Some(id) = hit.filter(|i| i.starts_with("textedit:")) { + context_menu::choose(&mut app, &id); + assert_eq!(app.ui.dialog.as_deref(), Some(id.as_str())); + } } + // Several selected texts keep the TEXTEDIT command line: the window edits one object at a time. + let mut several = app(); + several.run("text", json!({ "at": [0, 0], "text": "hi" })).unwrap(); + several.run("text", json!({ "at": [0, 4], "text": "ho" })).unwrap(); + select_all(&mut several); + assert!(ids(&[context_menu::object_entries(&several)]).iter().any(|i| i == "textedit")); // Polyline Edit, not the command's bare "Polyline" label. - let mut app = app(); - app.run("pline", json!({ "vertices": [[0, 0], [10, 0]] })).unwrap(); - select_all(&mut app); - assert_eq!(labels(&[context_menu::object_entries(&app)]), ["Polyline Edit"]); + let mut pline = app(); + pline.run("pline", json!({ "vertices": [[0, 0], [10, 0]] })).unwrap(); + select_all(&mut pline); + assert_eq!(labels(&[context_menu::object_entries(&pline)]), ["Polyline Edit"]); } #[test] From 322c5e9bbfce895dbe7cc109d7393153ab77cf64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=81=E4=BC=AA?= <56018602+r4x2t7@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:52:05 +0800 Subject: [PATCH 170/531] TEXTEDIT: the field keeps its undo history per object, and the shortcut works on macOS The multiline field is keyed by drawing and handle, so two edits never share a Ctrl+Z trail, and the field's persisted state is removed with the window - otherwise the undo history would offer a previous object's text to whoever is edited next. The commit shortcut now checks Control rather than the platform Command modifier, matching the Ctrl+Enter the window advertises. --- crates/ui-egui/src/textdlg.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/textdlg.rs b/crates/ui-egui/src/textdlg.rs index c9a279660..b0c56e4ef 100644 --- a/crates/ui-egui/src/textdlg.rs +++ b/crates/ui-egui/src/textdlg.rs @@ -70,6 +70,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, spec: &str, open: &mut bool let mut keep = *open; let mut commit = false; let mut cancel = false; + // The field's undo history is keyed by drawing and handle: two edits on the same drawing + // must not share a Ctrl+Z trail, and neither must an edit on two different drawings. + let field = egui::Id::unique("textedit_field").with(st.uid).with(&st.handle); egui::Window::new(crate::tl!("Edit Text")) .id(egui::Id::unique("Edit Text")) .open(&mut keep) @@ -79,9 +82,10 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, spec: &str, open: &mut bool .show(ctx, |ui| { let head = format!("{} · {}", crate::i18n::t(&st.kind), st.handle); ui.label(RichText::new(head).color(t.text_faint).small()); - let r = ui.add(egui::TextEdit::multiline(&mut st.text).desired_width(f32::INFINITY).desired_rows(3).hint_text(crate::tl!("Text"))); + let r = + ui.add(egui::TextEdit::multiline(&mut st.text).id(field).desired_width(f32::INFINITY).desired_rows(3).hint_text(crate::tl!("Text"))); // Ctrl+Enter commits from inside the field, so a multiline text can keep plain Enter. - if r.has_focus() && ui.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Enter)) { + if r.has_focus() && ui.input(|i| i.modifiers.ctrl && i.key_pressed(egui::Key::Enter)) { commit = true; } ui.horizontal(|ui| { @@ -124,9 +128,14 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, spec: &str, open: &mut bool *open = keep; // The state lives exactly as long as the window does: a closed window leaves nothing // behind, so reopening it reads the drawing's text instead of an edit the user cancelled. + // The field's own persisted state goes with it — otherwise the undo history would offer a + // previous object's text to whoever is edited next. if keep { ctx.data_mut(|d| d.insert_temp(sid, st)); } else { - ctx.data_mut(|d| d.remove_temp::(sid)); + ctx.data_mut(|d| { + d.remove_temp::(sid); + d.remove::(field); + }); } } From a70223e25fff223ea7191f1ebb71db0a10c0752f Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:11:31 +0700 Subject: [PATCH 171/531] TRIM: a polyline cuts itself where it touches itself, in Quick mode too A polyline that is one of the cutting edges was cut at its vertices and where two of its segments cross, not where a vertex of it (an end included) touches another of its segments. Trimmed there, a polyline whose end returns onto its own segment lost the stretch past the touch too. In Quick mode with every object it didn't cut itself at all. As AutoCAD 2024 does (Standard mode by accoreconsole; Quick mode in AutoCAD itself, picking on screen): - a vertex touching another segment of the same polyline cuts that segment, in Standard and in Quick mode; - a piece whose two ends meet is left closed, without the repeated vertex, its arcs kept. Edges::quick is gone: nothing reads it any more. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 39 +++++--- crates/engine/src/cmd/trimextend.rs | 4 +- .../tests/it/break_trim_polyline_rules.rs | 97 ++++++++++++++++++- 3 files changed, 121 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index ede201ff9..870bcc36c 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -13,10 +13,6 @@ pub(crate) struct Edges<'a> { /// Implied edges (EDGEMODE 1): lines and the end segments of open polylines count as running /// on without end, arcs as whole circles. pub implied: bool, - /// Quick mode (TRIMEXTENDMODE 1), where `only: None` means every object but the one trimmed. - /// A trimmed polyline that is one of the edges cuts itself too: picked as one, or with every - /// object in Standard mode. - pub quick: bool, } /// All primitives of the cutting edges (excluding `exclude`). @@ -103,7 +99,9 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu } let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let cut = edge_segments(s, edges, h)?; - let itself = edges.only.map_or(!edges.quick, |o| o.contains(&h)); + // A polyline that is one of the edges (picked, or with every object in either mode) cuts + // itself too. + let itself = edges.only.is_none_or(|o| o.contains(&h)); let pieces: Vec = match &e.kind { EntityKind::Line(l) => { let ln = Line::new(l.a.xy(), l.b.xy()); @@ -284,8 +282,9 @@ const MAX_SELF_CROSSING_SEGMENTS: usize = 2048; const MAX_SELF_CROSSINGS: usize = 10_000; /// Where a polyline cuts itself, as lengths along it: the vertices between its segments (every -/// vertex of a closed one, its start included) and the points where two of its segments cross. -/// AutoCAD 2024 trims a polyline that is one of the cutting edges at these. +/// vertex of a closed one, its start included), the points where two of its segments cross, and +/// those where a vertex of it (an end included) touches another of its segments. AutoCAD 2024 +/// trims a polyline that is one of the cutting edges at these. fn self_cuts(segs: &[Segment], closed: bool) -> Vec { let mut starts = Vec::with_capacity(segs.len()); let mut acc = 0.0; @@ -307,9 +306,16 @@ fn self_cuts(segs: &[Segment], closed: bool) -> Vec { } for x in intersect_ext(a, b, false) { let (ta, tb) = (param_on(a, x), param_on(b, x)); - if inside(ta) && inside(tb) { - ts.push(a0 + ta * a.len()); - ts.push(b0 + tb * b.len()); + // A crossing cuts both segments; a vertex touching the other segment cuts that + // one (the vertex is a cut already). Two segments meeting at a vertex cut nothing + // more. + if inside(ta) || inside(tb) { + if inside(ta) { + ts.push(a0 + ta * a.len()); + } + if inside(tb) { + ts.push(b0 + tb * b.len()); + } crossings += 1; if crossings >= MAX_SELF_CROSSINGS { return ts; @@ -372,11 +378,20 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse } out.push(mk(sub_polyline(&doubled, a, b))); } else { + // A piece whose ends meet (the polyline touched itself there) is closed, without its + // repeated vertex, as AutoCAD leaves it. + let piece = |mut vs: Vec| { + let meets = vs.len() >= 4 && matches!((vs.first(), vs.last()), (Some(a), Some(b)) if a.p.near(b.p, 1e-9 * (1.0 + a.p.len()))); + if meets { + vs.pop(); + } + lwpoly(vs, meets) + }; if lo.is_finite() { - out.push(mk(sub_polyline(&segs, 0.0, lo))); + out.push(piece(sub_polyline(&segs, 0.0, lo))); } if hi.is_finite() { - out.push(mk(sub_polyline(&segs, hi, total))); + out.push(piece(sub_polyline(&segs, hi, total))); } } Ok(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect()) diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 922d28dd6..7b061cd78 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -181,7 +181,7 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result { _ => return Err(bad(cmd, "`mode` must be \"quick\" or \"standard\"")), }, }; - let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)?, quick }; + let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? }; let key = if extending { "extended" } else { "trimmed" }; if p.get("fence").is_some_and(|v| !v.is_null()) { let pts = points_param(p, "fence") @@ -243,7 +243,7 @@ impl TrimM { TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new() } } fn edges(&self, quick: bool, implied: bool) -> Edges<'_> { - Edges { only: self.edges.as_deref(), implied: !quick && implied, quick } + Edges { only: self.edges.as_deref(), implied: !quick && implied } } fn select_edges(&mut self, s: &mut Session) { s.echo(if self.extend { "Select boundary edges ..." } else { "Select cutting edges ..." }); diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs index 519a24664..33088043d 100644 --- a/crates/engine/tests/it/break_trim_polyline_rules.rs +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -4,8 +4,12 @@ //! - BREAK between two points of a closed polyline removes the stretch between them that doesn't //! run through its start vertex, whichever point comes first; BREAK or BREAKATPOINT at one point //! splits it there into two open polylines, and at its start vertex leaves it closed. -//! - In Standard mode, a polyline that is one of the cutting edges (picked, or with every object) -//! is also cut at its own vertices and where it crosses itself. +//! - A polyline that is one of the cutting edges (picked, or with every object, in Standard or +//! Quick mode) is also cut at its own vertices, where it crosses itself and where a vertex of it +//! touches another of its segments. A piece whose ends meet there is left closed. +//! +//! Quick mode was measured in AutoCAD 2024 itself, picking on screen: its scripted TRIM runs +//! Standard mode only. use cadcraft_engine::Session; use cadcraft_engine::doc::{EntityKind, Handle}; @@ -238,10 +242,93 @@ fn a_polyline_picked_as_an_edge_in_quick_mode_cuts_itself_too() { } #[test] -fn quick_mode_still_cuts_only_at_other_objects() { - // Not measured: AutoCAD's scripted TRIM runs Standard mode only. +fn quick_mode_with_every_object_cuts_a_polyline_at_its_own_vertex_too() { + // As Standard mode with every object: from the vertex at (40, 0), not from the line at x = 20. let mut s = Session::new(); let (p, ..) = arc_polyline(&mut s); s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick" })).unwrap(); - expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 0.0, 0.0)]), (false, false, &FROM_C)]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]); +} + +/// A rectangle, then an open polyline whose last vertex (6.9, 6.2) touches its second segment +/// inside the rectangle (reversed: whose first vertex does). The polyline's handle. +fn touching(s: &mut Session, reversed: bool) -> Handle { + pline(s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true); + let mut v = vec![[2.3, 3.3], [5.3, 8.0], [8.5, 4.4], [8.8, 7.8], [6.9, 6.2]]; + if reversed { + v.reverse(); + } + pline(s, json!(v), false) +} + +const RECT: [Vertex; 4] = [(3.9, 3.8, 0.0), (8.3, 3.8, 0.0), (8.3, 6.9, 0.0), (3.9, 6.9, 0.0)]; +/// Where the second segment crosses the rectangle's top and right sides. +const TOP: Vertex = (6.277777777777777, 6.9, 0.0); +const RIGHT: Vertex = (8.3, 4.625, 0.0); + +#[test] +fn a_polyline_is_cut_where_its_end_touches_it() { + let start: [Vertex; 3] = [(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP]; + let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.0), (8.8, 7.8, 0.0)]; + // Picked above the touch, in the rectangle: cut from the top side to the touch. What is left + // after it ends where it starts, so it is closed. Quick mode as picked on screen, and Standard + // mode with every object at the command line. + let mut s = Session::new(); + let p = touching(&mut s, false); + s.execute("trim", &json!({ "handle": p.hex(), "pick": [6.58, 6.56], "mode": "quick" })).unwrap(); + expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]); + let mut s = Session::new(); + let p = touching(&mut s, false); + run(&mut s, "TRIM O S\n\n6.58,6.56\n\n"); + expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]); + // Below the touch: cut from the touch to the right side. + let mut s = Session::new(); + let p = touching(&mut s, false); + trim(&mut s, p, [7.604, 5.408], None); + let end: [Vertex; 4] = [RIGHT, (8.5, 4.4, 0.0), (8.8, 7.8, 0.0), (6.9, 6.2, 0.0)]; + expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), (6.9, 6.2, 0.0)]), (false, false, &end)]); + // The first vertex touching: the closed loop is the piece that keeps the handle. + let mut s = Session::new(); + let p = touching(&mut s, true); + trim(&mut s, p, [6.58, 6.56], None); + expect( + &s, + p, + &[ + (false, true, &RECT), + (true, true, &[(6.9, 6.2, 0.0), (8.8, 7.8, 0.0), (8.5, 4.4, 0.0)]), + (false, false, &[TOP, (5.3, 8.0, 0.0), (2.3, 3.3, 0.0)]), + ], + ); +} + +#[test] +fn a_closed_piece_keeps_its_arcs() { + let mut s = Session::new(); + pline(&mut s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true); + let p = pline(&mut s, json!([[2.3, 3.3], [5.3, 8.0], { "p": [8.5, 4.4], "bulge": 0.3 }, [8.8, 7.8], [6.9, 6.2]]), false); + trim(&mut s, p, [6.58, 6.56], None); + let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.3), (8.8, 7.8, 0.0)]; + expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP]), (false, true, &looped)]); +} + +#[test] +fn a_polyline_is_cut_where_a_vertex_of_it_touches_it() { + // The vertex (6, 6) lies on the first segment, which is cut there. + let v = json!([[0, 0], [10, 10], [12, 4], [6, 6], [4, 12]]); + let mut s = Session::new(); + let p = pline(&mut s, v.clone(), false); + trim(&mut s, p, [3.0, 3.0], None); + expect(&s, p, &[(true, false, &[(6.0, 6.0, 0.0), (10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)])]); + let mut s = Session::new(); + let p = pline(&mut s, v, false); + trim(&mut s, p, [8.0, 8.0], None); + expect( + &s, + p, + &[ + (true, false, &[(0.0, 0.0, 0.0), (6.0, 6.0, 0.0)]), + (false, false, &[(10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)]), + ], + ); } From e35dfe6533f1dd715471d8e21da2a95bf153c777 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:46:23 +0700 Subject: [PATCH 172/531] TRIM: a pick on a vertex keeps the polyline; close only meeting ends A pick exactly on a cut (a vertex, now that a polyline cuts itself at each) found no piece on either side, and the whole polyline was erased. It now takes the piece of the segment it was found on: the one before a vertex the segment ends at, the one after a vertex it starts at. A piece was closed when its ends were within 1e-9 of the coordinates' size: about one unit 1e9 from the origin, so ends 0.58 apart closed. It is now rounding error only, 64 ULP of the larger coordinate. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 22 +++++++++++++-- .../tests/it/break_trim_polyline_rules.rs | 27 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 870bcc36c..2c01311e2 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -336,6 +336,8 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse let mut ts: Vec = Vec::new(); let mut acc = 0.0; let mut tp = 0.0; + // The pick is at the start of the segment it was found on (1), at its end (-1), or between. + let mut at_end = 0.0; let mut best = f64::INFINITY; for s in &segs { let len = s.len(); @@ -345,7 +347,15 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse let c = s.closest(pick); if c.dist(pick) < best { best = c.dist(pick); - tp = acc + param_on(s, c) * len; + let u = param_on(s, c); + tp = acc + u * len; + at_end = if u >= 1.0 - 1e-12 { + -1.0 + } else if u <= 1e-12 { + 1.0 + } else { + 0.0 + }; } acc += len; } @@ -358,6 +368,12 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse if ts.is_empty() { return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); } + // A pick right on a cut (a vertex picked exactly) takes the piece of the segment it was found + // on, rather than neither piece (which would erase the whole polyline). + let near = 1e-9 * total; + if ts.iter().any(|t| (t - tp).abs() <= near) { + tp += if at_end > 0.0 { 2.0 * near } else { -2.0 * near }; + } let lo = ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max); let hi = ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min); let mk = |vs: Vec| lwpoly(vs, false); @@ -381,7 +397,9 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse // A piece whose ends meet (the polyline touched itself there) is closed, without its // repeated vertex, as AutoCAD leaves it. let piece = |mut vs: Vec| { - let meets = vs.len() >= 4 && matches!((vs.first(), vs.last()), (Some(a), Some(b)) if a.p.near(b.p, 1e-9 * (1.0 + a.p.len()))); + // Within rounding of the coordinates, however far from the origin, and no more. + let meets = vs.len() >= 4 + && matches!((vs.first(), vs.last()), (Some(a), Some(b)) if a.p.near(b.p, 64.0 * f64::EPSILON * (1.0 + a.p.len().max(b.p.len())))); if meets { vs.pop(); } diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs index 33088043d..c6ef266a8 100644 --- a/crates/engine/tests/it/break_trim_polyline_rules.rs +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -312,6 +312,33 @@ fn a_closed_piece_keeps_its_arcs() { expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP]), (false, true, &looped)]); } +#[test] +fn a_pick_right_on_a_vertex_takes_the_segment_it_ends() { + // Not measured. The vertex (10, 0) is the only cut: the pick takes the segment before it + // instead of erasing the polyline. + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10]]), false); + trim(&mut s, p, [10.0, 0.0], None); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); +} + +#[test] +fn a_piece_whose_ends_only_come_near_stays_open_far_from_the_origin() { + // 1e9 out, as survey coordinates in millimetres are: the piece left runs from the line's cut + // to the polyline's end, 0.58 away, and stays open. + let o = 1e9; + let mut s = Session::new(); + let p = pline(&mut s, json!([[o + 2.3, 3.3], [o + 5.3, 8.0], [o + 8.5, 4.4], [o + 8.8, 7.8], [o + 7.4, 6.5]]), false); + line(&mut s, [o + 6.9, 5.0], [o + 6.9, 7.0]); + trim(&mut s, p, [o + 6.1, 7.1], None); + let got = polys(&s); + assert_eq!(got.len(), 2, "{got:?}"); + let (h, closed, vs) = &got[1]; + assert!(*h != p && !closed && vs.len() == 4, "{got:?}"); + let last = vs[3]; + assert!((last.0 - (o + 7.4)).abs() < 1e-6 && (last.1 - 6.5).abs() < 1e-6, "{last:?}"); +} + #[test] fn a_polyline_is_cut_where_a_vertex_of_it_touches_it() { // The vertex (6, 6) lies on the first segment, which is cut there. From 45d84f109086ac7031b8c803564301eec935088f Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 15:22:24 +0700 Subject: [PATCH 173/531] TRIM: only a pick on a cut picks a side of it A pick within 1e-9 of the polyline's length from a cut was moved across it. On a long polyline that window is wide: 10000 long, a pick inside a segment a millionth long was moved before the cut ahead of it, and 1e9 long, a pick half a unit up the second segment was moved onto the first, so the wrong segment was trimmed. Only a pick on a cut within rounding (4 ULP of the length) now picks a side of it; any other pick splits the cuts where it is. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 22 ++++++++++++------- .../tests/it/break_trim_polyline_rules.rs | 14 ++++++++++++ 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 2c01311e2..383e4c50a 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -368,14 +368,20 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse if ts.is_empty() { return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); } - // A pick right on a cut (a vertex picked exactly) takes the piece of the segment it was found - // on, rather than neither piece (which would erase the whole polyline). - let near = 1e-9 * total; - if ts.iter().any(|t| (t - tp).abs() <= near) { - tp += if at_end > 0.0 { 2.0 * near } else { -2.0 * near }; - } - let lo = ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max); - let hi = ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min); + // A pick on a cut (a vertex picked exactly: the same length within rounding) takes the piece + // of the segment it was found on, rather than neither piece (which would erase the whole + // polyline): the cuts are split just past that cut when the pick is at its segment's start, + // just before it otherwise. A pick off every cut splits them where it is. + let on = 4.0 * f64::EPSILON * (total + 1.0); + let split = if !ts.iter().any(|t| (t - tp).abs() <= on) { + tp + } else if at_end > 0.0 { + tp + 2.0 * on + } else { + tp - 2.0 * on + }; + let lo = ts.iter().copied().filter(|t| *t < split).fold(f64::NEG_INFINITY, f64::max); + let hi = ts.iter().copied().filter(|t| *t > split).fold(f64::INFINITY, f64::min); let mk = |vs: Vec| lwpoly(vs, false); let mut out = Vec::new(); if p.closed { diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs index c6ef266a8..f5d05257d 100644 --- a/crates/engine/tests/it/break_trim_polyline_rules.rs +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -322,6 +322,20 @@ fn a_pick_right_on_a_vertex_takes_the_segment_it_ends() { expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); } +#[test] +fn a_pick_inside_a_segment_stays_on_its_side_of_a_cut() { + // A segment a millionth long between two vertices: a pick in it takes it, not the one before. + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [10, 0], [10.000001, 0], [10000, 0]]), false); + trim(&mut s, p, [10.0000005, 0.0], None); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), (false, false, &[(10.000001, 0.0, 0.0), (10000.0, 0.0, 0.0)])]); + // 1e9 long: half a unit up the second segment is on the second segment. + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 10]]), false); + trim(&mut s, p, [1e9, 0.5], None); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)])]); +} + #[test] fn a_piece_whose_ends_only_come_near_stays_open_far_from_the_origin() { // 1e9 out, as survey coordinates in millimetres are: the piece left runs from the line's cut From 04f06a2f87769cdab0651c40c46b58d183a20bd3 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 2 Nov 2026 15:25:55 +0500 Subject: [PATCH 174/531] A tile's rectangle and the view it shows are judged apart Two from review, both about one `*ACTIVE` record carrying two separate things: where the tile sits on the screen (10/11) and the view it shows (12/22, 40). Reading: the two were one `ok`, and the early return came before the view was read. A first `*ACTIVE` with a usable view and an unusable rectangle therefore lost the view, and a file whose header carries none opened on the extent fit instead of where it was saved. They are judged apart now -- `view_ok` decides the saved view, `tile_ok` decides the tile -- so the rectangle is still refused while the view it holds is kept. Writing: the tiled branch emitted the stored tiles as they stand, so updating `header.set_saved_view` on a drawing with several tiles wrote the new view in HEADER and the old one in the first `*ACTIVE`. The read takes its view from that record, so the update did not survive a round trip. The first record now carries the saved view while keeping its own place on the screen, and the tiles after it are untouched. Three tests: a bad rectangle still gives its view (and the rectangle is still refused), a record with no usable view leaves the header alone, and a view set on a two-tile drawing comes back from a round trip with both tiles still there, the first keeping its half of the screen and the second its own view. --- crates/io/src/dxf_read/tables.rs | 20 +++++++----- crates/io/src/dxf_write/layout.rs | 14 +++++++-- crates/io/src/tests.rs | 52 +++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 11 deletions(-) diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 001944b86..c7a600b1f 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -324,18 +324,22 @@ fn vport_record(d: &mut Drawing, t: &T) { let centred = t.f(12).is_some() && t.f(22).is_some(); let height = t.fd(40, 0.0); let unit = |v: f64| v.is_finite() && (-1e-9..=1.0 + 1e-9).contains(&v); - let ok = [min.x, min.y, max.x, max.y].into_iter().all(unit) - && max.x > min.x + 1e-6 - && max.y > min.y + 1e-6 - && center.is_finite() - && height.is_finite() - && height > 0.0; - if name.is_empty() || !ok { + // One record carries two separate things: where the tile sits on the screen (10/11) and the + // view it shows (12/22, 40). They are judged apart, because a record can hold a usable view + // with a tile rectangle that is not usable -- a first `*ACTIVE` like that used to return + // before the view was read, so a file whose header has no view opened on the extent fit + // instead of where it was saved (noted in review). + let view_ok = center.is_finite() && height.is_finite() && height > 0.0; + let tile_ok = [min.x, min.y, max.x, max.y].into_iter().all(unit) && max.x > min.x + 1e-6 && max.y > min.y + 1e-6; + if name.is_empty() { return; } - if first_active && centred { + if first_active && centred && view_ok { d.header.set_saved_view(center, height); } + if !view_ok || !tile_ok { + return; + } let aspect = t.f(41).filter(|a| a.is_finite() && *a > 0.0).unwrap_or(0.0); let clamp = |p: Vec2| Vec2::new(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0)); let tile = VportTile { min: clamp(min), max: clamp(max), center, height, aspect }; diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 7384fb766..7a6ed9d83 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -75,9 +75,17 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { }; let single = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center, height, aspect: ASPECT }; let tiled = d.vports.iter().find(|c| c.is_active() && c.tiles.len() > 1); - let mut records: Vec<(&str, &VportTile)> = match tiled { - Some(c) => c.tiles.iter().map(|t| (VportConfig::ACTIVE, t)).collect(), - None => vec![(VportConfig::ACTIVE, &single)], + // The first `*ACTIVE` record is the one a reader takes the view from, so it carries the saved + // view while keeping its own place on the screen and the tiles after it unchanged. Writing + // the stored tiles as they stand put the new view in HEADER and the old one here, and the + // read takes this one, so updating the view of a tiled drawing did not survive a round trip + // (noted in review). + let first = tiled.and_then(|c| c.tiles.first()).map(|t| VportTile { center, height, ..*t }); + let mut records: Vec<(&str, &VportTile)> = match (tiled, first.as_ref()) { + (Some(c), Some(first)) => { + std::iter::once((VportConfig::ACTIVE, first)).chain(c.tiles.iter().skip(1).map(|t| (VportConfig::ACTIVE, t))).collect() + } + _ => vec![(VportConfig::ACTIVE, &single)], }; records.extend(d.vports.iter().filter(|c| !c.is_active() && !c.name.is_empty()).flat_map(|c| c.tiles.iter().map(|t| (c.name.as_str(), t)))); let th = table_head(w, "VPORT", records.len()); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 230c202f7..edb48fa20 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -587,6 +587,58 @@ fn a_viewport_record_without_a_centre_keeps_the_header_view() { assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the header pair is kept"); } +/// Updating the saved view of a drawing that has several model-space tiles survives a round +/// trip. The write put the new view in HEADER but emitted the stored tiles unchanged, and the +/// read takes its view from the first `*ACTIVE` record, so the update was read back as the old +/// view (noted in review of #1602). +#[test] +fn a_saved_view_set_on_a_tiled_drawing_survives_a_round_trip() { + let mut d = sample(); + // Two tiles side by side, the first the current one, each with its own old view. + let tile = |min: Vec2, max: Vec2, center: Vec2| VportTile { min, max, center, height: 10.0, aspect: 1.0 }; + d.vports.push(VportConfig { + name: VportConfig::ACTIVE.to_string(), + tiles: vec![tile(Vec2::ZERO, Vec2::new(0.5, 1.0), Vec2::new(1.0, 1.0)), tile(Vec2::new(0.5, 0.0), Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0))], + }); + d.header.set_saved_view(Vec2::new(70.0, 80.0), 30.0); + + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(back.header.saved_view(), Some((Vec2::new(70.0, 80.0), 30.0)), "the view that was set is the one read back"); + // The tiled configuration is still there, and the first tile keeps its own half of the screen. + let active = back.vports.iter().find(|c| c.is_active()).expect("the tiled configuration is kept"); + assert_eq!(active.tiles.len(), 2, "both tiles are written: {:?}", active.tiles); + assert_eq!(active.tiles[0].max, Vec2::new(0.5, 1.0), "the first tile keeps its rectangle"); + assert_eq!(active.tiles[1].center, Vec2::new(2.0, 2.0), "and the second tile keeps its own view"); +} + +/// A first `*ACTIVE` record can hold a usable view (12/22 centre, 40 height) with a tile +/// rectangle that is not usable. The record used to be dropped whole before the view was read, +/// so a file whose header carries no view opened on the extent fit rather than where it was +/// saved (noted in review of #1602). +#[test] +fn a_viewport_record_with_a_bad_tile_still_gives_its_view() { + // No `$VIEWCTR`/`$VIEWSIZE`, and a tile whose corners are equal (10/11 both 0,0), so the + // rectangle is unusable while the view is not: centre 50,50 and height 20. + const BAD_TILE: &str = "\ +0\nSECTION\n2\nHEADER\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n0.0\n21\n0.0\n\ +12\n50.0\n22\n50.0\n40\n20.0\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let d = read_dxf(BAD_TILE.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the view the record holds is read"); + // The unusable rectangle is still refused, so the split did not make the tile permissive. + assert!(d.vports.iter().all(|c| c.tiles.is_empty()), "the tile itself is not kept: {:?}", d.vports); + + // And a record with no usable view either leaves the header alone, as before. + const NEITHER: &str = "\ +0\nSECTION\n2\nHEADER\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n0.0\n21\n0.0\n\ +12\n50.0\n22\n50.0\n40\n0.0\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let neither = read_dxf(NEITHER.as_bytes()).unwrap(); + assert_eq!(neither.header.saved_view(), None, "a zero height is not a view, so the header keeps none"); +} + #[test] fn dxf_roundtrips_page_setup() { let mut d = sample(); From 9c2b8a2589aff9ee4e6988c267b16d074cbae618 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:15:46 +0700 Subject: [PATCH 175/531] TRIM: a pick on a cut takes the piece next to that cut, by index The split point was moved 2 x 4 ULP off a cut the pick was on. When two cuts are closer than that (1e9 out, a segment a few ULP long) it moved past the other cut too, and the long segment before was trimmed instead of the short one picked. The cut the pick is on (the nearest within rounding) now bounds the piece directly: with the next cut when the pick is at its segment's start, with the previous one otherwise. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 21 ++++++++++--------- .../tests/it/break_trim_polyline_rules.rs | 19 +++++++++++++++++ 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 383e4c50a..e5bef9b8e 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -370,18 +370,19 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse } // A pick on a cut (a vertex picked exactly: the same length within rounding) takes the piece // of the segment it was found on, rather than neither piece (which would erase the whole - // polyline): the cuts are split just past that cut when the pick is at its segment's start, - // just before it otherwise. A pick off every cut splits them where it is. + // polyline): from that cut to the next when the pick is at its segment's start, from the one + // before to that cut otherwise. A pick off every cut takes the piece between the cuts either + // side of it. let on = 4.0 * f64::EPSILON * (total + 1.0); - let split = if !ts.iter().any(|t| (t - tp).abs() <= on) { - tp - } else if at_end > 0.0 { - tp + 2.0 * on - } else { - tp - 2.0 * on + let on_cut = ts.iter().enumerate().map(|(i, t)| (i, (t - tp).abs())).filter(|(_, d)| *d <= on).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i); + let (lo, hi) = match on_cut { + Some(i) if at_end > 0.0 => (ts.get(i).copied().unwrap_or(f64::NEG_INFINITY), ts.get(i + 1).copied().unwrap_or(f64::INFINITY)), + Some(i) => (i.checked_sub(1).and_then(|j| ts.get(j)).copied().unwrap_or(f64::NEG_INFINITY), ts.get(i).copied().unwrap_or(f64::INFINITY)), + None => ( + ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max), + ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min), + ), }; - let lo = ts.iter().copied().filter(|t| *t < split).fold(f64::NEG_INFINITY, f64::max); - let hi = ts.iter().copied().filter(|t| *t > split).fold(f64::INFINITY, f64::min); let mk = |vs: Vec| lwpoly(vs, false); let mut out = Vec::new(); if p.closed { diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs index f5d05257d..7fe34c08c 100644 --- a/crates/engine/tests/it/break_trim_polyline_rules.rs +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -336,6 +336,25 @@ fn a_pick_inside_a_segment_stays_on_its_side_of_a_cut() { expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)])]); } +#[test] +fn a_pick_on_a_vertex_next_to_a_very_short_segment_takes_that_segment() { + // 1e9 out, a segment 5e-7 long, a few roundings of the length, so both its ends are within + // rounding of a pick on the vertex it ends at: that pick takes it, not the long segment before. + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 5e-7], [1e9, 10]]), false); + trim(&mut s, p, [1e9, 5e-7], None); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)]), (false, false, &[(1e9, 5e-7, 0.0), (1e9, 10.0, 0.0)])]); +} + +#[test] +fn a_pick_on_a_closed_polylines_start_vertex_takes_its_first_segment() { + // Not measured. The pick is at the start of the first segment, which it was found on. + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10], [0, 10]]), true); + trim(&mut s, p, [0.0, 0.0], None); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)])]); +} + #[test] fn a_piece_whose_ends_only_come_near_stays_open_far_from_the_origin() { // 1e9 out, as survey coordinates in millimetres are: the piece left runs from the line's cut From 36e8c02682c6eecafbf1d1255dcfd7b141fabb3f Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:54:11 -0300 Subject: [PATCH 176/531] Leave the parity docs to the maintainers AGENTS.md: PRs name the affected rows and maintainers update docs/file-format-parity.md in batches. --- docs/file-format-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 34318ea7a..d85415123 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -143,7 +143,6 @@ our output in AutoCAD black-box. | 2026-10-29 | minor | R2000 DXF: CLASS records written without group 91 (instance count), which came with the 2004 format; AutoCAD LT 2026 stopped responding on every R2000 DXF CADCraft saved (checked black-box in AutoCAD LT 2026) | | 2026-10-26 | minor | CC-046: ATTEDIT and -ATTEDIT value changes invalidate derived justified baselines before DXF/DWG export; preserve alignment anchors, unchanged values and Aligned/Fit endpoints. Review follow-up: baseline recomputation preserves insertion elevation independently of alignment elevation. The shared writer correction also applies to justified TEXT. Independent of attribute editor UI; reverting the follow-up restores elevation loss on recomputation, while reverting the value setter restores stale XY baselines. | | 2026-10-25 | minor | LAYOUT SAveas (`layout.saveas`) writes a layout as a drawing template: its page setup and paper space objects, no model space objects or other layouts, and only the named objects they use | -| 2026-10-23 | minor | DXF/DWG save: a layout whose media is named wider than tall (`ISO_full_bleed_A3_(420.00_x_297.00_MM)`) keeps its paper size in that order (44 = 420, 45 = 297) and its plot rotation relative to the media, instead of a portrait size with rotation 1 that ZWCAD plotted as a shrunk portrait page (#1463); other media are written as before | | 2026-10-22 | minor | DXF/DWG save: angular, diametric and radial dimensions get standard DIMASSOC objects (one centre reference to the circle for radial/diametric, the definition points for angular), so AutoCAD follows their geometry; the standard objects of those kinds are read back too, without CADCraft's xdata (#1651) | | 2026-10-19 | minor | DXF/DWG save: angular dimension block text honors DIMDSEP, including per-dimension overrides (#1646) | | 2026-10-19 | minor | A file's own arrowhead blocks with standard names (AutoCAD's `_Dot`, `_DotSmall`), named only by a dimension style, are kept and saved as they were instead of being replaced by CADCraft's solids; PURGE keeps arrowhead blocks dimension styles name | From 946af8745855fdb6eff8c5340c965b48a307c529 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Mon, 2 Nov 2026 08:54:58 -0300 Subject: [PATCH 177/531] A proxy whose class the file doesn't name is reported as not saved From 2013 the DWG keeps another program's proxy entity with the class its group 91 names, so the loss report skipped every ACAD_PROXY_ENTITY. Saving drops a proxy whose group 91 names no class of the file's CLASSES, though, so that one is now counted. The group 91 helpers move to cadcraft_doc::foreign so the engine can ask Foreign::proxy_class. --- crates/doc/src/foreign.rs | 32 +++++++++++++++++++ crates/engine/src/cmd/file.rs | 6 ++-- crates/engine/tests/save_reports_not_saved.rs | 23 +++++++++++-- crates/io/src/dxf_raw.rs | 28 +--------------- 4 files changed, 56 insertions(+), 33 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 80ebbc3a3..d71b21b47 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -82,6 +82,12 @@ pub struct Foreign { } impl Foreign { + /// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any. + /// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name. + pub fn proxy_class(&self, tags: &[RawTag]) -> Option<&str> { + class_index(class_number(tags.iter().map(|r| (r.code, r.value.as_str())))).and_then(|i| self.class_order.get(i)).map(String::as_str) + } + pub fn is_empty(&self) -> bool { self.objects.is_empty() && self.dictionary.is_empty() @@ -98,3 +104,29 @@ impl Foreign { self.data_store.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim())).collect() } } + +/// Where a proxy's class number is: its first group 91 outside the `102 {NAME` … `102 }` groups +/// (an application's can hold a 91 of its own) and before any xdata. +pub fn class_group>(groups: impl IntoIterator) -> Option { + let mut in_group = false; + for (i, (code, value)) in groups.into_iter().enumerate() { + match code { + 1000.. => return None, + 102 => in_group = value.as_ref().trim().starts_with('{'), + 91 if !in_group => return Some(i), + _ => {} + } + } + None +} + +/// A proxy's class number (see [`class_group`]). +pub fn class_number>(groups: impl IntoIterator + Clone) -> Option { + let i = class_group(groups.clone())?; + groups.into_iter().nth(i).and_then(|(_, v)| v.as_ref().trim().parse().ok()) +} + +/// The place in CLASSES a class number names (500 is the first class). +pub fn class_index(number: Option) -> Option { + usize::try_from(number?.checked_sub(500)?).ok() +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index d9014b13b..0f9bb28c4 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -733,8 +733,8 @@ const MODELER_TYPES: [&str; 3] = ["3DSOLID", "REGION", "BODY"]; /// [`not_saved`] for a file saved as `version`. From 2013 on, a 3D solid, region or body the data /// store has a record for keeps its geometry and is not counted, and neither is another program's -/// proxy entity: the DWG writes it with its class (before 2013 it has no class to name, and the -/// DWG leaves it out). +/// proxy entity whose class the file names: the DWG writes it with that class. Before 2013, or +/// when its group 91 names no class of the file, the DWG leaves it out and it is counted. pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap { let mut out: std::collections::BTreeMap = std::collections::BTreeMap::new(); let stored = if version >= Version::R2013 { d.foreign.data_store_entities() } else { Default::default() }; @@ -744,7 +744,7 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && stored.contains(&e.handle) { continue; } - if version >= Version::R2013 && u.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") { + if version >= Version::R2013 && u.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") && d.foreign.proxy_class(&u.tags).is_some() { continue; } let n = out.entry(u.dxf_type.clone()).or_insert(0); diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 6753151fd..c847dad88 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -83,18 +83,35 @@ fn solids_whose_geometry_the_data_store_keeps_are_not_reported_from_2013() { assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 2), ("REGION".to_string(), 1)].into_iter().collect()); } -/// Another program's proxy entity reaches a 2013 or later DWG with its class; before 2013 the DWG -/// leaves it out and says so. +/// Another program's proxy entity reaches a 2013 or later DWG with the class its group 91 names; +/// before 2013, or when the file has no such class, the DWG leaves it out and says so. #[test] fn proxy_entities_are_reported_only_before_2013() { use cadcraft_engine::cmd::file::{Version, not_saved_as}; + use cadcraft_engine::doc::foreign::Foreign; + let proxy = |class: i64| { + EntityKind::Unknown(Unknown { + dxf_type: "ACAD_PROXY_ENTITY".into(), + tags: vec![ + RawTag { code: 8, value: "0".into() }, + RawTag { code: 90, value: "498".into() }, + RawTag { code: 91, value: class.to_string() }, + ], + }) + }; let mut d = Drawing::new_imperial(); - d.add(&Space::Model, Common::default(), unknown("ACAD_PROXY_ENTITY")).unwrap(); + d.add(&Space::Model, Common::default(), proxy(500)).unwrap(); d.add(&Space::Model, Common::default(), unknown("MLINE")).unwrap(); + d.foreign = std::sync::Arc::new(Foreign { class_order: vec!["MYAPP_THING".into()], ..Foreign::default() }); for v in [Version::R2013, Version::R2018] { assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1)].into_iter().collect(), "{v:?}"); } for v in [Version::R2004, Version::R2010] { assert_eq!(not_saved_as(&d, v), [("ACAD_PROXY_ENTITY".to_string(), 1), ("MLINE".to_string(), 1)].into_iter().collect(), "{v:?}"); } + // A class number the file's CLASSES don't have, or none at all: the DWG can't name the class, + // leaves the proxy out, and says so from 2013 on too. + d.add(&Space::Model, Common::default(), proxy(501)).unwrap(); + d.add(&Space::Model, Common::default(), unknown("ACAD_PROXY_ENTITY")).unwrap(); + assert_eq!(not_saved_as(&d, Version::R2018), [("ACAD_PROXY_ENTITY".to_string(), 2), ("MLINE".to_string(), 1)].into_iter().collect()); } diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 7857d3be3..96b236dba 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -16,7 +16,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; -use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject}; +use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number}; use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown}; use cadcraft_dxf::{Section, Tag}; @@ -559,32 +559,6 @@ fn is_proxy(kind: &str) -> bool { matches!(up(kind).as_str(), "ACAD_PROXY_OBJECT" | "ACAD_PROXY_ENTITY") } -/// Where a proxy's class number is: its first group 91 outside the `102 {NAME` … `102 }` groups -/// (an application's can hold a 91 of its own) and before any xdata. -fn class_group>(groups: impl IntoIterator) -> Option { - let mut in_group = false; - for (i, (code, value)) in groups.into_iter().enumerate() { - match code { - 1000.. => return None, - 102 => in_group = value.as_ref().trim().starts_with('{'), - 91 if !in_group => return Some(i), - _ => {} - } - } - None -} - -/// A proxy's class number (see [`class_group`]). -fn class_number>(groups: impl IntoIterator + Clone) -> Option { - let i = class_group(groups.clone())?; - groups.into_iter().nth(i).and_then(|(_, v)| v.as_ref().trim().parse().ok()) -} - -/// The place in CLASSES a class number names (500 is the first class). -fn class_index(number: Option) -> Option { - usize::try_from(number?.checked_sub(500)?).ok() -} - /// Set a proxy's class number (see [`class_group`]). fn set_class_number(tags: &mut [Tag], n: i64) { if let Some(t) = class_group(tags.iter().map(|t| (t.code, t.str()))).and_then(|i| tags.get_mut(i)) { From 5224f067e0557ed21fe34df1911359050daf5b00 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 2 Nov 2026 17:38:20 +0500 Subject: [PATCH 178/531] Carry the saved view onto the first tile only when there is one My previous commit put `center` and `height` on the first `*ACTIVE` tile unconditionally. Those two are the extents fallback when the header holds no saved view, and a tiled drawing can hold none -- `-VPORTS` splits the current view into tiles without setting one -- so the override replaced the first tile's own good view with a fit to the extents, and the drawing opened somewhere else (noted in review). Guarded on `saved_view().is_some()` now: with a view it is carried, without one the tiles are written as they stand, which is what they were before. `a_tiled_drawing_with_no_saved_view_keeps_its_first_tiles_view` asserts the first tile keeps its centre and height, the second keeps its own, and that the header read back is the tile's view rather than the writer's extents fit. --- crates/io/src/dxf_write/layout.rs | 9 ++++++++- crates/io/src/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 7a6ed9d83..a3387a15b 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -80,7 +80,14 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { // the stored tiles as they stand put the new view in HEADER and the old one here, and the // read takes this one, so updating the view of a tiled drawing did not survive a round trip // (noted in review). - let first = tiled.and_then(|c| c.tiles.first()).map(|t| VportTile { center, height, ..*t }); + // + // Only where there is a saved view to carry. `center` and `height` are the extents fallback + // when the header holds none, and a tiled drawing can hold none -- `-VPORTS` splits the + // current view into tiles without setting one -- so overriding regardless replaced a tile's + // own good view with that fallback, and the drawing opened on the extents instead of where + // its tile was (noted in review). + let saved = d.header.saved_view().is_some(); + let first = tiled.and_then(|c| c.tiles.first()).map(|t| if saved { VportTile { center, height, ..*t } } else { *t }); let mut records: Vec<(&str, &VportTile)> = match (tiled, first.as_ref()) { (Some(c), Some(first)) => { std::iter::once((VportConfig::ACTIVE, first)).chain(c.tiles.iter().skip(1).map(|t| (VportConfig::ACTIVE, t))).collect() diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index edb48fa20..482e5be8c 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -591,6 +591,30 @@ fn a_viewport_record_without_a_centre_keeps_the_header_view() { /// trip. The write put the new view in HEADER but emitted the stored tiles unchanged, and the /// read takes its view from the first `*ACTIVE` record, so the update was read back as the old /// view (noted in review of #1602). +/// A tiled drawing need not hold a saved view: `-VPORTS` splits the current view into tiles and +/// sets none. The first tile's own view is then the only one there is, and must not be replaced +/// by the extents fallback `vport_table` computes for a drawing with no view (noted in review). +#[test] +fn a_tiled_drawing_with_no_saved_view_keeps_its_first_tiles_view() { + let mut d = sample(); + let tile = |min: Vec2, max: Vec2, center: Vec2| VportTile { min, max, center, height: 10.0, aspect: 1.0 }; + d.vports.push(VportConfig { + name: VportConfig::ACTIVE.to_string(), + tiles: vec![tile(Vec2::ZERO, Vec2::new(0.5, 1.0), Vec2::new(1.0, 1.0)), tile(Vec2::new(0.5, 0.0), Vec2::new(1.0, 1.0), Vec2::new(2.0, 2.0))], + }); + assert_eq!(d.header.saved_view(), None, "the drawing holds no saved view"); + + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + let active = back.vports.iter().find(|c| c.is_active()).expect("the tiled configuration is kept"); + assert_eq!(active.tiles.len(), 2, "both tiles are written: {:?}", active.tiles); + assert_eq!(active.tiles[0].center, Vec2::new(1.0, 1.0), "the first tile keeps its own view"); + assert_eq!(active.tiles[0].height, 10.0, "and its own height"); + assert_eq!(active.tiles[1].center, Vec2::new(2.0, 2.0), "the second tile keeps its own view"); + // The read takes the header's view from that first record, so it is the tile's view and not + // the extents fit the writer would otherwise have put there. + assert_eq!(back.header.saved_view(), Some((Vec2::new(1.0, 1.0), 10.0)), "read from the first tile"); +} + #[test] fn a_saved_view_set_on_a_tiled_drawing_survives_a_round_trip() { let mut d = sample(); From 319351578e639c1288b93c142e3bc689cd0d0613 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Mon, 2 Nov 2026 10:28:26 -0300 Subject: [PATCH 179/531] A proxy whose number names no class is left out of the DWG dxf_to_dwg_as kept a proxy whose class number names no class of the DXF's CLASSES with that number, which names some other class of the DWG. It is now left out and counted, as a binary DXF's proxies are, and as CADCraft's own save already does. --- crates/dwg/src/lib.rs | 23 +++++++++++++++++------ crates/io/src/tests.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 5fc5aa69b..261a4896b 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -678,7 +678,8 @@ mod native { /// reader puts its own default classes first and numbers the DXF's after them, so the DXF /// number named another class in the DWG: a 2018 drawing's piping proxies became /// LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA File Converter refused the file. A - /// number that names no class of the DXF is left as it is. + /// proxy whose number names no class of the DXF is left out: kept as it is, its number would + /// name some other class of the DWG, for the same reason. /// /// Before 2013 (AC1027) acadrust writes only the classes it knows a pre-2013 DWG needs, and a /// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses @@ -715,24 +716,34 @@ mod native { let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) }; - let objects: Vec<(acadrust::Handle, i32)> = doc + let objects: Vec<(acadrust::Handle, Option)> = doc .objects .iter() .filter_map(|(h, o)| match o { - acadrust::objects::ObjectType::ProxyObject(p) => number(p.class_id).map(|n| (*h, n)), + acadrust::objects::ObjectType::ProxyObject(p) => Some((*h, number(p.class_id))), _ => None, }) .collect(); - let entities: Vec<(acadrust::Handle, i32)> = doc + let entities: Vec<(acadrust::Handle, Option)> = doc .entities() .filter_map(|e| match e { acadrust::entities::EntityType::Extended(x) => match &x.data { - acadrust::entities::ExtendedEntityData::Proxy(p) => number(p.class_id).map(|n| (x.common.handle, n)), + acadrust::entities::ExtendedEntityData::Proxy(p) => Some((x.common.handle, number(p.class_id))), _ => None, }, _ => None, }) .collect(); + let unmapped = |list: &[(acadrust::Handle, Option)]| list.iter().filter(|(_, n)| n.is_none()).map(|(h, _)| *h).collect::>(); + let (gone_objects, gone_entities) = (unmapped(&objects), unmapped(&entities)); + for h in &gone_objects { + doc.objects.remove(h); + } + for h in &gone_entities { + doc.remove_entity(*h); + } + let objects = objects.into_iter().filter_map(|(h, n)| Some((h, n?))); + let entities = entities.into_iter().filter_map(|(h, n)| Some((h, n?))); for (h, n) in objects { if let Some(acadrust::objects::ObjectType::ProxyObject(p)) = doc.objects.get_mut(&h) { p.class_id = n; @@ -747,7 +758,7 @@ mod native { } } } - 0 + gone_objects.len() + gone_entities.len() } /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 8a04e0691..4317bb172 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2883,6 +2883,41 @@ fn proxies_keep_their_class_in_dwg() { } } +/// An ASCII DXF given to the DWG conversion directly, with a proxy whose number names no class of +/// its CLASSES ([`proxy_file`]'s "Stray", 537): kept with that number it would name some other +/// class of the DWG, so the DWG leaves it out, as CADCraft's own save does, and keeps the proxies +/// whose classes it can name. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_proxy_whose_class_is_unknown_is_left_out_of_the_dwg() { + use acadrust::entities::{EntityType, ExtendedEntityData}; + use acadrust::objects::ObjectType; + let dwg = cadcraft_dwg::dxf_to_dwg_as(&proxy_file(), "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let class_of = |id: i32| doc.classes.iter().find(|c| i32::from(c.class_number) == id).map(|c| c.dxf_name.clone()); + let mut objects: Vec> = doc + .objects + .values() + .filter_map(|o| match o { + ObjectType::ProxyObject(p) => Some(class_of(p.class_id)), + _ => None, + }) + .collect(); + objects.sort(); + assert_eq!(objects, [Some("VISUALSTYLE".to_string()), Some("WIDGETX".to_string())]); + let entities: Vec> = doc + .entities() + .filter_map(|e| match e { + EntityType::Extended(x) => match &x.data { + ExtendedEntityData::Proxy(p) => Some(class_of(p.class_id)), + _ => None, + }, + _ => None, + }) + .collect(); + assert_eq!(entities, [Some("WIDGETX".to_string())]); +} + /// A binary DXF given to the DWG conversion directly: its CLASSES aren't read, so the proxies' /// numbers can't be mapped to the DWG's classes. Kept as they were, they named other classes /// (the ODA refuses such a file), so the DWG leaves them out, as a pre-2013 DWG does, and the From 7619133bd658a90863d5676182138387041007b9 Mon Sep 17 00:00:00 2001 From: ZachAR3 Date: Mon, 2 Nov 2026 16:07:30 +0100 Subject: [PATCH 180/531] docs: leave geometry-parity.md unchanged in this PR (#1594) --- docs/geometry-parity.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/geometry-parity.md b/docs/geometry-parity.md index 783f9bd87..6c11686a6 100644 --- a/docs/geometry-parity.md +++ b/docs/geometry-parity.md @@ -1,6 +1,6 @@ # Geometry parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (TRIM/EXTEND Quick mode two-point fence) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (ELLIPSE axis endpoints, other-axis point and Included angle as AutoCAD stores them) · **Target:** Autodesk AutoCAD 2027 CAD users trust numbers: a trimmed endpoint, an offset, an intersection or an area is either right to the last displayed digit or the tool is unusable for production drawings. This document @@ -83,7 +83,7 @@ constraints 10%. | Command | AutoCAD supports | CADCraft supports | |---|---|---| -| TRIM | every curve type, quick and standard modes | line, arc, circle, polyline; ellipse and spline via sampled cutting (`modify.rs:485-656`, `modify2.rs` `trim_other`); a closed spline leaves one open spline On a closed polyline a pick before the first or after the last cut keeps the run between the cuts and nothing more (#726). In Quick mode TRIM and EXTEND start a two-point fence from a pick in empty space, Standard mode a crossing window (#1594). | +| TRIM | every curve type, quick and standard modes | line, arc, circle, polyline; ellipse and spline via sampled cutting (`modify.rs:485-656`, `modify2.rs` `trim_other`); a closed spline leaves one open spline On a closed polyline a pick before the first or after the last cut keeps the run between the cuts and nothing more (#726). | | EXTEND | every open curve | line, arc, polyline, elliptical arc, open spline (runs on along its end tangent, `modify2/curve_edits.rs`) | | FILLET | lines, arcs, circles, polylines, ellipses, splines, xlines, rays; Trim/No trim | lines, arcs, circles (TTR circle), polyline mode, Trim/No trim, Multiple; elliptical arcs and splines with any of these (tangent circle from sampled offsets refined by Newton's method, `geom/src/fillet.rs`; arcs trimmed or extended round the ellipse, splines split at the touch point); two straight segments of one polyline (adjacent, or with one between that the corner replaces), a polyline's straight end segment with a line (the line joins it); not polyline arc segments, xlines or rays | | CHAMFER | lines, polylines, xlines, rays | lines, Distance/Angle, whole polylines (Polyline option), polyline segments as for FILLET (`modify2/fillet_pline.rs`); refuses arcs, ellipses and splines with a message, as AutoCAD; not xlines or rays | @@ -160,7 +160,6 @@ Total ≈ 90–140 h; items 1–6 parallelise across two or three agents. | Date | Change | Summary | |---|---|---| -| 2026-11-02 | minor | TRIM and EXTEND in Quick mode: a pick in empty space starts a two-point fence, as in AutoCAD; Standard mode keeps the crossing window (#1594) | | 2026-10-26 | minor | ELLIPSE from axis endpoints matches AutoCAD's stored geometry: the major axis points at the first endpoint (arcs drew on the opposite side of the center), a point at the other-axis prompt gives its distance from the center, and the end-angle prompt offers Included angle | | 2026-10-26 | minor | PEDIT Multiple at the command line (#2182): select objects, lines and arcs turned into polylines on Yes, then Close/Open/Join/Width/Fit/Spline/Decurve/Ltype gen/Reverse/Undo apply to all; Join joins the selected objects with each other within a fuzz distance | | 2026-10-22 | minor | Constraint expressions count operator chains toward the syntax-tree depth limit; evaluation shares one depth limit across operators and parameter references, with a 1 MiB-stack regression (#1936) | From 061ecd1cd67e0f23dceeaffe3e4f143e82bf2666 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:31:38 +0700 Subject: [PATCH 181/531] TRIM: a pick on a cut trims nothing; vertices in line don't cut Measured in AutoCAD 2024 (accoreconsole) and followed here: - A pick within 5e-7 of a cut along the polyline trims nothing, at any size; this replaces picking a side by cut index. - An edge through a closed polyline's start vertex cuts it there. - A closed polyline cut at one point is refused ("Curve must intersect cutting edges at least twice."); Quick mode leaves it in place. - A vertex between two line segments within 1e-8 of parallel, straight on or doubling back, is not a cut. - Crossing picks stay just inside a segment, off its vertices. A polyline's own crossings are searched only on the segment picked and those it runs straight on into, against the segments near them; past 2^24 pairs or 65,536 crossings the trim is refused instead of being made at some of its cuts. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/trim.rs | 194 ++++++++----- crates/engine/src/cmd/trimextend.rs | 13 +- .../tests/it/break_trim_polyline_rules.rs | 268 ++++++++++++++++-- .../engine/tests/it/trim_closed_polyline.rs | 10 +- 5 files changed, 373 insertions(+), 114 deletions(-) diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 02a9ab770..8270f5111 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -34,7 +34,7 @@ use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; pub(crate) use transform::transform_entities; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; -pub(crate) use trim::{Edges, extend, trim}; +pub(crate) use trim::{CUT_ONCE, Edges, extend, trim}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index e5bef9b8e..b8ec3965d 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -1,3 +1,5 @@ +use cadcraft_geom::Bounds2; + use super::{ Arc, EngineError, Entity, EntityKind, Handle, Line, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc, ccw_sweep, intersect_ext, line, lwpoly, norm_angle, @@ -171,7 +173,10 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu } keep.into_iter().collect() } - EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick, itself)?, + EntityKind::LwPolyline(p) => match trim_polyline(p, &cut, pick, itself)? { + Some(pieces) => pieces, + None => return Ok(vec![h]), + }, k => crate::cmd::modify2::trim_other(k, &cut, pick)?, }; replace_with_pieces(s, h, pieces) @@ -275,71 +280,122 @@ pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec out } -/// Upper bounds on the segments of a polyline searched for crossings with itself (the pairs grow -/// with the square) and on the crossings kept (hostile files); a longer polyline still cuts itself -/// at its vertices. -const MAX_SELF_CROSSING_SEGMENTS: usize = 2048; -const MAX_SELF_CROSSINGS: usize = 10_000; +/// Two line segments of a polyline within this sine of parallel run on as one, straight on or +/// doubling back: the vertex between them doesn't cut it, and they don't cut each other. AutoCAD +/// 2024 cuts at a bend of 1e-8 and not at one of 8e-9, whatever the lengths. +const STRAIGHT: f64 = 1e-8; -/// Where a polyline cuts itself, as lengths along it: the vertices between its segments (every -/// vertex of a closed one, its start included), the points where two of its segments cross, and -/// those where a vertex of it (an end included) touches another of its segments. AutoCAD 2024 -/// trims a polyline that is one of the cutting edges at these. -fn self_cuts(segs: &[Segment], closed: bool) -> Vec { - let mut starts = Vec::with_capacity(segs.len()); +/// Upper bounds on one trim's search for where a polyline crosses itself (hostile files): the pairs +/// of segments searched (those the piece picked can reach, times those near them) and the +/// crossings found. Past either the trim is refused, rather than made at some of its cuts. +const MAX_SELF_PAIRS: usize = 1 << 24; +const MAX_SELF_CROSSINGS: usize = 1 << 16; + +/// How near a cut a pick is on it, along the object: AutoCAD 2024 trims nothing for a pick within +/// 5e-7 of a cut on an open polyline and trims for one 5.1e-7 away, from 1e-3 to 1e9 long (around +/// a closed rectangle it reached a little further, to 1e-6). +const ON_CUT: f64 = 5e-7; + +/// AutoCAD 2024's refusal to trim a closed polyline cut at one point only. +pub(crate) const CUT_ONCE: &str = "Curve must intersect cutting edges at least twice."; + +/// Whether segments `a` and `b` of a polyline run on as one ([`STRAIGHT`]). +fn runs_on(a: &Segment, b: &Segment) -> bool { + let (Segment::Line(a), Segment::Line(b)) = (a, b) else { return false }; + let (u, v) = (a.b - a.a, b.b - b.a); + u.cross(v).abs() < STRAIGHT * u.len() * v.len() +} + +/// Where a polyline that is one of the cutting edges cuts itself around segment `k`, the one +/// picked, as lengths along it: at its vertices (every vertex of a closed one, its start included) +/// but those it runs straight on through ([`runs_on`]), and, on `k` and the segments it runs +/// straight on into, where another of its segments crosses them or a vertex of it (an end +/// included) touches them. The piece picked lies within those segments, so crossings elsewhere +/// don't bound it. AutoCAD 2024 trims a polyline that is one of the cutting edges at these. +fn self_cuts(segs: &[Segment], closed: bool, k: usize) -> Result> { + let n = segs.len(); + let mut starts = Vec::with_capacity(n); let mut acc = 0.0; for s in segs { starts.push(acc); acc += s.len(); } - let mut ts: Vec = starts.iter().copied().skip(usize::from(!closed)).collect(); - if segs.len() > MAX_SELF_CROSSING_SEGMENTS { - return ts; + let before = |i: usize| { + if i > 0 { + Some(i - 1) + } else if closed { + n.checked_sub(1) + } else { + None + } + }; + let after = |i: usize| { + if i + 1 < n { + Some(i + 1) + } else if closed { + Some(0) + } else { + None + } + }; + // Whether the polyline runs straight on through the vertex segment `i` starts at. + let straight = |i: usize| matches!((before(i).and_then(|j| segs.get(j)), segs.get(i)), (Some(a), Some(b)) if runs_on(a, b)); + let mut ts: Vec = (usize::from(!closed)..n).filter(|i| !straight(*i)).filter_map(|i| starts.get(i).copied()).collect(); + let mut run = vec![k]; + let mut i = k; + while let Some(j) = before(i).filter(|_| straight(i) && run.len() < n) { + run.push(j); + i = j; } - let inside = |t: f64| t > 1e-9 && t < 1.0 - 1e-9; - let parts: Vec<_> = segs.iter().zip(starts).map(|(s, t0)| (s, s.bounds(), t0)).collect(); - let mut crossings = 0; - for (i, (a, box_a, a0)) in parts.iter().enumerate() { - for (b, box_b, b0) in parts.iter().skip(i + 1) { - if !box_a.intersects(box_b) { + let mut i = k; + while let Some(j) = after(i).filter(|j| straight(*j) && run.len() < n) { + run.push(j); + i = j; + } + let boxes: Vec<_> = segs.iter().map(Segment::bounds).collect(); + let reach = run.iter().filter_map(|i| boxes.get(*i)).fold(Bounds2::EMPTY, |r, b| r.union(b)); + let near: Vec = (0..n).filter(|j| boxes.get(*j).is_some_and(|b| b.intersects(&reach))).collect(); + if run.len().saturating_mul(near.len()) > MAX_SELF_PAIRS { + return Err(EngineError::Other("Too many segments to trim the polyline where it crosses itself.".into())); + } + // A crossing, or a vertex of another segment touching this one, cuts it; so does a crossing + // where it runs straight on into the next. Two segments meeting at a vertex cut nothing more. + let cuts = |t: f64, i: usize| (t > 1e-9 && t < 1.0 - 1e-9) || (t <= 1e-9 && straight(i)) || (t >= 1.0 - 1e-9 && after(i).is_some_and(straight)); + let vertices = ts.len(); + for &i in &run { + let (Some(a), Some(box_a), Some(a0)) = (segs.get(i), boxes.get(i), starts.get(i)) else { continue }; + for &j in &near { + let (Some(b), Some(box_b)) = (segs.get(j), boxes.get(j)) else { continue }; + if j == i || runs_on(a, b) || !box_a.intersects(box_b) { continue; } for x in intersect_ext(a, b, false) { - let (ta, tb) = (param_on(a, x), param_on(b, x)); - // A crossing cuts both segments; a vertex touching the other segment cuts that - // one (the vertex is a cut already). Two segments meeting at a vertex cut nothing - // more. - if inside(ta) || inside(tb) { - if inside(ta) { - ts.push(a0 + ta * a.len()); - } - if inside(tb) { - ts.push(b0 + tb * b.len()); - } - crossings += 1; - if crossings >= MAX_SELF_CROSSINGS { - return ts; + let t = param_on(a, x); + if cuts(t, i) { + ts.push(a0 + t * a.len()); + if ts.len() - vertices > MAX_SELF_CROSSINGS { + return Err(EngineError::Other("Too many crossings to trim the polyline where it crosses itself.".into())); } } } } } - ts + Ok(ts) } /// Trim a polyline at the piece containing `pick`, between the cuts by `cut` and, when it is one -/// of the cutting edges (`itself`), by its own vertices and crossings ([`self_cuts`]). -fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result> { +/// of the cutting edges (`itself`), by its own ([`self_cuts`]). `None`: the pick is on a cut +/// ([`ON_CUT`]), which trims nothing. +fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result>> { let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; let segs = pl.segments(); let total: f64 = segs.iter().map(Segment::len).sum(); let mut ts: Vec = Vec::new(); let mut acc = 0.0; - let mut tp = 0.0; - // The pick is at the start of the segment it was found on (1), at its end (-1), or between. - let mut at_end = 0.0; + // The pick's length along the polyline and the segment it is on. + let (mut tp, mut k) = (0.0, 0); let mut best = f64::INFINITY; - for s in &segs { + for (i, s) in segs.iter().enumerate() { let len = s.len(); for x in cut.iter().flat_map(|c| intersect_ext(s, c, false)) { ts.push(acc + param_on(s, x) * len); @@ -347,42 +403,34 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse let c = s.closest(pick); if c.dist(pick) < best { best = c.dist(pick); - let u = param_on(s, c); - tp = acc + u * len; - at_end = if u >= 1.0 - 1e-12 { - -1.0 - } else if u <= 1e-12 { - 1.0 - } else { - 0.0 - }; + tp = acc + param_on(s, c) * len; + k = i; } acc += len; } - ts.retain(|t| *t > 1e-9 && *t < total - 1e-9); if itself { - // A closed polyline also cuts itself at its start vertex. - ts.extend(self_cuts(&segs, p.closed).into_iter().filter(|t| (*t > 1e-9 || p.closed) && *t < total - 1e-9)); + ts.extend(self_cuts(&segs, p.closed, k)?); + } + // An open polyline's ends cut nothing; a closed one's start vertex cuts it like any other (a + // cut there is at 0 or at its length, which the pieces below take as one). + if !p.closed { + ts.retain(|t| *t > 1e-9 && *t < total - 1e-9); } ts.sort_by(f64::total_cmp); if ts.is_empty() { return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); } - // A pick on a cut (a vertex picked exactly: the same length within rounding) takes the piece - // of the segment it was found on, rather than neither piece (which would erase the whole - // polyline): from that cut to the next when the pick is at its segment's start, from the one - // before to that cut otherwise. A pick off every cut takes the piece between the cuts either - // side of it. - let on = 4.0 * f64::EPSILON * (total + 1.0); - let on_cut = ts.iter().enumerate().map(|(i, t)| (i, (t - tp).abs())).filter(|(_, d)| *d <= on).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i); - let (lo, hi) = match on_cut { - Some(i) if at_end > 0.0 => (ts.get(i).copied().unwrap_or(f64::NEG_INFINITY), ts.get(i + 1).copied().unwrap_or(f64::INFINITY)), - Some(i) => (i.checked_sub(1).and_then(|j| ts.get(j)).copied().unwrap_or(f64::NEG_INFINITY), ts.get(i).copied().unwrap_or(f64::INFINITY)), - None => ( - ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max), - ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min), - ), - }; + // How far apart two lengths along the polyline are, round its start too when it is closed. + let apart = |s: f64, t: f64| if p.closed { (s - t).abs().min(total - (s - t).abs()) } else { (s - t).abs() }; + if p.closed && ts.first().is_some_and(|f| ts.iter().all(|t| apart(*f, *t) <= ON_CUT)) { + return Err(EngineError::Other(CUT_ONCE.into())); + } + // A pick on a cut trims nothing. + if ts.iter().any(|t| apart(*t, tp) <= ON_CUT) { + return Ok(None); + } + let lo = ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max); + let hi = ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min); let mk = |vs: Vec| lwpoly(vs, false); let mut out = Vec::new(); if p.closed { @@ -394,11 +442,7 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse if hi.is_finite() { hi } else { ts.first().copied().unwrap_or(total) + total }, ); let doubled: Vec = segs.iter().chain(segs.iter()).copied().collect(); - let (a, mut b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) }; - // A single cut leaves the whole outline, opened there. - if b <= a + 1e-9 { - b += total; - } + let (a, b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) }; out.push(mk(sub_polyline(&doubled, a, b))); } else { // A piece whose ends meet (the polyline touched itself there) is closed, without its @@ -419,7 +463,7 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse out.push(piece(sub_polyline(&segs, hi, total))); } } - Ok(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect()) + Ok(Some(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect())) } pub(super) fn param_on(s: &Segment, p: Vec2) -> f64 { diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 7b061cd78..8b655765b 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -9,7 +9,7 @@ use cadcraft_geom::{Bounds2, Line, Vec2, line_line}; use serde_json::{Value, json}; use super::helpers::{line, lwpoly, rect_vertices}; -use super::modify::{Edges, extend, trim}; +use super::modify::{CUT_ONCE, Edges, extend, trim}; use super::{bad, point_param, points_param}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; @@ -31,8 +31,10 @@ fn proj_mode(s: &Session) -> i64 { } /// Whether a trim error says the object meets no cutting edge (a Quick-mode trim then erases it). +/// A closed polyline cut at one point meets one, and is left as it is. fn misses_edges(e: &EngineError) -> bool { - e.to_string().contains("intersect") + let m = e.to_string(); + m.contains("intersect") && m != CUT_ONCE } /// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses @@ -103,7 +105,12 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu for w in pl.windows(2) { let (Some(p), Some(q)) = (w.first(), w.get(1)) else { continue }; let seg = Line::new(*p, *q); - let cands = [*p, *q, seg.closest(a)].into_iter().chain(sides.iter().filter_map(|sd| line_line(sd, &seg))); + // Kept `tol` inside the segment: a vertex, where two segments meet, is a cut of a + // polyline that is one of its own edges, and a pick on a cut trims nothing. + let e = (tol / seg.len()).min(0.5); + let cands = [seg.at(e), seg.at(1.0 - e), seg.at(seg.param_of(a).clamp(e, 1.0 - e))] + .into_iter() + .chain(sides.iter().filter_map(|sd| line_line(sd, &seg))); for c in cands.filter(|c| inside(*c)) { if best.is_none_or(|b| c.dist(a) < b.dist(a)) { best = Some(c); diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs index 7fe34c08c..41bf5ae88 100644 --- a/crates/engine/tests/it/break_trim_polyline_rules.rs +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -6,7 +6,10 @@ //! splits it there into two open polylines, and at its start vertex leaves it closed. //! - A polyline that is one of the cutting edges (picked, or with every object, in Standard or //! Quick mode) is also cut at its own vertices, where it crosses itself and where a vertex of it -//! touches another of its segments. A piece whose ends meet there is left closed. +//! touches another of its segments. A piece whose ends meet there is left closed. A vertex +//! between two line segments in line (within 1e-8, straight on or doubling back) doesn't cut it. +//! - A pick within 5e-7 of a cut along the polyline, whatever its size, trims nothing. An edge +//! through a closed polyline's start vertex cuts it there. //! //! Quick mode was measured in AutoCAD 2024 itself, picking on screen: its scripted TRIM runs //! Standard mode only. @@ -313,46 +316,221 @@ fn a_closed_piece_keeps_its_arcs() { } #[test] -fn a_pick_right_on_a_vertex_takes_the_segment_it_ends() { - // Not measured. The vertex (10, 0) is the only cut: the pick takes the segment before it - // instead of erasing the polyline. - let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10]]), false); - trim(&mut s, p, [10.0, 0.0], None); - expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); -} - -#[test] -fn a_pick_inside_a_segment_stays_on_its_side_of_a_cut() { - // A segment a millionth long between two vertices: a pick in it takes it, not the one before. - let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [10, 0], [10.000001, 0], [10000, 0]]), false); - trim(&mut s, p, [10.0000005, 0.0], None); - expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), (false, false, &[(10.000001, 0.0, 0.0), (10000.0, 0.0, 0.0)])]); - // 1e9 long: half a unit up the second segment is on the second segment. +fn a_pick_half_a_unit_from_a_vertex_1e9_out_trims_the_segment_it_is_on() { let mut s = Session::new(); let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 10]]), false); trim(&mut s, p, [1e9, 0.5], None); expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)])]); } -#[test] -fn a_pick_on_a_vertex_next_to_a_very_short_segment_takes_that_segment() { - // 1e9 out, a segment 5e-7 long, a few roundings of the length, so both its ends are within - // rounding of a pick on the vertex it ends at: that pick takes it, not the long segment before. +// ---------------- a pick on a cut ---------------- + +/// The polyline `v`, with a line from `a` to `b` when given, trimmed at `pick` with every object +/// as an edge, or only the line when `only_line`; returns the polyline's handle. +fn trimmed(v: Value, closed: bool, edge: Option<([f64; 2], [f64; 2])>, only_line: bool, pick: [f64; 2]) -> (Session, Handle) { let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 5e-7], [1e9, 10]]), false); - trim(&mut s, p, [1e9, 5e-7], None); - expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)]), (false, false, &[(1e9, 5e-7, 0.0), (1e9, 10.0, 0.0)])]); + let p = pline(&mut s, v, closed); + let l = edge.map(|(a, b)| line(&mut s, a, b)); + trim(&mut s, p, pick, l.filter(|_| only_line).as_ref().map(std::slice::from_ref)); + (s, p) } #[test] -fn a_pick_on_a_closed_polylines_start_vertex_takes_its_first_segment() { - // Not measured. The pick is at the start of the first segment, which it was found on. - let mut s = Session::new(); - let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10], [0, 10]]), true); - trim(&mut s, p, [0.0, 0.0], None); - expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)])]); +fn a_pick_on_a_cut_trims_nothing() { + // The vertex (10, 0) is the only cut. A pick whose nearest point is within 5e-7 of it, on it + // or off to the side, leaves the polyline as it was; one 6e-7 from it trims the segment it is + // on. + let v = || json!([[0, 0], [10, 0], [10, 10]]); + let whole: [Vertex; 3] = [(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)]; + for pick in [[10.0, 0.0], [10.0, 4e-7], [10.5, 4e-7], [9.99999999, 0.0]] { + let (s, p) = trimmed(v(), false, None, false, pick); + expect(&s, p, &[(true, false, &whole)]); + } + let (s, p) = trimmed(v(), false, None, false, [10.0, 6e-7]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]); + let (s, p) = trimmed(v(), false, None, false, [9.9999994, 0.0]); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); +} + +#[test] +fn a_pick_on_a_cut_is_within_the_same_distance_at_any_size() { + // A polyline a thousandth across, and one 1e9 long with a line through its vertex: 1e-7 from + // the vertex is on the cut, 1e-6 off it. + let small = || json!([[0, 0], [0.001, 0], [0.001, 0.001]]); + let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-7]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0), (0.001, 0.001, 0.0)])]); + let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-6]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0)])]); + let long = || json!([[0, 0], [10, 0], [10, 1e9]]); + let through = Some(([0.0, -10.0], [20.0, 10.0])); + let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-7]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 1e9, 0.0)])]); + let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-6]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]); +} + +#[test] +fn a_pick_on_a_cut_by_another_edge_trims_nothing() { + // The line x = 5 is the edge: picks on it and 4e-7 past it leave the polyline as it was, one + // 6e-7 past it trims the rest. + let v = || json!([[0, 0], [10, 0], [10, 10]]); + let edge = Some(([5.0, -5.0], [5.0, 5.0])); + for pick in [[5.0, 0.0], [5.0000004, 0.0]] { + let (s, p) = trimmed(v(), false, edge, true, pick); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); + } + let (s, p) = trimmed(v(), false, edge, true, [5.0000006, 0.0]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)])]); +} + +#[test] +fn a_pick_on_a_vertex_an_edge_runs_through_trims_nothing() { + // The line's cut is found on the segments either side of the vertex, a rounding apart: the + // pick on the vertex still leaves the polyline as it was, rather than splitting it there. + let cases = [ + ([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([23.3, 7.7], [45.7, 2.3])), + ([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([2.0 * 23.3 - 45.7, 2.0 * 7.7 - 2.3], [45.7, 2.3])), + ([[1.3, 2.7], [37.9, 11.3], [55.1, 48.7]], ([4.5, 43.5], [71.3, -20.9])), + ]; + for (v, edge) in cases { + let (s, p) = trimmed(json!(v), false, Some(edge), true, v[1]); + let whole: Vec = v.iter().map(|q| (q[0], q[1], 0.0)).collect(); + expect(&s, p, &[(true, false, &whole)]); + } +} + +#[test] +fn an_edge_through_a_closed_polylines_start_vertex_cuts_it_there() { + // The line cuts the rectangle at (0, 0) and at (10, 10) on its top. The pick takes the piece + // it is on, whichever vertex the rectangle starts at; 4e-7 from (0, 0) it trims nothing. + let rect = || json!([[0, 0], [100, 0], [100, 10], [0, 10]]); + let edge = Some(([-5.0, -5.0], [15.0, 15.0])); + let left: [Vertex; 3] = [(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)]; + let (s, p) = trimmed(rect(), true, edge, true, [50.0, 0.0]); + expect(&s, p, &[(true, false, &left)]); + let (s, p) = trimmed(json!([[50, 0], [100, 0], [100, 10], [0, 10], [0, 0]]), true, edge, true, [50.0, 10.0]); + expect(&s, p, &[(true, false, &left)]); + let (s, p) = trimmed(rect(), true, edge, true, [0.0, 5.0]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (10.0, 10.0, 0.0)])]); + let whole: [Vertex; 4] = [(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (0.0, 10.0, 0.0)]; + let (s, p) = trimmed(rect(), true, edge, true, [0.0, 4e-7]); + expect(&s, p, &[(true, true, &whole)]); + // The rectangle alone, picked on its start vertex, and 4e-7 from it on its last segment. + for pick in [[0.0, 0.0], [0.0, 4e-7]] { + let (s, p) = trimmed(rect(), true, None, false, pick); + expect(&s, p, &[(true, true, &whole)]); + } +} + +#[test] +fn a_closed_polyline_cut_at_one_point_is_left_as_it_was() { + // A line touching the rectangle only at its start vertex, and one crossing its bottom once and + // ending inside: AutoCAD refuses either trim, and Quick mode doesn't erase the rectangle. + for (a, b, pick) in [([-5.0, 5.0], [5.0, -5.0], [50.0, 0.0]), ([50.0, -5.0], [50.0, 5.0], [20.0, 0.0])] { + for mode in ["standard", "quick"] { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true); + let l = line(&mut s, a, b); + let before = polys(&s); + let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick, "edges": [l.hex()], "mode": mode })); + assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice."), "{a:?} {mode}"); + assert_eq!(polys(&s), before, "{a:?} {mode}"); + } + } +} + +// ---------------- where a polyline runs straight on ---------------- + +#[test] +fn a_vertex_the_polyline_runs_straight_on_through_doesnt_cut_it() { + // (5, 0) lies between two segments in line: the pick takes everything back to the cut before + // it, the start of the polyline or the closed polyline's start vertex. + let v = || json!([[0, 0], [5, 0], [10, 0], [10, 10]]); + let (s, p) = trimmed(v(), false, None, false, [7.0, 0.0]); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); + let (s, p) = trimmed(v(), true, None, false, [7.0, 0.0]); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (0.0, 0.0, 0.0)])]); + // A crossing on the segment in line before the one picked bounds the piece, as does one on the + // segment in line after it, and one right at the vertex in line. + let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [2, 10], [2, -5]]), false, None, false, [7.0, 0.0]); + expect( + &s, + p, + &[ + (true, false, &[(0.0, 0.0, 0.0), (2.0, 0.0, 0.0)]), + (false, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (2.0, 10.0, 0.0), (2.0, -5.0, 0.0)]), + ], + ); + let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [8, 10], [8, -5]]), false, None, false, [3.5, 0.0]); + expect(&s, p, &[(true, false, &[(8.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (8.0, 10.0, 0.0), (8.0, -5.0, 0.0)])]); + let at_vertex = || json!([[0, 0], [5, 0], [10, 0], [10, 10], [5, 10], [5, -5]]); + let rest: [Vertex; 4] = [(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)]; + let (s, p) = trimmed(at_vertex(), false, None, false, [7.0, 0.0]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)]), (false, false, &rest)]); + let (s, p) = trimmed(at_vertex(), false, None, false, [3.0, 0.0]); + expect(&s, p, &[(true, false, &[(5.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)])]); + // Straight on, or doubling back over itself: no cut at all. + for (v, pick) in [(json!([[0, 0], [5, 0], [10, 0]]), [7.0, 0.0]), (json!([[0, 0], [10, 0], [5, 0]]), [2.0, 0.0])] { + let mut s = Session::new(); + let p = pline(&mut s, v, false); + let before = polys(&s); + assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": pick })).is_err()); + assert_eq!(polys(&s), before); + } +} + +#[test] +fn a_bend_of_1e_8_cuts_a_polyline_and_a_smaller_one_doesnt() { + // The bend at (5, 0), as the sine of its angle, whatever the segments' lengths. + for (end, pick, cuts) in [ + ([10.0, 4e-8], [7.0, 0.0], false), + ([10.0, 6e-8], [7.0, 0.0], true), + ([5005.0, 1e-6], [700.0, 0.0], false), + ([5005.0, 0.01], [700.0, 0.0], true), + ] { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [5, 0], end]), false); + let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick })); + assert_eq!((r.is_ok(), polys(&s)[0].2.len()), if cuts { (true, 2) } else { (false, 3) }, "{end:?}"); + } + // Two arcs of one circle, or a line and an arc on from it, cut where they meet. + let q = 0.41421356237309503; + let (s, p) = trimmed(json!([{ "p": [0, 0], "bulge": -q }, { "p": [5, 5], "bulge": -q }, [10, 0]]), false, None, false, [8.5355339, 3.5355339]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, -q), (5.0, 5.0, 0.0)])]); + let (s, p) = trimmed(json!([[0, 0], { "p": [5, 0], "bulge": q }, [10, 5]]), false, None, false, [8.5355339, 1.4644661]); + expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)])]); +} + +#[test] +fn a_polyline_of_thousands_of_segments_is_cut_where_it_crosses_itself() { + // 3,003 segments, the last crossing the first at (50, 0): the pick on the first takes it from + // there to the vertex (100, 0), as with a few segments. + let mut v = vec![json!([0, 0]), json!([100, 0]), json!([100, 20])]; + v.extend((1..=3000).map(|i| json!([100.0 - f64::from(i) / 60.0, 20.0 + f64::from(i % 2)]))); + v.push(json!([50, -10])); + let (s, p) = trimmed(json!(v), false, None, false, [75.0, 0.0]); + let got = polys(&s); + assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::>()); + assert!(got[0].0 == p && same(&got[0].2, &[(0.0, 0.0, 0.0), (50.0, 0.0, 0.0)]), "{:?}", got[0]); + assert_eq!((got[1].2.len(), got[1].2.first().copied()), (3003, Some((100.0, 0.0, 0.0)))); +} + +#[test] +fn a_polyline_too_long_to_search_for_its_own_crossings_is_left_as_it_was() { + // 4,100 segments in line: the run picked times those near it is past the bound searched. 300 + // segments in line over the same stretch, back and forth, crossed by 300 more: 90,000 + // crossings, past the bound kept. The trim is refused, and Quick mode doesn't erase the + // polyline as one no edge crosses. + let mut back_and_forth: Vec<[f64; 2]> = (0..=300).map(|i| [if i % 2 == 0 { 0.0 } else { 10.0 }, 0.0]).collect(); + back_and_forth.extend((0..300).map(|i| [0.5 + f64::from(i) * 0.03, if i % 2 == 0 { 5.0 } else { -5.0 }])); + for (v, why) in [(json!((0..=4100).map(|i| [i, 0]).collect::>()), "Too many segments"), (json!(back_and_forth), "Too many crossings")] { + let mut s = Session::new(); + let p = pline(&mut s, v, false); + let before = polys(&s); + let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": [0.2, 0], "mode": "quick" })); + assert!(r.is_err_and(|e| e.to_string().contains(why)), "{why}"); + assert_eq!(polys(&s), before); + } } #[test] @@ -392,3 +570,31 @@ fn a_polyline_is_cut_where_a_vertex_of_it_touches_it() { ], ); } + +#[test] +fn a_long_run_in_line_on_a_large_polyline_is_cut_where_it_is_crossed() { + // 1,000 segments in line along y = 0, then 20,002 more, the last crossing the run at x = 500.25: + // only the few segments near the run are searched, and the pick takes it from the crossing to + // the corner (1000, 0). + let mut v: Vec = (0..=1000).map(|i| json!([i, 0])).collect(); + v.push(json!([1000, 200])); + v.extend((1..=20000).map(|i| json!([1000.0 - f64::from(i) * 499.75 / 20000.0, 200.0 + f64::from(i % 2)]))); + v.push(json!([500.25, -10])); + let (s, p) = trimmed(json!(v), false, None, false, [999.5, 0.0]); + let got = polys(&s); + assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::>()); + assert!(got[0].0 == p && got[0].2.len() == 502 && got[0].2.last() == Some(&(500.25, 0.0, 0.0)), "{:?}", got[0].2.last()); + assert_eq!((got[1].2.first().copied(), got[1].2.last().copied()), (Some((1000.0, 0.0, 0.0)), Some((500.25, -10.0, 0.0)))); +} + +#[test] +fn a_crossing_window_whose_nearest_point_is_a_vertex_trims_the_segment_it_ends() { + // The window's first corner is nearest the vertex (10, 0), a cut of the polyline: the segment + // before it goes, either way round the window, as in AutoCAD. + for (a, b) in [([10.5, -0.5], [8.0, 2.0]), ([8.0, 2.0], [10.5, -0.5])] { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10]]), false); + s.execute("trim", &json!({ "crossing": [a, b], "mode": "standard" })).unwrap(); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); + } +} diff --git a/crates/engine/tests/it/trim_closed_polyline.rs b/crates/engine/tests/it/trim_closed_polyline.rs index 921c06242..f3bc38432 100644 --- a/crates/engine/tests/it/trim_closed_polyline.rs +++ b/crates/engine/tests/it/trim_closed_polyline.rs @@ -123,11 +123,13 @@ fn undo_restores_the_closed_polyline() { } #[test] -fn a_single_cut_still_opens_the_outline_there() { +fn a_single_cut_leaves_the_outline_as_it_was() { + // As AutoCAD 2024 does (measured with accoreconsole on a 100 x 10 rectangle cut once on its + // bottom): it refuses, "Curve must intersect cutting edges at least twice." let mut s = Session::new(); let p = handle(s.execute("pline", &json!({ "vertices": square(), "closed": true })).unwrap()); let cutter = handle(s.execute("line", &json!({ "points": [[2, -1], [2, 1]] })).unwrap()); - s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] })).unwrap(); - let all = [(2.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)]; - assert_eq!(polys(&s), vec![(false, all.to_vec())]); + let r = s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] })); + assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice.")); + assert_eq!(polys(&s), vec![(true, vec![(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0)])]); } From fd3a0b9e150c82a24c9692ce08212b2ba83b5bf4 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 05:20:20 -0700 Subject: [PATCH 182/531] aliases: persist ALIASEDIT aliases in the user profile (#1899) ALIASEDIT kept its aliases in a process-wide store and nothing saved or restored them, so they were gone after a restart. The engine now gives the set and the alias file REINIT reads to the host profile (alias_profile) and restores them (restore_aliases) in CadApp's profile_json / load_profile, bounded and safe on a malformed saved set; command names still win. The Command Aliases dialog says where the aliases are kept. --- crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/file/pgp.rs | 40 +++++++ crates/engine/tests/aliases.rs | 42 +++++++ crates/ui-egui/src/aliasdlg.rs | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/options.rs | 18 ++- crates/ui-egui/tests/alias_persistence.rs | 133 ++++++++++++++++++++++ docs/customization.md | 14 ++- docs/ui-parity.md | 3 +- 9 files changed, 242 insertions(+), 12 deletions(-) create mode 100644 crates/ui-egui/tests/alias_persistence.rs diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 234769ad4..ca821c0b6 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -16,7 +16,7 @@ use super::{CommandSpec, EngineError, Interactive, always, bad, bool_or, find_co use crate::{Accept, Input, Prompt, Result, Session, Step}; /// The rules the Command Aliases dialog checks before it sends an alias to ALIASEDIT. -pub use pgp::{MAX_ALIASES, alias_name, command_id}; +pub use pgp::{MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases}; pub(crate) use pgp::{specs as alias_specs, user_alias}; pub use template::{qnew_template, set_qnew_template}; diff --git a/crates/engine/src/cmd/file/pgp.rs b/crates/engine/src/cmd/file/pgp.rs index 515feac7f..ae848fd80 100644 --- a/crates/engine/src/cmd/file/pgp.rs +++ b/crates/engine/src/cmd/file/pgp.rs @@ -6,6 +6,11 @@ //! (programs the file would have the application start) are never run: they are skipped with a //! note. CADCraft ships no alias file; the aliases built into the command catalog stay the //! defaults. +//! +//! The aliases are user settings, never part of a drawing: [`alias_profile`] gives them (and the +//! file REINIT reads) to the host's user profile, and [`restore_aliases`] brings them back on the +//! next start. The desktop and web hosts keep that profile; the headless CLI has no profile, so +//! aliases set in a script last for that session only. use std::collections::BTreeMap; use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; @@ -24,6 +29,8 @@ const MAX_ALIAS_CHARS: usize = 64; const MAX_LINE_CHARS: usize = 4096; /// Most warnings reported. const MAX_WARNINGS: usize = 100; +/// Longest alias file path kept in the user profile. +const MAX_ALIAS_FILE_CHARS: usize = 1024; #[derive(Default)] struct Aliases { @@ -43,6 +50,39 @@ pub(crate) fn user_alias(name: &str) -> Option { store().map.get(name).cloned() } +/// The user aliases and the file REINIT reads, as the host's user profile keeps them: +/// `{"aliases": {alias: command}, "file": path or null}`. Not drawing data. +pub fn alias_profile() -> Value { + let st = store(); + json!({ "aliases": st.map, "file": st.file }) +} + +/// Restore aliases saved by [`alias_profile`], replacing the user aliases and the file. +/// +/// The saved set is untrusted (a hand-edited or older profile): entries that are not aliases of +/// real commands are skipped, command names are never aliased, at most [`MAX_ALIASES`] are kept, +/// and a malformed section changes nothing. +pub fn restore_aliases(saved: &Value) { + let Some(obj) = saved.as_object() else { return }; + let file = match obj.get("file") { + None | Some(Value::Null) => None, + Some(Value::String(f)) if f.chars().count() <= MAX_ALIAS_FILE_CHARS && !f.chars().any(char::is_control) => Some(f.clone()), + Some(Value::String(_)) => None, + // A file entry that is not a path makes the section malformed: keep the aliases as they are. + Some(_) => return, + }; + let Some(map) = obj.get("aliases").and_then(Value::as_object) else { return }; + let mut aliases = BTreeMap::new(); + for (alias, target) in map.iter().take(MAX_ALIASES) { + let Ok(name) = alias_name(alias) else { continue }; + let Some(id) = target.as_str().and_then(command_id) else { continue }; + aliases.insert(name, id); + } + let mut st = store(); + st.map = aliases; + st.file = file; +} + /// The command id `target` names (`*LINE`, `_.line`, `-LAYER`…), if there is such a command. pub fn command_id(target: &str) -> Option { let t = target.trim().trim_start_matches('*').trim().trim_start_matches(['_', '.']).to_ascii_lowercase(); diff --git a/crates/engine/tests/aliases.rs b/crates/engine/tests/aliases.rs index d1b39bb81..625354f60 100644 --- a/crates/engine/tests/aliases.rs +++ b/crates/engine/tests/aliases.rs @@ -75,6 +75,48 @@ fn reinit_reads_the_alias_file_again() { s.execute("aliasedit", &json!({ "clear": true })).unwrap(); } +#[test] +fn a_saved_alias_profile_restores_without_overriding_commands() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + s.execute("aliasedit", &json!({ "set": { "zzp": "qsave", "zzcmd": "line" } })).unwrap(); + let saved = cadcraft_engine::cmd::file::alias_profile(); + assert_eq!(saved["aliases"]["zzp"], json!("qsave")); + + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + assert_eq!(resolve_alias("zzp"), "zzp"); + cadcraft_engine::cmd::file::restore_aliases(&saved); + assert_eq!(resolve_alias("zzp"), "qsave"); + assert_eq!(resolve_alias("zzcmd"), "line"); + assert_eq!(resolve_alias("line"), "line", "command names win"); + assert_eq!(resolve_alias("c"), "circle", "built-in aliases still resolve"); + + // Hostile saved entries are skipped, and an oversized set is capped without panicking. + let mut hostile = serde_json::Map::new(); + for i in 0..12_000 { + hostile.insert(format!("ZZ{i}"), json!("line")); + } + hostile.insert("LINE".into(), json!("circle")); + hostile.insert("ZZLONG".into(), json!("x".repeat(5000))); + hostile.insert("ZZNUM".into(), json!(3)); + cadcraft_engine::cmd::file::restore_aliases(&json!({ "aliases": hostile, "file": "mine.pgp" })); + assert_eq!(resolve_alias("line"), "line", "a restored alias never overrides a command name"); + assert_eq!(resolve_alias("zzlong"), "zzlong"); + assert_eq!(resolve_alias("zzn"), "zzn"); + let listing = s.execute("aliasedit", &json!({})).unwrap(); + let restored = listing["aliases"].as_object().map_or(0, serde_json::Map::len); + assert!(restored <= cadcraft_engine::cmd::file::MAX_ALIASES, "the restored set is capped, not {restored}"); + assert!(restored > 9_000, "the valid entries restore, not just {restored}"); + assert_eq!(listing["file"], json!("mine.pgp")); + + // A malformed section is skipped without changing what ALIASEDIT holds. + cadcraft_engine::cmd::file::restore_aliases(&json!({ "aliases": { "zzchange": "circle" }, "file": 7 })); + assert_eq!(resolve_alias("zzchange"), "zzchange", "a malformed section restores nothing"); + s.execute("aliasedit", &json!({ "clear": true })).unwrap(); + assert_eq!(resolve_alias("zz0"), "zz0", "clear still empties the restored set"); +} + #[test] fn hostile_alias_files_never_panic() { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/ui-egui/src/aliasdlg.rs b/crates/ui-egui/src/aliasdlg.rs index 6caded5f8..5d50c0694 100644 --- a/crates/ui-egui/src/aliasdlg.rs +++ b/crates/ui-egui/src/aliasdlg.rs @@ -161,6 +161,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { Some(f) => ui.label(crate::tf!("Alias file: {file}", file = f)), None => ui.label(crate::tl!("No alias file loaded. REINIT replaces these aliases with a file's.")), }; + ui.label(RichText::new(crate::tl!("Aliases are saved in your CADCraft profile and survive restarts.")).small()); ui.horizontal(|ui| { let label = ui.label(crate::tl!("Filter")); ui.text_edit_singleline(&mut st.filter).labelled_by(label.id); diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bbb70e489..533652667 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1363,6 +1363,7 @@ More than {n} aliases. Понад {n} псевдонімів. Alias file: {file} Файл псевдонімів: {file} No alias file loaded. REINIT replaces these aliases with a file's. Файл псевдонімів не завантажено. REINIT замінює ці псевдоніми псевдонімами з файлу. + Aliases are saved in your CADCraft profile and survive restarts. Псевдоніми зберігаються в профілі CADCraft і не зникають після перезапуску. Alias Псевдонім Command Команда overrides built-in замінює вбудований diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index 27f778735..e9af7f6cc 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -27,9 +27,9 @@ //! SAVETIME, SAVEFILEPATH and ISAVEBAK are the engine's save settings, kept with the autosave state //! rather than in the profile. //! -//! The profile variables and the interface preferences survive restarts: the host saves -//! [`CadApp::profile_json`] under [`PROFILE_KEY`] next to the interface prefs and restores it with -//! [`CadApp::load_profile`]. +//! The profile variables, the user's ALIASEDIT aliases and the interface preferences survive +//! restarts: the host saves [`CadApp::profile_json`] under [`PROFILE_KEY`] next to the interface +//! prefs and restores it with [`CadApp::load_profile`]. mod dialog; @@ -327,13 +327,14 @@ fn reset_ui(app: &mut CadApp) { impl CadApp { /// The user profile kept across restarts, as JSON for the host's storage ([`PROFILE_KEY`]): - /// the engine's profile variables and the interface preferences the interface prefs - /// ([`CadApp::prefs_json`]) and the desktop workspace file (panels, command line) do not - /// already keep. + /// the engine's profile variables, the user's aliases (ALIASEDIT, not drawing data) and the + /// interface preferences the interface prefs ([`CadApp::prefs_json`]) and the desktop + /// workspace file (panels, command line) do not already keep. pub fn profile_json(&self) -> String { json!({ "version": 1, "sysvars": cadcraft_engine::cmd::options::profile(&self.session), + "aliases": cadcraft_engine::cmd::file::alias_profile(), "systemCursor": self.ui.system_cursor, "modelBackground": color_json(self.options.model_background), "paperBackground": color_json(self.options.paper_background), @@ -355,6 +356,11 @@ impl CadApp { if let Some(vars) = v.get("sysvars") { cadcraft_engine::cmd::options::restore(&mut self.session, vars); } + // The user's aliases (ALIASEDIT) are settings, not drawing data; a malformed section is + // skipped by the engine without touching the aliases already in use. + if let Some(aliases) = v.get("aliases") { + cadcraft_engine::cmd::file::restore_aliases(aliases); + } let mut c = UiChanges::default(); for key in ["systemCursor", "modelBackground", "paperBackground", "selectionColor", "snapMarkerSize", "timeSensitiveRightClick", "interfaceScale"] diff --git a/crates/ui-egui/tests/alias_persistence.rs b/crates/ui-egui/tests/alias_persistence.rs new file mode 100644 index 000000000..a3b26d86a --- /dev/null +++ b/crates/ui-egui/tests/alias_persistence.rs @@ -0,0 +1,133 @@ +//! ALIASEDIT aliases are user settings (#1899): they are saved in the user profile the desktop +//! and web hosts keep across restarts (`profile_json` → `load_profile`), never in the drawing. +//! The alias store is process-wide, so these tests run one at a time and use their own names. + +use std::sync::Mutex; + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::MAX_ALIASES; +use cadcraft_engine::cmd::resolve_alias; +use cadcraft_ui_egui::{CadApp, Services}; +use serde_json::{Value, json}; + +static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); + +fn app() -> CadApp { + CadApp::new(Session::new(), Services::default()) +} + +fn lock() -> std::sync::MutexGuard<'static, ()> { + ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn profile(value: &str) -> Value { + serde_json::from_str(value).unwrap_or(Value::Null) +} + +#[test] +fn aliases_survive_a_restart_and_command_names_still_win() { + let _one = lock(); + let mut a = app(); + a.run("aliasedit", json!({ "set": { "zzpersist": "qsave" } })).unwrap(); + let saved = a.profile_json(); + assert!(profile(&saved)["aliases"]["aliases"].get("zzpersist").is_some(), "the profile holds the alias: {saved}"); + + // A fresh app restores the profile: the alias works, built-ins and command names unchanged. + let mut b = app(); + b.load_profile(&saved); + assert_eq!(resolve_alias("zzpersist"), "qsave"); + assert_eq!(resolve_alias("ZZPERSIST"), "qsave"); + assert_eq!(resolve_alias("c"), "circle", "built-in aliases still resolve"); + assert_eq!(resolve_alias("line"), "line", "command names still win"); + assert_eq!(resolve_alias("zzunknown"), "zzunknown"); + + // A hand-edited profile can't make an alias take over a command name. + let mut edited = profile(&saved); + edited["aliases"]["aliases"]["line"] = json!("circle"); + let mut c = app(); + c.load_profile(&edited.to_string()); + assert_eq!(resolve_alias("line"), "line", "a restored alias never overrides a command name"); + a.run("aliasedit", json!({ "clear": true })).unwrap(); +} + +#[test] +fn removed_and_cleared_aliases_stay_removed() { + let _one = lock(); + let mut a = app(); + a.run("aliasedit", json!({ "set": { "zzgone": "line", "zzkeep": "circle" } })).unwrap(); + assert_eq!(resolve_alias("zzgone"), "line"); + + a.run("aliasedit", json!({ "remove": ["zzgone"] })).unwrap(); + let saved = a.profile_json(); + let mut b = app(); + b.load_profile(&saved); + assert_eq!(resolve_alias("zzgone"), "zzgone", "a removed alias stays removed"); + assert_eq!(resolve_alias("zzkeep"), "circle", "the other aliases still restore"); + + a.run("aliasedit", json!({ "clear": true })).unwrap(); + let cleared = a.profile_json(); + let mut c = app(); + c.load_profile(&cleared); + assert_eq!(resolve_alias("zzkeep"), "zzkeep", "a cleared alias stays cleared"); + assert_eq!(profile(&cleared)["aliases"]["aliases"], json!({}), "the profile holds no user aliases"); +} + +#[test] +fn malformed_or_oversized_saved_aliases_are_skipped_safely() { + let _one = lock(); + let mut a = app(); + a.run("aliasedit", json!({ "set": { "zzsafe": "line" } })).unwrap(); + let saved = profile(&a.profile_json()); + assert_eq!(resolve_alias("zzsafe"), "line"); + + let mut huge = serde_json::Map::new(); + for i in 0..MAX_ALIASES.saturating_add(2_000) { + huge.insert(format!("zz{i}"), json!("line")); + } + let mut huge_saved = saved.clone(); + huge_saved["aliases"] = json!({ "aliases": huge, "file": "mine.pgp" }); + let mut bad_values = saved.clone(); + bad_values["aliases"] = json!({ "aliases": { "zzbad": 5, "zznames": { "x": 1 }, "zzreal": "line" } }); + let mut not_an_object = saved.clone(); + not_an_object["aliases"] = json!("zzsafe, *LINE"); + let oversized = format!(r#"{{"aliases": {}, "pad": "{}"}}"#, saved["aliases"], "x".repeat(70_000)); + + let mut b = app(); + b.load_profile(&huge_saved.to_string()); // must not panic + let listing = b.run("aliasedit", json!({})).unwrap(); + let count = listing["aliases"].as_object().map_or(0, serde_json::Map::len); + assert!(count <= MAX_ALIASES, "restored {count} aliases"); + for bad in [bad_values.to_string(), not_an_object.to_string(), oversized] { + b.load_profile(&bad); // must not panic + } + // Entries that aren't aliases of real commands are skipped. + assert_eq!(resolve_alias("zzbad"), "zzbad", "a non-string command is skipped"); + assert_eq!(resolve_alias("zzreal"), "line", "valid entries beside bad ones still restore"); + a.run("aliasedit", json!({ "clear": true })).unwrap(); +} + +#[test] +fn a_loaded_alias_file_survives_with_its_path_and_reinit_rereads_it() { + let _one = lock(); + let dir = std::env::temp_dir().join(format!("cadcraft-alias-profile-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("mine.pgp").to_string_lossy().into_owned(); + std::fs::write(&file, "ZZPROFILE, *RECTANG\n").unwrap(); + + let mut a = app(); + a.run("aliasedit", json!({ "file": file.clone() })).unwrap(); + assert_eq!(resolve_alias("zzprofile"), "rectang"); + let saved = a.profile_json(); + assert_eq!(profile(&saved)["aliases"]["file"], json!(file), "the profile remembers the alias file"); + + // A restart keeps both the aliases and the file REINIT reads. + let mut b = app(); + b.load_profile(&saved); + assert_eq!(resolve_alias("zzprofile"), "rectang"); + let listing = b.run("aliasedit", json!({})).unwrap(); + assert_eq!(listing["file"], json!(file)); + std::fs::write(&file, "ZZPROFILE, *CIRCLE\n").unwrap(); + b.run("reinit", json!({})).unwrap(); + assert_eq!(resolve_alias("zzprofile"), "circle", "REINIT re-reads the restored file"); + a.run("aliasedit", json!({ "clear": true })).unwrap(); +} diff --git a/docs/customization.md b/docs/customization.md index 33d1f8a2f..71c64d140 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -8,7 +8,7 @@ and what is not there yet. | LISP routines (`.lsp`) | Run with APPLOAD or `(load "name")`. The core language, `command`, entity lists, selection sets, `get…` input and `c:` commands work. | [autolisp.md](autolisp.md) | | Startup LISP (`acad.lsp`, `acaddoc.lsp`) | Loaded from the support folder at startup and for each drawing. | [autolisp.md](autolisp.md#at-startup) | | Scripts (`.scr`) | SCRIPT (Tools > Run Script...), `cadcraft-cli run --script-file`, and script text over MCP and the control channel. | below | -| Command aliases (`.pgp`) | ALIASEDIT `{file}` loads an alias file for the session; REINIT reads it again. | below | +| Command aliases (`.pgp`) | ALIASEDIT `{file}` loads an alias file and keeps it; the aliases and the file survive restarts. REINIT reads it again. | below | | Compiled plug-ins (C++, .NET) | Not supported. A plug-in API is planned, for plug-ins written in Rust and compiled to WebAssembly. | [gaps.md](gaps.md) (E4) | | Programs that drive the CAD program from outside | The JSON control channel, the MCP server and `cadcraft-cli`. Any language that can open a TCP socket or start a process can use them. | below | @@ -34,9 +34,15 @@ cadcraft-cli run drawing.dxf --script-file setup.scr --save out.dxf ## Command aliases -ALIASEDIT reads a `.pgp` alias file (`ALIAS, *COMMAND` lines) and adds its aliases for the rest of -the session. Lines that would start external programs are skipped. From a script or the control -channel: `aliasedit {"file": "/path/to/aliases.pgp"}`. +ALIASEDIT reads a `.pgp` alias file (`ALIAS, *COMMAND` lines) and adds its aliases. Lines that +would start external programs are skipped. From a script or the control channel: +`aliasedit {"file": "/path/to/aliases.pgp"}`. + +Aliases are user settings, never part of a drawing. The desktop and web apps keep them, and the +file REINIT reads, in the user profile (`cadcraft.profile`), so aliases added, edited or removed in +the Command Aliases dialog (or with ALIASEDIT's `set`, `remove` and `clear`) are there after a +restart, and REINIT reads the same file again. The headless CLI has no user profile: there, aliases +last for that run. ## Driving CADCraft from another program diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3522b5091..3d3fb4541 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -168,7 +168,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Workspaces | Drafting & Annotation, 3D Modeling | no | | Browser panel layout storage | not applicable | Versioned, validated panel placement and visibility saved through the browser host; floating palettes remain embedded. Requires available browser storage and a completed host save; named workspaces and drawing persistence are separate. | | Options / Preferences dialog | many tabs | **no** (issue #23) | -| Customisation (CUI, aliases editor, tool palettes) | yes | Command Aliases dialog (ALIASEDIT, #1381); no CUI or tool palettes | +| Customisation (CUI, aliases editor, tool palettes) | yes | Command Aliases dialog (ALIASEDIT, #1381); user aliases persist in the profile (#1899); no CUI or tool palettes | | Themes | Dark, Light | Dark, Light, System (#179) | | Accessibility | VoiceOver basics | AccessKit through eframe; screen-reader coverage untested; magnifier issue #39; animation effects follow the OS setting (View ▸ Accessibility ▸ Animation Effects: System, On, Off) | @@ -211,6 +211,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | 2026-10-14 | minor | Selection cycling (#1143): the list and badge of SELECTIONCYCLING, Shift+Space through overlapping objects (#1145) | | 2026-10-14 | minor | Hatch Edit dialog adds boundaries from picked points or closed objects and removes selected loops | | 2026-10-14 | minor | Holding Shift overrides ortho while it is held (on when ORTHOMODE is off, off when it is on), as in AutoCAD | +| 2026-10-22 | minor | ALIASEDIT aliases are kept in the user profile and restored after a restart (#1899) | | 2026-10-16 | minor | ALIASEDIT opens the Command Aliases dialog (#1381) | | 2026-10-18 | minor | In-window menu bar: once a menu is open, pointing at another title closes it and opens that one (#1567) | | 2026-10-13 | minor | Options ▸ Selection adds Select using two clicks only; PICKDRAG 0 disables drag-window creation/completion, 2 preserves clicks or drag, and the preference survives restart; UI pointer and profile regressions | From c9082d974d7d25ab91e660eb1f764697696bc55a Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 08:59:04 -0700 Subject: [PATCH 183/531] aliases: the profile loader accepts a full alias set (#1899) `MAX_PROFILE_BYTES` (64 KiB) was smaller than a valid profile: ALIASEDIT holds up to 10,000 aliases, and a serialized full set can be megabytes. On restart `load_profile` then dropped the whole profile, aliases and unrelated settings included. The engine now states the largest alias section `alias_profile` can produce (`MAX_ALIAS_PROFILE_BYTES`, from the alias count, name and command-id limits, and the alias file path); the loader's cap is that plus fixed room for the sysvars and interface preferences. Hostile input over the cap is still rejected without changing anything. Tests: a full 10,000-alias profile (620 KB, far past the old 64 KiB) restores completely, one byte over the new cap is refused, every catalog command id fits the bound, and the hostile-profile tests now pad past the real cap. --- crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/file/pgp.rs | 23 ++++++++++++ crates/ui-egui/src/options.rs | 12 +++++- crates/ui-egui/tests/alias_persistence.rs | 45 ++++++++++++++++++++++- crates/ui-egui/tests/it/options_dialog.rs | 2 +- 5 files changed, 79 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index ca821c0b6..325b2c636 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -16,7 +16,7 @@ use super::{CommandSpec, EngineError, Interactive, always, bad, bool_or, find_co use crate::{Accept, Input, Prompt, Result, Session, Step}; /// The rules the Command Aliases dialog checks before it sends an alias to ALIASEDIT. -pub use pgp::{MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases}; +pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases}; pub(crate) use pgp::{specs as alias_specs, user_alias}; pub use template::{qnew_template, set_qnew_template}; diff --git a/crates/engine/src/cmd/file/pgp.rs b/crates/engine/src/cmd/file/pgp.rs index ae848fd80..71dfee5c1 100644 --- a/crates/engine/src/cmd/file/pgp.rs +++ b/crates/engine/src/cmd/file/pgp.rs @@ -25,6 +25,8 @@ use super::{CommandSpec, Result, Session, bad, bool_or, find_command}; pub const MAX_ALIASES: usize = 10_000; /// Longest alias name. const MAX_ALIAS_CHARS: usize = 64; +/// Longest command id (the catalog's longest is `texttofront.dimensions`; a test keeps it true). +const MAX_COMMAND_ID_CHARS: usize = 32; /// Longest line read. const MAX_LINE_CHARS: usize = 4096; /// Most warnings reported. @@ -32,6 +34,13 @@ const MAX_WARNINGS: usize = 100; /// Longest alias file path kept in the user profile. const MAX_ALIAS_FILE_CHARS: usize = 1024; +/// The largest alias section [`alias_profile`] can produce: [`MAX_ALIASES`] entries, each a +/// [`MAX_ALIAS_CHARS`]-character name (up to four UTF-8 bytes per character, and JSON adds its +/// quotes) mapped to a command id, plus the alias file path and the section's keys. A host that +/// keeps the section in its user profile allows at least this much, so a full set always comes +/// back after a restart. +pub const MAX_ALIAS_PROFILE_BYTES: usize = MAX_ALIASES * (MAX_ALIAS_CHARS * 4 + MAX_COMMAND_ID_CHARS + 6) + MAX_ALIAS_FILE_CHARS * 4 + 64; + #[derive(Default)] struct Aliases { /// Lower-case alias → command id. @@ -241,3 +250,17 @@ pub(crate) fn specs() -> Vec { CommandSpec::new("reinit", "Reinitialize", run_reinit).params("{file? | text?} (default: the alias file loaded last)").enabled(always).noundo(), ] } + +#[cfg(test)] +mod tests { + use super::MAX_COMMAND_ID_CHARS; + + /// [`super::MAX_ALIAS_PROFILE_BYTES`] bounds a saved alias's command id by the longest id in + /// the catalog: keep that true as commands are added. + #[test] + fn every_command_id_fits_the_saved_alias_bound() { + for spec in crate::cmd::command_specs() { + assert!(spec.id.chars().count() <= MAX_COMMAND_ID_CHARS, "`{}` exceeds the alias profile bound", spec.id); + } + } +} diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index e9af7f6cc..907b1e32c 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -38,6 +38,8 @@ pub use dialog::dialog; use egui::Color32; use serde_json::{Map, Value, json}; +use cadcraft_engine::cmd::file::MAX_ALIAS_PROFILE_BYTES; + use crate::CadApp; use crate::animation::AnimationPref; use crate::theme::{self, ThemePref}; @@ -45,8 +47,14 @@ use crate::theme::{self, ThemePref}; /// The host storage key for [`CadApp::profile_json`]. pub const PROFILE_KEY: &str = "cadcraft.profile"; -/// The largest saved profile [`CadApp::load_profile`] reads. -const MAX_PROFILE_BYTES: usize = 64 * 1024; +/// The largest saved profile [`CadApp::load_profile`] reads: everything [`CadApp::profile_json`] +/// writes — a full ALIASEDIT alias set (up to [`MAX_ALIAS_PROFILE_BYTES`]) and the profile +/// variables, colours and interface preferences — plus the JSON around them. A valid profile is +/// never refused; anything larger is corrupt or hostile. +pub const MAX_PROFILE_BYTES: usize = MAX_ALIAS_PROFILE_BYTES + PROFILE_OVERHEAD_BYTES; + +/// Room for the profile variables, the interface preferences and the JSON around them. +const PROFILE_OVERHEAD_BYTES: usize = 64 * 1024; /// The longest SAVEFILEPATH the JSON form accepts. const MAX_PATH_CHARS: usize = 1024; diff --git a/crates/ui-egui/tests/alias_persistence.rs b/crates/ui-egui/tests/alias_persistence.rs index a3b26d86a..5080905ed 100644 --- a/crates/ui-egui/tests/alias_persistence.rs +++ b/crates/ui-egui/tests/alias_persistence.rs @@ -7,6 +7,7 @@ use std::sync::Mutex; use cadcraft_engine::Session; use cadcraft_engine::cmd::file::MAX_ALIASES; use cadcraft_engine::cmd::resolve_alias; +use cadcraft_ui_egui::options::MAX_PROFILE_BYTES; use cadcraft_ui_egui::{CadApp, Services}; use serde_json::{Value, json}; @@ -90,7 +91,7 @@ fn malformed_or_oversized_saved_aliases_are_skipped_safely() { bad_values["aliases"] = json!({ "aliases": { "zzbad": 5, "zznames": { "x": 1 }, "zzreal": "line" } }); let mut not_an_object = saved.clone(); not_an_object["aliases"] = json!("zzsafe, *LINE"); - let oversized = format!(r#"{{"aliases": {}, "pad": "{}"}}"#, saved["aliases"], "x".repeat(70_000)); + let oversized = format!(r#"{{"aliases": {}, "pad": "{}"}}"#, saved["aliases"], "x".repeat(MAX_PROFILE_BYTES)); let mut b = app(); b.load_profile(&huge_saved.to_string()); // must not panic @@ -106,6 +107,48 @@ fn malformed_or_oversized_saved_aliases_are_skipped_safely() { a.run("aliasedit", json!({ "clear": true })).unwrap(); } +#[test] +fn a_full_alias_set_saved_by_the_profile_restores_after_a_restart() { + let _one = lock(); + // ALIASEDIT holds up to MAX_ALIASES aliases. Long names make the saved profile far larger + // than a small one, and the loader must still accept everything `profile_json` writes. + let mut a = app(); + let mut set = serde_json::Map::new(); + let mut names = Vec::new(); + for i in 0..MAX_ALIASES { + let name = format!("zz{i:05}alias{}", "x".repeat(40)); + names.push(name.clone()); + set.insert(name, json!("line")); + } + a.run("aliasedit", json!({ "set": set })).unwrap(); + let saved = a.profile_json(); + assert!(saved.len() > 64 * 1024, "the saved profile crosses 64 KiB: {} bytes", saved.len()); + assert!(saved.len() <= MAX_PROFILE_BYTES, "the limit covers a full alias set: {} bytes", saved.len()); + + let mut b = app(); + b.load_profile(&saved); + let listing = b.run("aliasedit", json!({})).unwrap(); + let count = listing["aliases"].as_object().map_or(0, serde_json::Map::len); + assert_eq!(count, MAX_ALIASES, "every saved alias restores"); + for name in [names.first(), names.last()].into_iter().flatten() { + assert_eq!(resolve_alias(name), "line", "restored {name}"); + } + a.run("aliasedit", json!({ "clear": true })).unwrap(); +} + +#[test] +fn a_profile_one_byte_over_the_limit_is_refused_safely() { + let _one = lock(); + let defaults = app().run("options", json!({})).unwrap(); + // Still valid JSON that would change PICKBOX, so accepting it would show. + let overhead = r#"{"sysvars":{"PICKBOX":9},"pad":""}"#.len(); + let over = format!(r#"{{"sysvars":{{"PICKBOX":9}},"pad":"{}"}}"#, "x".repeat(MAX_PROFILE_BYTES + 1 - overhead)); + assert_eq!(over.len(), MAX_PROFILE_BYTES + 1); + let mut b = app(); + b.load_profile(&over); // must not panic + assert_eq!(b.run("options", json!({})).unwrap(), defaults, "an oversized profile changes nothing"); +} + #[test] fn a_loaded_alias_file_survives_with_its_path_and_reinit_rereads_it() { let _one = lock(); diff --git a/crates/ui-egui/tests/it/options_dialog.rs b/crates/ui-egui/tests/it/options_dialog.rs index be6869e4a..7a020afb2 100644 --- a/crates/ui-egui/tests/it/options_dialog.rs +++ b/crates/ui-egui/tests/it/options_dialog.rs @@ -138,7 +138,7 @@ fn hostile_saved_profiles_are_ignored() { "[]".into(), r#"{"sysvars": "PICKBOX"}"#.into(), r#"{"sysvars": {"PICKBOX": "x", "LUNITS": 4, "FONTALT": "evil.ttf"}, "modelBackground": "red", "snapMarkerSize": -1}"#.into(), - format!(r#"{{"sysvars": {{"PICKBOX": 5}}, "pad": "{}"}}"#, "x".repeat(70_000)), + format!(r#"{{"sysvars": {{"PICKBOX": 5}}, "pad": "{}"}}"#, "x".repeat(options::MAX_PROFILE_BYTES)), ] { let mut b = app(); b.load_profile(&bad); From f977b6e7cc33fc0248890d55981f16de7724da30 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Mon, 2 Nov 2026 08:09:44 -0800 Subject: [PATCH 184/531] docs: leave the parity tables to the maintainers The affected rows are named in the pull request description, as AGENTS.md asks. --- docs/ui-parity.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3d3fb4541..3522b5091 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -168,7 +168,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Workspaces | Drafting & Annotation, 3D Modeling | no | | Browser panel layout storage | not applicable | Versioned, validated panel placement and visibility saved through the browser host; floating palettes remain embedded. Requires available browser storage and a completed host save; named workspaces and drawing persistence are separate. | | Options / Preferences dialog | many tabs | **no** (issue #23) | -| Customisation (CUI, aliases editor, tool palettes) | yes | Command Aliases dialog (ALIASEDIT, #1381); user aliases persist in the profile (#1899); no CUI or tool palettes | +| Customisation (CUI, aliases editor, tool palettes) | yes | Command Aliases dialog (ALIASEDIT, #1381); no CUI or tool palettes | | Themes | Dark, Light | Dark, Light, System (#179) | | Accessibility | VoiceOver basics | AccessKit through eframe; screen-reader coverage untested; magnifier issue #39; animation effects follow the OS setting (View ▸ Accessibility ▸ Animation Effects: System, On, Off) | @@ -211,7 +211,6 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | 2026-10-14 | minor | Selection cycling (#1143): the list and badge of SELECTIONCYCLING, Shift+Space through overlapping objects (#1145) | | 2026-10-14 | minor | Hatch Edit dialog adds boundaries from picked points or closed objects and removes selected loops | | 2026-10-14 | minor | Holding Shift overrides ortho while it is held (on when ORTHOMODE is off, off when it is on), as in AutoCAD | -| 2026-10-22 | minor | ALIASEDIT aliases are kept in the user profile and restored after a restart (#1899) | | 2026-10-16 | minor | ALIASEDIT opens the Command Aliases dialog (#1381) | | 2026-10-18 | minor | In-window menu bar: once a menu is open, pointing at another title closes it and opens that one (#1567) | | 2026-10-13 | minor | Options ▸ Selection adds Select using two clicks only; PICKDRAG 0 disables drag-window creation/completion, 2 preserves clicks or drag, and the preference survives restart; UI pointer and profile regressions | From 3a9b653b5178af6f29cd7ae92ee0f5fcbfbbb162 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:10:51 +0700 Subject: [PATCH 185/531] TRIM: a cut by another edge at the pick is passed over Measured in AutoCAD 2024 (accoreconsole): a pick within 5e-7 of a cut by another edge doesn't leave the polyline as it is. AutoCAD runs the piece on across that cut to the next one either side: with lines at x = 3 and 7, a pick on 3 removes 0 to 7; with lines at 3, 5 and 7, a pick on 5 removes 3 to 7. A pick that near one of the polyline's own cuts (a vertex, where it is one of its own edges) still trims nothing. When every cut is passed over, the refusal doesn't say "intersect", so Quick mode doesn't erase the polyline as one no edge crosses. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 41 +++++---- .../tests/it/break_trim_polyline_rules.rs | 87 ++++++++++++++----- 2 files changed, 92 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index b8ec3965d..c7fba40f4 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -291,11 +291,16 @@ const STRAIGHT: f64 = 1e-8; const MAX_SELF_PAIRS: usize = 1 << 24; const MAX_SELF_CROSSINGS: usize = 1 << 16; -/// How near a cut a pick is on it, along the object: AutoCAD 2024 trims nothing for a pick within -/// 5e-7 of a cut on an open polyline and trims for one 5.1e-7 away, from 1e-3 to 1e9 long (around -/// a closed rectangle it reached a little further, to 1e-6). +/// How near a cut a pick is on it, along the object. AutoCAD 2024 trims nothing for a pick that +/// near one of a polyline's own cuts, and passes over a cut by another edge, the trim running on +/// across it. On open polylines from 1e-3 to 1e9 long it was within 5e-7, and 5.1e-7 away trimmed +/// at the cut (around a closed rectangle it reached a little further, to 1e-6). const ON_CUT: f64 = 5e-7; +/// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick, +/// so Quick mode leaves it in place rather than erasing it as one no edge crosses. +const ON_THE_CUT: &str = "The pick is on the cut: nothing to trim."; + /// AutoCAD 2024's refusal to trim a closed polyline cut at one point only. pub(crate) const CUT_ONCE: &str = "Curve must intersect cutting edges at least twice."; @@ -384,8 +389,8 @@ fn self_cuts(segs: &[Segment], closed: bool, k: usize) -> Result> { } /// Trim a polyline at the piece containing `pick`, between the cuts by `cut` and, when it is one -/// of the cutting edges (`itself`), by its own ([`self_cuts`]). `None`: the pick is on a cut -/// ([`ON_CUT`]), which trims nothing. +/// of the cutting edges (`itself`), by its own ([`self_cuts`]). `None`: the pick is on one of its +/// own cuts ([`ON_CUT`]), which trims nothing. fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result>> { let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; let segs = pl.segments(); @@ -408,27 +413,31 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itse } acc += len; } - if itself { - ts.extend(self_cuts(&segs, p.closed, k)?); - } + let mut own = if itself { self_cuts(&segs, p.closed, k)? } else { Vec::new() }; // An open polyline's ends cut nothing; a closed one's start vertex cuts it like any other (a // cut there is at 0 or at its length, which the pieces below take as one). if !p.closed { ts.retain(|t| *t > 1e-9 && *t < total - 1e-9); - } - ts.sort_by(f64::total_cmp); - if ts.is_empty() { - return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); + own.retain(|t| *t > 1e-9 && *t < total - 1e-9); } // How far apart two lengths along the polyline are, round its start too when it is closed. let apart = |s: f64, t: f64| if p.closed { (s - t).abs().min(total - (s - t).abs()) } else { (s - t).abs() }; + // A pick on one of its own cuts trims nothing; a cut by another edge there is passed over, and + // the piece runs on across it. + if own.iter().any(|t| apart(*t, tp) <= ON_CUT) { + return Ok(None); + } + let found = ts.len(); + ts.retain(|t| apart(*t, tp) > ON_CUT); + let passed = ts.len() < found; + ts.extend(own); + ts.sort_by(f64::total_cmp); + if ts.is_empty() { + return Err(EngineError::Other(if passed { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into())); + } if p.closed && ts.first().is_some_and(|f| ts.iter().all(|t| apart(*f, *t) <= ON_CUT)) { return Err(EngineError::Other(CUT_ONCE.into())); } - // A pick on a cut trims nothing. - if ts.iter().any(|t| apart(*t, tp) <= ON_CUT) { - return Ok(None); - } let lo = ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max); let hi = ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min); let mk = |vs: Vec| lwpoly(vs, false); diff --git a/crates/engine/tests/it/break_trim_polyline_rules.rs b/crates/engine/tests/it/break_trim_polyline_rules.rs index 41bf5ae88..82c369756 100644 --- a/crates/engine/tests/it/break_trim_polyline_rules.rs +++ b/crates/engine/tests/it/break_trim_polyline_rules.rs @@ -8,8 +8,9 @@ //! Quick mode) is also cut at its own vertices, where it crosses itself and where a vertex of it //! touches another of its segments. A piece whose ends meet there is left closed. A vertex //! between two line segments in line (within 1e-8, straight on or doubling back) doesn't cut it. -//! - A pick within 5e-7 of a cut along the polyline, whatever its size, trims nothing. An edge -//! through a closed polyline's start vertex cuts it there. +//! - A pick within 5e-7 of one of the polyline's own cuts, whatever its size, trims nothing; a cut +//! by another edge that near the pick is passed over. An edge through a closed polyline's start +//! vertex cuts it there. //! //! Quick mode was measured in AutoCAD 2024 itself, picking on screen: its scripted TRIM runs //! Standard mode only. @@ -325,16 +326,34 @@ fn a_pick_half_a_unit_from_a_vertex_1e9_out_trims_the_segment_it_is_on() { // ---------------- a pick on a cut ---------------- -/// The polyline `v`, with a line from `a` to `b` when given, trimmed at `pick` with every object -/// as an edge, or only the line when `only_line`; returns the polyline's handle. -fn trimmed(v: Value, closed: bool, edge: Option<([f64; 2], [f64; 2])>, only_line: bool, pick: [f64; 2]) -> (Session, Handle) { +type Edge = ([f64; 2], [f64; 2]); + +/// The polyline `v`, with lines `edges`, trimmed at `pick` with every object as an edge, or only +/// the lines when `only_lines`; the polyline's handle and whether the trim was made. +fn attempt(v: Value, closed: bool, edges: &[Edge], only_lines: bool, pick: [f64; 2]) -> (Session, Handle, bool) { let mut s = Session::new(); let p = pline(&mut s, v, closed); - let l = edge.map(|(a, b)| line(&mut s, a, b)); - trim(&mut s, p, pick, l.filter(|_| only_line).as_ref().map(std::slice::from_ref)); + let ls: Vec = edges.iter().map(|(a, b)| line(&mut s, *a, *b).hex()).collect(); + let mut params = json!({ "handle": p.hex(), "pick": pick }); + if only_lines { + params["edges"] = json!(ls); + } + let made = s.execute("trim", ¶ms).is_ok(); + (s, p, made) +} + +/// [`attempt`] with at most one line, which must trim. +fn trimmed(v: Value, closed: bool, edge: Option, only_line: bool, pick: [f64; 2]) -> (Session, Handle) { + let (s, p, made) = attempt(v, closed, edge.as_slice(), only_line, pick); + assert!(made, "{pick:?}"); (s, p) } +/// A vertical line through x = `x`. +fn at(x: f64) -> Edge { + ([x, -5.0], [x, 5.0]) +} + #[test] fn a_pick_on_a_cut_trims_nothing() { // The vertex (10, 0) is the only cut. A pick whose nearest point is within 5e-7 of it, on it @@ -370,31 +389,57 @@ fn a_pick_on_a_cut_is_within_the_same_distance_at_any_size() { } #[test] -fn a_pick_on_a_cut_by_another_edge_trims_nothing() { - // The line x = 5 is the edge: picks on it and 4e-7 past it leave the polyline as it was, one - // 6e-7 past it trims the rest. - let v = || json!([[0, 0], [10, 0], [10, 10]]); - let edge = Some(([5.0, -5.0], [5.0, 5.0])); +fn a_cut_by_another_edge_at_the_pick_is_passed_over() { + // A pick within 5e-7 of a cut by another edge runs the piece on across it, to the next cut + // either side; 6e-7 away the cut holds. + let flat = || json!([[0, 0], [10, 0]]); + let piece = |a: f64, b: f64| [(a, 0.0, 0.0), (b, 0.0, 0.0)]; + for pick in [[3.0, 0.0], [3.0000004, 0.0]] { + let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, pick); + expect(&s, p, &[(true, false, &piece(7.0, 10.0))]); + } + let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, [3.0000006, 0.0]); + expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]); + // Lines at 3, 5 and 7: picked on 5, 3 to 7 goes; picked on 7, 5 to the end. + let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [5.0, 0.0]); + expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]); + let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [7.0, 0.0]); + expect(&s, p, &[(true, false, &piece(0.0, 5.0))]); + // Every object an edge: on to the polyline's own vertex (10, 0). + let (s, p, _) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], false, [5.0, 0.0]); + expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); + // A closed rectangle cut at x = 30 and 70 top and bottom, picked on the bottom at 30: round + // its start vertex, from 30 on the top to 70 on the bottom. + let tall = |x: f64| ([x, -5.0], [x, 15.0]); + let (s, p, _) = attempt(json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true, &[tall(30.0), tall(70.0)], true, [30.0, 0.0]); + expect(&s, p, &[(true, false, &[(70.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (30.0, 10.0, 0.0)])]); + // One line only, picked on its cut or 4e-7 past it: no cut is left, and nothing is trimmed. for pick in [[5.0, 0.0], [5.0000004, 0.0]] { - let (s, p) = trimmed(v(), false, edge, true, pick); + let (s, p, made) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], true, pick); + assert!(!made); expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]); } - let (s, p) = trimmed(v(), false, edge, true, [5.0000006, 0.0]); - expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)])]); + // In Quick mode too: the polyline meets the line, so it isn't erased as one no edge crosses. + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [10, 0]]), false); + line(&mut s, [5.0, -5.0], [5.0, 5.0]); + assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": [5, 0], "mode": "quick" })).is_err()); + expect(&s, p, &[(true, false, &piece(0.0, 10.0))]); } #[test] fn a_pick_on_a_vertex_an_edge_runs_through_trims_nothing() { - // The line's cut is found on the segments either side of the vertex, a rounding apart: the - // pick on the vertex still leaves the polyline as it was, rather than splitting it there. + // The line's cut is found on the segments either side of the vertex, a rounding apart. Both + // are passed over, so no cut is left and the polyline stays as it was, not split there. let cases = [ ([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([23.3, 7.7], [45.7, 2.3])), ([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([2.0 * 23.3 - 45.7, 2.0 * 7.7 - 2.3], [45.7, 2.3])), ([[1.3, 2.7], [37.9, 11.3], [55.1, 48.7]], ([4.5, 43.5], [71.3, -20.9])), ]; for (v, edge) in cases { - let (s, p) = trimmed(json!(v), false, Some(edge), true, v[1]); + let (s, p, made) = attempt(json!(v), false, &[edge], true, v[1]); let whole: Vec = v.iter().map(|q| (q[0], q[1], 0.0)).collect(); + assert!(!made); expect(&s, p, &[(true, false, &whole)]); } } @@ -402,7 +447,8 @@ fn a_pick_on_a_vertex_an_edge_runs_through_trims_nothing() { #[test] fn an_edge_through_a_closed_polylines_start_vertex_cuts_it_there() { // The line cuts the rectangle at (0, 0) and at (10, 10) on its top. The pick takes the piece - // it is on, whichever vertex the rectangle starts at; 4e-7 from (0, 0) it trims nothing. + // it is on, whichever vertex the rectangle starts at. 4e-7 from (0, 0) that cut is passed + // over, which leaves one, and the trim is refused. let rect = || json!([[0, 0], [100, 0], [100, 10], [0, 10]]); let edge = Some(([-5.0, -5.0], [15.0, 15.0])); let left: [Vertex; 3] = [(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)]; @@ -413,7 +459,8 @@ fn an_edge_through_a_closed_polylines_start_vertex_cuts_it_there() { let (s, p) = trimmed(rect(), true, edge, true, [0.0, 5.0]); expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (10.0, 10.0, 0.0)])]); let whole: [Vertex; 4] = [(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (0.0, 10.0, 0.0)]; - let (s, p) = trimmed(rect(), true, edge, true, [0.0, 4e-7]); + let (s, p, made) = attempt(rect(), true, edge.as_slice(), true, [0.0, 4e-7]); + assert!(!made); expect(&s, p, &[(true, true, &whole)]); // The rectangle alone, picked on its start vertex, and 4e-7 from it on its last segment. for pick in [[0.0, 0.0], [0.0, 4e-7]] { From 0fa45daf2529e2b35efbc161263497aae58159a4 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 01:01:58 -0700 Subject: [PATCH 186/531] UI: a visible close button on every panel header (fixes #1838) Every dockable panel header now carries an X beside its title, so closing a palette no longer has to be discovered in the tab context menu. The button queues the same Close action as that menu item. Tab and floating group headers use the docking surface's header callback; accordion title bars place the same button left of the stock collapse control. The accessible name includes the panel ("Close Layers"), the tooltip says "Close panel", and the drawing canvas stays unclosable. Regression test: crates/ui-egui/tests/docking_workflows.rs. It opens the External References tab and checks its button does not cover the title, closes the default Layers accordion entry, closes a floating Properties group, and still closes Layers through the context menu. --- crates/ui-egui/src/docking.rs | 77 +++++++++++++++++++- crates/ui-egui/tests/it/docking_workflows.rs | 40 ++++++++++ 2 files changed, 116 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 50fb52a25..3aae5a26e 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -343,7 +343,33 @@ pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) { if let Some(panel) = app.raise_panel.take() { area = area.raise_panel(panel); } - let mut output = area.show_content(ui, &workspace.layout, &style, &mut Panels { app }); + let (mut output, header_close) = { + let mut panels = Panels { app, close: None }; + let output = area.show_content(ui, &workspace.layout, &style, &mut panels); + (output, panels.close) + }; + // Accordion title bars are rendered by the shared surface without a header callback, so + // place the same close button over their title bar, left of the stock collapse control. + let mut close = header_close; + for panel in stack_panels(&workspace.layout) { + if !permissions(&panel).closable { + continue; + } + let Some(title) = ui.ctx().read_response(egui::Id::unique("cadcraft-docking").with(("tab", panel))) else { continue }; + if !title.rect.is_positive() { + continue; + } + let rect = egui::Rect::from_center_size( + egui::pos2(title.rect.right() - 18.0 - CLOSE_BUTTON * 0.5 - 4.0, title.rect.center().y), + egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON), + ); + if close_button(ui, panel, rect) { + close = Some(panel); + } + } + if let Some(panel) = close { + output.actions.push(Action::Close { panel }); + } // Keys typed in a floating panel's own OS window run the main window's shortcuts and // command line; files dropped on one open like files dropped on the main window. app.forward_native_input(ui.ctx(), std::mem::take(&mut output.forwarded_events), output.forwarded_modifiers); @@ -388,6 +414,42 @@ pub fn native_input_blocked(app: &crate::CadApp, ctx: &egui::Context) -> bool { /// The panels' contents, names, size limits and icons for the dock area. pub struct Panels<'a> { pub app: &'a mut crate::CadApp, + /// The panel whose header close button was clicked this frame. + pub close: Option, +} + +/// Size of a panel header's close button, in points. +const CLOSE_BUTTON: f32 = 16.0; + +/// A visible close button for a panel header. It runs the same action as the tab context +/// menu's "Close panel"; the accessible name includes the panel so the headers stay distinct. +fn close_button(ui: &mut egui::Ui, panel: Panel, rect: egui::Rect) -> bool { + let t = crate::theme::Tokens::get(); + let response = ui.interact(rect, egui::Id::unique("cadcraft-docking").with(("close", panel.id())), egui::Sense::click()); + let label = format!("Close {}", crate::i18n::t(panel.label())); + crate::icons::describe_control(ui, &response, &label, None, false); + if response.hovered() { + ui.painter().rect_filled(rect.expand(2.0), 2.0, t.control_hover.gamma_multiply(0.6)); + } + crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Close, false); + response.on_hover_text(crate::tl!("Close panel")).clicked() +} + +/// Panels whose title bar is an accordion entry rather than a tab group header. +fn stack_panels(layout: &Layout) -> Vec { + let mut panels = Vec::new(); + let mut nodes: Vec<&Node> = layout.root.iter().collect(); + while let Some(node) = nodes.pop() { + match node { + Node::Split { first, second, .. } => { + nodes.push(first); + nodes.push(second); + } + Node::Stack { entries } => panels.extend(entries.iter().map(|entry| entry.panel)), + Node::Tabs { .. } => {} + } + } + panels } impl DockContent for Panels<'_> { @@ -434,6 +496,19 @@ impl DockContent for Panels<'_> { crate::icons::paint(painter, rect, icon, false); true } + fn group_header_width(&self, _panels: &[Panel], active: &Panel, _floating: bool, _strip_width: f32) -> f32 { + if permissions(active).closable { CLOSE_BUTTON + 8.0 } else { 0.0 } + } + fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[Panel], active: &Panel, _floating: bool) { + let header = ui.max_rect(); + let rect = egui::Rect::from_center_size( + egui::pos2(header.right() - CLOSE_BUTTON * 0.5 - 4.0, header.center().y), + egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON), + ); + if close_button(ui, *active, rect) { + self.close = Some(*active); + } + } } fn panel_limits(panel: &Panel) -> PanelLimits { diff --git a/crates/ui-egui/tests/it/docking_workflows.rs b/crates/ui-egui/tests/it/docking_workflows.rs index c457052ff..479a9ce4b 100644 --- a/crates/ui-egui/tests/it/docking_workflows.rs +++ b/crates/ui-egui/tests/it/docking_workflows.rs @@ -593,3 +593,43 @@ fn group_drag_bar_moves_the_whole_group_into_the_other_dock() { assert_eq!(frames(layout), [[Panel::Canvas]]); assert_eq!(h.state().session.doc().unwrap(), &document); } + +#[test] +fn every_panel_header_has_a_close_button_that_closes_like_the_context_menu() { + let mut h = harness(None, 1280.0, 1.0); + assert!(h.query_by_label("Close Tool Sets").is_some(), "docked tab headers show a close button"); + assert!(h.query_by_label("Close Drawing").is_none(), "the drawing view is not a closable panel"); + // External References opens as a tabbed pane; its button sits beside the title, not over it. + h.state_mut().run("ui.dock", json!({"operation":"open","panel":"externalReferences"})).unwrap(); + h.run_steps(4); + assert!(h.state().ui.docking.layout.contains(&Panel::ExternalRefs)); + let close = h.get_by_label("Close External References").rect(); + let title = h.get_by_role_and_label(egui::accesskit::Role::Tab, "External References").rect(); + assert!(!close.intersects(title), "the close button does not cover the panel title"); + h.get_by_label("Close External References").click(); + h.run_steps(4); + assert!(!h.state().ui.docking.layout.contains(&Panel::ExternalRefs)); + + // Accordion headers (the default Layers/Properties stack) get one too. + assert!(h.state().ui.docking.layout.contains(&Panel::Layers)); + h.get_by_label("Close Layers").click(); + h.run_steps(4); + assert!(!h.state().ui.docking.layout.contains(&Panel::Layers)); + + // The context menu still closes the same panel after it is reopened. + h.state_mut().run("ui.dock", json!({"operation":"open","panel":"layers"})).unwrap(); + h.run_steps(4); + assert!(h.state().ui.docking.layout.contains(&Panel::Layers)); + h.get_by_role_and_label(egui::accesskit::Role::Tab, "Layers").click_button(PointerButton::Secondary); + h.run_steps(3); + h.get_by_label("Close panel").click(); + h.run_steps(4); + assert!(!h.state().ui.docking.layout.contains(&Panel::Layers)); + + // Floating panels get the same button in their group header. + h.state_mut().run("ui.dock", json!({"operation":"float","panel":"properties","rect":[400,250,300,350]})).unwrap(); + h.run_steps(4); + h.get_by_label("Close Properties").click(); + h.run_steps(4); + assert!(!h.state().ui.docking.layout.contains(&Panel::Properties)); +} From f370a5580ef87e9bf45cbe69521a4a70f50eea99 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:23:59 +0700 Subject: [PATCH 187/531] TRIM: lines, arcs and circles pass over a cut at the pick Measured in AutoCAD 2024 (accoreconsole). A line, an arc or a circle picked within 5e-7 of a cut by another edge runs the trim on across that cut, as a polyline does: a line cut at x = 3 and 7 and picked on 3 loses 0 to 7; a circle cut at 60, 120, 240 and 300 degrees and picked on 60 loses the arc from 300 round to 120. With no cut left, nothing is trimmed, and Quick mode leaves the object in place, as it meets an edge. An arc picked just off its start is now trimmed at its start: the pick was taken as being at the arc's end, round the circle. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 32 +++- crates/engine/tests/it/main.rs | 1 + .../engine/tests/it/trim_cut_at_the_pick.rs | 171 ++++++++++++++++++ 3 files changed, 196 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/it/trim_cut_at_the_pick.rs diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index c7fba40f4..50fa397fc 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -115,10 +115,12 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu .collect(); ts.sort_by(f64::total_cmp); let tp = ln.param_of(pick).clamp(0.0, 1.0); + let found = ts.len(); + ts.retain(|t| (t - tp).abs() * ln.len() > ON_CUT); let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max); let hi = ts.iter().copied().filter(|t| *t > tp).fold(1.0, f64::min); if lo == 0.0 && hi == 1.0 { - return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); + return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into())); } let mut v = Vec::new(); if lo > 0.0 { @@ -137,11 +139,18 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu let mut ts: Vec = cut.iter().flat_map(|c| intersect_ext(&seg, c, false)).map(param).filter(|t| *t > 1e-9 && *t < sweep - 1e-9).collect(); ts.sort_by(f64::total_cmp); - let tp = param(pick).min(sweep); + // A pick off the arc is at the end it is nearer, round the circle. + let tp = match param(pick) { + t if t <= sweep => t, + t if t - sweep < TAU - t => sweep, + _ => 0.0, + }; + let found = ts.len(); + ts.retain(|t| (t - tp).abs() * ga.radius > ON_CUT); let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max); let hi = ts.iter().copied().filter(|t| *t > tp).fold(sweep, f64::min); if lo == 0.0 && hi == sweep { - return Err(EngineError::Other("Object does not intersect a cutting edge.".into())); + return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into())); } let mut v = Vec::new(); if lo > 0.0 { @@ -157,10 +166,16 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu let mut angs: Vec = cut.iter().flat_map(|x| intersect_ext(&full, x, false)).map(|p| c.center.xy().angle_to(p)).collect(); angs.sort_by(f64::total_cmp); angs.dedup_by(|a, b| (*a - *b).abs() < 1e-9); - if angs.len() < 2 { - return Err(EngineError::Other("Circle must intersect cutting edges at two or more points.".into())); - } let ap = c.center.xy().angle_to(pick); + let found = angs.len(); + angs.retain(|a| { + let d = norm_angle(a - ap); + d.min(TAU - d) * c.radius > ON_CUT + }); + if angs.len() < 2 { + let why = if found >= 2 { ON_THE_CUT } else { "Circle must intersect cutting edges at two or more points." }; + return Err(EngineError::Other(why.into())); + } // The removed arc runs between the two intersections around the pick. let n = angs.len(); let mut keep = None; @@ -293,8 +308,9 @@ const MAX_SELF_CROSSINGS: usize = 1 << 16; /// How near a cut a pick is on it, along the object. AutoCAD 2024 trims nothing for a pick that /// near one of a polyline's own cuts, and passes over a cut by another edge, the trim running on -/// across it. On open polylines from 1e-3 to 1e9 long it was within 5e-7, and 5.1e-7 away trimmed -/// at the cut (around a closed rectangle it reached a little further, to 1e-6). +/// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within +/// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further, +/// to 1e-6; on a line, further still, to 5e-4 on one 10 long). const ON_CUT: f64 = 5e-7; /// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick, diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 58c38b5f0..4f131d364 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -143,6 +143,7 @@ mod text_left_justify; mod tolerance; mod transparent; mod trim_closed_polyline; +mod trim_cut_at_the_pick; mod trim_extend_options; mod trim_keeps_z_and_width; mod undo_count; diff --git a/crates/engine/tests/it/trim_cut_at_the_pick.rs b/crates/engine/tests/it/trim_cut_at_the_pick.rs new file mode 100644 index 000000000..451c71ded --- /dev/null +++ b/crates/engine/tests/it/trim_cut_at_the_pick.rs @@ -0,0 +1,171 @@ +//! TRIM of a line, an arc or a circle picked on a cut, as AutoCAD 2024 does it (measured with +//! accoreconsole on these drawings): a cut within 5e-7 of the pick, along the object, is passed +//! over, and the piece runs on across it to the next cut either side. With no cut left, nothing is +//! trimmed. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle}; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +/// Vertical lines through x = `xs`, from y = -15 to 15; their handles. +fn edges(s: &mut Session, xs: &[f64]) -> Vec { + xs.iter().map(|x| handle(&s.execute("line", &json!({ "points": [[x, -15], [x, 15]] })).unwrap()).hex()).collect() +} + +/// Every object but the edges: lines as their ends, arcs and circles as their angles in degrees. +fn shapes(s: &Session, edges: &[String]) -> Vec<(Handle, Vec)> { + let r = |v: f64| (v * 1e9).round() / 1e9; + s.doc() + .unwrap() + .model + .iter() + .filter(|e| !edges.contains(&e.handle.hex())) + .map(|e| { + let v = match &e.kind { + EntityKind::Line(l) => vec![l.a.x, l.a.y, l.b.x, l.b.y], + EntityKind::Arc(a) => vec![a.start.to_degrees(), a.end.to_degrees()], + EntityKind::Circle(_) => Vec::new(), + k => panic!("{k:?}"), + }; + (e.handle, v.into_iter().map(r).collect()) + }) + .collect() +} + +/// Trim `h` at `pick` with `edges`: whether the trim was made. +fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: &[String]) -> bool { + s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": edges })).is_ok() +} + +/// A line from (0, 0) to (10, 0) with vertical lines through `xs`, trimmed at `pick`. +fn line_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec)>, Handle) { + let mut s = Session::new(); + let h = handle(&s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap()); + let es = edges(&mut s, xs); + let made = trim(&mut s, h, pick, &es); + (made, shapes(&s, &es), h) +} + +#[test] +fn a_line_picked_on_its_only_cut_is_left_as_it_was() { + for pick in [[5.0, 0.0], [5.0000004, 0.0], [4.9999996, 0.0]] { + let (made, got, h) = line_trimmed(&[5.0], pick); + assert!(!made, "{pick:?}"); + assert_eq!(got, vec![(h, vec![0.0, 0.0, 10.0, 0.0])], "{pick:?}"); + } +} + +#[test] +fn a_line_picked_on_one_of_two_cuts_loses_the_pieces_both_sides() { + // Cuts at x = 3 and 7: on 3, 0 to 7 goes; 4e-7 past 7, 3 to the end; between them, 3 to 7. + let (_, got, h) = line_trimmed(&[3.0, 7.0], [3.0, 0.0]); + assert_eq!(got, vec![(h, vec![7.0, 0.0, 10.0, 0.0])]); + let (_, got, h) = line_trimmed(&[3.0, 7.0], [7.0000004, 0.0]); + assert_eq!(got, vec![(h, vec![0.0, 0.0, 3.0, 0.0])]); + let (_, got, h) = line_trimmed(&[3.0, 7.0], [5.0, 0.0]); + assert_eq!(got.len(), 2); + assert_eq!(got[0], (h, vec![0.0, 0.0, 3.0, 0.0])); + assert_eq!(got[1].1, vec![7.0, 0.0, 10.0, 0.0]); +} + +/// An arc of radius 10 about the origin from 0 to 180 degrees, with vertical lines through `xs`, +/// trimmed at `pick`. +fn arc_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec)>, Handle) { + let mut s = Session::new(); + let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 })).unwrap()); + let es = edges(&mut s, xs); + let made = trim(&mut s, h, pick, &es); + (made, shapes(&s, &es), h) +} + +#[test] +fn an_arc_picked_on_its_only_cut_is_left_as_it_was() { + // The line x = 0 cuts it at 90 degrees: on the cut and 4e-7 along from it nothing is trimmed, + // 6e-7 along the arc from 90 to 180 goes. + for pick in [[0.0, 10.0], [-4e-7, 10.0]] { + let (made, got, h) = arc_trimmed(&[0.0], pick); + assert!(!made, "{pick:?}"); + assert_eq!(got, vec![(h, vec![0.0, 180.0])], "{pick:?}"); + } + let (_, got, h) = arc_trimmed(&[0.0], [-6e-7, 10.0]); + assert_eq!(got, vec![(h, vec![0.0, 90.0])]); +} + +#[test] +fn an_arc_picked_on_its_last_cut_loses_the_rest() { + // Cuts at 60 and 120 degrees, picked on 120: from 60 to the end goes. + let (_, got, h) = arc_trimmed(&[5.0, -5.0], [-5.0, 75f64.sqrt()]); + assert_eq!(got, vec![(h, vec![0.0, 60.0])]); +} + +/// A circle of radius 10 about the origin, with vertical lines through `xs`, trimmed at `pick`. +fn circle_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec)>, Handle) { + let mut s = Session::new(); + let h = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap()); + let es = edges(&mut s, xs); + let made = trim(&mut s, h, pick, &es); + (made, shapes(&s, &es), h) +} + +#[test] +fn a_circle_picked_on_a_cut_loses_the_arcs_both_sides() { + // Lines at x = 5 and -5 cut it at 60, 120, 240 and 300 degrees. Picked on 60, and 4e-7 along + // from it, the arc from 300 round to 120 goes; picked at 90, the arc from 60 to 120. + let y = 75f64.sqrt(); + for pick in [[5.0, y], [4.9999998, y + 2e-7 * 5.0 / y]] { + let (_, got, h) = circle_trimmed(&[5.0, -5.0], pick); + assert_eq!(got, vec![(h, vec![120.0, 300.0])], "{pick:?}"); + } + let (_, got, h) = circle_trimmed(&[5.0, -5.0], [0.0, 10.0]); + assert_eq!(got, vec![(h, vec![120.0, 60.0])]); +} + +#[test] +fn a_circle_picked_on_one_of_two_cuts_is_left_as_it_was() { + // One line, cutting it at 60 and 300 degrees: picked on 60, one cut is left and the trim is + // refused. + let (made, got, h) = circle_trimmed(&[5.0], [5.0, 75f64.sqrt()]); + assert!(!made); + assert_eq!(got, vec![(h, Vec::new())]); +} + +#[test] +fn quick_mode_leaves_an_object_picked_on_its_only_cut() { + // The line, the arc and the circle each meet the edges, at the pick, so Quick mode doesn't + // erase them as objects no edge crosses. + let y = 75f64.sqrt(); + let cases = [ + ("line", json!({ "points": [[0, 0], [10, 0]] }), 5.0, [5.0, 0.0]), + ("arc", json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 }), 0.0, [0.0, 10.0]), + ("circle", json!({ "center": [0, 0], "radius": 10 }), 5.0, [5.0, y]), + ]; + for (cmd, shape, x, pick) in cases { + let mut s = Session::new(); + let h = handle(&s.execute(cmd, &shape).unwrap()); + let es = edges(&mut s, &[x]); + let r = s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "mode": "quick" })); + assert!(r.is_err(), "{cmd}"); + assert!(s.doc().unwrap().entity(h).is_some(), "{cmd} was erased"); + assert_eq!(shapes(&s, &es).len(), 1, "{cmd}"); + } +} + +#[test] +fn an_arc_picked_just_off_one_end_loses_the_piece_at_that_end() { + // From 0 to 90 degrees, cut at 45: picked just before its start the piece from 0 goes, just + // past its end the piece to 90. + let x = 10.0 * std::f64::consts::FRAC_PI_4.cos(); + let trimmed = |pick: [f64; 2]| { + let mut s = Session::new(); + let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap()); + let es = edges(&mut s, &[x]); + assert!(trim(&mut s, h, pick, &es)); + shapes(&s, &es) + }; + assert_eq!(trimmed([10.0, -0.01])[0].1, vec![45.0, 90.0]); + assert_eq!(trimmed([-0.01, 10.0])[0].1, vec![0.0, 45.0]); +} From 5644c6c9468dc66db9a6c78bfb1d668500dcfdfb Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 01:38:17 -0700 Subject: [PATCH 188/531] docs: document the functions touched by #1838 --- crates/ui-egui/src/docking.rs | 10 ++++++++++ crates/ui-egui/tests/it/docking_workflows.rs | 3 +++ 2 files changed, 13 insertions(+) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 3aae5a26e..f5e3dc57a 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -311,6 +311,10 @@ pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result) -> Vec { } impl DockContent for Panels<'_> { + /// Render `panel`'s existing view; Layers, Properties and External References scroll + /// independently, and the drawing canvas paints its own background before the view. fn body(&mut self, ui: &mut egui::Ui, panel: &Panel) { let app = &mut *self.app; match panel { @@ -496,9 +502,13 @@ impl DockContent for Panels<'_> { crate::icons::paint(painter, rect, icon, false); true } + /// Reserve header space for the close button only when `active` may be closed, so the + /// drawing view's title gets no empty gap. fn group_header_width(&self, _panels: &[Panel], active: &Panel, _floating: bool, _strip_width: f32) -> f32 { if permissions(active).closable { CLOSE_BUTTON + 8.0 } else { 0.0 } } + /// Draw the close button at the right edge of a tab-group header and remember the panel + /// to close once the docking surface has returned, so layout changes stay outside rendering. fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[Panel], active: &Panel, _floating: bool) { let header = ui.max_rect(); let rect = egui::Rect::from_center_size( diff --git a/crates/ui-egui/tests/it/docking_workflows.rs b/crates/ui-egui/tests/it/docking_workflows.rs index 479a9ce4b..e2b3ea3a1 100644 --- a/crates/ui-egui/tests/it/docking_workflows.rs +++ b/crates/ui-egui/tests/it/docking_workflows.rs @@ -594,6 +594,9 @@ fn group_drag_bar_moves_the_whole_group_into_the_other_dock() { assert_eq!(h.state().session.doc().unwrap(), &document); } +/// Guard that every closable panel header offers a visible close button: a docked tab group, +/// the default accordion stack, and a floating group. Each click must remove the panel, the +/// button must not cover the title, and the tab context menu must still close the same panel. #[test] fn every_panel_header_has_a_close_button_that_closes_like_the_context_menu() { let mut h = harness(None, 1280.0, 1.0); From df2a5131af087726c74de86dfc53e520967af75e Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 09:32:13 -0700 Subject: [PATCH 189/531] i18n: the panel close button's accessible name translates as a whole The header close button built its name by joining an English "Close" to the translated panel label, so Spanish screen readers heard "Close Capas". A single translatable "Close {panel}" template now carries both parts, and the tooltip's "Close panel" joins the catalogs too. Spanish gets both rows, Ukrainian (the reference catalog) is required to have them, and docking.rs joins the scanned sources so future marked strings stay covered. Regression test: a Spanish harness finds "Cerrar Capas" and "Cerrar Propiedades" by accessible name, proves "Close Capas" is gone, and closes Layers through the localized button. --- crates/ui-egui/src/docking.rs | 9 ++++++++- crates/ui-egui/src/i18n/es.tsv | 2 ++ crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/uk.tsv | 2 ++ crates/ui-egui/tests/it/docking_workflows.rs | 15 +++++++++++++++ 5 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index f5e3dc57a..ade26a65c 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -425,12 +425,19 @@ pub struct Panels<'a> { /// Size of a panel header's close button, in points. const CLOSE_BUTTON: f32 = 16.0; +/// The accessible name of a header's close button. One translated template carries both the +/// verb and the panel name, so a catalog translates the whole name instead of leaving an +/// English verb in front of a translated panel label. +fn close_label(panel: Panel) -> String { + crate::tf!("Close {panel}", panel = crate::i18n::t(panel.label())) +} + /// A visible close button for a panel header. It runs the same action as the tab context /// menu's "Close panel"; the accessible name includes the panel so the headers stay distinct. fn close_button(ui: &mut egui::Ui, panel: Panel, rect: egui::Rect) -> bool { let t = crate::theme::Tokens::get(); let response = ui.interact(rect, egui::Id::unique("cadcraft-docking").with(("close", panel.id())), egui::Sense::click()); - let label = format!("Close {}", crate::i18n::t(panel.label())); + let label = close_label(panel); crate::icons::describe_control(ui, &response, &label, None, false); if response.hovered() { ui.painter().rect_filled(rect.expand(2.0), 2.0, t.control_hover.gamma_multiply(0.6)); diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8c45b7f97..08bf4f6b7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -139,11 +139,13 @@ Clip Viewport Delimitar ventana gráfica Clipboard Portapapeles Close Cerrar + Close {panel} Cerrar {panel} Close All Cerrar todo Close All Other Drawings Cerrar todos los demás dibujos Close Array Editing Cerrar la edición de matriz Close Comparison Cerrar comparación Export Comparison Exportar comparación + Close panel Cerrar panel Closed Cerrada Coincident Coincidente Collapse Palettes Contraer paletas diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 034f261e1..60697c2ed 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -91,6 +91,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "chrome", "cmdline", "credits", + "docking", "dialogs", "hatchdlg", "aliasdlg", diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bbb70e489..3e5fd341f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -141,11 +141,13 @@ Clip Viewport Обрізати видовий екран Clipboard Буфер обміну Close Закрити + Close {panel} Закрити {panel} Close All Закрити всі Close All Other Drawings Закрити всі інші креслення Closed Замкнений Close Comparison Закрити порівняння Export Comparison Експортувати порівняння + Close panel Закрити панель Coincident Збіг Collapse Palettes Згорнути палітри Collapse Tool Sets Згорнути набори інструментів diff --git a/crates/ui-egui/tests/it/docking_workflows.rs b/crates/ui-egui/tests/it/docking_workflows.rs index e2b3ea3a1..6672a9206 100644 --- a/crates/ui-egui/tests/it/docking_workflows.rs +++ b/crates/ui-egui/tests/it/docking_workflows.rs @@ -636,3 +636,18 @@ fn every_panel_header_has_a_close_button_that_closes_like_the_context_menu() { h.run_steps(4); assert!(!h.state().ui.docking.layout.contains(&Panel::Properties)); } + +/// The accessible name is one translated string, not an English verb glued to a translated +/// panel label: Spanish readers must hear "Cerrar Capas", never "Close Capas". +#[test] +fn spanish_close_button_accessible_name_is_localized_as_a_whole() { + let mut h = harness(None, 1280.0, 1.0); + h.state_mut().run("ui.language", json!({"lang": "es"})).unwrap(); + h.run_steps(4); + assert!(h.query_by_label("Cerrar Capas").is_some(), "the accordion close button is named in Spanish"); + assert!(h.query_by_label("Cerrar Propiedades").is_some(), "every panel's close button follows the language"); + assert!(h.query_by_label("Close Capas").is_none(), "no English verb survives the translation"); + h.get_by_label("Cerrar Capas").click(); + h.run_steps(4); + assert!(!h.state().ui.docking.layout.contains(&Panel::Layers), "the localized name still closes its panel"); +} From 0156fd9b9faabf999a7815f3fc13272bf6e2e523 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Mon, 2 Nov 2026 08:26:29 -0800 Subject: [PATCH 190/531] docking: follow the shared surface's stock tab menu and non-exhaustive node The dock area's tab menu item is "Close Panel" in the pinned craft-ui, and Node is non-exhaustive, so the accordion scan needs a catch-all arm. --- crates/ui-egui/src/docking.rs | 3 ++- crates/ui-egui/tests/it/docking_workflows.rs | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index ade26a65c..cb7710950 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -457,7 +457,8 @@ fn stack_panels(layout: &Layout) -> Vec { nodes.push(second); } Node::Stack { entries } => panels.extend(entries.iter().map(|entry| entry.panel)), - Node::Tabs { .. } => {} + // Tab groups draw their own header; nothing else stacks an accordion entry. + _ => {} } } panels diff --git a/crates/ui-egui/tests/it/docking_workflows.rs b/crates/ui-egui/tests/it/docking_workflows.rs index 6672a9206..a741a036c 100644 --- a/crates/ui-egui/tests/it/docking_workflows.rs +++ b/crates/ui-egui/tests/it/docking_workflows.rs @@ -123,7 +123,7 @@ fn palette_icons_are_painted_in_code_and_shown_in_an_iconic_column() { let ctx = egui::Context::default(); let mut paint = |panel: Panel| { let mut painted = false; - let mut content = Panels { app: &mut app }; + let mut content = Panels { app: &mut app, close: None }; let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::background()); let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(20.0, 20.0)); @@ -625,7 +625,8 @@ fn every_panel_header_has_a_close_button_that_closes_like_the_context_menu() { assert!(h.state().ui.docking.layout.contains(&Panel::Layers)); h.get_by_role_and_label(egui::accesskit::Role::Tab, "Layers").click_button(PointerButton::Secondary); h.run_steps(3); - h.get_by_label("Close panel").click(); + // The docking surface's stock tab menu item ("Close Panel"), not our tooltip. + h.get_by_label("Close Panel").click(); h.run_steps(4); assert!(!h.state().ui.docking.layout.contains(&Panel::Layers)); From a3e82dc9ce0bf63708c381bcb48ff21fe73e3398 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Sat, 24 Oct 2026 18:50:06 -0700 Subject: [PATCH 191/531] plot: model-space plots take their units from the paper (#1828) --- crates/engine/src/cmd/exchange.rs | 20 +-- crates/io/src/pdf.rs | 17 +-- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/plot_model_metric_units.rs | 119 +++++++++++++++ crates/render/src/paper.rs | 141 ++++++++++++++++++ crates/ui-egui/src/managers.rs | 2 +- 6 files changed, 275 insertions(+), 25 deletions(-) create mode 100644 crates/io/tests/it/plot_model_metric_units.rs diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index f6ce1e9b6..889258015 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use cadcraft_color::Rgb; -use cadcraft_doc::{Drawing, Entity, EntityKind, PageSetup, Space}; +use cadcraft_doc::{Drawing, Entity, EntityKind, Space}; use cadcraft_geom::{Bounds2, Mat3, Vec2}; use cadcraft_render::paper::{self, Sheet}; use cadcraft_render::raster::{RasterOptions, View}; @@ -308,18 +308,8 @@ fn run_preview(s: &mut Session, p: &Value) -> Result { let d = s.doc()?; let mut page = match space.layout() { Some(n) => d.layout(n).map(|l| l.page.clone()).unwrap_or_default(), - None => { - // Model space plots on A4 (metric) or ANSI A, like the PDF plotter. - let mut page = PageSetup::default(); - if paper::paper_unit_mm(d) == 1.0 - && let Some(a4) = paper::paper_size("A4") - { - page.paper = a4.name.into(); - page.width_mm = a4.width_mm; - page.height_mm = a4.height_mm; - } - page - } + // Model space plots on ISO A4 (metric) or ANSI A, like the PDF plotter. + None => paper::model_page(d), }; if let Some(name) = str_param(p, "paper") { let ps = paper::paper_size(name).ok_or_else(|| bad("preview", format!("unknown paper size `{name}`")))?; @@ -327,6 +317,10 @@ fn run_preview(s: &mut Session, p: &Value) -> Result { page.width_mm = ps.width_mm; page.height_mm = ps.height_mm; } + // A model-space plot takes its units from the paper it was given (a layout keeps its page setup's). + if matches!(space, Space::Model) { + paper::apply_model_paper_units(&mut page); + } if let Some(l) = p.get("landscape").and_then(Value::as_bool) { page.landscape = l; } diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index ba9d65867..612ecc729 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -290,17 +290,8 @@ fn links_json(v: Option<&Value>) -> Vec<(Handle, String)> { pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result { let mut page = match space.layout() { Some(n) => d.layout(n).map(|l| l.page.clone()).ok_or_else(|| IoError::Format(format!("no layout `{n}`")))?, - None => { - let mut p = PageSetup::default(); - if paper::paper_unit_mm(d) == 1.0 - && let Some(a4) = paper::paper_size("A4") - { - p.paper = a4.name.into(); - p.width_mm = a4.width_mm; - p.height_mm = a4.height_mm; - } - p - } + // Model space has no stored page setup: ISO A4 in a metric drawing, ANSI A otherwise. + None => paper::model_page(d), }; if let Some(name) = &o.paper { let ps = paper::paper_size(name).ok_or_else(|| IoError::Format(format!("unknown paper size `{name}`")))?; @@ -323,6 +314,10 @@ pub fn page_for(d: &Drawing, space: &Space, o: &PdfOptions) -> Result if let (Space::Model, Some(m)) = (space, o.margins) { page.margins_mm = m; } + // A model-space plot takes its units from the paper it was given; a layout keeps its page setup's. + if matches!(space, Space::Model) { + paper::apply_model_paper_units(&mut page); + } page.width_mm = page.width_mm.clamp(1.0, MAX_SHEET_MM); page.height_mm = page.height_mm.clamp(1.0, MAX_SHEET_MM); Ok(page) diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 79c4e4b3e..fbb5ddbb2 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -52,6 +52,7 @@ mod pdf_layers; #[path = "../support/pdf_read.rs"] mod pdf_read; mod plot_layout_scale; +mod plot_model_metric_units; mod plot_model_png_scale; mod plot_styles; mod polyface_roundtrip; diff --git a/crates/io/tests/it/plot_model_metric_units.rs b/crates/io/tests/it/plot_model_metric_units.rs new file mode 100644 index 000000000..cdb91b7d6 --- /dev/null +++ b/crates/io/tests/it/plot_model_metric_units.rs @@ -0,0 +1,119 @@ +//! #1828: a model-space plot at 1:1 in a drawing whose units are millimetres puts a 10 mm line +//! at 28.35 pt on an ISO A4 sheet, whatever MEASUREMENT says. A drawing made in millimetres by +//! changing the drawing units (UNITS sets INSUNITS, not MEASUREMENT) was plotted 25.4 times too +//! large, because model-space paper units were taken as inches. +//! +//! The model plot's units are the paper's, never the layouts' page setups': a layout whose page +//! setup is in inches still plots its paper space in inches (#1866). + +use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, PageSetup, Space}; +use cadcraft_geom::Vec3; +use cadcraft_io::plot; +use serde_json::{Value, json}; + +use crate::pdf_read; + +/// The page size in points. +fn media_box(pdf: &[u8]) -> (f64, f64) { + pdf_read::read(pdf).media() +} + +/// The plotted length in points of the single horizontal line. +fn line_pt(pdf: &[u8]) -> f64 { + let doc = pdf_read::read(pdf); + let xs: Vec = pdf_read::drawn(doc.content()).iter().filter(|o| o.op == "m" || o.op == "l").filter_map(|o| o.nums.first().copied()).collect(); + assert_eq!(xs.len(), 2, "one line, two ends: {xs:?}"); + (xs[1] - xs[0]).abs() +} + +/// A drawing with one 10-unit line in model space and the given drawing units. +fn drawing(insunits: i64, measurement: i64) -> Drawing { + let mut d = Drawing::new_imperial(); + d.header.set_i64("INSUNITS", insunits); + d.header.set_i64("MEASUREMENT", measurement); + let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }); + d.add(&Space::Model, Common::default(), line).unwrap(); + d +} + +/// Plot the model at 1:1 on the named paper, as the Plot dialog does. +fn plot_on(d: &Drawing, paper: &str) -> Vec { + let opts: Value = json!({ + "paper": paper, + "landscape": false, + "fit": false, + "scale": 1, + "lineweights": false, + "compress": false, + }); + plot(d, &Space::Model, &opts).unwrap() +} + +const A4_PT: (f64, f64) = (595.28, 841.89); +const ANSI_A_PT: (f64, f64) = (612.0, 792.0); +const TEN_MM_PT: f64 = 28.3465; +const TEN_IN_PT: f64 = 720.0; + +fn assert_pt(actual: f64, want: f64) { + assert!((actual - want).abs() < 0.01, "{actual} pt, want {want}"); +} + +/// The MediaBox is the sheet in points (A4 or ANSI A, portrait). +fn assert_media(pdf: &[u8], size: (f64, f64)) { + let (w, h) = media_box(pdf); + assert!((w - size.0).abs() < 0.01 && (h - size.1).abs() < 0.01, "{w} x {h} pt, want {size:?}"); +} + +#[test] +fn model_plot_in_a_metric_drawing_is_one_to_one() { + let pdf = plot_on(&drawing(4, 1), "ISO A4"); + assert_media(&pdf, A4_PT); + assert_pt(line_pt(&pdf), TEN_MM_PT); +} + +#[test] +fn model_plot_follows_the_length_unit_when_measurement_says_inches() { + // A drawing started imperial whose units the user changed to millimetres with UNITS: + // MEASUREMENT stays 0, the length unit is what says the drawing is in millimetres. + let pdf = plot_on(&drawing(4, 0), "ISO A4"); + assert_media(&pdf, A4_PT); + assert_pt(line_pt(&pdf), TEN_MM_PT); +} + +#[test] +fn model_plot_takes_units_from_the_paper() { + // A millimetre sheet at 1:1 prints one drawing unit per millimetre, whatever the drawing's + // length unit is. + let pdf = plot_on(&drawing(1, 0), "ISO A4"); + assert_media(&pdf, A4_PT); + assert_pt(line_pt(&pdf), TEN_MM_PT); + // An inch sheet prints one drawing unit per inch, whatever the drawing's length unit is. + let pdf = plot_on(&drawing(4, 0), "ANSI A"); + assert_media(&pdf, ANSI_A_PT); + assert_pt(line_pt(&pdf), TEN_IN_PT); +} + +#[test] +fn layout_plot_keeps_its_page_setup_units() { + // The @echelon regression: a metric drawing whose layout has a page setup in inches. The + // layout's paper space is in inches (25.4 mm per unit), not in the drawing's millimetres, + // and its A4 sheet is still A4. + let mut d = drawing(4, 0); + let mut l = Layout::new("SHEET", 3); + l.page = PageSetup { + paper: "ISO A4".into(), + width_mm: 210.0, + height_mm: 297.0, + margins_mm: [0.0; 4], + landscape: false, + paper_mm: false, + ..PageSetup::default() + }; + d.layouts.push(l); + let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }); + d.add(&Space::Paper("SHEET".into()), Common::default(), line).unwrap(); + let opts = json!({"fit": false, "scale": 1, "lineweights": false, "compress": false}); + let pdf = plot(&d, &Space::Paper("SHEET".into()), &opts).unwrap(); + assert_media(&pdf, A4_PT); + assert_pt(line_pt(&pdf), TEN_IN_PT); +} diff --git a/crates/render/src/paper.rs b/crates/render/src/paper.rs index ff4a027ba..5fce1bace 100644 --- a/crates/render/src/paper.rs +++ b/crates/render/src/paper.rs @@ -2,6 +2,8 @@ //! //! Paper-space units are millimetres in metric drawings (`MEASUREMENT` = 1) and on layouts whose //! page setup is in millimetres, and inches otherwise. The sheet's lower-left corner is the paper-space origin. +//! Model-space plots have no stored page setup, so they take their units from the paper itself +//! ([`model_page`], [`model_unit_mm`]). use cadcraft_doc::{Drawing, PageSetup}; use cadcraft_geom::{Bounds2, Vec2}; @@ -81,6 +83,59 @@ pub fn paper_unit_mm(d: &Drawing) -> f64 { if d.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 25.4 } } +/// Whether the drawing's length unit is metric: `INSUNITS` millimetres to kilometres and +/// angstroms to parsecs (4..=7, 11..=20) are metric, inches to US survey units (1, 2, 3, 8, 9, +/// 10, 21, 22, 23, 24) imperial. A unitless drawing (`INSUNITS` 0, absent or unknown, as files +/// without `$INSUNITS` are read, #1209) falls back to `MEASUREMENT` = 1. +/// +/// `MEASUREMENT` only chooses the imperial or ISO hatch and linetype libraries (#1649, #1826), +/// so it is not what says a drawing is metric: a drawing whose units are millimetres but whose +/// MEASUREMENT is 0 — what UNITS leaves when the user picks millimetres, and what AutoCAD writes +/// for many metric drawings — is metric by this test (#1828). +pub fn metric_length_unit(d: &Drawing) -> bool { + match d.header.i64("INSUNITS", 0) { + // Inches, feet, miles, microinches, mils, yards and US survey units. + 1 | 2 | 3 | 8 | 9 | 10 | 21 | 22 | 23 | 24 => false, + // Millimetres, centimetres, metres, kilometres, angstroms, nanometres, microns, + // decimetres to gigametres, astronomical units, light years and parsecs. + 4..=7 | 11..=20 => true, + // Unitless: as MEASUREMENT says. + _ => d.header.i64("MEASUREMENT", 0) == 1, + } +} + +/// Millimetres per paper unit of the paper named by `page`, from the paper itself: 1.0 for ISO +/// and user-defined millimetre sizes, 25.4 for the ANSI, ARCH and Legal sheets. A name that is +/// no known paper size is treated as a user millimetre size (1.0). +pub fn model_unit_mm(page: &PageSetup) -> f64 { + match paper_size(&page.paper) { + Some(p) if p.imperial => 25.4, + _ => 1.0, + } +} + +/// The page a model-space plot starts from: ISO A4 in a drawing whose length unit is metric, +/// ANSI A otherwise. Model space has no stored page setup, so the plot takes its sheet (and its +/// units) from here unless the caller picks another paper. +pub fn model_page(d: &Drawing) -> PageSetup { + let mut page = PageSetup::default(); + if let Some(p) = paper_size(if metric_length_unit(d) { "A4" } else { "ANSI A" }) { + page.paper = p.name.into(); + page.width_mm = p.width_mm; + page.height_mm = p.height_mm; + } + apply_model_paper_units(&mut page); + page +} + +/// Set a model-space plot's paper units once its paper is known: the paper's own units decide +/// (ISO and user millimetre sizes are millimetres, ANSI and ARCH sheets inches), as a model-space +/// page setup's "plot paper units" would. Layouts keep their stored page setup and go through +/// [`page_unit_mm`]; only model-space callers use this. +pub fn apply_model_paper_units(page: &mut PageSetup) { + page.paper_mm = model_unit_mm(page) == 1.0; +} + /// Millimetres per paper-space unit on a layout with page setup `page`: millimetres when the /// page says so (plot paper units mm), else as the drawing's MEASUREMENT says. Drawings from /// AutoCAD often have MEASUREMENT 0 with layouts in millimetres (#1058). @@ -139,6 +194,92 @@ pub fn sheet(d: &Drawing, layout: &str) -> Option { mod tests { use super::*; + #[test] + fn metric_length_unit_reads_the_length_unit() { + // Metric units, whatever MEASUREMENT says. + let mut d = Drawing::new_imperial(); + d.header.set_i64("MEASUREMENT", 0); + for u in [4, 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] { + d.header.set_i64("INSUNITS", u); + assert!(metric_length_unit(&d), "INSUNITS {u} is metric"); + } + // Imperial units, even with MEASUREMENT 1. + d.header.set_i64("MEASUREMENT", 1); + for u in [1, 2, 3, 8, 9, 10, 21, 22, 23, 24] { + d.header.set_i64("INSUNITS", u); + assert!(!metric_length_unit(&d), "INSUNITS {u} is imperial"); + } + // Unitless: as MEASUREMENT says. + for u in [0, 25] { + d.header.set_i64("INSUNITS", u); + d.header.set_i64("MEASUREMENT", 1); + assert!(metric_length_unit(&d), "unitless with MEASUREMENT 1 is metric"); + d.header.set_i64("MEASUREMENT", 0); + assert!(!metric_length_unit(&d), "unitless with MEASUREMENT 0 is imperial"); + } + d.header.vars.remove("INSUNITS"); + d.header.vars.remove("MEASUREMENT"); + assert!(!metric_length_unit(&d), "no units at all is imperial, as before"); + } + + #[test] + fn paper_unit_mm_still_follows_measurement() { + let mut m = Drawing::new_metric(); + assert_eq!(paper_unit_mm(&m), 1.0); + m.header.set_i64("MEASUREMENT", 0); + assert_eq!(paper_unit_mm(&m), 25.4, "layouts stay on MEASUREMENT (page setups in inches fit)"); + let mut i = Drawing::new_imperial(); + assert_eq!(paper_unit_mm(&i), 25.4); + i.header.set_i64("INSUNITS", 4); + assert_eq!(paper_unit_mm(&i), 25.4, "a metric length unit does not move layout paper units"); + i.header.set_i64("MEASUREMENT", 1); + assert_eq!(paper_unit_mm(&i), 1.0); + } + + #[test] + fn model_unit_mm_reads_the_paper() { + let page = |name: &str| PageSetup { paper: name.into(), ..PageSetup::default() }; + assert_eq!(model_unit_mm(&page("ISO A4")), 1.0); + assert_eq!(model_unit_mm(&page("ISO A0")), 1.0); + assert_eq!(model_unit_mm(&page("ANSI A")), 25.4); + assert_eq!(model_unit_mm(&page("ARCH D")), 25.4); + assert_eq!(model_unit_mm(&page("User (300.00 x 400.00 MM)")), 1.0); + assert_eq!(model_unit_mm(&page("nope")), 1.0, "an unknown paper is a user millimetre size"); + assert_eq!(model_unit_mm(&PageSetup::default()), 25.4, "the default page is ANSI A"); + } + + #[test] + fn model_page_is_a4_for_metric_drawings() { + let mut d = Drawing::new_metric(); + let page = model_page(&d); + assert_eq!(page.paper, "ISO A4 (210.00 x 297.00 MM)"); + assert_eq!((page.width_mm, page.height_mm), (210.0, 297.0)); + assert!(page.paper_mm, "A4 in a metric drawing is in millimetres"); + // The length unit decides, not MEASUREMENT. + d.header.set_i64("MEASUREMENT", 0); + assert_eq!(model_page(&d).paper, "ISO A4 (210.00 x 297.00 MM)"); + // An imperial drawing starts on ANSI A. + let page = model_page(&Drawing::new_imperial()); + assert_eq!(page.paper, "ANSI A (8.50 x 11.00 Inches)"); + assert!((page.width_mm - 215.9).abs() < 1e-9 && (page.height_mm - 279.4).abs() < 1e-9); + assert!(!page.paper_mm, "ANSI A in an imperial drawing is in inches"); + } + + #[test] + fn model_paper_units_follow_the_chosen_paper() { + // The sheet decides, whatever the drawing's length unit is. + let mut a4 = PageSetup { paper: "ISO A4 (210.00 x 297.00 MM)".into(), ..PageSetup::default() }; + apply_model_paper_units(&mut a4); + assert!(a4.paper_mm, "ISO A4 is a millimetre sheet"); + let mut ansi = PageSetup { paper: "ANSI A (8.50 x 11.00 Inches)".into(), ..PageSetup::default() }; + apply_model_paper_units(&mut ansi); + assert!(!ansi.paper_mm, "ANSI A is an inch sheet"); + // A user size in millimetres is one to one. + let mut user = PageSetup { paper: "User (300.00 x 400.00 MM)".into(), ..PageSetup::default() }; + apply_model_paper_units(&mut user); + assert!(user.paper_mm); + } + #[test] fn lookup_and_sheet() { assert_eq!(paper_size("a4").map(|p| p.width_mm), Some(210.0)); diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index 42266d3b6..9e35d6c0d 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -835,7 +835,7 @@ fn plot_page(d: &cadcraft_doc::Drawing, target: &str) -> cadcraft_doc::PageSetup return page; } let mut page = cadcraft_doc::PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..Default::default() }; - if cadcraft_render::paper::paper_unit_mm(d) == 1.0 + if cadcraft_render::paper::metric_length_unit(d) && let Some(a4) = cadcraft_render::paper_size("A4") { page.paper = a4.name.into(); From ff6b0e375bb3f31b203cae92c7dabb9345d03d8b Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 05:16:40 -0700 Subject: [PATCH 192/531] Alias Editor: import an existing .pgp file (#1900) --- apps/cadcraft/src/main.rs | 8 + crates/ui-egui/src/aliasdlg.rs | 258 ++++++++++++++++++++++++++++++++- crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/lib.rs | 10 ++ docs/customization.md | 5 +- 5 files changed, 283 insertions(+), 2 deletions(-) diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index c591c10b3..f6dc19508 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -179,6 +179,14 @@ fn services() -> Services { dialog.pick_file().map(|p| p.to_string_lossy().to_string()) })), no_file_system: false, + pick_pgp: Some(Box::new(|dir: Option<&str>| { + let dialog = rfd::FileDialog::new().add_filter(i18n::t("Alias files (PGP)"), &["pgp"]); + let dialog = match dir { + Some(dir) => dialog.set_directory(dir), + None => dialog, + }; + dialog.pick_file().map(|p| p.to_string_lossy().to_string()) + })), } } diff --git a/crates/ui-egui/src/aliasdlg.rs b/crates/ui-egui/src/aliasdlg.rs index 6caded5f8..40f144c37 100644 --- a/crates/ui-egui/src/aliasdlg.rs +++ b/crates/ui-egui/src/aliasdlg.rs @@ -33,6 +33,9 @@ pub struct AliasDlgState { pub filter: String, pub form: Option
, pub error: Option, + /// The warnings the last imported file reported (skipped lines, external commands, unknown + /// commands); the first few are shown in the dialog and all of them on the command line. + pub warnings: Vec, /// ALIASEDIT typed again while open: bring the window to the front on the next frame. pub raise: bool, } @@ -143,6 +146,79 @@ pub fn apply(app: &mut CadApp) -> bool { } } +/// Whether `path` names a `.pgp` file, whatever its case. +fn is_pgp(path: &str) -> bool { + std::path::Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("pgp")) +} + +/// Report a failed import in the dialog (when it is open) and on the command line; returns it so +/// the caller can too. +fn refused(app: &mut CadApp, msg: String) -> String { + app.session.echo(msg.clone()); + if let Some(st) = app.alias_dlg.as_mut() { + st.error = Some(msg.clone()); + st.warnings.clear(); + } + msg +} + +/// Load the `.pgp` alias file at `path` through ALIASEDIT, replacing the user aliases as typing +/// `ALIASEDIT {file}` does. The dialog refreshes to what ALIASEDIT holds now, so OK and Apply see +/// no pending difference; the file's warnings are kept for display. Non-`.pgp` and unreadable +/// files are ordinary errors, never a panic. +pub fn import(app: &mut CadApp, path: &str) -> Result<(), String> { + if !is_pgp(path) { + return Err(refused(app, format!("Import: {path} is not a .pgp alias file"))); + } + match app.run("aliasedit", json!({ "file": path })) { + Ok(v) => { + let aliases: BTreeMap = v + .get("aliases") + .and_then(Value::as_object) + .map(|m| m.iter().filter_map(|(a, c)| Some((a.clone(), c.as_str()?.to_string()))).collect()) + .unwrap_or_default(); + let file = v.get("file").and_then(Value::as_str).unwrap_or(path).to_string(); + let loaded = v.get("loaded").and_then(Value::as_u64).unwrap_or(0); + let warnings: Vec = v + .get("warnings") + .and_then(Value::as_array) + .map(|w| w.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + if let Some(dir) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) { + app.ui.last_pgp_dir = Some(dir.to_string_lossy().to_string()); + } + app.session.echo(format!("{loaded} command alias(es) imported from {path}.")); + for w in &warnings { + app.session.echo(format!("Import {path}: {w}")); + } + if let Some(st) = app.alias_dlg.as_mut() { + st.user = aliases.clone(); + st.applied = aliases; + st.file = Some(file); + st.form = None; + st.selected = None; + st.error = None; + st.warnings = warnings; + } + Ok(()) + } + Err(e) => Err(refused(app, e)), + } +} + +/// Import…: ask the host for a `.pgp` file (starting in the folder the last import came from), +/// then load it. A cancelled picker is a no-op; without a native picker (the web) the error names +/// the ALIASEDIT path form instead. +pub fn pick_and_import(app: &mut CadApp) -> Result<(), String> { + let dir = app.ui.last_pgp_dir.clone(); + let picked = app.services.pick_pgp.as_ref().map(|pick| pick(dir.as_deref())); + match picked { + None => Err(refused(app, crate::tl!("Import: there is no file dialog here; run ALIASEDIT with a path.").to_string())), + Some(None) => Ok(()), + Some(Some(path)) => import(app, &path), + } +} + /// Command Aliases window that edits the in-memory alias set in `app.alias_dlg`; OK/Apply send the differences to ALIASEDIT, read the resulting aliases and source file back, and show any error. pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { if app.alias_dlg.is_none() { @@ -150,7 +226,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } let built = built_in(); let warn = Tokens::get().warn; - let (mut ok, mut cancel, mut apply_clicked) = (false, false, false); + let (mut ok, mut cancel, mut apply_clicked, mut import_clicked) = (false, false, false, false); let Some(st) = app.alias_dlg.as_mut() else { return }; let id = egui::Id::unique("aliasedit_dialog"); if std::mem::take(&mut st.raise) { @@ -221,6 +297,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { { st.user.remove(s); } + if ui.button(crate::tl!("Import…")).clicked() { + import_clicked = true; + } }); let mut save = false; let mut discard = false; @@ -261,6 +340,15 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { if let Some(e) = &st.error { ui.colored_label(warn, e.as_str()); } + if !st.warnings.is_empty() { + for w in st.warnings.iter().take(3) { + ui.colored_label(warn, w.as_str()); + } + let more = st.warnings.len().saturating_sub(3); + if more > 0 { + ui.label(crate::tf!("{n} more warnings; see the command line.", n = more)); + } + } ui.separator(); ui.horizontal(|ui| { ok = ui.button(crate::tl!("OK")).clicked(); @@ -268,6 +356,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { apply_clicked = ui.button(crate::tl!("Apply")).clicked(); }); }); + if import_clicked { + let _ = pick_and_import(app); + } if (ok && apply(app)) || cancel { *open = false; } else if apply_clicked { @@ -277,3 +368,168 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { app.alias_dlg = None; } } + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::path::PathBuf; + use std::rc::Rc; + use std::sync::atomic::{AtomicU32, Ordering}; + use std::sync::{Mutex, MutexGuard, PoisonError}; + + use cadcraft_engine::Session; + use serde_json::json; + + use crate::{CadApp, Services}; + + use super::{open, pick_and_import}; + + /// The alias store is process-wide, so the tests that load files take turns and clear it. + fn alone() -> MutexGuard<'static, ()> { + static LOCK: Mutex<()> = Mutex::new(()); + LOCK.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn temp_dir(name: &str) -> PathBuf { + static N: AtomicU32 = AtomicU32::new(0); + let dir = std::env::temp_dir().join(format!("cadcraft-alias-{}-{}-{name}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::create_dir_all(&dir); + dir + } + + /// An app whose Import picker answers `answer` and records the folder it was asked to start in. + fn app_with_pick(answer: Option) -> (CadApp, Rc>>>) { + let asked = Rc::new(RefCell::new(Vec::new())); + let log = Rc::clone(&asked); + let answer = Rc::new(RefCell::new(answer)); + let services = Services { + pick_pgp: Some(Box::new(move |dir: Option<&str>| { + log.borrow_mut().push(dir.map(str::to_string)); + answer.borrow().clone() + })), + ..Services::default() + }; + (CadApp::new(Session::new(), services), asked) + } + + fn clear(app: &mut CadApp) { + let _ = app.run("aliasedit", json!({ "clear": true })); + } + + #[test] + fn import_loads_the_aliases_shows_the_path_and_warnings() { + let _guard = alone(); + let dir = temp_dir("good"); + let path = dir.join("aliases.pgp"); + std::fs::write(&path, "; our own aliases\nXXL, *LINE\nXXC, *CIRCLE\nNOPE, *NOTACOMMAND\nEXT, notepad.exe\n").unwrap_or_default(); + let picked = path.to_string_lossy().to_string(); + let (mut app, asked) = app_with_pick(Some(picked.clone())); + open(&mut app); + + pick_and_import(&mut app).expect("the file loads"); + + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user.get("xxl").map(String::as_str), Some("line")); + assert_eq!(st.user.get("xxc").map(String::as_str), Some("circle")); + assert_eq!(st.file.as_deref(), Some(picked.as_str()), "the imported path is shown"); + assert_eq!(st.applied, st.user, "an import leaves nothing for Apply to resend"); + assert!(st.error.is_none()); + assert!(st.warnings.iter().any(|w| w.contains("unknown command")), "unknown commands are reported: {:?}", st.warnings); + assert!(st.warnings.iter().any(|w| w.contains("external command")), "external commands are reported: {:?}", st.warnings); + assert!(app.session.log.iter().any(|l| l.contains("unknown command")), "the command line shows the full warnings"); + assert_eq!(app.ui.last_pgp_dir.as_deref(), Some(dir.to_string_lossy().as_ref()), "the import folder is remembered"); + assert_eq!(asked.borrow().as_slice(), [None], "the first import has no folder yet"); + + // The next import starts where the last file was. + open(&mut app); + let _ = pick_and_import(&mut app); + assert_eq!(asked.borrow().as_slice(), [None, Some(dir.to_string_lossy().to_string())]); + + clear(&mut app); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_cancelled_picker_changes_nothing() { + let _guard = alone(); + let (mut app, asked) = app_with_pick(None); + open(&mut app); + let before = app.alias_dlg.clone(); + + pick_and_import(&mut app).expect("cancelling is not an error"); + + assert_eq!(asked.borrow().len(), 1, "the picker was offered"); + assert_eq!(app.alias_dlg, before, "a cancelled picker leaves the aliases, file and errors alone"); + clear(&mut app); + } + + #[test] + fn non_pgp_and_malformed_files_are_ordinary_errors() { + let _guard = alone(); + let dir = temp_dir("bad"); + let text = dir.join("aliases.txt"); + std::fs::write(&text, "XXL, *LINE\n").unwrap_or_default(); + let (mut app, _) = app_with_pick(Some(text.to_string_lossy().to_string())); + open(&mut app); + let before = app.alias_dlg.clone().unwrap_or_default(); + + let e = pick_and_import(&mut app).expect_err("a .txt file is not an alias file"); + + assert!(e.contains(".pgp"), "{e}"); + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user, before.user, "the refused file changes no alias"); + assert_eq!(st.file, before.file); + assert!(st.error.as_deref().is_some_and(|e| e.contains(".pgp")), "{:?}", st.error); + + // Malformed lines are warnings with the aliases that did parse, never a panic. + let broken = dir.join("broken.pgp"); + std::fs::write(&broken, "not an alias line\nNOSUCH, *NOTACOMMAND\n; comment\nXXL, *LINE\n").unwrap_or_default(); + let (mut app, _) = app_with_pick(Some(broken.to_string_lossy().to_string())); + open(&mut app); + pick_and_import(&mut app).expect("malformed lines are warnings"); + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user.get("xxl").map(String::as_str), Some("line")); + assert!(st.warnings.len() >= 2, "{:?}", st.warnings); + assert!(st.error.is_none(), "{:?}", st.error); + + // A file that cannot be read is an error, reported in the dialog. + let missing = dir.join("missing.pgp"); + let (mut app, _) = app_with_pick(Some(missing.to_string_lossy().to_string())); + open(&mut app); + let e = pick_and_import(&mut app).expect_err("a missing file is an ordinary error"); + assert!(e.contains("missing.pgp"), "{e}"); + assert!(app.alias_dlg.as_ref().is_some_and(|st| st.error.is_some())); + + clear(&mut app); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn the_last_import_folder_round_trips_through_prefs() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.last_pgp_dir = Some("/tmp/our-aliases".into()); + let saved = app.prefs_json(); + assert!(saved.contains("lastPgpDir"), "{saved}"); + + let mut restored = CadApp::new(Session::new(), Services::default()); + restored.load_prefs(&saved); + assert_eq!(restored.ui.last_pgp_dir.as_deref(), Some("/tmp/our-aliases")); + + restored.load_prefs(r#"{"lastPgpDir": 3}"#); + assert_eq!(restored.ui.last_pgp_dir.as_deref(), Some("/tmp/our-aliases"), "malformed values are ignored"); + restored.load_prefs(r#"{"lastPgpDir": ""}"#); + assert_eq!(restored.ui.last_pgp_dir.as_deref(), Some("/tmp/our-aliases"), "an empty value is ignored"); + } + + #[test] + fn no_picker_reports_a_path_prompt_error_without_changing_aliases() { + let mut app = CadApp::new(Session::new(), Services::default()); + open(&mut app); + let before = app.alias_dlg.clone(); + let e = pick_and_import(&mut app).expect_err("the web has no native picker"); + assert!(e.contains("ALIASEDIT"), "{e}"); + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user, before.as_ref().map(|b| b.user.clone()).unwrap_or_default()); + assert!(st.error.as_deref().is_some_and(|e| e.contains("ALIASEDIT"))); + } +} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bbb70e489..2f73b7cfd 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1369,6 +1369,10 @@ built-in вбудований Add… Додати… Edit… Змінити… + Import… Імпортувати… + Import: there is no file dialog here; run ALIASEDIT with a path. Імпорт: тут немає діалогу вибору файлів; запустіть ALIASEDIT із шляхом. + {n} more warnings; see the command line. Ще {n} попереджень; див. командний рядок. + Alias files (PGP) Файли псевдонімів (PGP) Save alias Зберегти псевдонім Discard Скасувати зміни Customize Налаштування інтерфейсу diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 142a589a3..6cf3ae327 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -128,6 +128,8 @@ pub struct UiState { pub recent_files: Vec, /// The folder the last APPLOAD file came from: the next pick starts there. pub last_lisp_dir: Option, + /// The folder the Command Aliases dialog last imported a `.pgp` file from. + pub last_pgp_dir: Option, } /// A DXF/DWG file version (2000 … 2018). @@ -206,6 +208,7 @@ impl Default for UiState { save_version: SaveVersion::default().year().to_string(), recent_files: Vec::new(), last_lisp_dir: None, + last_pgp_dir: None, } } } @@ -222,6 +225,8 @@ pub struct Services { /// The host has no file system to read a path from (the browser): a dropped file's contents /// are what it loads, and APPLOAD says so instead of asking for a name it cannot read. pub no_file_system: bool, + /// Pick a `.pgp` alias file, starting in the folder given (the last import's). + pub pick_pgp: Option) -> Option>>, } pub struct CadApp { @@ -478,6 +483,8 @@ impl CadApp { } if let Some(dir) = &self.ui.last_lisp_dir { prefs["lispDir"] = json!(dir); + if let Some(dir) = self.ui.last_pgp_dir.as_deref().filter(|d| !d.is_empty()) { + prefs["lastPgpDir"] = json!(dir); } prefs.to_string() } @@ -512,6 +519,9 @@ impl CadApp { if let Some(dir) = v.get("lispDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { self.ui.last_lisp_dir = Some(dir.to_string()); } + if let Some(dir) = v.get("lastPgpDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { + self.ui.last_pgp_dir = Some(dir.to_string()); + } } /// Make the system cursor the interface default (`on`) and turn it on; saved preferences and diff --git a/docs/customization.md b/docs/customization.md index 33d1f8a2f..2ddf26d3e 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -36,7 +36,10 @@ cadcraft-cli run drawing.dxf --script-file setup.scr --save out.dxf ALIASEDIT reads a `.pgp` alias file (`ALIAS, *COMMAND` lines) and adds its aliases for the rest of the session. Lines that would start external programs are skipped. From a script or the control -channel: `aliasedit {"file": "/path/to/aliases.pgp"}`. +channel: `aliasedit {"file": "/path/to/aliases.pgp"}`. The Command Aliases dialog's **Import…** +button picks a `.pgp` file, loads it the same way, shows its path and warnings, and remembers the +folder it came from; on the web (no native file dialog) type `ALIASEDIT` with the file's contents +instead. ## Driving CADCraft from another program From 168f4a699a2fb9af7558f358b8cabf54651fba27 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 09:37:33 -0700 Subject: [PATCH 193/531] Alias Editor: point the web at ALIASEDIT's text parameter (#1900) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Without a native picker the Import… message told users to give ALIASEDIT a path, but the web has no file system and rejects paths. Name the supported route instead: the file's contents in ALIASEDIT's text parameter. The Ukrainian reference translation and the customization docs follow the new wording; the desktop picker path is unchanged. --- crates/ui-egui/src/aliasdlg.rs | 12 +++++++++--- crates/ui-egui/src/i18n/uk.tsv | 2 +- docs/customization.md | 4 ++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/aliasdlg.rs b/crates/ui-egui/src/aliasdlg.rs index 40f144c37..17b49db29 100644 --- a/crates/ui-egui/src/aliasdlg.rs +++ b/crates/ui-egui/src/aliasdlg.rs @@ -208,12 +208,15 @@ pub fn import(app: &mut CadApp, path: &str) -> Result<(), String> { /// Import…: ask the host for a `.pgp` file (starting in the folder the last import came from), /// then load it. A cancelled picker is a no-op; without a native picker (the web) the error names -/// the ALIASEDIT path form instead. +/// the ALIASEDIT `text` form, since the web has no file system to read a path from. pub fn pick_and_import(app: &mut CadApp) -> Result<(), String> { let dir = app.ui.last_pgp_dir.clone(); let picked = app.services.pick_pgp.as_ref().map(|pick| pick(dir.as_deref())); match picked { - None => Err(refused(app, crate::tl!("Import: there is no file dialog here; run ALIASEDIT with a path.").to_string())), + None => Err(refused( + app, + crate::tl!("Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter.").to_string(), + )), Some(None) => Ok(()), Some(Some(path)) => import(app, &path), } @@ -522,12 +525,15 @@ mod tests { } #[test] - fn no_picker_reports_a_path_prompt_error_without_changing_aliases() { + fn no_picker_points_at_aliasedit_text_without_changing_aliases() { let mut app = CadApp::new(Session::new(), Services::default()); open(&mut app); let before = app.alias_dlg.clone(); let e = pick_and_import(&mut app).expect_err("the web has no native picker"); assert!(e.contains("ALIASEDIT"), "{e}"); + assert!(e.contains("contents"), "the web is told to give the file's contents: {e}"); + assert!(e.contains("text"), "the web is told which parameter carries the contents: {e}"); + assert!(!e.contains("path"), "the web has no file system, so a path is not the supported form: {e}"); let st = app.alias_dlg.as_ref().expect("the dialog stays open"); assert_eq!(st.user, before.as_ref().map(|b| b.user.clone()).unwrap_or_default()); assert!(st.error.as_deref().is_some_and(|e| e.contains("ALIASEDIT"))); diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2f73b7cfd..dd0712d50 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1370,7 +1370,7 @@ Add… Додати… Edit… Змінити… Import… Імпортувати… - Import: there is no file dialog here; run ALIASEDIT with a path. Імпорт: тут немає діалогу вибору файлів; запустіть ALIASEDIT із шляхом. + Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. Імпорт: тут немає діалогу вибору файлів; запустіть ALIASEDIT із вмістом файлу в параметрі text. {n} more warnings; see the command line. Ще {n} попереджень; див. командний рядок. Alias files (PGP) Файли псевдонімів (PGP) Save alias Зберегти псевдонім diff --git a/docs/customization.md b/docs/customization.md index 2ddf26d3e..edf14fc54 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -38,8 +38,8 @@ ALIASEDIT reads a `.pgp` alias file (`ALIAS, *COMMAND` lines) and adds its alias the session. Lines that would start external programs are skipped. From a script or the control channel: `aliasedit {"file": "/path/to/aliases.pgp"}`. The Command Aliases dialog's **Import…** button picks a `.pgp` file, loads it the same way, shows its path and warnings, and remembers the -folder it came from; on the web (no native file dialog) type `ALIASEDIT` with the file's contents -instead. +folder it came from; on the web (no native file dialog) type `ALIASEDIT` with the file's contents in +its `text` parameter instead. ## Driving CADCraft from another program From b254a28a5e39d4a9e970ef09073a8b11fb57e4cb Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Mon, 2 Nov 2026 08:38:27 -0800 Subject: [PATCH 194/531] aliases: keep the APPLOAD picker beside the PGP picker on main --- crates/ui-egui/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6cf3ae327..62e7b48ea 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -483,6 +483,7 @@ impl CadApp { } if let Some(dir) = &self.ui.last_lisp_dir { prefs["lispDir"] = json!(dir); + } if let Some(dir) = self.ui.last_pgp_dir.as_deref().filter(|d| !d.is_empty()) { prefs["lastPgpDir"] = json!(dir); } From e8e76d2e608fc6bc243494eb7bc7029e9a1e8d4d Mon Sep 17 00:00:00 2001 From: assamaral Date: Mon, 2 Nov 2026 17:24:11 -0300 Subject: [PATCH 195/531] Menus: test that every menu follows the reference menu tree's order Reads xtask/data/menu-catalog.txt (the parity oracle) into a tree and checks menus::tree against it at every level. Fails on main: 19 menus and submenus list their items in command registration order. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/menus.rs | 101 ++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index bf0468d08..9b9559916 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -8,6 +8,43 @@ use crate::CadApp; /// The top-level menus, in order. pub const MENUS: &[&str] = &["File", "Edit", "View", "Insert", "Format", "Tools", "Draw", "Dimension", "Modify", "Window", "Help"]; +/// The reference menu tree (feature names, four spaces per level): the order every menu lists +/// its items in. The same file is `cargo xtask parity`'s oracle. +const REFERENCE_TREE: &str = include_str!("../../../xtask/data/menu-catalog.txt"); + +/// A menu of the reference tree: its label and its items, in order. +struct Reference { + label: &'static str, + children: Vec, +} + +/// The reference tree's top-level menus. +fn reference() -> &'static [Reference] { + static TREE: std::sync::OnceLock> = std::sync::OnceLock::new(); + TREE.get_or_init(|| { + // The menus being read, outermost first; a line closes every menu deeper than its indent. + let mut open = vec![Reference { label: "", children: Vec::new() }]; + let close = |open: &mut Vec| { + if let Some(done) = open.pop() + && let Some(parent) = open.last_mut() + { + parent.children.push(done); + } + }; + for line in REFERENCE_TREE.lines().filter(|l| !l.trim().is_empty()) { + let depth = (line.len() - line.trim_start_matches(' ').len()) / 4; + while open.len() > depth + 1 { + close(&mut open); + } + open.push(Reference { label: line.trim(), children: Vec::new() }); + } + while open.len() > 1 { + close(&mut open); + } + open.pop().map(|root| root.children).unwrap_or_default() + }) +} + /// File ▸ Open Recent: one `ui.recent.` item per recent file, then Clear Recent Files. pub const OPEN_RECENT: &str = "Open Recent"; const RECENT_ITEM: &str = "ui.recent."; @@ -993,6 +1030,70 @@ mod tests { } } +#[cfg(test)] +mod reference_order_tests { + use cadcraft_engine::Session; + + use super::{Entry, Reference, reference, tree}; + use crate::{CadApp, Services}; + + fn label(e: &Entry) -> &str { + match e { + Entry::Item { label, .. } | Entry::Sub { label, .. } => label, + } + } + + /// Every item the reference lists comes in the reference's order, at every level, and the + /// items the reference lacks follow them. + fn check(path: &str, entries: &[Entry], reference: &[Reference], failures: &mut Vec) { + let known = |e: &Entry| reference.iter().any(|r| r.label == label(e)); + let listed: Vec<&str> = entries.iter().filter(|e| known(e)).map(label).collect(); + let expected: Vec<&str> = reference.iter().map(|r| r.label).filter(|l| listed.contains(l)).collect(); + if listed != expected { + failures.push(format!("{path}: {listed:?} should be {expected:?}")); + } + if let (Some(unlisted), Some(last)) = (entries.iter().position(|e| !known(e)), entries.iter().rposition(known)) + && unlisted < last + { + failures.push(format!("{path}: {} comes before the reference's items", entries.get(unlisted).map_or("?", label))); + } + for e in entries { + if let Entry::Sub { label, children } = e + && let Some(r) = reference.iter().find(|r| r.label == *label) + { + check(&format!("{path} > {label}"), children, &r.children, failures); + } + } + } + + #[test] + fn menus_follow_the_reference_tree() { + let app = CadApp::new(Session::new(), Services::default()); + let mut failures = Vec::new(); + for (menu, entries) in tree(&app) { + let r = reference().iter().find(|r| r.label == menu).unwrap_or_else(|| panic!("{menu} is not in the reference tree")); + check(&menu, &entries, &r.children, &mut failures); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); + } + + #[test] + fn reference_tree_is_nested_by_indentation() { + assert_eq!(reference().iter().map(|r| r.label).collect::>(), super::MENUS); + let draw = reference().iter().find(|r| r.label == "Draw").unwrap(); + let circle = draw.children.iter().find(|r| r.label == "Circle").unwrap(); + assert_eq!(circle.children.first().map(|r| r.label), Some("Center, Radius")); + } + + #[test] + fn open_recent_stays_after_open() { + let app = CadApp::new(Session::new(), Services::default()); + let file = tree(&app).into_iter().find(|(m, _)| m == "File").map(|(_, e)| e).unwrap_or_default(); + let open = file.iter().position(|e| matches!(e, Entry::Item { id, .. } if id == "open")).unwrap(); + assert_eq!(file.get(open + 1).map(label), Some(super::OPEN_RECENT)); + } +} + #[cfg(test)] mod shortcut_label_tests { use super::shortcut_label; From dd3ffe7ae701d5df9b4201b9fedaf973d48f2bf8 Mon Sep 17 00:00:00 2001 From: assamaral Date: Mon, 2 Nov 2026 17:38:28 -0300 Subject: [PATCH 196/531] Menus list their items in the reference menu tree's order menus::tree sorts every menu, at every level, by xtask/data/menu-catalog.txt (embedded with include_str!, so the parity oracle is the one source): the items the reference has come first, in its order; the rest keep registration order. The in-window menu bar, the native macOS menu and ui.menu.list all follow. Labels are unchanged. Co-Authored-By: Claude Fable 5.1 --- crates/ui-egui/src/menus.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9b9559916..11daaf07f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -45,6 +45,22 @@ fn reference() -> &'static [Reference] { }) } +/// Put `entries` in `reference`'s order: the items the reference lists first, as it lists them, +/// then the rest in registration order. Submenus the reference has are ordered the same way. +fn order(entries: &mut [Entry], reference: &[Reference]) { + let position = |label: &str| reference.iter().position(|r| r.label == label).unwrap_or(usize::MAX); + entries.sort_by_key(|e| match e { + Entry::Item { label, .. } | Entry::Sub { label, .. } => position(label), + }); + for e in entries { + if let Entry::Sub { label, children } = e + && let Some(r) = reference.iter().find(|r| r.label == *label) + { + order(children, &r.children); + } + } +} + /// File ▸ Open Recent: one `ui.recent.` item per recent file, then Clear Recent Files. pub const OPEN_RECENT: &str = "Open Recent"; const RECENT_ITEM: &str = "ui.recent."; @@ -658,6 +674,11 @@ pub fn tree(app: &CadApp) -> Vec<(String, Vec)> { let at = file.iter().position(|e| matches!(e, Entry::Item { id, .. } if id == "open")).map_or(0, |i| i + 1); file.insert(at, Entry::Sub { label: OPEN_RECENT.into(), children: recent_entries(app) }); } + for (menu, entries) in &mut out { + if let Some(r) = reference().iter().find(|r| r.label == menu) { + order(entries, &r.children); + } + } out } From deca6b1062fc7d723f667853d85fc0ce819c65b3 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 14:25:33 +1100 Subject: [PATCH 197/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a91ee2f25..89dc37025 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-03 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 449 registered commands. +**Menu breadth: 305 / 491 items (62%)** · 458 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 37 | 49% | +| View | 75 | 38 | 51% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -65,7 +65,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -80,15 +79,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -126,7 +120,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From f1790d2be7ed80154c7f614227b367415798aef0 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 14:49:47 +1100 Subject: [PATCH 198/531] Drop the parity checklist change (maintainers regenerate it) --- docs/parity-checklist.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 89dc37025..a91ee2f25 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-11-03 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 305 / 491 items (62%)** · 458 registered commands. +**Menu breadth: 298 / 491 items (61%)** · 449 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 38 | 51% | +| View | 75 | 37 | 49% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 71 | 84% | -| Draw | 87 | 56 | 64% | +| Tools | 85 | 66 | 78% | +| Draw | 87 | 55 | 63% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -65,6 +65,7 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser +- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -79,10 +80,15 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place +- Tools > New UCS > World - Tools > New UCS > Face +- Tools > New UCS > View +- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector +- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y +- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -120,6 +126,7 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing +- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From 51b3e8b112029fe4903422844b5f9569ec55b7ba Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 14:59:25 +1100 Subject: [PATCH 199/531] UCS: Chinese strings for the UCS menu and fmt after merging main --- crates/io/src/dxf_write/sections.rs | 12 +++++++++++- crates/ui-egui/src/i18n/zh.tsv | 7 +++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 6fffd2d7c..b49604eff 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -557,7 +557,17 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { layout_obj( w, LayoutWriteContext { drawing: d, dictionary: layout_dict }, - LayoutWriteData { handle: model_layout, name: "Model", tab: 0, block_record: ms_br, flags: 1, page: &model_page, view: None, ucs: None, limits: None }, + LayoutWriteData { + handle: model_layout, + name: "Model", + tab: 0, + block_record: ms_br, + flags: 1, + page: &model_page, + view: None, + ucs: None, + limits: None, + }, ); for (i, (_, brh, l)) in ps_brs.iter().enumerate() { let h = layout_handles.get(i).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index de4e6a633..514c7fa1f 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1453,3 +1453,10 @@ menu Dimension 标注 menu Draw 绘图 menu Modify 修改 menu View 视图 + 3 Point 三点 + New UCS 新建 UCS + Origin 原点 + UCS UCS + UCS Icon at Origin 原点处的 UCS 图标 + World 世界 + Z Z From 4b532f6c24208b3bc481ca385f304f05c52527cc Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 3 Nov 2026 08:01:13 +0400 Subject: [PATCH 200/531] i18n(ka): translate the strings added upstream; prompts without the trailing "or" Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 2 +- crates/ui-egui/src/i18n/ka.tsv | 44 ++++++++++++++++++++++------------ docs/localization-parity.md | 4 ++-- docs/localization.md | 2 +- 4 files changed, 33 insertions(+), 19 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 13ed80ef8..a731731f0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,7 +95,7 @@ Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity. | Indonesian | none | 0% | | Japanese | none | 0% | | Greek | complete current catalog | 1,330 current source keys; independent proofreading pending | -| Georgian | complete current catalog | 1,383 rows; terminology decided by a native speaker | +| Georgian | complete current catalog | 1,458 rows; terminology decided by a native speaker | | German | partial | ≈ 100% of the catalog (989 rows) | | Korean | none | 0% | | Vietnamese | none | 0% | diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 843a8ff8a..e40f492c7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -295,7 +295,7 @@ Enter a vertex editing option შეიყვანეთ წვეროს რედაქტირების ვარიანტი Enter an option შეიყვანეთ ვარიანტი Enter angle of xline შეიყვანეთ დამხმარე ხაზის კუთხე - Enter angle of xline (0) or შეიყვანეთ დამხმარე ხაზის კუთხე (0) ან + Enter angle of xline (0) შეიყვანეთ დამხმარე ხაზის კუთხე (0) Enter area of rectangle in current units შეიყვანეთ მართკუთხედის ფართობი მიმდინარე ერთეულებში Enter attribute prompt შეიყვანეთ ატრიბუტის მოთხოვნა Enter attribute tag name შეიყვანეთ ატრიბუტის ტეგის სახელი @@ -306,7 +306,7 @@ Enter default attribute value შეიყვანეთ ატრიბუტის ნაგულისხმევი მნიშვნელობა Enter degree of spline შეიყვანეთ სპლაინის ხარისხი Enter delta angle შეიყვანეთ კუთხის ნამატი - Enter delta length or შეიყვანეთ სიგრძის ნამატი ან + Enter delta length შეიყვანეთ სიგრძის ნამატი Enter dimension text შეიყვანეთ ზომის ტექსტი Enter dimension text (<> = measurement) შეიყვანეთ ზომის ტექსტი (<> = გაზომილი მნიშვნელობა) Enter dimension value or [name=expression] შეიყვანეთ ზომის მნიშვნელობა ან [name=expression] @@ -813,8 +813,8 @@ Select an arc or circle მონიშნეთ რკალი ან წრე Select an arc. მონიშნეთ რკალი. Select an object მონიშნეთ ობიექტი - Select an object to change or მონიშნეთ შესაცვლელი ობიექტი ან - Select an object to measure or მონიშნეთ გასაზომი ობიექტი ან + Select an object to change მონიშნეთ შესაცვლელი ობიექტი + Select an object to measure მონიშნეთ გასაზომი ობიექტი Select an object. მონიშნეთ ობიექტი. Select an open curve. მონიშნეთ ღია მრუდი. Select an open line, arc, polyline, ellipse arc or spline. მონიშნეთ ღია ხაზი, რკალი, ტეხილი, ელიფსური რკალი ან სპლაინი. @@ -828,9 +828,8 @@ Select first line მონიშნეთ პირველი ხაზი Select first line or arc მონიშნეთ პირველი ხაზი ან რკალი Select first object მონიშნეთ პირველი ობიექტი - Select first object or მონიშნეთ პირველი ობიექტი ან Select first point მონიშნეთ პირველი წერტილი - Select nested objects to copy or მონიშნეთ ჩადგმული ობიექტები კოპირებისთვის ან + Select nested objects to copy მონიშნეთ ჩადგმული ობიექტები კოპირებისთვის Select object მონიშნეთ ობიექტი Select object to dimension მონიშნეთ ობიექტი ზომის დასატანად Select object to divide მონიშნეთ დასაყოფი ობიექტი @@ -851,7 +850,7 @@ Select one polyline (Multiple is available through the JSON form). მონიშნეთ ერთი ტეხილი (Multiple ხელმისაწვდომია JSON ფორმით). Select path curve მონიშნეთ ტრაექტორიის მრუდი Select point or object მონიშნეთ წერტილი ან ობიექტი - Select polyline or მონიშნეთ ტეხილი ან + Select polyline მონიშნეთ ტეხილი Select second line მონიშნეთ მეორე ხაზი Select second line or shift-select to apply corner მონიშნეთ მეორე ხაზი, ან Shift-ით მონიშნეთ კუთხის შესაქმნელად Select second object მონიშნეთ მეორე ობიექტი @@ -911,9 +910,8 @@ Specify axis endpoint of ellipse მიუთითეთ ელიფსის ღერძის ბოლო წერტილი Specify base diameter მიუთითეთ ფუძის დიამეტრი Specify base point მიუთითეთ საბაზო წერტილი - Specify base point or მიუთითეთ საბაზო წერტილი ან Specify base point or displacement (drag with the middle mouse button for realtime pan) მიუთითეთ საბაზო წერტილი ან წანაცვლება (რეალურ დროში პანორამისთვის გადაათრიეთ მაუსის შუა ღილაკით) - Specify base radius or მიუთითეთ ფუძის რადიუსი ან + Specify base radius მიუთითეთ ფუძის რადიუსი Specify center of donut მიუთითეთ რგოლის ცენტრი Specify center of ellipse მიუთითეთ ელიფსის ცენტრი Specify center of polygon მიუთითეთ მრავალკუთხედის ცენტრი @@ -955,7 +953,7 @@ Specify first point on circle: _tan to მიუთითეთ პირველი წერტილი წრეზე: _tan to Specify first source point მიუთითეთ პირველი საწყისი წერტილი Specify height მიუთითეთ სიმაღლე - Specify helix height or მიუთითეთ სპირალის სიმაღლე ან + Specify helix height მიუთითეთ სპირალის სიმაღლე Specify included angle მიუთითეთ შიგა კუთხე Specify insertion base point მიუთითეთ ჩასმის საბაზო წერტილი Specify insertion point მიუთითეთ ჩასმის წერტილი @@ -1038,7 +1036,6 @@ Specify new width for all segments მიუთითეთ ახალი სიგანე ყველა სეგმენტისთვის Specify next point მიუთითეთ შემდეგი წერტილი Specify offset distance მიუთითეთ წანაცვლების მანძილი - Specify offset distance or მიუთითეთ წანაცვლების მანძილი ან Specify opposite corner მიუთითეთ მოპირდაპირე კუთხე Specify other corner point მიუთითეთ მეორე კუთხის წერტილი Specify other endpoint of axis მიუთითეთ ღერძის მეორე ბოლო წერტილი @@ -1051,7 +1048,6 @@ Specify radius of circle მიუთითეთ წრის რადიუსი Specify rotation angle მიუთითეთ შემობრუნების კუთხე Specify rotation angle of text მიუთითეთ ტექსტის შემობრუნების კუთხე - Specify rotation angle or მიუთითეთ შემობრუნების კუთხე ან Specify scale factor მიუთითეთ მასშტაბის კოეფიციენტი Specify second angle endpoint მიუთითეთ კუთხის მეორე ბოლო წერტილი Specify second break point მიუთითეთ გაწყვეტის მეორე წერტილი @@ -1084,9 +1080,9 @@ Specify third source point or მიუთითეთ მესამე საწყისი წერტილი ან <გაგრძელება> Specify through point მიუთითეთ გავლის წერტილი Specify top diameter მიუთითეთ ზედა დიამეტრი - Specify top radius or მიუთითეთ ზედა რადიუსი ან + Specify top radius მიუთითეთ ზედა რადიუსი Specify total angle მიუთითეთ სრული კუთხე - Specify total length or მიუთითეთ სრული სიგრძე ან + Specify total length მიუთითეთ სრული სიგრძე Specify width for rectangles მიუთითეთ მართკუთხედების სიგანე Sphere სფერო Spline სპლაინი @@ -1267,8 +1263,8 @@ Stretch Vertex წვეროს გაწელვა Edit Array მასივის რედაქტირება Save changes to {name}? შევინახო ცვლილებები ნახაზში {name}? - Save changes to block "{name}"? შევინახო ცვლილებები ბლოკში „{name}“? Your changes will be lost if you don't save them. თუ ცვლილებებს არ შეინახავთ, ისინი დაიკარგება. + Save changes to block "{name}"? შევინახო ცვლილებები ბლოკში „{name}“? Don't Save არ შეინახო Close Array Editing მასივის რედაქტირების დახურვა Multiline... მულტიხაზი... @@ -1297,6 +1293,8 @@ Automatic save every ავტომატური შენახვა ყოველ min წთ Automatic save file location ავტომატური შენახვის ფაილის მდებარეობა + Backup copy სარეზერვო ასლი + Create backup copy with each save სარეზერვო ასლის შექმნა ყოველი შენახვისას Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. ჯერ ფაილის არმქონე ნახაზები ნაგულისხმევ ვერსიაში ინახება. 0 წუთი ავტომატურ შენახვას გამორთავს. Time-sensitive right-click: a quick click is Enter, holding opens the menu დროზე დამოკიდებული მარჯვენა დაწკაპება: მოკლე დაწკაპება Enter-ია, დაჭერით გაიხსნება მენიუ Turned off, a right-click while a command runs always opens the shortcut menu. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება ყოველთვის კონტექსტურ მენიუს ხსნის. @@ -1458,3 +1456,19 @@ menu View ხედი First corner პირველი კუთხე Opposite corner საპირისპირო კუთხე Window < ფანჯარა < + Oops წაშლილის აღდგენა + Change შეცვლა + Change Properties თვისებების შეცვლა + Units ერთეულები + Find All ყველას ძებნა + Find what: რა მოიძებნოს: + Match case რეგისტრის გათვალისწინება + Replace ჩანაცვლება + Replace All ყველას ჩანაცვლება + Replace with: ჩანაცვლება: + Replacement text ჩამნაცვლებელი ტექსტი + Results შედეგები + Searches the current space. ძიება მიმდინარე სივრცეში. + Text to find მოსაძებნი ტექსტი + Whole words მთლიანი სიტყვები + Nothing found ვერაფერი მოიძებნა diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 4a7c13e7a..c41162eff 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -73,7 +73,7 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | -| Georgian | ka | 1,384 catalog rows (1,378 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release builds (web builds too once #1971 adds it to the web faces); English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | +| Georgian | ka | 1,458 catalog rows (1,452 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release builds (web builds too once #1971 adds it to the web faces); English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Bosnian | bs | 1,442 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes | Latin: yes (bundled egui fonts) | AI-assisted; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | @@ -92,7 +92,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| | 2026-10-30 | minor | Bosnian (`bs`, Latin, Ijekavian) added: 1,442 rows, one/few/other plurals, `bs-*` locales; AI-assisted, native proofreading pending | -| 2026-10-23 | minor | Georgian (`ka`) added: 1,384 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the embedded craft-fonts `Geor` face loaded when a build has it (the pin is #1971); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; terminology decided by a native speaker | +| 2026-10-23 | minor | Georgian (`ka`) added: 1,458 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the embedded craft-fonts `Geor` face loaded when a build has it (the pin is #1971); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; terminology decided by a native speaker | | 2026-10-22 | minor | Command line IME: enabled while a prompt collects text, composition shown but not saved, commit inserted once; single-line TEXT edits accept CJK input (#1761) | | 2026-10-19 | minor | Brazilian Portuguese: row brought up to date (it still read 0%); native-speaker terminology pass on 69 rows (Bind as Integrar, prompt keywords and SPDX kept in English, Thaw Layer, Snap type, Revolve fixed; snap, viewport, grip, offset, layer on/off and multiline wording made consistent with Brazilian usage) | | 2026-10-15 | minor | Greek (`el`) catalog: 1,330 rows, context/plural/locale/font tests; review pending | diff --git a/docs/localization.md b/docs/localization.md index 0d97cdfb7..ee6b1fc0b 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -120,7 +120,7 @@ follow-up work. ## Georgian (`ka`) interface -Georgian has **1,384 rows**: 1,378 ordinary labels, four contextual menu headings (**ზომების +Georgian has **1,458 rows**: 1,452 ordinary labels, four contextual menu headings (**ზომების დატანა** for the Dimension menu, **ზომა** for the object; **ხატვა** for Draw) and two single-form count templates, since a Georgian noun stays singular after a numeral ("5 კომიტი"). It covers the union of the existing catalogs, and no marked UI literal falls back to English. Commands are verbal From f99307f2cd9f4da3676bac563cf2d8993b910c81 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 15:11:08 +1100 Subject: [PATCH 201/531] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a91ee2f25..89dc37025 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-03 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 449 registered commands. +**Menu breadth: 305 / 491 items (62%)** · 458 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 37 | 49% | +| View | 75 | 38 | 51% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 66 | 78% | -| Draw | 87 | 55 | 63% | +| Tools | 85 | 71 | 84% | +| Draw | 87 | 56 | 64% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -65,7 +65,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser -- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -80,15 +79,10 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place -- Tools > New UCS > World - Tools > New UCS > Face -- Tools > New UCS > View -- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector -- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y -- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -126,7 +120,6 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing -- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From 8157cd2fc1e1083939212e55c6dccf21f1793cff Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 15:43:33 +1100 Subject: [PATCH 202/531] Drop the parity checklist change (maintainers regenerate it) --- docs/parity-checklist.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 89dc37025..a91ee2f25 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,20 +1,20 @@ # Parity checklist -> **Generated:** 2026-11-03 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 305 / 491 items (62%)** · 458 registered commands. +**Menu breadth: 298 / 491 items (61%)** · 449 registered commands. | Menu | Items | Covered | % | |---|---|---|---| | File | 22 | 13 | 59% | | Edit | 13 | 12 | 92% | -| View | 75 | 38 | 51% | +| View | 75 | 37 | 49% | | Insert | 11 | 5 | 45% | | Format | 27 | 26 | 96% | -| Tools | 85 | 71 | 84% | -| Draw | 87 | 56 | 64% | +| Tools | 85 | 66 | 78% | +| Draw | 87 | 55 | 63% | | Dimension | 28 | 28 | 100% | | Modify | 113 | 53 | 47% | | Window | 22 | 3 | 14% | @@ -65,6 +65,7 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - View > Render > Light > New Distant Light - View > Render > Light > Light Glyphs - View > Render > Materials Browser +- View > UCS Icon > Origin - View > UCS Icon > Properties... - View > ViewCube > Settings - View > Lights @@ -79,10 +80,15 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Tools > Spelling - Tools > Update Fields - Tools > Edit Xref in Place +- Tools > New UCS > World - Tools > New UCS > Face +- Tools > New UCS > View +- Tools > New UCS > Origin - Tools > New UCS > Z Axis Vector +- Tools > New UCS > 3 Point - Tools > New UCS > X - Tools > New UCS > Y +- Tools > New UCS > Z - Tools > Named UCS... - Tools > Customize > Interface (CUI)... - Tools > Import Settings @@ -120,6 +126,7 @@ Menu-breadth parity: a reference menu item counts as covered when a CADCraft com - Draw > 3D Modeling > Meshes > Meshes, Ruled Surface - Draw > 3D Modeling > Meshes > Meshes, Edge Surface - Draw > 3D Modeling > Setup > Drawing +- Draw > 3D Modeling > Setup > View - Draw > 3D Modeling > Setup > Profile - Modify > Object > External Reference > Frame - Modify > Object > Image > Adjust... From 9bd5c479e39be920139c223a4516d0e14d5bcb19 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 15:45:05 +1100 Subject: [PATCH 203/531] OLE2FRAME: SCALE carries a frame with a uniform positive factor (review on #2587) ole_frame_accepts took only a translation, so SCALE on a selection with a frame failed as a whole. A uniform positive scale keeps the frame axis-aligned and upper-left, so the corner rewrite handles it; rotation and mirroring are still refused. Tests: scale_carries_an_ole_frame_with_the_rest_of_the_selection, mocoro_scales_an_ole_frame, ole_frame_accepts_translations_and_uniform_positive_scales_only. --- crates/doc/src/extents.rs | 24 ++++++++-- crates/engine/src/cmd/modify/transform.rs | 4 +- crates/engine/src/cmd/modify2/mocoro.rs | 2 +- crates/engine/tests/ole_frame_transform.rs | 52 +++++++++++++++++++--- 4 files changed, 70 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 568cb7023..596a194a5 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -109,7 +109,7 @@ fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3, frame } } -/// Move an OLE2FRAME by `m`, a translation: its two corners are mapped through `m` (a DWG save +/// Move an OLE2FRAME by `m`, a translation or a uniform positive scale: its two corners are mapped through `m` (a DWG save /// writes the frame's position from these groups), and so are the corners at the start of its OLE /// data (310 groups), which a reader of the saved file may trust instead. Other transforms do not keep a frame axis /// aligned, so callers refuse them (see [`ole_frame_accepts`]). A frame with no usable corners is @@ -129,10 +129,12 @@ pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) ole_data_transform(tags, m, frame); } -/// Whether `m` can move an OLE2FRAME: only a translation (move, copy, stretch of the whole frame). +/// Whether `m` can move an OLE2FRAME: a translation (move, copy, stretch of the whole frame) or a +/// uniform scale with a positive factor, which keep the frame axis aligned and its upper-left corner +/// upper-left. pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool { const T: f64 = 1e-12; - (m.a - 1.0).abs() < T && m.b.abs() < T && m.c.abs() < T && (m.d - 1.0).abs() < T + m.b.abs() < T && m.c.abs() < T && m.a > 0.0 && (m.a - m.d).abs() <= T * m.a.abs().max(1.0) } /// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification @@ -677,4 +679,20 @@ mod tests { assert!(extents.width() > drawn.width()); } } + + /// A translation, and a uniform positive scale about any point, keep a frame axis aligned and + /// upper-left; a rotation, a mirror, a non-uniform or non-positive scale do not. + #[test] + fn ole_frame_accepts_translations_and_uniform_positive_scales_only() { + use cadcraft_geom::Mat3; + let p = Vec2::new(3.0, -4.0); + assert!(ole_frame_accepts(&Mat3::translate(p))); + assert!(ole_frame_accepts(&Mat3::scale_about(p, 2.5))); + assert!(ole_frame_accepts(&Mat3::scale_about(p, 1e-3))); + assert!(!ole_frame_accepts(&Mat3::scale(2.0, 3.0))); + assert!(!ole_frame_accepts(&Mat3::scale_about(p, -1.0))); + assert!(!ole_frame_accepts(&Mat3::scale_about(p, 0.0))); + assert!(!ole_frame_accepts(&Mat3::rotate_about(p, 0.5))); + assert!(!ole_frame_accepts(&Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)))); + } } diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 589fc4b2d..d1e6a463e 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -21,7 +21,7 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, }) } -/// An OLE2FRAME only translates (its corners stay axis aligned): refuse any other `m` before anything +/// An OLE2FRAME only translates or scales uniformly (its corners stay axis aligned): refuse any other `m` before anything /// changes, instead of reporting success and leaving the frame where it was. pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<()> { if cadcraft_doc::ole_frame_accepts(m) { @@ -37,7 +37,7 @@ pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool }; if hs.iter().any(ole) { return Err(crate::EngineError::Other( - "An OLE object can only be moved or copied; rotating, scaling and mirroring it are not supported.".into(), + "An OLE object can only be moved, copied or scaled uniformly; rotating and mirroring it are not supported.".into(), )); } Ok(()) diff --git a/crates/engine/src/cmd/modify2/mocoro.rs b/crates/engine/src/cmd/modify2/mocoro.rs index 93732a7cf..47d6833fb 100644 --- a/crates/engine/src/cmd/modify2/mocoro.rs +++ b/crates/engine/src/cmd/modify2/mocoro.rs @@ -108,7 +108,7 @@ pub(super) fn run_mocoro(s: &mut Session, p: &Value) -> Result { } // Every option is checked before the drawing changes. let ops = list.iter().enumerate().map(|(i, v)| parse_op(i, v)).collect::>>()?; - // An OLE frame only translates: a rotate or scale step that would refuse it must do so before an + // An OLE frame only translates or scales uniformly: a rotate step (or any step) that would refuse it must do so before an // earlier move or copy changes the drawing (a refused command is not rolled back). for op in &ops { match *op { diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index 653d9f017..2578c4e18 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -41,14 +41,12 @@ fn move_and_copy_carry_an_ole_frame() { } #[test] -fn rotate_scale_and_mirror_refuse_an_ole_frame() { +fn rotate_and_mirror_refuse_an_ole_frame() { let (mut s, h) = session(); let before = corners(&s); - for (cmd, p) in [ - ("rotate", json!({ "handles": [h], "base": [0, 0], "angle": 30 })), - ("scale", json!({ "handles": [h], "base": [0, 0], "factor": 2 })), - ("mirror", json!({ "handles": [h], "p1": [0, 0], "p2": [1, 0] })), - ] { + for (cmd, p) in + [("rotate", json!({ "handles": [h], "base": [0, 0], "angle": 30 })), ("mirror", json!({ "handles": [h], "p1": [0, 0], "p2": [1, 0] }))] + { let e = s.execute(cmd, &p).expect_err(cmd); assert!(e.to_string().contains("OLE object"), "{cmd}: {e}"); } @@ -180,3 +178,45 @@ fn a_locked_ole_frame_does_not_block_an_in_place_rotation() { let cadcraft_engine::doc::EntityKind::Line(l) = &e.kind else { panic!("line") }; assert!((l.b.y - 10.0).abs() < 1e-9 && l.b.x.abs() < 1e-9, "{l:?}"); } + +/// The four corners (x, y) in the OLE data header, read back from the 310 groups. +fn data_corners(s: &Session) -> Vec<(f64, f64)> { + let hex: String = data_tags(s).concat(); + let bytes: Vec = (0..hex.len() / 2).map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()).collect(); + let f = |o: usize| f64::from_le_bytes(bytes[o..o + 8].try_into().unwrap()); + (0..4).map(|c| (f(2 + c * 24), f(10 + c * 24))).collect() +} + +fn line_in(s: &mut Session) -> String { + let ln = s.execute("line", &json!({ "points": [[1, 2], [4, 6]] })).unwrap(); + ln["handle"].as_str().or_else(|| ln["handles"][0].as_str()).unwrap().to_string() +} + +fn line_ends(s: &Session, h: &str) -> ((f64, f64), (f64, f64)) { + let e = s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(h).unwrap()).unwrap(); + let EntityKind::Line(l) = &e.kind else { panic!("line") }; + ((l.a.x, l.a.y), (l.b.x, l.b.y)) +} + +/// SCALE with a uniform positive factor carries an OLE frame with the rest of the selection: the +/// corner groups and the corners in the OLE data are both mapped (review on #2587). +#[test] +fn scale_carries_an_ole_frame_with_the_rest_of_the_selection() { + let (mut s, h) = data_session(&[10, 100, 40], None); + let ln = line_in(&mut s); + s.execute("scale", &json!({ "handles": [ln.clone(), h], "base": [0, 0], "factor": 2 })).unwrap(); + assert_eq!(line_ends(&s, &ln), ((2.0, 4.0), (8.0, 12.0))); + let want: Vec<(i32, String)> = [(10, "60"), (20, "-38"), (11, "70"), (21, "-44")].iter().map(|(c, v)| (*c, v.to_string())).collect(); + let tags: Vec<(i32, String)> = corners(&s).into_iter().filter(|(c, _)| *c != 310).collect(); + assert_eq!(tags, want); + assert_eq!(data_corners(&s), vec![(60.0, -38.0), (70.0, -38.0), (70.0, -44.0), (60.0, -44.0)]); +} + +/// MOCORO with a scale step carries the frame too, like SCALE. +#[test] +fn mocoro_scales_an_ole_frame() { + let (mut s, h) = data_session(&[10, 100, 40], None); + s.execute("mocoro", &json!({ "handles": [h], "base": [0, 0], "ops": [{ "scale": 3 }] })).unwrap(); + assert_eq!(data_corners(&s)[0], (90.0, -57.0)); + assert_eq!(corners(&s)[0].1, "90"); +} From 8cc2c4e8478b14a2bbdef6dd2be7cff274227e4b Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 15:45:20 +1100 Subject: [PATCH 204/531] OLE2FRAME: corner match has a fixed ceiling at large coordinates (review on #2587) The relative tolerance grew with the coordinate: at 1e9 a payload 0.5 off the frame still matched and was rewritten. It is now capped at CORNER_EPS (1e-6), still above an ulp at 1e9. Tests: a_half_unit_offset_at_large_coordinates_is_not_the_frame, exact_corners_at_large_coordinates_still_move. --- crates/doc/src/extents.rs | 53 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 596a194a5..4eaa0b754 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -75,7 +75,7 @@ fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3, frame // other header is not ours to rewrite. let [x1, y1, x2, y2] = frame; let want = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]; - let near = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0); + let near = |a: f64, b: f64| (a - b).abs() <= (1e-9 * a.abs().max(b.abs()).max(1.0)).min(CORNER_EPS); for (c, (wx, wy)) in want.iter().enumerate() { let at = OLE_HEADER + c * 24; let rd = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes); @@ -109,6 +109,12 @@ fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3, frame } } +/// Ceiling for the tolerance when matching the corners in the OLE data to the frame's. The header +/// holds the same f64 the frame groups print, so they agree to a few ulps; a fixed ceiling keeps +/// distinct geometry from matching at large coordinates, where a relative tolerance would grow to +/// whole units. +const CORNER_EPS: f64 = 1e-6; + /// Move an OLE2FRAME by `m`, a translation or a uniform positive scale: its two corners are mapped through `m` (a DWG save /// writes the frame's position from these groups), and so are the corners at the start of its OLE /// data (310 groups), which a reader of the saved file may trust instead. Other transforms do not keep a frame axis @@ -679,6 +685,51 @@ mod tests { assert!(extents.width() > drawn.width()); } } + /// An OLE2FRAME at large coordinates, with its OLE data header holding the frame's corners + /// shifted by `dx` in x. + fn big_frame(dx: f64) -> Vec { + let (x1, y1, x2, y2) = (1e9, 1e9, 1e9 + 10.0, 1e9 + 5.0); + let mut blob = vec![1u8, 0]; + for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] { + for v in [x + dx, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let tag = |code: i32, value: String| crate::RawTag { code, value }; + vec![ + tag(10, x1.to_string()), + tag(20, y1.to_string()), + tag(11, x2.to_string()), + tag(21, y2.to_string()), + tag(310, blob.iter().map(|b| format!("{b:02X}")).collect()), + ] + } + + /// The x of the first corner in the OLE data of a [`big_frame`]. + fn data_x(tags: &[crate::RawTag]) -> f64 { + let hex = tags.last().map(|t| t.value.as_str()).unwrap_or_default(); + let bytes: Vec = (0..hex.len() / 2).filter_map(|i| u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()).collect(); + bytes.get(2..10).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).unwrap_or(f64::NAN) + } + + /// The match between the frame and the corners in its OLE data does not loosen with the + /// coordinate: half a unit off at 1e9 is not the frame, so the bytes stay as they are (review + /// on #2587). + #[test] + fn a_half_unit_offset_at_large_coordinates_is_not_the_frame() { + let mut tags = big_frame(0.5); + let before = tags.last().cloned(); + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1.0, 1.0))); + assert_eq!(tags.first().map(|t| t.value.as_str()), Some("1000000001"), "the frame tags move"); + assert_eq!(tags.last().map(|t| &t.value), before.as_ref().map(|t| &t.value), "the 310 bytes stay identical"); + } + + #[test] + fn exact_corners_at_large_coordinates_still_move() { + let mut tags = big_frame(0.0); + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1.0, 1.0))); + assert_eq!(data_x(&tags), 1e9 + 1.0); + } /// A translation, and a uniform positive scale about any point, keep a frame axis aligned and /// upper-left; a rotation, a mirror, a non-uniform or non-positive scale do not. From 48165e6cd93f3191794efbd1e5e4d5f82cdf03ea Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 16:15:10 +1100 Subject: [PATCH 205/531] io tests: order the ole_frame module as rustfmt wants after the merge --- crates/io/tests/it/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 29e695875..2ed30c966 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -47,9 +47,9 @@ mod mtext_columns_roundtrip; mod mtext_embedded_object; mod mtext_line_spacing; mod multiline_attributes; -mod ole_frame; #[cfg(not(target_arch = "wasm32"))] mod ole2frame_roundtrip; +mod ole_frame; mod paperview_marker; mod passthrough_image_roundtrip; mod pdf_followups; From f6a97d273f173148d3c7e7884269ef2862a5415f Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:20:28 +0700 Subject: [PATCH 206/531] EXTEND: a polyline extends the end on the pick's side of its middle Measured in AutoCAD 2024 (accoreconsole): EXTEND on an open polyline extends the end on the pick's side of the polyline's middle parameter, not the end vertex nearer the pick. The pick's parameter is the segment it is nearest, counted from 0, plus how far along it; from half the number of segments on, the last end extends. (0,220) (20,220) (20,230) (15,221) picked at (16,220) is 0.8 of 3, so the first end extends, though the last vertex is 1.4 from the pick. A repeated vertex counts as a segment, so the parameter is computed over the vertex pairs rather than Polyline::segments. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 20 ++- .../tests/it/extend_polyline_end_choice.rs | 170 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 3 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 crates/engine/tests/it/extend_polyline_end_choice.rs diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 9f8e856dd..8a2d2e253 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -344,7 +344,25 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re EntityKind::LwPolyline(p) if !p.closed && p.vertices.len() >= 2 => { let mut vs = p.vertices.clone(); let n = vs.len(); - let from_end = vs.last().is_some_and(|l| pick.dist(l.p) < vs.first().map(|f| pick.dist(f.p)).unwrap_or(f64::INFINITY)); + // The pick's parameter: the segment it is nearest, plus how far along it. AutoCAD 2024 + // extends the end on that side of the polyline's middle parameter, the last from the + // middle on, not the end nearer the pick. A repeated vertex counts as a segment, so + // these come from the vertices, not `Polyline::segments`, which skips it. + let at = vs + .windows(2) + .enumerate() + .filter_map(|(i, w)| { + let (a, b) = (w.first()?, w.get(1)?); + let seg = match cadcraft_geom::bulge_to_arc(a.p, b.p, a.bulge) { + Some((arc, ccw)) => Segment::Arc { arc, ccw }, + None => Segment::Line(Line::new(a.p, b.p)), + }; + let c = seg.closest(pick); + Some((c.dist(pick), i as f64 + param_on(&seg, c))) + }) + .min_by(|x, y| x.0.total_cmp(&y.0)) + .map_or(0.0, |(_, t)| t); + let from_end = 2.0 * at >= (n - 1) as f64; let (i_end, i_prev) = if from_end { (n - 1, n - 2) } else { (0, 1) }; let end = vs.get(i_end).map(|v| v.p).unwrap_or_default(); let prev = vs.get(i_prev).map(|v| v.p).unwrap_or_default(); diff --git a/crates/engine/tests/it/extend_polyline_end_choice.rs b/crates/engine/tests/it/extend_polyline_end_choice.rs new file mode 100644 index 000000000..30bd884d0 --- /dev/null +++ b/crates/engine/tests/it/extend_polyline_end_choice.rs @@ -0,0 +1,170 @@ +//! Which end of an open polyline EXTEND runs on, as AutoCAD 2024 chooses it (measured with +//! accoreconsole on these drawings): the end on the pick's side of the polyline's middle parameter. +//! The pick's parameter is the segment it is nearest, counted from 0, plus how far along that +//! segment it is; from half the number of segments on, the last end extends, below it the first. +//! Neither the end vertex nearer the pick nor the length along the polyline decides. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle}; +use serde_json::{Value, json}; + +type Vertex = (f64, f64, f64); + +fn handle(v: &Value) -> String { + v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned() +} + +/// The open polyline `vertices` with lines `edges`, extended at `pick` to the lines; its vertices +/// with their bulges. +fn extended(vertices: &[Vertex], edges: &[([f64; 2], [f64; 2])], pick: [f64; 2]) -> Vec { + let mut s = Session::new(); + let vs: Vec = vertices.iter().map(|(x, y, b)| json!({ "p": [x, y], "bulge": b })).collect(); + let p = handle(&s.execute("pline", &json!({ "vertices": vs, "closed": false })).unwrap()); + let es: Vec = edges.iter().map(|(a, b)| handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())).collect(); + s.execute("extend", &json!({ "handle": p, "pick": pick, "edges": es })).unwrap(); + match &s.doc().unwrap().entity(Handle::parse_hex(&p).unwrap()).unwrap().kind { + EntityKind::LwPolyline(l) => l.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect(), + k => panic!("{k:?}"), + } +} + +fn same(got: &[Vertex], want: &[Vertex]) -> bool { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-6) +} + +/// Vertical lines through x = `xs`, from `y0` to `y1`. +fn at(xs: &[f64], y0: f64, y1: f64) -> Vec<([f64; 2], [f64; 2])> { + xs.iter().map(|x| ([*x, y0], [*x, y1])).collect() +} + +fn flat(pts: &[(f64, f64)]) -> Vec { + pts.iter().map(|(x, y)| (*x, *y, 0.0)).collect() +} + +#[test] +fn the_end_on_the_picks_side_of_the_middle_parameter_extends() { + // (name, vertices, edges, pick, the vertices AutoCAD leaves). Lines at both ends, so either + // end could extend. + let cases: Vec<(&str, Vec, Vec<([f64; 2], [f64; 2])>, [f64; 2], Vec<(f64, f64)>)> = vec![ + // 1.2 of 3 segments: the first end, though the pick is on a vertex of the middle one. + ( + "1.2 of 3", + flat(&[(0.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)]), + at(&[-5.0, 25.0], 155.0, 170.0), + [10.0, 161.0], + vec![(-5.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)], + ), + // 0.8: the first end, though the last vertex is nearer the pick. + ( + "0.8, last vertex nearer", + flat(&[(0.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)]), + vec![([-5.0, 215.0], [-5.0, 235.0]), ([0.0, 210.0], [30.0, 210.0])], + [16.0, 220.0], + vec![(-5.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)], + ), + ( + "0.2", + flat(&[(0.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)]), + vec![([-5.0, 235.0], [-5.0, 255.0]), ([-10.0, 230.0], [30.0, 230.0])], + [4.0, 240.0], + vec![(-5.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)], + ), + ( + "1.9", + flat(&[(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (4.0, 280.0)]), + at(&[-5.0, 10.0], 255.0, 285.0), + [2.0, 278.0], + vec![(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (10.0, 280.0)], + ), + // 0.9: the first end, though 18 of the 22 units along is nearer the last. + ( + "0.9, length nearer the last", + flat(&[(0.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)]), + at(&[-5.0, 25.0], 295.0, 305.0), + [18.0, 300.0], + vec![(-5.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)], + ), + ( + "1.1", + flat(&[(0.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)]), + at(&[-5.0, 10.0], 315.0, 345.0), + [2.0, 322.0], + vec![(-5.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)], + ), + ( + "1.25", + flat(&[(0.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)]), + at(&[-5.0, 40.0], 395.0, 425.0), + [30.0, 405.0], + vec![(-5.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)], + ), + ( + "1.75", + flat(&[(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (31.0, 460.0)]), + at(&[-5.0, 40.0], 435.0, 465.0), + [1.0, 455.0], + vec![(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (40.0, 460.0)], + ), + ("0.6 of 1", flat(&[(0.0, 480.0), (20.0, 480.0)]), at(&[-5.0, 25.0], 475.0, 485.0), [12.0, 480.0], vec![(0.0, 480.0), (25.0, 480.0)]), + // 1.8 of 4, the end of the segment picked: the first end. + ( + "1.8 of 4", + flat(&[(0.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)]), + vec![([-5.0, 495.0], [-5.0, 525.0]), ([15.0, 530.0], [25.0, 530.0])], + [10.0, 508.0], + vec![(-5.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)], + ), + ( + "2.8 of 4", + flat(&[(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 560.0)]), + vec![([-5.0, 535.0], [-5.0, 565.0]), ([15.0, 570.0], [25.0, 570.0])], + [18.0, 550.0], + vec![(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 570.0)], + ), + // Right on the middle parameter, 1.5 of 3: the last end. + ( + "1.5 of 3", + flat(&[(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (20.0, 610.0)]), + at(&[-5.0, 25.0], 595.0, 615.0), + [10.0, 605.0], + vec![(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (25.0, 610.0)], + ), + ]; + for (name, vertices, edges, pick, want) in cases { + let got = extended(&vertices, &edges, pick); + assert!(same(&got, &flat(&want)), "{name}: {got:?}"); + } +} + +#[test] +fn the_parameter_runs_along_an_arc_segment_too() { + // The middle segment an arc of bulge -18, swinging round to within 2 of the first vertex: + // picked 60% along it (1.6 of 3), 3.6 from the first vertex and 18.3 from the last, the last + // end extends. + let got = extended( + &[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (20.0, 1.0, 0.0)], + &at(&[-5.0, 25.0], -10.0, 10.0), + [1.804081304825758, 3.0714821777453793], + ); + assert!(same(&got, &[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (25.0, 1.0, 0.0)]), "{got:?}"); + // The end segment an arc of bulge -0.5: picked on it (1.6 of 2) the last end runs on round + // its circle to x = 14.3; the same polyline turned round, picked on its first segment (0.4), + // the first end does. + let got = extended(&[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5), (14.0, 40.0, 0.0)], &at(&[14.3], 30.0, 50.0), [12.0, 41.0]); + assert!(same(&got, &[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5776771824075506), (14.3, 39.47979589711327, 0.0)]), "{got:?}"); + let got = extended(&[(0.0, 60.0, -0.5), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)], &at(&[-0.3], 50.0, 70.0), [2.0, 61.0]); + assert!(same(&got, &[(-0.3, 59.47979589711327, -0.5776771824075504), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)]), "{got:?}"); +} + +#[test] +fn a_repeated_vertex_counts_as_a_segment() { + // (10, 0) twice: three segments, the middle one of no length. Picked on (10, 0), the end of + // the first, 1.0 of 3: the first end extends (counting two segments it would be the last). + // Picked 1 up the last segment, 2.1 of 3: the last end. + let vs = flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)]); + let edges = vec![([-5.0, -10.0], [-5.0, 10.0]), ([-10.0, 15.0], [20.0, 15.0])]; + let got = extended(&vs, &edges, [10.0, 0.0]); + assert!(same(&got, &flat(&[(-5.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)])), "{got:?}"); + let got = extended(&vs, &edges, [10.0, 1.0]); + assert!(same(&got, &flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 15.0)])), "{got:?}"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 9e014d4b1..f0ac7d623 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -48,6 +48,7 @@ mod dynamic_block_data; mod dynamic_grips; mod explode_stretched; mod extend_polyline_arc_end; +mod extend_polyline_end_choice; mod fillet_chamfer; mod fix_holds_grips; mod followups_626; From 0a0a820759852c7017f38e59b3e26a3394bbb595 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 16:36:05 +1100 Subject: [PATCH 207/531] OLE2FRAME: any transform leaves the frame axis-aligned and its data consistent (review on #2587) EXPLODE, REFEDIT, paste and array placement call EntityKind::transform with rotations and mirrors, which left groups 10/20 not upper-left and the data header not matching. ole_frame_transform now takes the box of the two mapped corners (upper-left, lower-right) and writes the header as UL, UR, LR, LL of that box. Test: a_rotated_frame_stays_axis_aligned_and_consistent (rotate 30 and mirror). --- crates/doc/src/extents.rs | 72 ++++++++++++++++++++++++++++++++------- 1 file changed, 60 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 4eaa0b754..5e52f5a1f 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -49,9 +49,10 @@ const OLE_HEADER: usize = 2; /// lower right, lower left). const OLE_CORNERS: usize = 12; -/// Move the four corners at the start of the OLE data (the 310 groups' hex, in order) by `m`, -/// keeping z and every tag's length. Data that is not valid hex or is too short is left alone. -fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3, frame: [f64; 4]) { +/// Replace the four corners at the start of the OLE data (the 310 groups' hex, in order) by `new` +/// (upper left, upper right, lower right, lower left), keeping z and every tag's length. Data that +/// is not valid hex, too short, or whose corners are not the old `frame`'s is left alone. +fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4]) { let idx: Vec = outside_app(tags).into_iter().filter(|&i| tags.get(i).is_some_and(|t| t.code == 310)).collect(); let mut bytes: Vec = Vec::new(); let mut lens: Vec = Vec::new(); @@ -88,11 +89,10 @@ fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3, frame for c in 0..4 { let at = OLE_HEADER + c * 24; let rd = |o: usize| out.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).filter(|v| v.is_finite()); - let (Some(x), Some(y)) = (rd(at), rd(at + 8)) else { return }; - let p = m.apply(Vec2::new(x, y)); - if !(p.x.is_finite() && p.y.is_finite()) { + if rd(at).is_none() || rd(at + 8).is_none() { return; } + let Some(p) = new.get(c).copied() else { return }; if let Some(s) = out.get_mut(at..at + 8) { s.copy_from_slice(&p.x.to_le_bytes()); } @@ -115,10 +115,12 @@ fn ole_data_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3, frame /// whole units. const CORNER_EPS: f64 = 1e-6; -/// Move an OLE2FRAME by `m`, a translation or a uniform positive scale: its two corners are mapped through `m` (a DWG save -/// writes the frame's position from these groups), and so are the corners at the start of its OLE -/// data (310 groups), which a reader of the saved file may trust instead. Other transforms do not keep a frame axis -/// aligned, so callers refuse them (see [`ole_frame_accepts`]). A frame with no usable corners is +/// Transform an OLE2FRAME by `m`: its two corners are mapped through `m` (a DWG save writes the +/// frame's position from these groups), and so are the corners at the start of its OLE data (310 +/// groups), which a reader of the saved file may trust instead. The frame stays axis aligned with +/// its upper-left corner first: the result is the box of the two mapped corners. Commands refuse a +/// rotation or mirror (see [`ole_frame_accepts`]), but internal callers such as EXPLODE, REFEDIT and +/// paste still apply them, and must leave a consistent frame. A frame with no usable corners is /// left alone. pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { let Some([(ix1, x1), (iy1, y1), (ix2, x2), (iy2, y2)]) = ole_corner_groups(tags) else { return }; @@ -127,12 +129,14 @@ pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) if !(a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { return; } - for (i, v) in [(ix1, a.x), (iy1, a.y), (ix2, b.x), (iy2, b.y)] { + let (lo, hi) = (Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y))); + let (ul, lr) = (Vec2::new(lo.x, hi.y), Vec2::new(hi.x, lo.y)); + for (i, v) in [(ix1, ul.x), (iy1, ul.y), (ix2, lr.x), (iy2, lr.y)] { if let Some(t) = tags.get_mut(i) { t.value = v.to_string(); } } - ole_data_transform(tags, m, frame); + ole_data_transform(tags, [ul, Vec2::new(lr.x, ul.y), lr, Vec2::new(ul.x, lr.y)], frame); } /// Whether `m` can move an OLE2FRAME: a translation (move, copy, stretch of the whole frame) or a @@ -746,4 +750,48 @@ mod tests { assert!(!ole_frame_accepts(&Mat3::rotate_about(p, 0.5))); assert!(!ole_frame_accepts(&Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)))); } + /// The corners (x, y) in the OLE data header of a frame built by [`big_frame`]-style tags. + fn header_corners(tags: &[crate::RawTag]) -> Vec<(f64, f64)> { + let hex: String = tags.iter().filter(|t| t.code == 310).map(|t| t.value.as_str()).collect(); + let bytes: Vec = (0..hex.len() / 2).filter_map(|i| u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()).collect(); + let f = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).unwrap_or(f64::NAN); + (0..4).map(|c| (f(2 + c * 24), f(10 + c * 24))).collect() + } + + fn small_frame() -> Vec { + let mut blob = vec![1u8, 0]; + for (x, y) in [(30.0f64, -19.0f64), (35.0, -19.0), (35.0, -22.0), (30.0, -22.0)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() }; + vec![ + tag(10, "30"), + tag(20, "-19"), + tag(11, "35"), + tag(21, "-22"), + crate::RawTag { code: 310, value: blob.iter().map(|b| format!("{b:02X}")).collect() }, + ] + } + + /// Internal callers (EXPLODE, REFEDIT, paste, array placement) transform a frame by any matrix. + /// It stays axis aligned: groups 10/20 are the upper-left of the box of the mapped corners, + /// 11/21 the lower-right, and the OLE data holds the same box (review on #2587). + #[test] + fn a_rotated_frame_stays_axis_aligned_and_consistent() { + use cadcraft_geom::Mat3; + let rotate = Mat3::rotate_about(Vec2::new(1.0, 2.0), 30f64.to_radians()); + let mirror = Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)); + for m in [rotate, mirror] { + let mut tags = small_frame(); + let mapped = [m.apply(Vec2::new(30.0, -19.0)), m.apply(Vec2::new(35.0, -22.0))]; + let (minx, maxx) = (mapped[0].x.min(mapped[1].x), mapped[0].x.max(mapped[1].x)); + let (miny, maxy) = (mapped[0].y.min(mapped[1].y), mapped[0].y.max(mapped[1].y)); + ole_frame_transform(&mut tags, &m); + let g = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.parse::().ok()).unwrap_or(f64::NAN); + assert_eq!((g(10), g(20), g(11), g(21)), (minx, maxy, maxx, miny)); + assert_eq!(header_corners(&tags), vec![(minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny)]); + } + } } From be413af02691c5ce7b3d5ab9474ab1e33021c03c Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 16:37:51 +1100 Subject: [PATCH 208/531] OLE2FRAME: arrays refuse before adding copies; clearer refusal (review on #2587) ARRAYPATH with align and polar arrays that rotate items refused part way, leaving the earlier copies in the drawing. Every copy's matrix is now checked before the first copy is made. The refusal text names the other unsupported transforms. Test: arraypath_refuses_before_adding_any_copy. --- crates/engine/src/cmd/array.rs | 10 ++++++++-- crates/engine/src/cmd/modify/transform.rs | 2 +- crates/engine/src/cmd/modify2/patharray.rs | 13 +++++++++++-- crates/engine/tests/ole_frame_transform.rs | 16 ++++++++++++++++ 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index da96ccfed..5fc16b310 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -247,9 +247,15 @@ fn max_count(s: &Session, others: u64, objs: usize) -> u64 { } fn copy_all(s: &mut Session, hs: &[Handle], mats: impl Iterator) -> Result { + // Every copy is checked before the first is made: a refusal part way would leave the copies + // already added in the drawing (a failed command is not rolled back). + let mats: Vec = mats.collect(); + for m in &mats { + super::modify::refuse_ole_frames(s, hs, m, true)?; + } let mut n = 0; - for m in mats { - n += transform_entities(s, hs, &m, true)?.len(); + for m in &mats { + n += transform_entities(s, hs, m, true)?.len(); } Ok(n) } diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index d1e6a463e..2fad5ee7b 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -37,7 +37,7 @@ pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool }; if hs.iter().any(ole) { return Err(crate::EngineError::Other( - "An OLE object can only be moved, copied or scaled uniformly; rotating and mirroring it are not supported.".into(), + "An OLE object can only be moved, copied or scaled uniformly; other transforms (rotation, mirroring, non-uniform scale, alignment) are not supported.".into(), )); } Ok(()) diff --git a/crates/engine/src/cmd/modify2/patharray.rs b/crates/engine/src/cmd/modify2/patharray.rs index 3f9445249..aff058ab5 100644 --- a/crates/engine/src/cmd/modify2/patharray.rs +++ b/crates/engine/src/cmd/modify2/patharray.rs @@ -35,14 +35,23 @@ pub(crate) fn arraypath( }; crate::cmd::array::check_size(s, n as u64, objs.len())?; let Some((p0, t0)) = c.at_length(0.0) else { return Ok(Vec::new()) }; - let mut out = Vec::new(); + let mut mats = Vec::new(); for i in 1..n { let Some((p, t)) = c.at_length(step * i as f64) else { continue }; let mut m = Mat3::translate(p - p0); if align { m = Mat3::rotate_about(p, t.angle() - t0.angle()).then_before(m); } - out.extend(crate::cmd::modify::transform_entities(s, &objs, &m, true)?); + mats.push(m); + } + // Every copy is checked before the first is made: a refusal part way would leave the copies + // already added in the drawing (a failed command is not rolled back). + for m in &mats { + crate::cmd::modify::refuse_ole_frames(s, &objs, m, true)?; + } + let mut out = Vec::new(); + for m in &mats { + out.extend(crate::cmd::modify::transform_entities(s, &objs, m, true)?); } Ok(out) } diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index 2578c4e18..3569d39e5 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -220,3 +220,19 @@ fn mocoro_scales_an_ole_frame() { assert_eq!(data_corners(&s)[0], (90.0, -57.0)); assert_eq!(corners(&s)[0].1, "90"); } + +/// ARRAYPATH with align rotates each copy, which an OLE frame refuses. The refusal comes before +/// the first copy is added: an error does not roll the drawing back (review on #2587). +#[test] +fn arraypath_refuses_before_adding_any_copy() { + let (mut s, h) = session(); + // Straight for 30 units, then a right-angle bend: the first copies only move, a later one turns. + let path = s.execute("pline", &json!({ "points": [[0, 0], [30, 0], [30, 30]] })).unwrap(); + let path = path["handle"].as_str().or_else(|| path["handles"][0].as_str()).unwrap().to_string(); + let count = s.doc().unwrap().model.len(); + let before = corners(&s); + let e = s.execute("arraypath", &json!({ "handles": [h], "path": path, "count": 7, "align": true })).expect_err("align"); + assert!(e.to_string().contains("OLE object"), "{e}"); + assert_eq!(s.doc().unwrap().model.len(), count, "no copy was added"); + assert_eq!(corners(&s), before); +} From 457627df33ffcfa1bf94219b304c4e912b45b516 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 16:44:30 +1100 Subject: [PATCH 209/531] OLE2FRAME: validate hex strictly, rewrite only the header groups, cheaper corner lookup (review on #2587) A sign in a hex pair is no longer accepted; only the 310 groups holding the 98-byte header are decoded and rewritten, in place and without cloning the payload; the corner lookup is one allocation-free pass; the io ole_frame test module is not built for wasm like its DWG siblings; Unknown::is_ole_frame replaces five copies of the type check. Tests: a_plus_sign_in_ole_data_is_not_hex, a_large_ole_payload_only_rewrites_its_leading_groups. --- apps/cadcraft-cli/src/output.rs | 2 +- crates/doc/src/entity.rs | 9 +- crates/doc/src/extents.rs | 137 ++++++++++++++++------ crates/engine/src/cmd/modify/transform.rs | 2 +- crates/io/tests/it/main.rs | 1 + crates/render/src/draw.rs | 2 +- 6 files changed, 110 insertions(+), 43 deletions(-) diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index f1c742ed3..46283753e 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -167,7 +167,7 @@ pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> // An OLE2FRAME's frame outline is drawn, so it isn't an undrawn entity; its content is // not, which gets a note of its own. if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind { - if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") && cadcraft_engine::doc::ole_frame(&u.tags).is_some() { + if u.is_ole_frame() && cadcraft_engine::doc::ole_frame(&u.tags).is_some() { ole = ole.saturating_add(1); continue; } diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 33111e832..1237463f1 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -60,6 +60,13 @@ pub struct Unknown { pub tags: Vec, } +impl Unknown { + /// Whether this is an OLE2FRAME (the type name is matched without regard to case). + pub fn is_ole_frame(&self) -> bool { + self.dxf_type.eq_ignore_ascii_case("OLE2FRAME") + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum EntityKind { @@ -465,7 +472,7 @@ impl EntityKind { let a = if mirror { t.rotation() } else { t.rotation() + rot }; t.dir = Vec2::from_angle(cadcraft_geom::norm_angle(a)).to3(0.0); } - EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => crate::ole_frame_transform(&mut u.tags, m), + EntityKind::Unknown(u) if u.is_ole_frame() => crate::ole_frame_transform(&mut u.tags, m), EntityKind::Unknown(_) => {} } } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 5e52f5a1f..7713395a4 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -11,28 +11,40 @@ pub const MAX_BLOCK_DEPTH: usize = 16; /// Positions in `tags` of the groups outside application-defined `102 {` .. `102 }` groups, whose /// codes are the application's own and not the entity's. -fn outside_app(tags: &[crate::RawTag]) -> Vec { +fn outside_app(tags: &[crate::RawTag]) -> impl Iterator + '_ { let mut in_app = false; - let mut out = Vec::new(); - for (i, t) in tags.iter().enumerate() { + tags.iter().enumerate().filter_map(move |(i, t)| { if t.code == 102 { in_app = t.value.starts_with('{'); - } else if !in_app { - out.push(i); + None + } else { + (!in_app).then_some(i) } - } - out + }) } -/// The positions of the frame's corner groups 10, 20, 11, 21 (in that order) and their values. +/// The positions of the frame's corner groups 10, 20, 11, 21 (in that order) and their values: +/// the first of each outside application groups, found in one pass that stops at the last. fn ole_corner_groups(tags: &[crate::RawTag]) -> Option<[(usize, f64); 4]> { - let own = outside_app(tags); - let find = |code: i32| { - let i = own.iter().copied().find(|&i| tags.get(i).is_some_and(|t| t.code == code))?; - let v = tags.get(i)?.value.trim().parse::().ok().filter(|v| v.is_finite())?; - Some((i, v)) - }; - Some([find(10)?, find(20)?, find(11)?, find(21)?]) + let mut found: [Option<(usize, f64)>; 4] = [None; 4]; + for i in outside_app(tags) { + let Some(t) = tags.get(i) else { continue }; + let slot = match t.code { + 10 => 0, + 20 => 1, + 11 => 2, + 21 => 3, + _ => continue, + }; + if let Some(f) = found.get_mut(slot).filter(|f| f.is_none()) { + *f = Some((i, t.value.trim().parse::().ok().filter(|v| v.is_finite())?)); + if found.iter().all(Option::is_some) { + break; + } + } + } + let [Some(a), Some(b), Some(c), Some(d)] = found else { return None }; + Some([a, b, c, d]) } /// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right @@ -50,26 +62,34 @@ const OLE_HEADER: usize = 2; const OLE_CORNERS: usize = 12; /// Replace the four corners at the start of the OLE data (the 310 groups' hex, in order) by `new` -/// (upper left, upper right, lower right, lower left), keeping z and every tag's length. Data that -/// is not valid hex, too short, or whose corners are not the old `frame`'s is left alone. +/// (upper left, upper right, lower right, lower left), keeping z and every group's length and +/// letter case. Only the groups that cover the header are decoded and rewritten; the rest of the +/// payload is not touched. Data that is not valid hex, too short, or whose corners are not the old +/// `frame`'s is left alone. fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4]) { - let idx: Vec = outside_app(tags).into_iter().filter(|&i| tags.get(i).is_some_and(|t| t.code == 310)).collect(); - let mut bytes: Vec = Vec::new(); - let mut lens: Vec = Vec::new(); - for &i in &idx { + const END: usize = OLE_HEADER + OLE_CORNERS * 8; + let mut bytes: Vec = Vec::with_capacity(END); + // The groups read, and how many leading bytes of each belong to the header. + let mut spans: Vec<(usize, usize)> = Vec::new(); + for i in outside_app(tags).filter(|&i| tags.get(i).is_some_and(|t| t.code == 310)) { + if bytes.len() >= END { + break; + } let Some(t) = tags.get(i) else { return }; let s = t.value.trim(); if s.len() % 2 != 0 || !s.is_ascii() { return; } - for k in (0..s.len()).step_by(2) { - let Some(b) = s.get(k..k + 2).and_then(|h| u8::from_str_radix(h, 16).ok()) else { return }; + let take = (s.len() / 2).min(END - bytes.len()); + for k in 0..take { + // `from_str_radix` also takes a sign, so each digit is checked first. + let Some(h) = s.get(2 * k..2 * k + 2).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) else { return }; + let Ok(b) = u8::from_str_radix(h, 16) else { return }; bytes.push(b); } - lens.push(s.len() / 2); + spans.push((i, take)); } - let end = OLE_HEADER + OLE_CORNERS * 8; - if bytes.len() < end { + if bytes.len() < END { return; } // Only data whose corners are this frame's corners (UL, UR, LR, LL) has the layout above; any @@ -85,26 +105,23 @@ fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4 return; } } - let mut out = bytes.clone(); - for c in 0..4 { + for (c, p) in new.iter().enumerate() { let at = OLE_HEADER + c * 24; - let rd = |o: usize| out.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).filter(|v| v.is_finite()); - if rd(at).is_none() || rd(at + 8).is_none() { - return; - } - let Some(p) = new.get(c).copied() else { return }; - if let Some(s) = out.get_mut(at..at + 8) { + if let Some(s) = bytes.get_mut(at..at + 8) { s.copy_from_slice(&p.x.to_le_bytes()); } - if let Some(s) = out.get_mut(at + 8..at + 16) { + if let Some(s) = bytes.get_mut(at + 8..at + 16) { s.copy_from_slice(&p.y.to_le_bytes()); } } let mut pos = 0; - for (&i, &n) in idx.iter().zip(&lens) { - let (Some(t), Some(chunk)) = (tags.get_mut(i), out.get(pos..pos + n)) else { return }; + for (i, n) in spans { + let (Some(t), Some(chunk)) = (tags.get_mut(i), bytes.get(pos..pos + n)) else { return }; let lower = t.value.bytes().any(|b| b.is_ascii_lowercase()); - t.value = chunk.iter().map(|b| if lower { format!("{b:02x}") } else { format!("{b:02X}") }).collect(); + let hex: String = chunk.iter().map(|b| if lower { format!("{b:02x}") } else { format!("{b:02X}") }).collect(); + // Leave any padding around the digits, and the digits after the header, as they were. + let start = t.value.len() - t.value.trim_start().len(); + t.value.replace_range(start..start + 2 * n, &hex); pos += n; } } @@ -410,7 +427,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } EntityKind::LwPolyline(p) => lwpolyline_bounds(p), // An OLE object's content is not drawn, but its frame is, so the frame counts (#2422). - EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points), + EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points), kind => { let mut b = Bounds2::EMPTY; for p in kind.prims() { @@ -794,4 +811,46 @@ mod tests { assert_eq!(header_corners(&tags), vec![(minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny)]); } } + /// `from_str_radix` accepts a leading sign, so "+A" must not count as a hex byte (review on + /// #2587): data with one is not valid and MOVE leaves its bytes alone. + #[test] + fn a_plus_sign_in_ole_data_is_not_hex() { + let mut tags = small_frame(); + let hex = tags.last().map(|t| t.value.clone()).unwrap_or_default(); + // The marker's first byte is 01: "+1" would decode to the same byte. + let signed = format!("+1{}", hex.get(2..).unwrap_or_default()); + if let Some(t) = tags.last_mut() { + t.value = signed.clone(); + } + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0))); + assert_eq!(tags.first().map(|t| t.value.as_str()), Some("40"), "the frame tags still move"); + assert_eq!(tags.last().map(|t| t.value.as_str()), Some(signed.as_str())); + } + + /// A payload of 1,000 groups of 127 bytes: only the group(s) holding the 98-byte header are + /// rewritten. Later groups stay as they were, even ones that are not valid hex or have padding + /// (the old code re-encoded the whole payload and gave up on any bad group). + #[test] + fn a_large_ole_payload_only_rewrites_its_leading_groups() { + let mut tags = small_frame(); + let first = tags.pop().map(|t| t.value).unwrap_or_default(); + let mut head = first.clone(); + // Fill the first group up to 127 bytes. + head.push_str(&"ab".repeat(127 - first.len() / 2)); + tags.push(crate::RawTag { code: 310, value: head }); + for g in 1..1000 { + let value = match g { + 2 => format!(" {} ", "Ab".repeat(127)), + 500 => "ZZ".repeat(127), + _ => "ab".repeat(127), + }; + tags.push(crate::RawTag { code: 310, value }); + } + let rest: Vec = tags.iter().skip(5).map(|t| t.value.clone()).collect(); + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0))); + assert_eq!(header_corners(&tags[..5]), vec![(40.0, -14.0), (45.0, -14.0), (45.0, -17.0), (40.0, -17.0)]); + let after: Vec = tags.iter().skip(5).map(|t| t.value.clone()).collect(); + assert_eq!(after, rest, "every group after the first is string-identical"); + assert_eq!(tags.get(4).map(|t| t.value.len()), Some(254), "the first group keeps its length"); + } } diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 2fad5ee7b..219468f93 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -32,7 +32,7 @@ pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool d.entity(*h).is_some_and(|e| { // An in-place edit skips an object on a locked layer (see edit_entities), so it cannot be refused. let locked = !copy && d.layer(&e.common.layer).is_some_and(|l| l.locked); - !locked && matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME")) + !locked && matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.is_ole_frame()) }) }; if hs.iter().any(ole) { diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 2ed30c966..55b96bdc8 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -49,6 +49,7 @@ mod mtext_line_spacing; mod multiline_attributes; #[cfg(not(target_arch = "wasm32"))] mod ole2frame_roundtrip; +#[cfg(not(target_arch = "wasm32"))] mod ole_frame; mod paperview_marker; mod passthrough_image_roundtrip; diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index abfe536e8..3b1b6bbbb 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -235,7 +235,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { } } // An OLE object's content is not drawn; its frame, from its two corner points, is. - EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => { + EntityKind::Unknown(u) if u.is_ole_frame() => { if let Some(q) = cadcraft_doc::ole_frame(&u.tags) { b.polyline(ctx, rgb, lw, &q); } From 1b7cf50fbe962a624127cc9ea9ad99d018dafb64 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:15:56 +0700 Subject: [PATCH 210/531] Arc points a hair outside the sweep take the nearer end EXTEND, TRIM, BREAK, DIVIDE and MEASURE place a point on an arc segment by its angle from the arc's start. A point the closest-point search accepts just before the start (within the 1e-12 sweep tolerance) wrapped round to nearly a full turn and was clamped to the far end: - EXTEND on a polyline picked there extended the wrong end; - TRIM put a second cut at the far end of an arc span when a cutting edge ran through the vertex where the span starts (63 of 400 angles through that vertex on main), and took out the arc alone; - DIVIDE and MEASURE ran from the wrong end. `curves::seg_param` now sends an angle outside the sweep to the nearer end. TRIM's `param_on` is that function, and EXTEND takes its pick parameter from `curves::vertex_param_of`, the walk DIVIDE uses. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/curves.rs | 12 +++++- crates/engine/src/cmd/draw2/tests.rs | 19 +++++++++ crates/engine/src/cmd/modify/trim.rs | 27 ++---------- .../tests/it/extend_polyline_end_choice.rs | 17 ++++++++ crates/engine/tests/it/main.rs | 1 + .../it/trim_cut_where_an_arc_span_starts.rs | 42 +++++++++++++++++++ 6 files changed, 93 insertions(+), 25 deletions(-) create mode 100644 crates/engine/tests/it/trim_cut_where_an_arc_span_starts.rs diff --git a/crates/engine/src/cmd/curves.rs b/crates/engine/src/cmd/curves.rs index ca918834a..d98612f67 100644 --- a/crates/engine/src/cmd/curves.rs +++ b/crates/engine/src/cmd/curves.rs @@ -546,7 +546,17 @@ pub fn seg_param(s: &Segment, p: Vec2) -> f64 { match s { Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0), Segment::Arc { arc, ccw } => { - let t = (cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15)).clamp(0.0, 1.0); + // A point just outside the sweep (on the arc within tolerance of an end) goes to the + // nearer end: a hair before the start is the start, not round the circle to the end. + let a = cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start); + let sweep = arc.sweep().max(1e-15); + let t = if a <= sweep { + a / sweep + } else if a - sweep < TAU - a { + 1.0 + } else { + 0.0 + }; if *ccw { t } else { 1.0 - t } } } diff --git a/crates/engine/src/cmd/draw2/tests.rs b/crates/engine/src/cmd/draw2/tests.rs index efad025ca..94c8bde92 100644 --- a/crates/engine/src/cmd/draw2/tests.rs +++ b/crates/engine/src/cmd/draw2/tests.rs @@ -601,6 +601,25 @@ fn measure_spline_by_its_own_parameter() { assert!(pts.len() == 3 && [7.0, 4.0, 1.0].iter().all(|x| pts.iter().any(|p| near(*p, *x, 0.0))), "{pts:?}"); } +/// A pick a hair outside an arc's sweep beside its start is at its start, for an arc and for a +/// polyline's arc span alike: MEASURE runs from there (round the circle it was the far end). +#[test] +fn measure_from_a_pick_a_hair_before_an_arcs_start() { + let curves = [ + ("arc", json!({"center": [0, 0], "radius": 1, "start": 0, "end": 180})), + ("pline", json!({"vertices": [{"p": [1, 0], "bulge": 1}, [-1, 0]]})), + ]; + for (cmd, args) in curves { + let mut s = Session::new(); + let e = h(&s.execute(cmd, &args).unwrap()); + s.execute("measure", &json!({"handle": e, "length": 1, "from": [1, -1e-13]})).unwrap(); + let pts: Vec = + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p.xy()) } else { None }).collect(); + // From (1, 0), a point every radian. + assert!(pts.len() == 3 && [1.0f64, 2.0, 3.0].iter().all(|a| pts.iter().any(|p| near(*p, a.cos(), a.sin()))), "{cmd}: {pts:?}"); + } +} + /// MEASURE counts every vertex in a polyline's parameter, coincident ones too (AutoCAD's polyline /// parameter is the vertex index; the chain drops zero-length spans), and picks an ellipse's end /// by the ellipse parameter like any other curve: AutoCAD 2024 runs both measured cases below from diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 8a2d2e253..d584da50b 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -272,16 +272,7 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> R Ok(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect()) } -pub(super) fn param_on(s: &Segment, p: Vec2) -> f64 { - match s { - Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0), - Segment::Arc { arc, ccw } => { - let t = norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15); - let t = t.clamp(0.0, 1.0); - if *ccw { t } else { 1.0 - t } - } - } -} +pub(super) use crate::cmd::curves::seg_param as param_on; /// A polyline arc segment on `ga`'s circle that ends at `end` after turning through `sweep` /// (signed, positive counterclockwise), run on round the circle to the nearest boundary edge: the @@ -348,20 +339,8 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re // extends the end on that side of the polyline's middle parameter, the last from the // middle on, not the end nearer the pick. A repeated vertex counts as a segment, so // these come from the vertices, not `Polyline::segments`, which skips it. - let at = vs - .windows(2) - .enumerate() - .filter_map(|(i, w)| { - let (a, b) = (w.first()?, w.get(1)?); - let seg = match cadcraft_geom::bulge_to_arc(a.p, b.p, a.bulge) { - Some((arc, ccw)) => Segment::Arc { arc, ccw }, - None => Segment::Line(Line::new(a.p, b.p)), - }; - let c = seg.closest(pick); - Some((c.dist(pick), i as f64 + param_on(&seg, c))) - }) - .min_by(|x, y| x.0.total_cmp(&y.0)) - .map_or(0.0, |(_, t)| t); + let spans: Vec<_> = vs.windows(2).filter_map(|w| Some((w.first()?.p, w.get(1)?.p, w.first()?.bulge))).collect(); + let at = crate::cmd::curves::vertex_param_of(&spans, pick); let from_end = 2.0 * at >= (n - 1) as f64; let (i_end, i_prev) = if from_end { (n - 1, n - 2) } else { (0, 1) }; let end = vs.get(i_end).map(|v| v.p).unwrap_or_default(); diff --git a/crates/engine/tests/it/extend_polyline_end_choice.rs b/crates/engine/tests/it/extend_polyline_end_choice.rs index 30bd884d0..c314f123c 100644 --- a/crates/engine/tests/it/extend_polyline_end_choice.rs +++ b/crates/engine/tests/it/extend_polyline_end_choice.rs @@ -168,3 +168,20 @@ fn a_repeated_vertex_counts_as_a_segment() { let got = extended(&vs, &edges, [10.0, 1.0]); assert!(same(&got, &flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 15.0)])), "{got:?}"); } + +#[test] +fn a_pick_a_hair_outside_an_arc_end_counts_as_that_end() { + // A single semicircle from (1, 0) to (-1, 0). Picked 1e-13 outside its sweep at the first + // vertex, the pick is on the arc's start, not round the circle at its end: the first end runs + // on to x = 0, three quarters of the way round. + let b = 1.0 + 2f64.sqrt(); + let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [1.0, -1e-13]); + assert!(same(&got, &[(0.0, -1.0, b), (-1.0, 0.0, 0.0)]), "{got:?}"); + // A hair past its end is the last end. + let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [-1.0, -1e-13]); + assert!(same(&got, &[(1.0, 0.0, b), (0.0, -1.0, 0.0)]), "{got:?}"); + // Turning clockwise, the arc's start angle is the polyline's last vertex: a hair outside it is + // the last end. + let got = extended(&[(1.0, 0.0, -1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], 0.5, 2.0), [-1.0, 1e-13]); + assert!(same(&got, &[(1.0, 0.0, -b), (0.0, 1.0, 0.0)]), "{got:?}"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f0ac7d623..5db7f8d12 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -158,6 +158,7 @@ mod text_left_justify; mod tolerance; mod transparent; mod trim_closed_polyline; +mod trim_cut_where_an_arc_span_starts; mod trim_extend_options; mod undo_count; mod undo_layout_tab; diff --git a/crates/engine/tests/it/trim_cut_where_an_arc_span_starts.rs b/crates/engine/tests/it/trim_cut_where_an_arc_span_starts.rs new file mode 100644 index 000000000..63dc562c2 --- /dev/null +++ b/crates/engine/tests/it/trim_cut_where_an_arc_span_starts.rs @@ -0,0 +1,42 @@ +//! TRIM on a polyline cut through the vertex where an arc span starts: the cut is at that vertex +//! only. Where the crossing came out a hair before the arc's start angle it was also put at the +//! arc's far end, round the circle, and TRIM took out the arc alone. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +fn handle(v: serde_json::Value) -> String { + v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned() +} + +#[test] +fn the_cut_is_at_the_arc_spans_start_vertex_only() { + // (0, 0) to (10, 0), a semicircle round (15, 5) to (10, 10), then on to (0, 10). A line + // through (10, 0) running up to the left crosses the top span at x = 10 + 10 cot(angle); + // picked on the arc, the polyline goes from (10, 0) to there. + for k in 0..172 { + let th = (91.0 + f64::from(k) * 0.25).to_radians(); + let d = [th.cos() * 30.0, th.sin() * 30.0]; + let mut s = Session::new(); + let p = handle(s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [10, 0], "bulge": 1 }, [10, 10], [0, 10]] })).unwrap()); + let e = handle(s.execute("line", &json!({ "points": [[10.0 - d[0], -d[1]], [10.0 + d[0], d[1]]] })).unwrap()); + s.execute("trim", &json!({ "handle": p, "pick": [15, 5], "edges": [e] })).unwrap(); + let pieces: Vec> = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::LwPolyline(l) => Some(l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()), + _ => None, + }) + .collect(); + let x = 10.0 + 10.0 / th.tan(); + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6; + let ok = pieces.len() == 2 + && pieces.iter().any(|v| v.len() == 2 && near(v[0], (0.0, 0.0)) && near(v[1], (10.0, 0.0))) + && pieces.iter().any(|v| v.len() == 2 && near(v[0], (x, 10.0)) && near(v[1], (0.0, 10.0))); + assert!(ok, "{:.2} degrees: {pieces:?}", th.to_degrees()); + } +} From e8408851cddf7e5ef94d69344a77c52e4f4dcde9 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 3 Nov 2026 11:17:59 +0400 Subject: [PATCH 211/531] docs: the Georgian face paragraph describes glyph support only Choosing ka, its English fallback and the picker name come with the language PR (#2016), which registers ka; this PR alone doesn't. Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 4 ++-- docs/localization.md | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 91c2982f9..d10d43abb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,9 +188,9 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr` and `el`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar` and `hu`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the -optional craft-fonts input or the operating system; Georgian needs the craft-fonts Georgian (`Geor`) face. Without a suitable font, the saved choice is +optional craft-fonts input or the operating system. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts `{"interfaceLanguage":"uk"}`; `ui.inspect` reports the saved choice in its UI state. Invalid choices leave the current language unchanged. Menus, command labels and prompt text diff --git a/docs/localization.md b/docs/localization.md index 1d6a71ae6..4c9baef0c 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -104,9 +104,8 @@ Hangul can't be shown. This change does not fix platform IME issues or localize The bundled egui fonts have no Georgian letters. Georgian is drawn with the Noto Sans Georgian face (`Geor`) of the craft-fonts build input, which release builds embed (`craft-fonts-ref` in the workflows, and `web-craft-fonts` for the web build, whose embedded faces include it). The face loads -in every interface language, so the picker shows **ქართული**. A build without craft-fonts keeps the -saved `ka` choice but shows the interface in English, names the language **Georgian** in the picker, -and the language command reports that a Georgian font is needed. +in every interface language, so Georgian text (file, layout and layer names, labels) draws. A build +without craft-fonts has no Georgian face. ## Greek (`el`) interface From f9cb70500dd0a189690f6bc475e38e0d03104290 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 3 Nov 2026 11:17:59 +0400 Subject: [PATCH 212/531] docs: Georgian font fallback in the Georgian section Co-Authored-By: Claude Opus 5.5 --- docs/localization.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/localization.md b/docs/localization.md index ee6b1fc0b..cb175cba9 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -132,6 +132,12 @@ the meaning of each English string, with Georgian technical-drawing vocabulary ( მომრგვალება, ფასკა, წანაცვლება, ობიექტზე მიბმა, ხედვის არე); terminology and doubtful strings were decided by a native Georgian speaker (@devius). No other product's localization was consulted. +egui's bundled faces have no Georgian letters, so Georgian is drawn with the craft-fonts Noto Sans +Georgian (`Geor`) face, which loads in every interface language when a build embeds it; the picker +then shows **ქართული**. A build without that face keeps the saved `ka` choice but shows the interface +in English, names the language **Georgian** in the picker, and the language command reports that a +Georgian font is needed. + ## Adding translations The implementation follows the display-time catalog pattern used by From 0722afc5bdbafe3c69b1d12d6a1eaa1612acd775 Mon Sep 17 00:00:00 2001 From: mkzung <103102868+mkzung@users.noreply.github.com> Date: Mon, 2 Nov 2026 18:09:37 +0000 Subject: [PATCH 213/531] DWG: keep opaque registered entities and their source classes --- crates/doc/src/foreign.rs | 24 + crates/dwg/Cargo.toml | 1 + crates/dwg/src/lib.rs | 6 + crates/dwg/src/proxy_transport.rs | 445 ++++++++++++++++++ crates/engine/src/cmd/file.rs | 4 + crates/engine/tests/save_reports_not_saved.rs | 17 + crates/io/src/dxf_raw.rs | 58 ++- crates/io/tests/registered_proxy.rs | 189 ++++++++ xtask/src/layers.rs | 4 +- 9 files changed, 739 insertions(+), 9 deletions(-) create mode 100644 crates/dwg/src/proxy_transport.rs create mode 100644 crates/io/tests/registered_proxy.rs diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 406f4e12b..0386739b5 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -55,6 +55,8 @@ impl ForeignExtra { pub struct Foreign { /// CLASS records (groups after `0 CLASS`) of the kept objects' and entities' types. pub classes: Vec>, + /// Classes retain every source position, including duplicate names. + pub complete_class_table: bool, /// Kept objects, in file order. pub objects: Vec, /// Entries of the named object dictionary that CADCraft doesn't write itself: (key, object). @@ -78,6 +80,28 @@ pub struct Foreign { } impl Foreign { + /// a standard proxy entity whose exact source CLASS can be written back. + pub fn preserves_proxy_entity(&self, tags: &[RawTag]) -> bool { + if !self.complete_class_table { + return false; + } + let mut depth = 0usize; + for tag in tags.iter().take_while(|t| t.code < 1000) { + if tag.code == 102 { + let value = tag.value.trim(); + if value.starts_with('{') { + depth = depth.saturating_add(1); + } else if value == "}" { + depth = depth.saturating_sub(1); + } + } else if tag.code == 91 && depth == 0 { + let class = tag.value.trim().parse::().ok().and_then(|n| n.checked_sub(500)).and_then(|i| self.classes.get(i)); + return class.is_some_and(|c| c.iter().any(|t| t.code == 281 && t.value.trim() == "1")); + } + } + false + } + pub fn is_empty(&self) -> bool { self.objects.is_empty() && self.dictionary.is_empty() diff --git a/crates/dwg/Cargo.toml b/crates/dwg/Cargo.toml index 23d1c82d2..5e6e67a51 100644 --- a/crates/dwg/Cargo.toml +++ b/crates/dwg/Cargo.toml @@ -17,3 +17,4 @@ log = { workspace = true } [target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dependencies] # MPL-2.0: used as an unmodified dependency only (see plan/adr/0001 and NOTICE). acadrust = "0.6.6" +cadcraft-dxf = { workspace = true } diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index f143b7be8..55aaa464f 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -66,6 +66,8 @@ fn mb(n: u64) -> String { pub mod worker; #[cfg(not(no_dwg_bridge))] pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_noted, serve_if_asked, use_own_worker, use_worker}; +#[cfg(not(no_dwg_bridge))] +mod proxy_transport; #[cfg(not(no_dwg_bridge))] mod native { @@ -107,6 +109,7 @@ mod native { } let mut notes = read_notes(&outcome.stats); let mut doc = outcome.document; + guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|_| "the DWG proxy conversion failed".to_string())??; let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|_| "the DWG post-processing failed on this file".to_string())?; if orphans > 0 { let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; @@ -734,6 +737,7 @@ mod native { mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } + let classes = super::proxy_transport::read_classes(dxf)?; let data = dxf.to_vec(); let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? @@ -746,6 +750,8 @@ mod native { None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, None => {} } + guarded(AssertUnwindSafe(|| super::proxy_transport::restore_classes(&mut doc, classes))) + .map_err(|_| "the DXF proxy class conversion failed".to_string())??; // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. let unwritten = guarded(AssertUnwindSafe(|| { super::fail_in_test("convert"); diff --git a/crates/dwg/src/proxy_transport.rs b/crates/dwg/src/proxy_transport.rs new file mode 100644 index 000000000..8139f5c0d --- /dev/null +++ b/crates/dwg/src/proxy_transport.rs @@ -0,0 +1,445 @@ +//! Opaque application records use the source file's class table, never decoder defaults. + +use std::collections::{HashMap, HashSet}; + +use acadrust::CadDocument; +use acadrust::classes::{DxfClass, ProxyFlags}; +use acadrust::entities::{EntityType, ExtendedEntityData, ProxyEntityData}; +use acadrust::objects::{ObjectType, ProxyPayload}; +use cadcraft_dxf::Tag; + +fn class_number(index: usize) -> Result { + index.checked_add(500).and_then(|n| i16::try_from(n).ok()).ok_or_else(|| "DXF: too many application classes".into()) +} + +/// Replace the dependency's private registered-class envelope with a standard proxy. +pub(super) fn prepare(doc: &mut CadDocument) -> Result<(), String> { + let classes: Vec<_> = doc.classes.iter().cloned().collect(); + let mut numbers = HashMap::new(); + let mut identities = HashMap::new(); + for (index, class) in classes.iter().enumerate() { + let number = class_number(index)?; + numbers.entry(i32::from(class.class_number)).and_modify(|v| *v = None).or_insert(Some(i32::from(number))); + let identity = (class.dxf_name.as_str(), class.cpp_class_name.as_str(), class.is_an_entity); + identities.entry(identity).and_modify(|v| *v = None).or_insert(Some(number)); + } + let identity = |dxf: &str, cpp: &str, entity: bool| { + identities + .get(&(dxf, cpp, entity)) + .copied() + .flatten() + .map(i32::from) + .ok_or_else(|| format!("DWG: missing or ambiguous application CLASS for {dxf} ({cpp})")) + }; + let source = doc.dwg_source_version.unwrap_or(doc.version).version_code(); + let dwg_version = match source { + 1012 => 19, + 1014 => 21, + 1015 => 23, + 1018 => 25, + 1021 => 27, + 1024 => 29, + 1027 => 31, + 1032 => 33, + _ => return Ok(()), + }; + let maintenance = i32::from(doc.maintenance_version); + let remap = |id: i32| numbers.get(&id).copied().flatten().ok_or_else(|| format!("DWG: proxy names missing application class {id}")); + // Only mutate proxies: entities_mut invalidates the decoder's verbatim records for every entity. + let handles: Vec<_> = doc + .entities() + .filter_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(_) => Some(e.common.handle), + ExtendedEntityData::RegisteredClass(data) if data.properties.is_empty() || data.payload.bit_count > 0 => Some(e.common.handle), + _ => None, + }, + _ => None, + }) + .collect(); + for handle in handles { + let text_payload = match doc.get_entity(handle) { + Some(EntityType::Extended(e)) if matches!(e.data, ExtendedEntityData::RegisteredClass(_)) => { + if let ExtendedEntityData::RegisteredClass(data) = &e.data + && !data.properties.is_empty() + { + return Err(format!("DWG: cannot transport semantic properties of {} as an opaque proxy", data.dxf_name)); + } + e.common.raw_record.as_deref().map(registered_text).transpose()?.unwrap_or_default() + } + _ => ProxyPayload::default(), + }; + let Some(EntityType::Extended(entity)) = doc.get_entity_mut(handle) else { continue }; + match &mut entity.data { + ExtendedEntityData::Proxy(data) => data.class_id = remap(data.class_id)?, + ExtendedEntityData::RegisteredClass(data) => { + let class_id = identity(&data.dxf_name, &data.cpp_class_name, true)?; + entity.data = ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id, + dxf_subclass: String::new(), + version: (maintenance << 16) | dwg_version, + dwg_version, + maintenance_version: maintenance, + from_dxf: false, + graphics: ProxyPayload::from_bytes(entity.common.graphic_data.as_deref().unwrap_or_default()), + payload: data.payload.clone(), + text_payload, + object_ids: data.object_ids.clone(), + }); + } + _ => {} + } + } + for object in doc.objects.values_mut() { + if let ObjectType::ProxyObject(proxy) = object { + proxy.class_id = remap(proxy.class_id)?; + } + } + Ok(()) +} + +/// The decoder's registered-class representation omits the separate R2007+ string stream. +fn registered_text(raw: &acadrust::entities::RawRecord) -> Result { + use acadrust::io::dwg::DwgVersion; + use acadrust::io::dwg::dwg_stream_readers::object_reader::DwgObjectReader; + use acadrust::io::dwg::dwg_stream_writers::bit_writer::DwgBitWriter; + use acadrust::types::DxfVersion; + + if raw.version < DxfVersion::AC1021 { + return Ok(ProxyPayload::default()); + } + let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| format!("DWG proxy text: {e}"))?; + let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "DWG proxy text: negative handle stream size")?; + let total_bits = raw.data.len().checked_mul(8).ok_or("DWG proxy text: record too large")?; + if handle_bits > total_bits { + return Err("DWG proxy text: handle stream exceeds record".into()); + } + // Frame the verbatim record for the dependency's checked object reader. + let mut frame = DwgBitWriter::new(version, raw.version); + frame.write_modular_short(raw.data.len()); + if raw.version >= DxfVersion::AC1024 { + frame.write_modular_char(handle_bits); + } + frame.write_bytes(&raw.data); + let reader = DwgObjectReader::new(frame.into_bytes(), raw.version, HashMap::new()).map_err(|e| format!("DWG proxy text: {e}"))?; + let (kind, mut streams) = reader.read_record_at(0).map_err(|e| format!("DWG proxy text: {e}"))?; + reader.read_common_entity_data(&mut streams, kind); + if kind == 498 { + // An existing registered-class envelope is a proxy and carries its class name first. + streams.read_variable_text(); + } else if kind < 500 { + return Err("DWG proxy text: registered entity has no application class".into()); + } + streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?; + let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "DWG proxy text: negative string stream size")?; + if bits > total_bits { + return Err("DWG proxy text: string stream exceeds record".into()); + } + let count = u32::try_from(bits).map_err(|_| "DWG proxy text: string stream too large")?; + let mut bytes = vec![0; bits.div_ceil(8)]; + for (index, byte) in bytes.iter_mut().enumerate() { + for bit in 0..8.min(bits.saturating_sub(index * 8)) { + if streams.read_text_bit() { + *byte |= 0x80 >> bit; + } + } + } + streams.check_error().map_err(|e| format!("DWG proxy text: {e}"))?; + Ok(ProxyPayload::from_bits(&bytes, count)) +} + +/// Parse ASCII or binary DXF with the bounded, code-page-aware DXF parser. +pub(super) fn read_classes(dxf: &[u8]) -> Result, String> { + let tags = cadcraft_dxf::parse(dxf).map_err(|e| format!("DXF classes: {e}"))?; + let mut classes = Vec::new(); + let mut in_classes = false; + let mut at = 0; + while let Some(tag) = tags.get(at) { + if tag.code != 0 { + at += 1; + continue; + } + let end = tags.get(at + 1..).unwrap_or_default().iter().position(|t| t.code == 0).map_or(tags.len(), |n| at + 1 + n); + let body = tags.get(at + 1..end).unwrap_or_default(); + match tag.str().as_str() { + "SECTION" => in_classes = body.first().is_some_and(|t| t.code == 2 && t.str() == "CLASSES"), + "ENDSEC" => in_classes = false, + "CLASS" if in_classes => classes.push(read_class(body, class_number(classes.len())?)?), + _ => {} + } + at = end; + } + Ok(classes) +} + +fn read_class(tags: &[Tag], number: i16) -> Result { + let text = |code| tags.iter().find(|t| t.code == code).map(Tag::str).unwrap_or_default(); + let integer = |code| tags.iter().find(|t| t.code == code).map_or(0, Tag::i64); + let mut class = DxfClass::new(text(1), text(2)); + if class.dxf_name.is_empty() || class.cpp_class_name.is_empty() { + return Err("DXF: application CLASS has no name".into()); + } + class.application_name = text(3); + class.proxy_flags = ProxyFlags(u16::try_from(integer(90)).map_err(|_| "DXF: invalid class proxy flags")?); + class.instance_count = i32::try_from(integer(91)).map_err(|_| "DXF: invalid class instance count")?; + class.was_zombie = integer(280) != 0; + class.is_an_entity = integer(281) != 0; + class.item_class_id = if class.is_an_entity { 498 } else { 499 }; + class.class_number = number; + Ok(class) +} + +/// Keep source class positions and metadata, adding missing decoder defaults only afterwards. +pub(super) fn restore_classes(doc: &mut CadDocument, classes: Vec) -> Result<(), String> { + let mut proxies = Vec::new(); + for entity in doc.entities() { + if let EntityType::Extended(e) = entity + && let ExtendedEntityData::Proxy(p) = &e.data + { + proxies.push((p.class_id, true)); + } + } + for object in doc.objects.values() { + if let ObjectType::ProxyObject(p) = object { + proxies.push((p.class_id, false)); + } + } + if proxies.is_empty() { + return Ok(()); + } + for (number, entity) in proxies { + let index = number.checked_sub(500).and_then(|n| usize::try_from(n).ok()); + if !index.and_then(|i| classes.get(i)).is_some_and(|c| c.is_an_entity == entity) { + return Err(format!("DXF: proxy names missing or incompatible application class {number}")); + } + } + if doc.version < acadrust::types::DxfVersion::AC1027 { + return Err("DWG: preserving application proxies requires AutoCAD 2013 or later; choose 2013/2018 DWG or DXF".into()); + } + let mut names: HashSet<_> = classes.iter().map(|c| c.dxf_name.to_uppercase()).collect(); + let defaults: Vec<_> = doc.classes.iter().filter(|c| names.insert(c.dxf_name.to_uppercase())).cloned().collect(); + doc.classes.clear(); + for mut class in classes.into_iter().chain(defaults) { + class.class_number = class_number(doc.classes.len())?; + doc.classes.push_preserving(class); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use acadrust::entities::{EntityCommon, ExtendedEntity, RegisteredClassEntityData}; + use acadrust::types::DxfVersion; + + fn proxy_doc() -> CadDocument { + let mut doc = CadDocument::new(); + doc.version = DxfVersion::AC1032; + doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id: 501, + dxf_subclass: String::new(), + version: 33, + dwg_version: 33, + maintenance_version: 0, + from_dxf: false, + graphics: ProxyPayload::default(), + payload: ProxyPayload::from_bits(&[0x80], 1), + text_payload: ProxyPayload::default(), + object_ids: vec![], + }), + }))) + .unwrap(); + doc + } + + #[test] + fn source_classes_keep_duplicates_and_metadata_before_defaults() { + let tags = vec![ + Tag::s(0, "SECTION"), + Tag::s(2, "CLASSES"), + Tag::s(0, "CLASS"), + Tag::s(1, "Объект"), + Tag::s(2, "First"), + Tag::s(3, "Первый"), + Tag::i(90, 1025), + Tag::i(91, 7), + Tag::i(280, 1), + Tag::i(281, 1), + Tag::s(0, "CLASS"), + Tag::s(1, "Объект"), + Tag::s(2, "Second"), + Tag::s(3, "Второй"), + Tag::i(90, 128), + Tag::i(281, 1), + Tag::s(0, "ENDSEC"), + Tag::s(0, "EOF"), + ]; + for bytes in [cadcraft_dxf::write_ascii(&tags).into_bytes(), cadcraft_dxf::write_binary(&tags, true)] { + let classes = read_classes(&bytes).unwrap(); + assert_eq!(classes.len(), 2); + assert_eq!(classes[0].application_name, "Первый"); + assert_eq!(classes[0].proxy_flags.0, 1025); + assert_eq!(classes[0].instance_count, 7); + assert!(classes[0].was_zombie); + let mut doc = proxy_doc(); + restore_classes(&mut doc, classes.clone()).unwrap(); + assert_eq!(doc.classes.iter().take(2).cloned().collect::>(), classes); + } + } + + #[test] + fn missing_negative_and_object_class_ids_are_rejected() { + for id in [-1, 499, 501, i32::MAX] { + let mut doc = proxy_doc(); + if let Some(EntityType::Extended(e)) = doc.entities_mut().next() + && let ExtendedEntityData::Proxy(p) = &mut e.data + { + p.class_id = id; + } + let mut class = DxfClass::new_entity("ENTITY", "Entity"); + class.class_number = 500; + assert!(restore_classes(&mut doc, vec![class]).is_err()); + } + assert!(restore_classes(&mut proxy_doc(), vec![DxfClass::new("A", "A"), DxfClass::new("B", "B")]).is_err()); + } + + #[test] + fn opaque_registered_class_ambiguity_is_not_guessed() { + let mut doc = CadDocument::new(); + doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom")); + doc.classes.push_preserving(DxfClass::new_entity("CUSTOM", "Custom")); + doc.add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "CUSTOM".into(), + cpp_class_name: "Custom".into(), + properties: vec![], + payload: ProxyPayload::from_bits(&[0x80], 1), + object_ids: vec![], + }), + }))) + .unwrap(); + assert!(prepare(&mut doc).unwrap_err().contains("ambiguous")); + assert!(class_number(usize::MAX).is_err()); + } + #[test] + fn semantic_records_keep_their_verbatim_data_and_mixed_payloads_are_rejected() { + use acadrust::entities::RawRecord; + use acadrust::objects::{SemanticProperty, SemanticPropertyValue}; + for payload in [ProxyPayload::default(), ProxyPayload::from_bits(&[0x80], 1)] { + let mut doc = CadDocument::new(); + let raw = RawRecord { data: vec![0xAA], handle_bits: 0, version: DxfVersion::AC1032 }; + let handle = doc + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "SEMANTIC".into(), + cpp_class_name: "Semantic".into(), + properties: vec![SemanticProperty { + subclass: "Semantic".into(), + code: 1, + value: SemanticPropertyValue::Text("value".into()), + }], + payload: payload.clone(), + object_ids: vec![], + }), + }))) + .unwrap(); + doc.get_entity_mut(handle).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone())); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + if payload.bit_count == 0 { + prepare(&mut doc).unwrap(); + assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); + } else { + assert!(prepare(&mut doc).unwrap_err().contains("semantic properties")); + } + } + } +} + +#[cfg(test)] +mod string_stream_tests { + use super::*; + use acadrust::entities::{EntityCommon, ExtendedEntity, RawRecord, RegisteredClassEntityData}; + use acadrust::types::DxfVersion; + use std::io::Cursor; + + #[test] + fn registered_transport_recovers_separate_non_byte_aligned_strings() { + for version in [DxfVersion::AC1027, DxfVersion::AC1032] { + let mut source = CadDocument::new(); + source.version = version; + source.classes.add_or_update(DxfClass::new_entity("CUSTOM_TEXT", "CustomText")); + let class_id = i32::from(source.classes.get_by_name("CUSTOM_TEXT").unwrap().class_number); + let text = ProxyPayload::from_bits(&[0xA5, 0xC7, 0xE0], 19); + let payload = ProxyPayload::from_bits(&[0x80], 1); + source + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon::default(), + data: ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id, + dxf_subclass: "CustomText".into(), + version: 33, + dwg_version: 33, + maintenance_version: 0, + from_dxf: false, + graphics: ProxyPayload::default(), + payload: payload.clone(), + text_payload: text.clone(), + object_ids: vec![], + }), + }))) + .unwrap(); + let bytes = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + let mut decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let entity = decoded.entities().next().unwrap(); + let handle = entity.common().handle; + let raw = entity.common().raw_record.clone().unwrap(); + assert_eq!(registered_text(&raw).unwrap().data(), text.data()); + assert_eq!(registered_text(&raw).unwrap().bit_count, 19); + let EntityType::Extended(entity) = decoded.get_entity_mut(handle).unwrap() else { panic!() }; + entity.data = ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "CUSTOM_TEXT".into(), + cpp_class_name: "CustomText".into(), + properties: vec![], + payload: payload.clone(), + object_ids: vec![], + }); + entity.common.raw_record = Some(raw); + prepare(&mut decoded).unwrap(); + for _ in 0..2 { + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&decoded).write_to_writer(&mut dxf).unwrap(); + let bytes = crate::dxf_to_dwg_as(&dxf, "AC1032").unwrap(); + decoded = acadrust::DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let p = decoded + .entities() + .find_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(p) => Some(p), + _ => None, + }, + _ => None, + }) + .unwrap(); + assert_eq!(p.payload.bit_count, 1); + assert_eq!(p.payload.data(), payload.data()); + assert_eq!(p.text_payload.bit_count, 19); + assert_eq!(p.text_payload.data(), text.data()); + } + } + } + + #[test] + fn invalid_string_stream_boundaries_return_errors() { + for handle_bits in [-1, 1000] { + let raw = RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 }; + assert!(registered_text(&raw).is_err()); + } + } +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 76a53da46..7d8164106 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -772,6 +772,10 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap if DWG_WRITES.contains(&u.dxf_type.as_str()) { continue; } + // A valid proxy keeps its opaque data and source class in modern DWG. + if version >= Version::R2013 && u.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") && d.foreign.preserves_proxy_entity(&u.tags) { + continue; + } let n = out.entry(u.dxf_type.clone()).or_insert(0); *n = n.saturating_add(1); } diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 80192bf53..5ba1c1f73 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -241,3 +241,20 @@ fn ole_objects_are_not_reported() { assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}"); } } + +#[test] +fn retained_proxy_is_not_reported_as_lost_in_modern_dwg() { + use cadcraft_engine::cmd::file::{Version, not_saved_as}; + let mut drawing = Drawing::new_metric(); + let tags = vec![RawTag { code: 91, value: "500".into() }]; + drawing.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags })).unwrap(); + let foreign = std::sync::Arc::make_mut(&mut drawing.foreign); + foreign.complete_class_table = true; + foreign.classes = vec![vec![RawTag { code: 1, value: "CUSTOM".into() }, RawTag { code: 281, value: "1".into() }]]; + assert!(not_saved_as(&drawing, Version::R2013).is_empty()); + assert!(not_saved_as(&drawing, Version::R2018).is_empty()); + assert_eq!(not_saved_as(&drawing, Version::R2010).get("ACAD_PROXY_ENTITY"), Some(&1)); + std::sync::Arc::make_mut(&mut drawing.foreign).classes.clear(); + assert_eq!(not_saved_as(&drawing, Version::R2018).get("ACAD_PROXY_ENTITY"), Some(&1)); + +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 1a2c8696b..524507a1b 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -417,10 +417,11 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { } } if proxies { + f.complete_class_table = classes.iter().filter(|(k, _, _)| k == "CLASS").count() <= MAX_OBJECTS; f.class_order = class_order; } for (kind, _, t) in &classes { - if kind == "CLASS" && val(t, 1).is_some_and(|n| types.contains(&up(&n))) && f.classes.len() < MAX_OBJECTS { + if kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS { f.classes.push(t.iter().map(raw).collect()); } } @@ -656,6 +657,8 @@ pub(crate) fn unknown_entity(u: &Unknown, e: &Entity, owner: &str, paper: bool) } _ if in_group => continue, 5 | 67 => continue, + // After a subclass marker, 330 can be proxy data even without a source owner. + 100 => owner_seen = true, 330 if !owner_seen => { owner_seen = true; continue; @@ -873,7 +876,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap| class_index(old).and_then(|i| f.class_order.get(i)).and_then(|n| numbers.get(n).copied()); + let renumber = |old| proxy_class_number(f, &numbers, old); // Entities of types CADCraft doesn't model, placed among the written ones. let mut planned = plan_unknown(d, &recs, tags, &roles, modern); for list in planned.values_mut() { @@ -969,11 +972,8 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap, d: &Drawing, reactors: &HashMap, old: Option) -> Option { + if f.complete_class_table { + class_index(old).filter(|&i| i < f.classes.len()).and(old) + } else { + class_index(old).and_then(|i| f.class_order.get(i)).and_then(|n| numbers.get(n).copied()) + } +} + +/// Source classes precede decoder-owned classes so proxy positions stay stable. +fn source_class_record(f: &Foreign, record: &Rec, recs: &[Rec], tags: &[Tag], class_names: &HashSet, out: &mut Vec) -> bool { + if record.sec != "CLASSES" { + return false; + } + if !f.complete_class_table { + if record.kind == "ENDSEC" { + for class in f.classes.iter().filter(|c| c.iter().find(|t| t.code == 1).is_some_and(|n| !class_names.contains(&up(&n.value)))) { + out.push(Tag::s(0, "CLASS")); + out.extend(class.iter().map(tag)); + } + } + return false; + } + if record.kind == "CLASS" { + return true; + } + if record.kind != "ENDSEC" { + return false; + } + for class in &f.classes { + out.push(Tag::s(0, "CLASS")); + out.extend(class.iter().map(tag)); + } + let source_names: HashSet<_> = f.classes.iter().filter_map(|c| c.iter().find(|t| t.code == 1)).map(|t| up(&t.value)).collect(); + for class in recs.iter().filter(|r| r.sec == "CLASSES" && r.kind == "CLASS") { + let body = tags.get(class.start + 1..class.end).unwrap_or_default(); + if val(body, 1).is_some_and(|n| !source_names.contains(&up(&n))) { + out.push(Tag::s(0, "CLASS")); + out.extend_from_slice(body); + } + } + false +} + /// Where the entities of types CADCraft doesn't model go: each before the next written entity of /// its space or block (else at the end of it), as `(section, record)` lists by the index of the /// record they precede. Owners come from the written block records. diff --git a/crates/io/tests/registered_proxy.rs b/crates/io/tests/registered_proxy.rs new file mode 100644 index 000000000..d50c078ab --- /dev/null +++ b/crates/io/tests/registered_proxy.rs @@ -0,0 +1,189 @@ +//! Synthetic application data must keep its identity as well as its bytes. +#![cfg(not(target_arch = "wasm32"))] +use acadrust::classes::DxfClass; +use acadrust::entities::{EntityCommon, EntityType, ExtendedEntity, ExtendedEntityData, Line, RegisteredClassEntityData}; +use acadrust::objects::{ProxyObjectReference, ProxyPayload, ProxyReferenceKind}; +use acadrust::types::{DxfVersion, Vector3}; +use cadcraft_doc::EntityKind; +use cadcraft_io::{SaveOptions, Version}; +use std::io::Cursor; + +fn source(version: DxfVersion) -> Vec { + source_payload(version, ProxyPayload::from_bits(&[0xA5, 0x80], 9)) +} + +fn source_payload(version: DxfVersion, payload: ProxyPayload) -> Vec { + let mut document = acadrust::CadDocument::new(); + document.version = version; + document.classes.add_or_update(DxfClass::new_entity("SPDSNOTEPOSITION", "mcsDbObjectNotePosition")); + let target = document.add_entity(EntityType::Line(Line::from_points(Vector3::ZERO, Vector3::new(10.0, 0.0, 0.0)))).unwrap(); + document + .add_entity(EntityType::Extended(Box::new(ExtendedEntity { + common: EntityCommon { graphic_data: Some(vec![0x12, 0x34, 0x56]), ..Default::default() }, + data: ExtendedEntityData::RegisteredClass(RegisteredClassEntityData { + dxf_name: "SPDSNOTEPOSITION".into(), + cpp_class_name: "mcsDbObjectNotePosition".into(), + properties: vec![], + payload, + object_ids: vec![ProxyObjectReference { kind: ProxyReferenceKind::HardPointer, handle: target }], + }), + }))) + .unwrap(); + acadrust::DwgWriter::write_to_vec(&document).unwrap() +} + +fn check(bytes: &[u8], name: &str) -> cadcraft_doc::Drawing { + let drawing = cadcraft_io::read(bytes, name).unwrap(); + assert_eq!(drawing.entity_count(), 2); + let line = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle; + let unknown = drawing + .model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Unknown(u) => Some(u), + _ => None, + }) + .unwrap(); + assert!(unknown.tags.iter().any(|t| t.code == 340 && t.value == line.hex())); + let dxf = if name.ends_with(".dwg") { cadcraft_dwg::dwg_to_dxf(bytes).unwrap() } else { bytes.to_vec() }; + let tags = cadcraft_dxf::parse(&dxf).unwrap(); + let sections = cadcraft_dxf::sections(&tags); + let classes = sections.iter().find(|s| s.name == "CLASSES").unwrap(); + let classes = cadcraft_dxf::records(&classes.tags); + let decoded = acadrust::DxfReader::from_reader(Cursor::new(dxf)).unwrap().read().unwrap(); + let proxy = decoded + .entities() + .find_map(|e| match e { + EntityType::Extended(e) => match &e.data { + ExtendedEntityData::Proxy(p) => Some(p), + _ => None, + }, + _ => None, + }) + .unwrap(); + assert_eq!(proxy.payload.bit_count, 9); + assert_eq!(proxy.payload.data(), [0xA5, 0x80]); + assert_eq!(proxy.graphics.data(), [0x12, 0x34, 0x56]); + let class = classes.get(usize::try_from(proxy.class_id - 500).unwrap()).unwrap(); + assert!(class.1.iter().any(|t| t.code == 1 && t.str() == "SPDSNOTEPOSITION")); + assert!(class.1.iter().any(|t| t.code == 2 && t.str() == "mcsDbObjectNotePosition")); + drawing +} + +#[test] +fn opaque_registered_entities_survive_repeated_saves_with_their_original_class() { + for source_version in [DxfVersion::AC1015, DxfVersion::AC1027, DxfVersion::AC1032] { + let input = source(source_version); + let initial = check(&input, "source.dwg"); + for target in [Version::R2013, Version::R2018] { + for name in ["copy.dxf", "copy.dwg"] { + let mut drawing = initial.clone(); + for _ in 0..3 { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(target), ..Default::default() }).unwrap(); + drawing = check(&bytes, name); + } + } + } + } +} + +#[test] +fn legacy_dwg_rejects_proxy_loss_while_legacy_dxf_retains_the_data() { + let drawing = check(&source(DxfVersion::AC1032), "source.dwg"); + for target in [Version::R2000, Version::R2004, Version::R2007, Version::R2010] { + let options = SaveOptions { version: Some(target), ..Default::default() }; + let error = cadcraft_io::write_with(&drawing, "old.dwg", &options).unwrap_err().to_string(); + assert!(error.contains("2013"), "{error}"); + let bytes = cadcraft_io::write_with(&drawing, "old.dxf", &options).unwrap(); + check(&bytes, "old.dxf"); + } +} + +fn duplicate_class_dxf() -> Vec { + let mut text = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n"); + for (cpp, entity, flags) in [("First", 1, 1025), ("Second", 1, 128), ("Object", 0, 17)] { + text.push_str(&format!("0\nCLASS\n1\nCUSTOM\n2\n{cpp}\n3\nSynthetic\n90\n{flags}\n91\n1\n280\n1\n281\n{entity}\n")); + } + text.push_str("0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n10\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n0\n20\n0\n11\n10\n21\n0\n"); + for (handle, class) in [("20", 500), ("21", 501)] { + text.push_str(&format!("0\nACAD_PROXY_ENTITY\n5\n{handle}\n100\nAcDbEntity\n8\n0\n100\nAcDbProxyEntity\n90\n498\n91\n{class}\n92\n0\n93\n9\n310\nA580\n330\n10\n340\n10\n350\n10\n360\n10\n94\n0\n95\n33\n70\n0\n")); + } + text.push_str("0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n3\nCUSTOM_OBJECT\n350\n30\n0\nACAD_PROXY_OBJECT\n5\n30\n330\nC\n100\nAcDbProxyObject\n90\n499\n91\n502\n93\n9\n310\nA580\n340\n10\n94\n0\n95\n33\n70\n0\n0\nENDSEC\n0\nEOF\n"); + text.into_bytes() +} + +#[test] +fn duplicate_names_keep_distinct_classes_for_entities_and_dictionary_objects() { + let source = duplicate_class_dxf(); + for binary in [false, true] { + let input = if binary { cadcraft_dxf::write_binary(&cadcraft_dxf::parse(&source).unwrap(), true) } else { source.clone() }; + let mut drawing = cadcraft_io::read(&input, "source.dxf").unwrap(); + for _ in 0..3 { + for name in ["copy.dxf", "copy.dwg"] { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let dxf = if name.ends_with(".dwg") { cadcraft_dwg::dwg_to_dxf(&bytes).unwrap() } else { bytes.clone() }; + let tags = cadcraft_dxf::parse(&dxf).unwrap(); + let sections = cadcraft_dxf::sections(&tags); + let classes = cadcraft_dxf::records(§ions.iter().find(|s| s.name == "CLASSES").unwrap().tags); + let custom: Vec<_> = classes.iter().filter(|(_, t)| t.iter().any(|t| t.code == 1 && t.str() == "CUSTOM")).collect(); + assert_eq!(custom.len(), 3); + for (class, (cpp, flags)) in custom.iter().zip([("First", 1025), ("Second", 128), ("Object", 17)]) { + assert!(class.1.iter().any(|t| t.code == 2 && t.str() == cpp)); + assert!(class.1.iter().any(|t| t.code == 90 && t.i64() == flags)); + assert!(class.1.iter().any(|t| t.code == 3 && t.str() == "Synthetic")); + assert!(class.1.iter().any(|t| t.code == 280 && t.i64() == 1)); + } + let records: Vec<_> = + sections.iter().flat_map(|s| cadcraft_dxf::records(&s.tags)).filter(|(kind, _)| kind.starts_with("ACAD_PROXY_")).collect(); + assert_eq!(records.len(), 3); + let mut identities = Vec::new(); + for (_, tags) in &records { + let id = tags.iter().find(|t| t.code == 91).unwrap().i64(); + identities.push(classes[usize::try_from(id - 500).unwrap()].1.iter().find(|t| t.code == 2).unwrap().str()); + assert!(tags.iter().any(|t| matches!(t.code, 93 | 161) && t.i64() == 9), "{name}: {tags:?}"); + assert!(tags.iter().any(|t| t.code == 310 && t.str() == "A580")); + } + identities.sort(); + assert_eq!(identities, ["First", "Object", "Second"]); + drawing = cadcraft_io::read(&bytes, name).unwrap(); + assert_eq!(drawing.entity_count(), 3); + let line = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle.hex(); + for entity in drawing.model.iter().filter_map(|e| if let EntityKind::Unknown(u) = &e.kind { Some(u) } else { None }) { + for code in [330, 340, 350, 360] { + assert!(entity.tags.iter().any(|t| t.code == code && t.value == line), "missing reference {code}"); + } + } + } + } + } +} + +#[test] +fn zero_bit_opaque_entities_are_still_retained() { + let source = source_payload(DxfVersion::AC1032, ProxyPayload::default()); + let mut drawing = cadcraft_io::read(&source, "source.dwg").unwrap(); + for name in ["copy.dxf", "copy.dwg", "again.dwg"] { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + drawing = cadcraft_io::read(&bytes, name).unwrap(); + assert_eq!(drawing.entity_count(), 2); + assert!(drawing.model.iter().any(|e| matches!(e.kind, EntityKind::Unknown(_)))); + } +} + +#[test] +fn proxies_inside_block_definitions_survive_repeated_saves() { + use cadcraft_doc::{Block, Common, Entity}; + let mut drawing = check(&source(DxfVersion::AC1032), "source.dwg"); + let kind = drawing.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).unwrap().kind.clone(); + let handle = drawing.new_handle(); + let mut block = Block::new("CUSTOM_BLOCK"); + block.entities.push(Entity { handle, common: Common::default(), kind }); + drawing.blocks.insert("CUSTOM_BLOCK".into(), std::sync::Arc::new(block)); + for name in ["copy.dxf", "copy.dwg", "again.dwg"] { + let bytes = cadcraft_io::write_with(&drawing, name, &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + drawing = check(&bytes, name); + let block = drawing.blocks.get("CUSTOM_BLOCK").unwrap(); + assert_eq!(block.entities.len(), 1); + assert!(block.entities.iter().any(|e| matches!(e.kind, EntityKind::Unknown(_)))); + } +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index d8db1c526..3ff45430e 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -35,7 +35,7 @@ impl Class { pub const TABLE: &[(&str, Class)] = &[ ("geom", Class::Layer(0)), ("dxf", Class::Standalone), - ("dwg", Class::Standalone), + ("dwg", Class::Layer(0)), ("color", Class::Layer(0)), ("doc", Class::Layer(1)), ("constraints", Class::Layer(2)), @@ -57,7 +57,7 @@ pub const TABLE: &[(&str, Class)] = &[ /// The L0 foundation is a small chain: `raster` builds on `color` and /// `geom`, which the §3 diagram draws on one line. The GPU backend (`gpu`) /// reuses the CPU reference (`compose`) for LUTs and parity tests. -pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["geom", "color"], &["fonts", "render"]]; +pub const INTRA_LAYER_ORDER: &[&[&str]] = &[&["dxf", "dwg"], &["geom", "color"], &["fonts", "render"]]; fn intra_layer_allowed(from: &str, to: &str) -> bool { let (from, to) = (short_name(from), short_name(to)); From d2052eb4c7bde7a66936e366e40141d02a2ef68b Mon Sep 17 00:00:00 2001 From: mkzung <103102868+mkzung@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:17:55 +0000 Subject: [PATCH 214/531] DWG: isolate proxy conversion failures and normalize proxy names --- crates/dwg/src/lib.rs | 7 +- crates/dwg/src/proxy_transport.rs | 170 ++++++++++++++++++++-------- crates/io/src/dxf_write.rs | 14 ++- crates/io/tests/registered_proxy.rs | 45 ++++++++ 4 files changed, 181 insertions(+), 55 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 55aaa464f..d3112c449 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -109,7 +109,9 @@ mod native { } let mut notes = read_notes(&outcome.stats); let mut doc = outcome.document; - guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|_| "the DWG proxy conversion failed".to_string())??; + notes.extend( + guarded(AssertUnwindSafe(|| super::proxy_transport::prepare(&mut doc))).map_err(|_| "the DWG proxy conversion failed".to_string())?, + ); let orphans = guarded(AssertUnwindSafe(|| post_process(&mut doc))).map_err(|_| "the DWG post-processing failed on this file".to_string())?; if orphans > 0 { let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; @@ -737,7 +739,6 @@ mod native { mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - let classes = super::proxy_transport::read_classes(dxf)?; let data = dxf.to_vec(); let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? @@ -750,7 +751,7 @@ mod native { None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, None => {} } - guarded(AssertUnwindSafe(|| super::proxy_transport::restore_classes(&mut doc, classes))) + guarded(AssertUnwindSafe(|| super::proxy_transport::restore_classes(&mut doc, || super::proxy_transport::read_classes(dxf)))) .map_err(|_| "the DXF proxy class conversion failed".to_string())??; // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. let unwritten = guarded(AssertUnwindSafe(|| { diff --git a/crates/dwg/src/proxy_transport.rs b/crates/dwg/src/proxy_transport.rs index 8139f5c0d..cbbc6a210 100644 --- a/crates/dwg/src/proxy_transport.rs +++ b/crates/dwg/src/proxy_transport.rs @@ -12,16 +12,16 @@ fn class_number(index: usize) -> Result { index.checked_add(500).and_then(|n| i16::try_from(n).ok()).ok_or_else(|| "DXF: too many application classes".into()) } -/// Replace the dependency's private registered-class envelope with a standard proxy. -pub(super) fn prepare(doc: &mut CadDocument) -> Result<(), String> { +/// Convert representable application records and report only the records left out. +pub(super) fn prepare(doc: &mut CadDocument) -> Vec { let classes: Vec<_> = doc.classes.iter().cloned().collect(); let mut numbers = HashMap::new(); let mut identities = HashMap::new(); for (index, class) in classes.iter().enumerate() { - let number = class_number(index)?; - numbers.entry(i32::from(class.class_number)).and_modify(|v| *v = None).or_insert(Some(i32::from(number))); + let number = class_number(index).ok(); + numbers.entry(i32::from(class.class_number)).and_modify(|v| *v = None).or_insert(number.map(i32::from)); let identity = (class.dxf_name.as_str(), class.cpp_class_name.as_str(), class.is_an_entity); - identities.entry(identity).and_modify(|v| *v = None).or_insert(Some(number)); + identities.entry(identity).and_modify(|v| *v = None).or_insert(number); } let identity = |dxf: &str, cpp: &str, entity: bool| { identities @@ -29,7 +29,7 @@ pub(super) fn prepare(doc: &mut CadDocument) -> Result<(), String> { .copied() .flatten() .map(i32::from) - .ok_or_else(|| format!("DWG: missing or ambiguous application CLASS for {dxf} ({cpp})")) + .ok_or_else(|| format!("missing or ambiguous application CLASS for {dxf:.80} ({cpp:.80})")) }; let source = doc.dwg_source_version.unwrap_or(doc.version).version_code(); let dwg_version = match source { @@ -41,10 +41,10 @@ pub(super) fn prepare(doc: &mut CadDocument) -> Result<(), String> { 1024 => 29, 1027 => 31, 1032 => 33, - _ => return Ok(()), + _ => return Vec::new(), }; let maintenance = i32::from(doc.maintenance_version); - let remap = |id: i32| numbers.get(&id).copied().flatten().ok_or_else(|| format!("DWG: proxy names missing application class {id}")); + let remap = |id: i32| numbers.get(&id).copied().flatten().ok_or_else(|| format!("proxy names missing or ambiguous application class {id}")); // Only mutate proxies: entities_mut invalidates the decoder's verbatim records for every entity. let handles: Vec<_> = doc .entities() @@ -57,46 +57,81 @@ pub(super) fn prepare(doc: &mut CadDocument) -> Result<(), String> { _ => None, }) .collect(); + let mut notes = Vec::new(); + let mut entity_count = 0usize; + let mut object_count = 0usize; for handle in handles { - let text_payload = match doc.get_entity(handle) { - Some(EntityType::Extended(e)) if matches!(e.data, ExtendedEntityData::RegisteredClass(_)) => { - if let ExtendedEntityData::RegisteredClass(data) = &e.data - && !data.properties.is_empty() - { - return Err(format!("DWG: cannot transport semantic properties of {} as an opaque proxy", data.dxf_name)); + let converted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let Some(EntityType::Extended(entity)) = doc.get_entity(handle) else { return Ok(None) }; + let data = match &entity.data { + ExtendedEntityData::Proxy(data) => { + let mut proxy = data.clone(); + proxy.class_id = remap(proxy.class_id)?; + ExtendedEntityData::Proxy(proxy) + } + ExtendedEntityData::RegisteredClass(data) => { + if !data.properties.is_empty() { + return Err(format!("cannot transport semantic properties of {:.80} as an opaque proxy", data.dxf_name)); + } + let class_id = identity(&data.dxf_name, &data.cpp_class_name, true)?; + let text_payload = entity.common.raw_record.as_deref().map(registered_text).transpose()?.unwrap_or_default(); + ExtendedEntityData::Proxy(ProxyEntityData { + proxy_id: 498, + class_id, + dxf_subclass: String::new(), + version: (maintenance << 16) | dwg_version, + dwg_version, + maintenance_version: maintenance, + from_dxf: false, + graphics: ProxyPayload::from_bytes(entity.common.graphic_data.as_deref().unwrap_or_default()), + payload: data.payload.clone(), + text_payload, + object_ids: data.object_ids.clone(), + }) + } + _ => return Ok(None), + }; + Ok(Some(data)) + })) + .unwrap_or_else(|_| Err("application record conversion failed".into())); + match converted { + Ok(Some(data)) => { + if let Some(EntityType::Extended(entity)) = doc.get_entity_mut(handle) { + entity.data = data; } - e.common.raw_record.as_deref().map(registered_text).transpose()?.unwrap_or_default() } - _ => ProxyPayload::default(), - }; - let Some(EntityType::Extended(entity)) = doc.get_entity_mut(handle) else { continue }; - match &mut entity.data { - ExtendedEntityData::Proxy(data) => data.class_id = remap(data.class_id)?, - ExtendedEntityData::RegisteredClass(data) => { - let class_id = identity(&data.dxf_name, &data.cpp_class_name, true)?; - entity.data = ExtendedEntityData::Proxy(ProxyEntityData { - proxy_id: 498, - class_id, - dxf_subclass: String::new(), - version: (maintenance << 16) | dwg_version, - dwg_version, - maintenance_version: maintenance, - from_dxf: false, - graphics: ProxyPayload::from_bytes(entity.common.graphic_data.as_deref().unwrap_or_default()), - payload: data.payload.clone(), - text_payload, - object_ids: data.object_ids.clone(), - }); + Ok(None) => {} + Err(why) => { + doc.remove_entity(handle); + entity_count = entity_count.saturating_add(1); + skipped_note(&mut notes, "entity", handle, &why); } - _ => {} } } - for object in doc.objects.values_mut() { + doc.objects.retain(|handle, object| { if let ObjectType::ProxyObject(proxy) = object { - proxy.class_id = remap(proxy.class_id)?; + match remap(proxy.class_id) { + Ok(id) => proxy.class_id = id, + Err(why) => { + object_count = object_count.saturating_add(1); + skipped_note(&mut notes, "object", *handle, &why); + return false; + } + } } + true + }); + if entity_count > 0 || object_count > 0 { + notes.insert(0, format!("DWG: partial read; application proxy records left out (entities: {entity_count}, objects: {object_count})")); + } + notes +} + +fn skipped_note(notes: &mut Vec, kind: &str, handle: acadrust::types::Handle, why: &str) { + if notes.len() < 6 { + let why: String = why.chars().take(256).collect(); + notes.push(format!("DWG: proxy {kind} {handle} left out: {why}")); } - Ok(()) } /// The decoder's registered-class representation omits the separate R2007+ string stream. @@ -191,7 +226,7 @@ fn read_class(tags: &[Tag], number: i16) -> Result { } /// Keep source class positions and metadata, adding missing decoder defaults only afterwards. -pub(super) fn restore_classes(doc: &mut CadDocument, classes: Vec) -> Result<(), String> { +pub(super) fn restore_classes(doc: &mut CadDocument, source: impl FnOnce() -> Result, String>) -> Result<(), String> { let mut proxies = Vec::new(); for entity in doc.entities() { if let EntityType::Extended(e) = entity @@ -208,6 +243,7 @@ pub(super) fn restore_classes(doc: &mut CadDocument, classes: Vec) -> if proxies.is_empty() { return Ok(()); } + let classes = source()?; for (number, entity) in proxies { let index = number.checked_sub(500).and_then(|n| usize::try_from(n).ok()); if !index.and_then(|i| classes.get(i)).is_some_and(|c| c.is_an_entity == entity) { @@ -286,7 +322,7 @@ mod tests { assert_eq!(classes[0].instance_count, 7); assert!(classes[0].was_zombie); let mut doc = proxy_doc(); - restore_classes(&mut doc, classes.clone()).unwrap(); + restore_classes(&mut doc, || Ok(classes.clone())).unwrap(); assert_eq!(doc.classes.iter().take(2).cloned().collect::>(), classes); } } @@ -302,11 +338,47 @@ mod tests { } let mut class = DxfClass::new_entity("ENTITY", "Entity"); class.class_number = 500; - assert!(restore_classes(&mut doc, vec![class]).is_err()); + assert!(restore_classes(&mut doc, || Ok(vec![class])).is_err()); } - assert!(restore_classes(&mut proxy_doc(), vec![DxfClass::new("A", "A"), DxfClass::new("B", "B")]).is_err()); + assert!(restore_classes(&mut proxy_doc(), || Ok(vec![DxfClass::new("A", "A"), DxfClass::new("B", "B")])).is_err()); } + #[test] + fn unrepresentable_proxies_keep_other_geometry_and_bounded_diagnostics() { + use acadrust::entities::{Line, RawRecord}; + use acadrust::objects::ProxyObject; + use acadrust::types::{Handle, Vector3}; + for count in [1, 10] { + let mut doc = proxy_doc(); + if let Some(EntityType::Extended(e)) = doc.entities_mut().next() + && let ExtendedEntityData::Proxy(p) = &mut e.data + { + p.class_id = i32::MAX; + } + let template = doc.entities().next().unwrap().clone(); + for _ in 1..count { + let mut entity = template.clone(); + entity.common_mut().handle = Handle::NULL; + doc.add_entity(entity).unwrap(); + } + let object = Handle::new(u64::MAX - 1); + assert!(!doc.objects.contains_key(&object)); + doc.objects.insert(object, ObjectType::ProxyObject(ProxyObject { handle: object, class_id: i32::MAX, ..Default::default() })); + let line = doc.add_entity(EntityType::Line(Line::from_points(Vector3::new(2.0, 3.0, 0.0), Vector3::new(12.0, 13.0, 0.0)))).unwrap(); + let raw = RawRecord { data: vec![0xAA, 0x55], handle_bits: 0, version: DxfVersion::AC1032 }; + doc.get_entity_mut(line).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone())); + let notes = prepare(&mut doc); + assert_eq!(notes.len(), (count + 1).min(6) + 1); + assert!(notes.iter().all(|n| n.starts_with("DWG:"))); + assert!(notes[0].contains(&format!("entities: {count}, objects: 1"))); + assert_eq!(doc.entities().count(), 1); + assert!(!doc.objects.contains_key(&object)); + let Some(EntityType::Line(actual)) = doc.get_entity(line) else { panic!("readable line") }; + assert_eq!(actual.start, Vector3::new(2.0, 3.0, 0.0)); + assert_eq!(actual.end, Vector3::new(12.0, 13.0, 0.0)); + assert_eq!(doc.get_entity(line).unwrap().common().raw_record.as_deref(), Some(&raw)); + } + } #[test] fn opaque_registered_class_ambiguity_is_not_guessed() { let mut doc = CadDocument::new(); @@ -323,11 +395,12 @@ mod tests { }), }))) .unwrap(); - assert!(prepare(&mut doc).unwrap_err().contains("ambiguous")); + assert!(prepare(&mut doc).iter().any(|n| n.contains("ambiguous"))); + assert_eq!(doc.entities().count(), 0); assert!(class_number(usize::MAX).is_err()); } #[test] - fn semantic_records_keep_their_verbatim_data_and_mixed_payloads_are_rejected() { + fn semantic_records_keep_verbatim_data_and_mixed_payloads_are_reported() { use acadrust::entities::RawRecord; use acadrust::objects::{SemanticProperty, SemanticPropertyValue}; for payload in [ProxyPayload::default(), ProxyPayload::from_bits(&[0x80], 1)] { @@ -352,10 +425,11 @@ mod tests { doc.get_entity_mut(handle).unwrap().common_mut().raw_record = Some(std::sync::Arc::new(raw.clone())); assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); if payload.bit_count == 0 { - prepare(&mut doc).unwrap(); + assert!(prepare(&mut doc).is_empty()); assert_eq!(doc.get_entity(handle).unwrap().common().raw_record.as_deref(), Some(&raw)); } else { - assert!(prepare(&mut doc).unwrap_err().contains("semantic properties")); + assert!(prepare(&mut doc).iter().any(|n| n.contains("semantic properties"))); + assert!(doc.get_entity(handle).is_none()); } } } @@ -411,7 +485,7 @@ mod string_stream_tests { object_ids: vec![], }); entity.common.raw_record = Some(raw); - prepare(&mut decoded).unwrap(); + assert!(prepare(&mut decoded).is_empty()); for _ in 0..2 { let mut dxf = Vec::new(); acadrust::DxfWriter::new(&decoded).write_to_writer(&mut dxf).unwrap(); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 411f1c4b2..3ce6393d8 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -127,11 +127,17 @@ pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String { cadcraft_dxf::write_ascii(&tags) } -/// Subclass markers the DWG bridge knows by another spelling (it matches them exactly): -/// AutoCAD writes a dynamic block lookup parameter's as `AcDbBlockLookUpParameter`, the bridge -/// reads `AcDbBlockLookupParameter`; otherwise the parameter loses its name and its lookup -/// action in the DWG, and AutoCAD's lookups stop working. +/// Proxy type names and lookup-parameter subclass names must match the bridge reader's spelling. +/// Ordinary DXF output retains source spellings. fn bridge_markers(tags: &mut [Tag]) { + for tag in tags.iter_mut().filter(|tag| tag.code == 0) { + for name in ["ACAD_PROXY_ENTITY", "ACAD_PROXY_OBJECT"] { + if tag.str().trim().eq_ignore_ascii_case(name) { + *tag = Tag::s(0, name); + break; + } + } + } for t in tags.iter_mut().filter(|t| t.code == 100) { if t.str().trim().eq_ignore_ascii_case("AcDbBlockLookupParameter") { *t = Tag::s(100, "AcDbBlockLookupParameter"); diff --git a/crates/io/tests/registered_proxy.rs b/crates/io/tests/registered_proxy.rs index d50c078ab..29559a6fb 100644 --- a/crates/io/tests/registered_proxy.rs +++ b/crates/io/tests/registered_proxy.rs @@ -187,3 +187,48 @@ fn proxies_inside_block_definitions_survive_repeated_saves() { assert!(block.entities.iter().any(|e| matches!(e.kind, EntityKind::Unknown(_)))); } } + +#[test] +fn unused_malformed_classes_do_not_block_plain_geometry() { + for (name, cpp, flags, count) in [("", "Unused", 0, 0), ("UNUSED", "", 0, 0), ("UNUSED", "Unused", 65536, 0), ("UNUSED", "Unused", 0, i64::MAX)] { + let dxf = format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n{name}\n2\n{cpp}\n3\nSynthetic\n90\n{flags}\n91\n{count}\n281\n1\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n10\n100\nAcDbEntity\n8\n0\n100\nAcDbLine\n10\n2\n20\n3\n11\n12\n21\n13\n0\nENDSEC\n0\nEOF\n" + ); + let bytes = cadcraft_dwg::dxf_to_dwg_as(dxf.as_bytes(), "AC1032").unwrap(); + let drawing = cadcraft_io::read(&bytes, "plain.dwg").unwrap(); + let lines: Vec<_> = drawing.model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l) } else { None }).collect(); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].a.x, 2.0); + assert_eq!(lines[0].a.y, 3.0); + assert_eq!(lines[0].b.x, 12.0); + assert_eq!(lines[0].b.y, 13.0); + } +} + +#[test] +fn proxy_spelling_is_preserved_in_dxf_and_normalized_only_for_dwg() { + let source = String::from_utf8(duplicate_class_dxf()).unwrap(); + for (entity, object) in [("acad_proxy_entity", "acad_proxy_object"), ("AcAd_PrOxY_EnTiTy", "AcAd_PrOxY_ObJeCt")] { + let dxf = source.replace("ACAD_PROXY_ENTITY", entity).replace("ACAD_PROXY_OBJECT", object); + let drawing = cadcraft_io::read(dxf.as_bytes(), "source.dxf").unwrap(); + assert_eq!(drawing.entity_count(), 3); + let out = cadcraft_io::write_with(&drawing, "copy.dxf", &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let tags = cadcraft_dxf::parse(&out).unwrap(); + assert!(tags.iter().any(|t| t.code == 0 && t.str() == entity)); + let bytes = cadcraft_io::write_with(&drawing, "copy.dwg", &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let decoded = cadcraft_dwg::dwg_to_dxf(&bytes).unwrap(); + let tags = cadcraft_dxf::parse(&decoded).unwrap(); + let proxies: Vec<_> = cadcraft_dxf::sections(&tags) + .iter() + .flat_map(|s| cadcraft_dxf::records(&s.tags)) + .filter(|(kind, _)| kind.starts_with("ACAD_PROXY_")) + .collect(); + assert_eq!(proxies.len(), 3); + for (_, tags) in proxies { + assert!(tags.iter().any(|t| t.code == 310 && t.str() == "A580")); + assert!(tags.iter().any(|t| matches!(t.code, 93 | 161) && t.i64() == 9)); + } + let recovered = cadcraft_io::read(&bytes, "copy.dwg").unwrap(); + assert_eq!(recovered.entity_count(), 3); + } +} From 56dc397680e1ab83e27392c82d24e283e7f42232 Mon Sep 17 00:00:00 2001 From: mkzung <103102868+mkzung@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:19:16 +0000 Subject: [PATCH 215/531] DWG: reconcile proxy preservation with current worker and lockfile --- Cargo.lock | 1 + crates/engine/tests/save_reports_not_saved.rs | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index c2f4ce914..8a7f05c89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -691,6 +691,7 @@ name = "cadcraft-dwg" version = "0.17.0" dependencies = [ "acadrust", + "cadcraft-dxf", "log", ] diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 5ba1c1f73..dc608c6b4 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -256,5 +256,4 @@ fn retained_proxy_is_not_reported_as_lost_in_modern_dwg() { assert_eq!(not_saved_as(&drawing, Version::R2010).get("ACAD_PROXY_ENTITY"), Some(&1)); std::sync::Arc::make_mut(&mut drawing.foreign).classes.clear(); assert_eq!(not_saved_as(&drawing, Version::R2018).get("ACAD_PROXY_ENTITY"), Some(&1)); - } From cf46d11e27fa3f145280c19556676be857276ab0 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 20:37:26 +0700 Subject: [PATCH 216/531] BREAK and BREAKATPOINT: test the measured ends, closing side and undo Pins AutoCAD 2024's results (accoreconsole, entget of every object after the command) for the cases that are easy to get wrong: - BREAKATPOINT at either end of a line, or at the end vertex of an open polyline, leaves the object whole; - at an open polyline's middle vertex it splits it there, the original keeping the first part; - BREAK of a closed polyline at two points of one side, either way round and on the side that closes it too, opens it with its own handle; - a circle trimmed or broken becomes an arc with its own handle. Undo after each break restores the object under its handle. Co-Authored-By: Claude Opus 5.5 --- .../tests/it/break_ends_and_closing_side.rs | 134 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 2 files changed, 135 insertions(+) create mode 100644 crates/engine/tests/it/break_ends_and_closing_side.rs diff --git a/crates/engine/tests/it/break_ends_and_closing_side.rs b/crates/engine/tests/it/break_ends_and_closing_side.rs new file mode 100644 index 000000000..968ab6b6c --- /dev/null +++ b/crates/engine/tests/it/break_ends_and_closing_side.rs @@ -0,0 +1,134 @@ +//! BREAKATPOINT and BREAK where the result is easy to get wrong, as AutoCAD 2024 runs them +//! (accoreconsole, `entget` of every object after the command, on these drawings): +//! +//! - BREAKATPOINT at either end of a line, or at the end vertex of an open polyline, leaves the +//! object whole; +//! - at an open polyline's middle vertex it splits it there, the original keeping the first part; +//! - BREAK of a closed polyline at two points of one side, either way round and on the side that +//! closes it too, opens it with its own handle; +//! - a circle trimmed or broken becomes an arc with its own handle. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle}; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +/// The model space objects in order: handle and kind. +fn objects(s: &Session) -> Vec<(Handle, EntityKind)> { + s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect() +} + +/// A polyline's closed flag and vertices (rounded to 1e-9). +fn pts(k: &EntityKind) -> (bool, Vec<(f64, f64)>) { + let EntityKind::LwPolyline(p) = k else { panic!("not a polyline: {k:?}") }; + let r = |v: f64| (v * 1e9).round() / 1e9; + (p.closed, p.vertices.iter().map(|v| (r(v.p.x), r(v.p.y))).collect()) +} + +fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle { + handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap()) +} + +fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle { + handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap()) +} + +fn run(s: &mut Session, script: &str) { + s.script(script).unwrap(); + assert!(s.running.is_none(), "{script}: {}", s.prompt_text()); +} + +#[test] +fn breakatpoint_at_an_end_leaves_the_object_whole() { + for at in ["100,0", "0,0"] { + let mut s = Session::new(); + let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]); + run(&mut s, &format!("BREAKATPOINT {at} {at}\n")); + let objs = objects(&s); + assert_eq!(objs.len(), 1, "{at}: {objs:?}"); + let EntityKind::Line(k) = &objs[0].1 else { panic!("{objs:?}") }; + assert!(objs[0].0 == l && (k.a.x, k.a.y, k.b.x, k.b.y) == (0.0, 0.0, 100.0, 0.0), "{at}: {objs:?}"); + } + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false); + run(&mut s, "BREAKATPOINT 50,30 50,30\n"); + let objs = objects(&s); + assert_eq!(objs.len(), 1, "{objs:?}"); + assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)]))); +} + +#[test] +fn breakatpoint_at_a_middle_vertex_splits_there_and_the_original_keeps_the_first_part() { + let mut s = Session::new(); + let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false); + run(&mut s, "BREAKATPOINT 50,0 50,0\n"); + let objs = objects(&s); + assert_eq!(objs.len(), 2, "{objs:?}"); + let first = objs.iter().find(|o| o.0 == p).expect("the original stays"); + let other = objs.iter().find(|o| o.0 != p).unwrap(); + assert_eq!(pts(&first.1), (false, vec![(0.0, 0.0), (50.0, 0.0)])); + assert_eq!(pts(&other.1), (false, vec![(50.0, 0.0), (50.0, 30.0)])); + // One undo brings back the polyline as it was, under its handle, and nothing else. + s.undo().unwrap(); + let objs = objects(&s); + assert_eq!(objs.len(), 1, "{objs:?}"); + assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)]))); +} + +#[test] +fn break_at_two_points_of_one_side_opens_a_closed_polyline_with_its_handle() { + let bottom = vec![(30.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 0.0), (20.0, 0.0)]; + // The side from (0, 10) back to the start vertex closes the rectangle. + let closing = vec![(0.0, 3.0), (0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 8.0)]; + for (script, want) in [("BREAK 20,0 30,0\n", &bottom), ("BREAK 30,0 20,0\n", &bottom), ("BREAK 0,8 0,3\n", &closing)] { + let mut s = Session::new(); + let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true); + run(&mut s, script); + let objs = objects(&s); + assert_eq!(objs.len(), 1, "{script}: {objs:?}"); + assert_eq!((objs[0].0, pts(&objs[0].1)), (r, (false, want.clone())), "{script}"); + // Undo closes it again. + s.undo().unwrap(); + let objs = objects(&s); + let rect = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0)]; + assert_eq!(objs.iter().map(|o| (o.0, pts(&o.1))).collect::>(), vec![(r, (true, rect))], "{script}"); + } +} + +#[test] +fn a_circle_trimmed_or_broken_becomes_an_arc_with_its_handle() { + // Trimmed between the lines x = -5 and x = 5, picked at its top: the arc from 120 to 60 + // degrees, round the bottom. + let mut s = Session::new(); + let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap()); + let l = line(&mut s, [-5.0, -20.0], [-5.0, 20.0]); + let m = line(&mut s, [5.0, -20.0], [5.0, 20.0]); + s.execute("trim", &json!({ "handle": c.hex(), "pick": [0, 10], "edges": [l.hex(), m.hex()] })).unwrap(); + // The arc's handle, and whether it is AutoCAD's: radius 10 round (0, 0), from `start` to + // `end` degrees (to 1e-9 radians, 0 and 360 alike). + let arc_is = |s: &Session, start: f64, end: f64| { + let objs = objects(s); + let (h, k) = objs.iter().find(|o| matches!(o.1, EntityKind::Arc(_))).cloned().expect("an arc"); + let EntityKind::Arc(a) = k else { panic!("not an arc") }; + let same = |got: f64, want: f64| { + let d = (got - want.to_radians()).rem_euclid(std::f64::consts::TAU); + d < 1e-9 || std::f64::consts::TAU - d < 1e-9 + }; + let ok = (a.radius - 10.0).abs() < 1e-9 && a.center.x.abs() < 1e-9 && a.center.y.abs() < 1e-9 && same(a.start, start) && same(a.end, end); + (h, ok) + }; + assert_eq!(arc_is(&s, 120.0, 60.0), (c, true)); + // Broken from (10, 0) to (0, 10): the arc from 90 degrees round to 0. + let mut s = Session::new(); + let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap()); + run(&mut s, "BREAK 10,0 0,10\n"); + assert_eq!(objects(&s).len(), 1); + assert_eq!(arc_is(&s, 90.0, 0.0), (c, true)); + // Undo gives the circle back under its handle. + s.undo().unwrap(); + let objs = objects(&s); + assert!(objs.len() == 1 && objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index cda13decd..2ab0e48bb 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -16,6 +16,7 @@ mod block_keep; mod block_redefine; mod blockreplace; mod break_closed_polyline; +mod break_ends_and_closing_side; mod break_join_locked_layers; mod break_keeps_z; mod break_trim_keep_handle; From 2cbd67f963350c60e8d2807830373889969e5943 Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:48:24 +0100 Subject: [PATCH 217/531] Keyboard Shortcuts dialog: any command gets a shortcut, and the user's wins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tools ▸ Customize ▸ Keyboard Shortcuts lists every command with its shortcut, a filter, and a button to record a new one (click, press the keys, Esc cancels), Clear, Default and Reset to Defaults. A shortcut the user gives wins over a built-in one: the command that had it loses it and the dialog says which; menus show the shortcut in force. Shortcuts are kept with the preferences (`shortcuts`), hostile entries dropped. JSON form `ui.shortcuts {set: {command: key or ""}, reset}` never opens the dialog. Clipboard keys, Delete and Cmd+Q stay as they are. Recording and the conflict rules come from the storey shortcuts of #1703. Co-authored-by: Alex-BB44 <273073052+Alex-BB44@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG --- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/keys.rs | 598 +++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 10 + crates/ui-egui/src/menus.rs | 28 +- 7 files changed, 644 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/src/keys.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1f8035434..40c9a9103 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -24,6 +24,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "hatch" => crate::hatchdlg::dialog(app, ctx, &mut open), "aliasedit" => crate::aliasdlg::dialog(app, ctx, &mut open), "find" => crate::finddlg::dialog(app, ctx, &mut open), + crate::keys::DIALOG => crate::keys::dialog(app, ctx, &mut open), "about" => about(ctx, &mut open), "preview" => crate::exchange::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2f391809e..11da7c703 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1026,3 +1026,10 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found + Keyboard Shortcuts... Raccourcis clavier... + Keyboard Shortcuts Raccourcis clavier + Replaces the shortcut of {commands} Remplace le raccourci de : {commands} + Needs Ctrl, Alt or a function key Il faut Ctrl, Alt ou une touche de fonction + Press the keys Appuyez sur les touches + Back to CADCraft's shortcut Revenir au raccourci de CADCraft + A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Un raccourci que vous définissez l'emporte sur celui de CADCraft. Les modifications s'appliquent tout de suite et sont conservées. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f9f41c798..02c8bd254 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -105,6 +105,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "dialogs", "hatchdlg", "aliasdlg", + "keys", "mtext_editor", "layers", "bedit", diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5d0660112..941bc8970 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1385,3 +1385,10 @@ Text to find Text to find Whole words Whole words Nothing found Nothing found + Keyboard Shortcuts... Комбінації клавіш... + Keyboard Shortcuts Комбінації клавіш + Replaces the shortcut of {commands} Замінює комбінацію клавіш команди: {commands} + Needs Ctrl, Alt or a function key Потрібна клавіша Ctrl, Alt або функціональна клавіша + Press the keys Натисніть клавіші + Back to CADCraft's shortcut Повернути комбінацію CADCraft + A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Ваша комбінація клавіш має перевагу над комбінацією CADCraft. Зміни застосовуються одразу й зберігаються. diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs new file mode 100644 index 000000000..322553127 --- /dev/null +++ b/crates/ui-egui/src/keys.rs @@ -0,0 +1,598 @@ +//! The user's keyboard shortcuts (Tools ▸ Customize ▸ Keyboard Shortcuts...): any command can get +//! one, and a shortcut the user gives wins over CADCraft's own; the command that had it loses it, +//! and the dialog says so. They are kept with the other preferences (`shortcuts`). +//! +//! Recording a shortcut (click, press the keys, Esc to cancel) and the conflict rules come from +//! the storey shortcuts of #1703 (@Alex-BB44). + +use std::collections::BTreeMap; + +use egui::{Key, KeyboardShortcut, Modifiers, RichText, vec2}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The user's shortcuts: command id → registry shortcut ("Cmd+Shift+K"). Empty: the command has +/// none (its built-in one is removed). +pub type UserKeys = BTreeMap; + +/// At most this many user shortcuts are kept; longer shortcut strings are refused (preferences +/// and JSON calls are hostile input). +pub const MAX_KEYS: usize = 1000; +const MAX_LEN: usize = 64; + +/// Commands whose built-in key is handled outside the shortcut table and stays as it is: the +/// clipboard keys arrive as clipboard events, Delete belongs to the command line, Cmd+Q to the +/// macOS app menu. +const FIXED: &[&str] = &["copyclip", "cutclip", "pasteclip", "erase.selection", "ui.quit"]; + +/// The dialog name in `UiState::dialog`. +pub const DIALOG: &str = "shortcuts"; + +fn same(a: &KeyboardShortcut, b: &KeyboardShortcut) -> bool { + a.logical_key == b.logical_key && a.modifiers == b.modifiers +} + +/// A registry shortcut string ("Cmd+Shift+G", "Alt+4", "F3") as a shortcut; `None` when empty or +/// not understood. +pub fn parse(s: &str) -> Option { + let mut m = Modifiers::NONE; + let mut key = None; + for part in s.split('+').map(str::trim).filter(|p| !p.is_empty()) { + match part.to_ascii_lowercase().as_str() { + "cmd" | "command" => m |= Modifiers::COMMAND, + // Control on macOS (on Windows and Linux, Ctrl is written Cmd: it is the command key). + "ctrl" => m |= Modifiers::CTRL, + "shift" => m |= Modifiers::SHIFT, + "alt" | "option" => m |= Modifiers::ALT, + _ if key.is_none() => key = Some(Key::from_name(part)?), + _ => return None, + } + } + key.map(|k| KeyboardShortcut::new(m, k)) +} + +/// A shortcut as a registry string: "Cmd+Shift+G". `mac`: Command is Cmd and Control is Ctrl; +/// elsewhere Control is the command key, Cmd. +pub fn format(m: Modifiers, k: Key, mac: bool) -> String { + let mut s = String::new(); + if (mac && m.mac_cmd) || (!mac && (m.command || m.ctrl)) || (mac && m.command && !m.ctrl) { + s.push_str("Cmd+"); + } + if mac && m.ctrl { + s.push_str("Ctrl+"); + } + if m.shift { + s.push_str("Shift+"); + } + if m.alt { + s.push_str("Alt+"); + } + // "+" and "-" would read as separators. + s.push_str(match k { + Key::Plus => "Plus", + Key::Minus => "Minus", + k => k.name(), + }); + s +} + +/// Whether `s` can be a user shortcut: with Cmd, Ctrl or Alt, or a function or paging key alone. +/// The keys the drawing area and the command line live on (letters as typing, Space, Enter, Tab, +/// Esc, Delete, Backspace, the arrows), the clipboard keys and Cmd+Q never are. +pub fn allowed(s: &KeyboardShortcut) -> bool { + let k = s.logical_key; + let never = + [Key::Space, Key::Enter, Key::Tab, Key::Escape, Key::Delete, Key::Backspace, Key::ArrowUp, Key::ArrowDown, Key::ArrowLeft, Key::ArrowRight]; + if never.contains(&k) { + return false; + } + let m = s.modifiers; + let command = m.command || m.ctrl || m.mac_cmd; + let reserved = command && !m.shift && !m.alt && [Key::C, Key::X, Key::V, Key::Q].contains(&k); + let alone_ok = matches!(k, Key::PageUp | Key::PageDown | Key::Home | Key::End) || k.name().starts_with('F') && k.name().len() > 1; + !reserved && (command || m.alt || alone_ok) +} + +/// Shortcuts are tried most specific first (egui lets a shortcut match with Shift or Alt held on +/// top), so Cmd+Shift+G reaches its own command before Cmd+G does. +pub fn by_specificity(pairs: &mut [(KeyboardShortcut, T)]) { + let weight = |s: &KeyboardShortcut| { + let m = s.modifiers; + u8::from(m.shift) + u8::from(m.alt) + u8::from(m.ctrl && !m.command) + u8::from(m.command || m.mac_cmd) + }; + pairs.sort_by_key(|(s, _)| std::cmp::Reverse(weight(s))); +} + +/// CADCraft's own shortcuts: the shortcut table, plus Cmd+8 (QuickCalc), which the shortcut +/// handler reads before a focused text field can take it. +fn defaults() -> Vec<(KeyboardShortcut, &'static str)> { + let mut v = crate::menus::builtin_shortcuts(); + v.push((KeyboardShortcut::new(Modifiers::COMMAND, Key::Num8), "ui.toggle.quickcalc")); + v +} + +/// The command a built-in shortcut belongs to in the editor: the table runs some commands' UI +/// form (`ui.open` for OPEN), which is the same command for the user. +fn owner(id: &str) -> &str { + id.strip_prefix("ui.").filter(|c| cadcraft_engine::find_command(c).is_some()).unwrap_or(id) +} + +fn known(id: &str) -> bool { + cadcraft_engine::find_command(id).is_some() || crate::menus::is_ui_command(id) +} + +/// The shortcuts in force: the user's first, then CADCraft's own unless the user gave that +/// command another shortcut or gave the key to another command. Most specific first. +pub fn effective(user: &UserKeys) -> Vec<(KeyboardShortcut, String)> { + let mut out: Vec<(KeyboardShortcut, String)> = Vec::new(); + for (id, key) in user { + if let Some(s) = parse(key).filter(allowed) + && !out.iter().any(|(o, _)| same(o, &s)) + { + out.push((s, id.clone())); + } + } + for (s, id) in defaults() { + if !user.contains_key(owner(id)) && !out.iter().any(|(o, _)| same(o, &s)) { + out.push((s, id.to_string())); + } + } + by_specificity(&mut out); + out +} + +/// [`effective`], worked out again only when the user's shortcuts change (the shortcut handler +/// asks every frame). +pub fn effective_cached(ctx: &egui::Context, user: &UserKeys) -> Vec<(KeyboardShortcut, String)> { + let id = egui::Id::new("user_keys_effective"); + if let Some((k, v)) = ctx.data(|m| m.get_temp::<(UserKeys, Vec<(KeyboardShortcut, String)>)>(id)) + && k == *user + { + return v; + } + let v = effective(user); + ctx.data_mut(|m| m.insert_temp(id, (user.clone(), v.clone()))); + v +} + +/// The shortcut a menu or the editor shows for `id`, whose built-in one is `default`: the user's, +/// or the built-in one unless the user gave that key to another command. +pub fn shown(user: &UserKeys, id: &str, default: Option<&str>) -> Option { + if let Some(k) = user.get(id) { + return (!k.is_empty()).then(|| k.clone()); + } + let d = default?; + let s = parse(d); + let taken = s.is_some_and(|s| user.iter().any(|(o, k)| o != id && parse(k).is_some_and(|u| same(&u, &s)))); + (!taken).then(|| d.to_string()) +} + +/// The built-in shortcut a command shows (its registry `key`, or a UI command's). +pub fn default_key(id: &str) -> Option<&'static str> { + cadcraft_engine::find_command(id).and_then(|c| c.shortcut).or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).and_then(|c| c.3)) +} + +/// Give `id` the shortcut `key` ("" removes its shortcut). The commands that had the key, built +/// in or the user's, lose it; they are returned so the caller can say so. +pub fn assign(user: &mut UserKeys, id: &str, key: &str) -> Result, String> { + if !known(id) { + return Err(format!("{id}: unknown command")); + } + if FIXED.contains(&id) { + return Err(format!("{id}: this shortcut can't be changed")); + } + let key = key.trim(); + if key.len() > MAX_LEN { + return Err("shortcut too long".into()); + } + if user.len() >= MAX_KEYS && !user.contains_key(id) { + return Err(format!("more than {MAX_KEYS} shortcuts")); + } + if key.is_empty() { + user.insert(id.to_string(), String::new()); + return Ok(Vec::new()); + } + let s = parse(key).ok_or_else(|| format!("{key}: not a shortcut"))?; + if !allowed(&s) { + return Err(format!("{key}: needs Ctrl, Alt or a function key")); + } + let mut replaced = Vec::new(); + for (other, k) in user.iter_mut() { + if other != id && parse(k).is_some_and(|o| same(&o, &s)) { + k.clear(); + replaced.push(other.clone()); + } + } + // A built-in owner already lost the key to the user command that had it. + let held = !replaced.is_empty(); + for (o, other) in defaults() { + let other = owner(other); + if !held && other != id && same(&o, &s) && !user.contains_key(other) && !replaced.iter().any(|r| r == other) { + replaced.push(other.to_string()); + } + } + user.insert(id.to_string(), format(s.modifiers, s.logical_key, false)); + Ok(replaced) +} + +/// The user's shortcuts from saved preferences: unknown commands, bad strings and anything past +/// [`MAX_KEYS`] are dropped. +pub fn from_prefs(v: &Value) -> UserKeys { + let Some(m) = v.as_object() else { return UserKeys::new() }; + m.iter() + .filter_map(|(id, k)| Some((id, k.as_str()?))) + .filter(|(id, k)| id.len() <= MAX_LEN && k.len() <= MAX_LEN && known(id) && !FIXED.contains(&id.as_str())) + .filter(|(_, k)| k.is_empty() || parse(k).is_some_and(|s| allowed(&s))) + .take(MAX_KEYS) + .map(|(id, k)| (id.clone(), k.to_string())) + .collect() +} + +/// `ui.shortcuts`: from a menu or typed, the Keyboard Shortcuts dialog; with parameters +/// `{set?: {command: shortcut or ""}, reset?: bool}` the JSON form, which answers the user's +/// shortcuts and the commands that lost theirs. +pub fn command(app: &mut CadApp, params: &Value) -> Result { + if params.is_null() { + app.ui.dialog = Some(DIALOG.into()); + return Ok(Value::Null); + } + let mut keys = app.ui.shortcuts.clone(); + if params.get("reset").and_then(Value::as_bool) == Some(true) { + keys.clear(); + } + let mut replaced = Vec::new(); + if let Some(set) = params.get("set") { + let set = set.as_object().ok_or("`set` must be an object of command: shortcut")?; + if set.len() > MAX_KEYS { + return Err(format!("more than {MAX_KEYS} shortcuts")); + } + for (id, key) in set { + let key = key.as_str().ok_or_else(|| format!("{id}: the shortcut must be a string"))?; + replaced.extend(assign(&mut keys, &id.to_ascii_lowercase(), key)?); + } + } + app.ui.shortcuts = keys; + Ok(json!({ "shortcuts": app.ui.shortcuts, "replaced": replaced })) +} + +const RECORDING: &str = "user_keys_recording"; + +/// Whether a shortcut is being recorded (every shortcut stays quiet meanwhile). +pub fn recording(ctx: &egui::Context) -> bool { + ctx.data(|m| m.get_temp::(egui::Id::new(RECORDING))).is_some() +} + +pub fn stop_recording(ctx: &egui::Context) { + ctx.data_mut(|m| m.remove::(egui::Id::new(RECORDING))); +} + +/// The commands the editor lists, sorted by the label shown: (id, label, what tells same labels +/// apart: the command name to type, or the menu an interface command sits in). +fn rows() -> Vec<(&'static str, String, String)> { + let mut v: Vec<(&'static str, String, String)> = Vec::new(); + for c in cadcraft_engine::command_specs() { + if !c.label.is_empty() && !v.iter().any(|(id, ..)| *id == c.id) { + v.push((c.id, crate::i18n::t(c.label).to_string(), c.id.to_ascii_uppercase())); + } + } + for (id, label, menu, _) in crate::menus::UI_COMMANDS { + if !label.is_empty() && !menu.is_empty() && owner(id) == *id && !v.iter().any(|(i, ..)| i == id) { + let path: Vec<&str> = menu.iter().take(menu.len().saturating_sub(1)).map(|m| crate::i18n::menu(m)).collect(); + v.push((id, crate::i18n::t(label).to_string(), path.join(" ▸ "))); + } + } + v.sort_by(|a, b| a.1.to_lowercase().cmp(&b.1.to_lowercase()).then(a.0.cmp(b.0))); + v +} + +fn label_of(id: &str) -> String { + cadcraft_engine::find_command(id) + .map(|c| crate::i18n::t(c.label).to_string()) + .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| crate::i18n::t(c.1).to_string())) + .unwrap_or_else(|| id.to_string()) +} + +/// The Keyboard Shortcuts dialog: every command with its shortcut, a filter, a click to record a +/// new one. Changes apply at once. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let mac = ctx.os().is_mac(); + let rec_id = egui::Id::new(RECORDING); + let filter_id = egui::Id::new("user_keys_filter"); + let note_id = egui::Id::new("user_keys_note"); + let mut recording: Option = ctx.data(|m| m.get_temp(rec_id)); + let mut filter: String = ctx.data(|m| m.get_temp(filter_id)).unwrap_or_default(); + let mut note: Option<(String, bool)> = ctx.data(|m| m.get_temp(note_id)); + // A key pressed while recording becomes that command's shortcut; Esc stops recording. + if let Some(id) = recording.clone() { + let pressed = ctx.input(|inp| { + inp.events.iter().find_map(|e| match e { + egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*key, *modifiers)), + _ => None, + }) + }); + if let Some((k, m)) = pressed { + if k != Key::Escape { + note = Some(match assign(&mut app.ui.shortcuts, &id, &format(m, k, mac)) { + Ok(lost) if lost.is_empty() => (String::new(), false), + Ok(lost) => { + let names: Vec = lost.iter().map(|l| label_of(l)).collect(); + (crate::tf!("Replaces the shortcut of {commands}", commands = names.join(", ")), false) + } + Err(_) => (crate::tl!("Needs Ctrl, Alt or a function key").to_string(), true), + }); + } + recording = None; + ctx.input_mut(|inp| inp.events.clear()); + } + } + let mut reset_all = false; + egui::Window::new(crate::tl!("Keyboard Shortcuts")) + .id(egui::Id::new("shortcuts_dialog")) + .open(open) + .collapsible(false) + .default_size(vec2(600.0, 520.0)) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Filter")); + ui.text_edit_singleline(&mut filter); + }); + let f = filter.trim().to_lowercase(); + let rows: Vec<(&'static str, String, String)> = rows() + .into_iter() + .filter(|(_, label, detail)| f.is_empty() || label.to_lowercase().contains(&f) || detail.to_lowercase().contains(&f)) + .collect(); + let row_h = ui.spacing().interact_size.y + 4.0; + egui::ScrollArea::vertical().max_height(360.0).auto_shrink([false, true]).show_rows(ui, row_h, rows.len(), |ui, range| { + for (id, label, detail) in rows.get(range).unwrap_or_default() { + ui.horizontal(|ui| { + let cell = |ui: &mut egui::Ui, w: f32, text: RichText| { + ui.allocate_ui_with_layout(vec2(w, row_h - 4.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_width(w); + ui.add(egui::Label::new(text).truncate()); + }); + }; + cell(ui, 190.0, RichText::new(label.as_str())); + cell(ui, 140.0, RichText::new(detail.as_str()).color(t.text_dim).small()); + let fixed = FIXED.contains(id); + let key = shown(&app.ui.shortcuts, id, default_key(id)); + let text = if recording.as_deref() == Some(*id) { + crate::tl!("Press the keys").to_string() + } else { + key.as_deref().map_or_else(|| crate::tl!("None").to_string(), |k| crate::menus::shortcut_label(k, mac)) + }; + let b = egui::Button::new(text).selected(recording.as_deref() == Some(*id)).min_size(vec2(120.0, 0.0)); + if ui.add_enabled(!fixed, b).clicked() { + recording = Some(id.to_string()); + note = None; + } + if !fixed && key.is_some() && ui.small_button(crate::tl!("Clear")).clicked() { + let _ = assign(&mut app.ui.shortcuts, id, ""); + } + if app.ui.shortcuts.contains_key(*id) + && ui.small_button(crate::tl!("Default")).on_hover_text(crate::tl!("Back to CADCraft's shortcut")).clicked() + { + app.ui.shortcuts.remove(*id); + } + }); + } + }); + match ¬e { + Some((n, true)) => { + ui.colored_label(t.warn, n.as_str()); + } + Some((n, false)) if !n.is_empty() => { + ui.label(RichText::new(n.as_str()).color(t.text_dim)); + } + _ => {} + } + ui.separator(); + ui.horizontal(|ui| { + reset_all = ui.button(crate::tl!("Reset to Defaults")).clicked(); + }); + ui.label( + RichText::new(crate::tl!("A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time.")) + .color(t.text_dim) + .small(), + ); + }); + if reset_all { + app.ui.shortcuts.clear(); + note = None; + } + if !*open { + recording = None; + note = None; + } + ctx.data_mut(|m| { + match &recording { + Some(r) => { + m.insert_temp(rec_id, r.clone()); + } + None => { + m.remove::(rec_id); + } + } + m.insert_temp(filter_id, filter); + match note { + Some(n) => { + m.insert_temp(note_id, n); + } + None => { + m.remove::<(String, bool)>(note_id); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_engine::Session; + + fn app() -> CadApp { + CadApp::new(Session::new(), crate::Services::default()) + } + + fn key(s: &str) -> KeyboardShortcut { + parse(s).unwrap_or_else(|| panic!("{s}")) + } + + fn runs(user: &UserKeys, s: &str) -> Option { + effective(user).into_iter().find(|(o, _)| same(o, &key(s))).map(|(_, id)| id) + } + + #[test] + fn shortcut_strings_round_trip() { + for s in ["Cmd+Shift+G", "Cmd+4", "F3", "Alt+PageUp", "Cmd+Plus", "Cmd+Minus"] { + let k = key(s); + assert_eq!(format(k.modifiers, k.logical_key, false), s); + } + assert!(parse("").is_none() && parse("Cmd+").is_none() && parse("Cmd+G+H").is_none() && parse("Hyper+G").is_none()); + } + + #[test] + fn typing_keys_clipboard_keys_and_quit_are_never_user_shortcuts() { + for s in ["L", "Shift+L", "Space", "Enter", "Escape", "Cmd+C", "Cmd+V", "Cmd+X", "Cmd+Q", "ArrowUp", "Delete"] { + assert!(!allowed(&key(s)), "{s}"); + } + for s in ["Cmd+L", "Alt+L", "F4", "PageDown", "Cmd+Shift+C"] { + assert!(allowed(&key(s)), "{s}"); + } + } + + #[test] + fn any_command_gets_a_shortcut_and_it_runs_it() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Cmd+L"), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+L").as_deref(), Some("line")); + // The built-in ones are untouched. + assert_eq!(runs(&user, "Cmd+S").as_deref(), Some("qsave")); + assert_eq!(runs(&UserKeys::new(), "Cmd+L"), None); + } + + #[test] + fn a_user_shortcut_wins_over_a_built_in_one_and_says_which() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Cmd+P"), Ok(vec!["plot".to_string()])); + assert_eq!(runs(&user, "Cmd+P").as_deref(), Some("line")); + assert_eq!(shown(&user, "plot", default_key("plot")), None, "Plot no longer shows Cmd+P"); + assert_eq!(shown(&user, "line", default_key("line")).as_deref(), Some("Cmd+P")); + // Given to a third command, the first user one loses it too. + assert_eq!(assign(&mut user, "circle", "Cmd+P"), Ok(vec!["line".to_string()])); + assert_eq!(runs(&user, "Cmd+P").as_deref(), Some("circle")); + assert_eq!(shown(&user, "line", default_key("line")), None); + // A table entry that runs a command's UI form belongs to that command (Cmd+O, OPEN). + assert_eq!(assign(&mut user, "line", "Cmd+O"), Ok(vec!["open".to_string()])); + assert_eq!(assign(&mut user, "line", "Cmd+8"), Ok(vec!["ui.toggle.quickcalc".to_string()])); + } + + #[test] + fn a_new_shortcut_replaces_the_commands_own_and_clear_removes_it() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "qsave", "Cmd+Shift+K"), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+S"), None, "Save's own Cmd+S is replaced"); + assert_eq!(runs(&user, "Cmd+Shift+K").as_deref(), Some("qsave")); + assert_eq!(assign(&mut user, "plot", ""), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+P"), None); + assert_eq!(shown(&user, "plot", default_key("plot")), None); + // OPEN through its UI form: its Cmd+O goes when OPEN gets another key. + assert_eq!(assign(&mut user, "open", "F4"), Ok(vec![])); + assert_eq!(runs(&user, "Cmd+O"), None); + } + + #[test] + fn bad_shortcuts_and_commands_are_refused() { + let mut user = UserKeys::new(); + assert!(assign(&mut user, "nosuchcommand", "Cmd+L").is_err()); + assert!(assign(&mut user, "line", "L").is_err()); + assert!(assign(&mut user, "line", "Cmd+Nothing").is_err()); + assert!(assign(&mut user, "line", &"Cmd+".repeat(1000)).is_err()); + assert!(assign(&mut user, "copyclip", "Cmd+K").is_err(), "the clipboard keys stay"); + assert!(user.is_empty()); + } + + #[test] + fn the_json_form_sets_resets_and_never_opens_the_dialog() { + let mut app = app(); + let v = app.run("ui.shortcuts", json!({"set": {"LINE": "Cmd+P"}})).unwrap(); + assert_eq!(v["shortcuts"], json!({"line": "Cmd+P"})); + assert_eq!(v["replaced"], json!(["plot"])); + assert_eq!(app.ui.dialog, None); + assert!(app.run("ui.shortcuts", json!({"set": {"line": 3}})).is_err()); + assert!(app.run("ui.shortcuts", json!({"set": "Cmd+P"})).is_err()); + assert_eq!(app.ui.shortcuts.get("line").map(String::as_str), Some("Cmd+P"), "a refused call changes nothing"); + let v = app.run("ui.shortcuts", json!({"reset": true})).unwrap(); + assert_eq!(v["shortcuts"], json!({})); + app.start("ui.shortcuts"); + assert_eq!(app.ui.dialog.as_deref(), Some(DIALOG)); + } + + #[test] + fn shortcuts_are_kept_with_the_preferences_and_hostile_ones_dropped() { + let mut a = app(); + let _ = a.run("ui.shortcuts", json!({"set": {"line": "Cmd+L", "plot": ""}})); + let mut b = app(); + b.load_prefs(&a.prefs_json()); + assert_eq!(b.ui.shortcuts, a.ui.shortcuts); + let hostile = + json!({"shortcuts": {"line": "L", "nosuch": "Cmd+K", "copyclip": "Cmd+K", "circle": 5, "arc": "Cmd+K", "x".repeat(5000): "Cmd+J"}}); + let mut c = app(); + c.load_prefs(&hostile.to_string()); + assert_eq!(c.ui.shortcuts, UserKeys::from([("arc".to_string(), "Cmd+K".to_string())])); + let many: serde_json::Map = (0..5000).map(|i| (format!("c{i}"), json!("Cmd+K"))).collect(); + c.load_prefs(&json!({ "shortcuts": many }).to_string()); + assert!(c.ui.shortcuts.len() <= MAX_KEYS); + c.load_prefs(r#"{"shortcuts": "Cmd+K"}"#); + } + + #[test] + fn the_menus_show_the_shortcut_in_force() { + let mut app = app(); + let _ = app.run("ui.shortcuts", json!({"set": {"line": "Cmd+P"}})); + let mut found = (None, None); + fn walk(es: &[crate::menus::Entry], found: &mut (Option>, Option>)) { + for e in es { + match e { + crate::menus::Entry::Item { id, shortcut, .. } if id == "line" => found.0 = Some(shortcut.clone()), + crate::menus::Entry::Item { id, shortcut, .. } if id == "plot" => found.1 = Some(shortcut.clone()), + crate::menus::Entry::Sub { children, .. } => walk(children, found), + _ => {} + } + } + } + for (_, es) in crate::menus::tree(&app) { + walk(&es, &mut found); + } + assert_eq!(found, (Some(Some("Cmd+P".into())), Some(None))); + } + + #[test] + fn a_recorded_key_runs_its_command_and_quiets_shortcuts_while_recording() { + let ctx = egui::Context::default(); + let mut app = app(); + let _ = app.run("ui.shortcuts", json!({"set": {"line": "F4"}})); + let press = |key: Key| egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }], + ..Default::default() + }; + let mut out = ctx.run_ui(press(Key::F4), |ui| crate::menus::shortcuts(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert_eq!(app.session.summary()["running"], json!("line")); + app.session.cancel(); + // Recording in the dialog: F4 becomes the recorded key, nothing runs. + app.ui.dialog = Some(DIALOG.into()); + ctx.data_mut(|m| m.insert_temp(egui::Id::new(RECORDING), "circle".to_string())); + let mut out = ctx.run_ui(press(Key::F6), |ui| { + crate::menus::shortcuts(&mut app, ui.ctx()); + let mut open = true; + dialog(&mut app, ui.ctx(), &mut open); + }); + out.textures_delta.clear(); + assert_eq!(app.session.summary()["running"], Value::Null); + assert_eq!(app.ui.shortcuts.get("circle").map(String::as_str), Some("F6")); + assert!(!recording(&ctx)); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d27712da2..7ecb0ae38 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -49,6 +49,7 @@ pub mod gpu; pub mod grip_dyn; pub mod i18n; pub mod icons; +pub mod keys; pub mod layers; pub mod managers; pub mod menus; @@ -117,6 +118,8 @@ pub struct UiState { pub start_tab: bool, pub dialog: Option, pub history_lines: usize, + /// The user's keyboard shortcuts ([`keys`]). + pub shortcuts: keys::UserKeys, /// Interface theme: "system" (follow the OS light/dark appearance), "light" or "dark". pub theme: theme::ThemePref, /// Animation effects (dialog and menu fades, smoothed scrolling): "system" (follow the OS @@ -203,6 +206,7 @@ impl Default for UiState { start_tab: false, dialog: None, history_lines: 3, + shortcuts: keys::UserKeys::new(), theme: theme::ThemePref::default(), animations: animation::AnimationPref::default(), save_format: SaveFormat::default(), @@ -488,6 +492,9 @@ impl CadApp { if let Some(dir) = &self.ui.last_lisp_dir { prefs["lispDir"] = json!(dir); } + if !self.ui.shortcuts.is_empty() { + prefs["shortcuts"] = json!(self.ui.shortcuts); + } prefs.to_string() } @@ -521,6 +528,9 @@ impl CadApp { if let Some(dir) = v.get("lispDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { self.ui.last_lisp_dir = Some(dir.to_string()); } + if let Some(keys) = v.get("shortcuts") { + self.ui.shortcuts = keys::from_prefs(keys); + } } /// Make the system cursor the interface default (`on`) and turn it on; saved preferences and diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 438c06d97..fad90472f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -74,6 +74,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.cmdline.clear", "Clear Command History", &[], None), ("ui.dialog.language", "Interface Language", &["Edit", "Interface Language"], None), ("ui.dialog.find", "Find and Replace", &[], Some("Cmd+F")), + ("ui.shortcuts", "Keyboard Shortcuts...", &["Tools", "Customize", "Keyboard Shortcuts..."], None), ("ui.language", "Language", &[], None), ("ui.noop", "", &[], None), ("ui.quit", "Quit CADCraft", &[], Some("Cmd+Q")), @@ -101,6 +102,9 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option Vec<(String, Vec)> { let mut out: Vec<(String, Vec)> = MENUS.iter().map(|m| (m.to_string(), Vec::new())).collect(); + let user = &app.ui.shortcuts; let mut add = |path: &[&str], label: &str, id: &str, shortcut: Option<&str>, enabled: bool| { let Some((top, rest)) = path.split_first() else { return }; let Some((_, entries)) = out.iter_mut().find(|(m, _)| m == top) else { return }; @@ -600,7 +605,7 @@ pub fn tree(app: &CadApp) -> Vec<(String, Vec)> { cur.push(Entry::Item { label: if seg.is_empty() { label.to_string() } else { seg.to_string() }, id: id.to_string(), - shortcut: shortcut.map(str::to_string), + shortcut: crate::keys::shown(user, id, shortcut), enabled, }); } else { @@ -847,33 +852,40 @@ pub(crate) fn builtin_shortcuts() -> Vec<(egui::KeyboardShortcut, &'static str)> ] } -/// Keyboard shortcuts and function keys. +/// Keyboard shortcuts and function keys: the user's ([`crate::keys`]) and CADCraft's own. pub fn shortcuts(app: &mut CadApp, ctx: &egui::Context) { use egui::{Key, KeyboardShortcut, Modifiers}; - let sc = |m: Modifiers, k: Key| KeyboardShortcut::new(m, k); - let cmd = Modifiers::COMMAND; - let pairs = builtin_shortcuts(); + // A recording ends with the dialog it was started in; while it lasts the keys are its own. + if app.ui.dialog.as_deref() != Some(crate::keys::DIALOG) { + crate::keys::stop_recording(ctx); + } + if crate::keys::recording(ctx) { + return; + } + let pairs = crate::keys::effective_cached(ctx, &app.ui.shortcuts); crate::clipboard::mirror(app, ctx); if app.closing.is_some() { return; } // A palette toggle is global even while its expression field owns keyboard focus. - if ctx.input_mut(|i| i.consume_shortcut(&sc(cmd, Key::Num8))) { + let quickcalc = KeyboardShortcut::new(Modifiers::COMMAND, Key::Num8); + if pairs.iter().any(|(s, id)| *s == quickcalc && id == "ui.toggle.quickcalc") && ctx.input_mut(|i| i.consume_shortcut(&quickcalc)) { run_transparent(app, "ui.toggle.quickcalc"); } if ctx.egui_wants_keyboard_input() { return; } // Cmd/Ctrl+C, X and V arrive as clipboard events, not key presses. - let mut fire = crate::clipboard::shortcut_commands(app, ctx); + let mut fire: Vec = crate::clipboard::shortcut_commands(app, ctx).into_iter().map(str::to_string).collect(); ctx.input_mut(|i| { for (s, id) in &pairs { if i.consume_shortcut(s) && !fire.contains(id) { - fire.push(*id); + fire.push(id.clone()); } } }); for id in fire { + let id = id.as_str(); // ISOPLANE (F5, Ctrl+E) switches the plane without cancelling the active command. if id == "isoplane" { if let Some(m) = app.session.execute(id, &json!({})).ok().and_then(|v| v.get("message").and_then(Value::as_str).map(str::to_string)) { From 7e141247dd8235ebe387d6aa1f7e82dd25511bcb Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:00:28 +0100 Subject: [PATCH 218/531] Shortcuts: keep a macOS Control key, and Shift+Cmd+C/V stay clipboard keys A recorded or JSON Ctrl+K (macOS Control) was stored as Cmd+K and Cmd+Ctrl lost its Control: shortcuts are now written the same on every platform, Cmd for the command key and Ctrl for a Control that isn't it. Copy with Base Point and Paste as Block arrive as clipboard events like Copy and Paste, so their keys can't be given to another command and they keep theirs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG --- crates/ui-egui/src/keys.rs | 64 ++++++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs index 322553127..6a0bda63b 100644 --- a/crates/ui-egui/src/keys.rs +++ b/crates/ui-egui/src/keys.rs @@ -23,9 +23,9 @@ pub const MAX_KEYS: usize = 1000; const MAX_LEN: usize = 64; /// Commands whose built-in key is handled outside the shortcut table and stays as it is: the -/// clipboard keys arrive as clipboard events, Delete belongs to the command line, Cmd+Q to the -/// macOS app menu. -const FIXED: &[&str] = &["copyclip", "cutclip", "pasteclip", "erase.selection", "ui.quit"]; +/// clipboard keys, Shift ones included, arrive as clipboard events, Delete belongs to the command +/// line, Cmd+Q to the macOS app menu. +const FIXED: &[&str] = &["copyclip", "cutclip", "pasteclip", "copybase", "pasteblock", "erase.selection", "ui.quit"]; /// The dialog name in `UiState::dialog`. pub const DIALOG: &str = "shortcuts"; @@ -35,7 +35,8 @@ fn same(a: &KeyboardShortcut, b: &KeyboardShortcut) -> bool { } /// A registry shortcut string ("Cmd+Shift+G", "Alt+4", "F3") as a shortcut; `None` when empty or -/// not understood. +/// not understood. Cmd is the command key (Ctrl on Windows and Linux); Ctrl alone is the Control +/// key of macOS, and Cmd+Ctrl both macOS keys. pub fn parse(s: &str) -> Option { let mut m = Modifiers::NONE; let mut key = None; @@ -50,17 +51,20 @@ pub fn parse(s: &str) -> Option { _ => return None, } } + if m.command && m.ctrl { + m.mac_cmd = true; + } key.map(|k| KeyboardShortcut::new(m, k)) } -/// A shortcut as a registry string: "Cmd+Shift+G". `mac`: Command is Cmd and Control is Ctrl; -/// elsewhere Control is the command key, Cmd. -pub fn format(m: Modifiers, k: Key, mac: bool) -> String { +/// A shortcut as a registry string ("Cmd+Shift+G"), the same on every platform: Cmd for the +/// command key, Ctrl for a Control that isn't it (macOS), so [`parse`] gives it back. +pub fn format(m: Modifiers, k: Key) -> String { let mut s = String::new(); - if (mac && m.mac_cmd) || (!mac && (m.command || m.ctrl)) || (mac && m.command && !m.ctrl) { + if m.command || m.mac_cmd { s.push_str("Cmd+"); } - if mac && m.ctrl { + if m.ctrl && (m.mac_cmd || !m.command) { s.push_str("Ctrl+"); } if m.shift { @@ -90,7 +94,8 @@ pub fn allowed(s: &KeyboardShortcut) -> bool { } let m = s.modifiers; let command = m.command || m.ctrl || m.mac_cmd; - let reserved = command && !m.shift && !m.alt && [Key::C, Key::X, Key::V, Key::Q].contains(&k); + // Shift+Cmd+C and Shift+Cmd+V are clipboard events too (Copy with Base Point, Paste as Block). + let reserved = command && !m.alt && ([Key::C, Key::X, Key::V].contains(&k) || k == Key::Q && !m.shift); let alone_ok = matches!(k, Key::PageUp | Key::PageDown | Key::Home | Key::End) || k.name().starts_with('F') && k.name().len() > 1; !reserved && (command || m.alt || alone_ok) } @@ -100,7 +105,7 @@ pub fn allowed(s: &KeyboardShortcut) -> bool { pub fn by_specificity(pairs: &mut [(KeyboardShortcut, T)]) { let weight = |s: &KeyboardShortcut| { let m = s.modifiers; - u8::from(m.shift) + u8::from(m.alt) + u8::from(m.ctrl && !m.command) + u8::from(m.command || m.mac_cmd) + u8::from(m.shift) + u8::from(m.alt) + u8::from(m.ctrl && (m.mac_cmd || !m.command)) + u8::from(m.command || m.mac_cmd) }; pairs.sort_by_key(|(s, _)| std::cmp::Reverse(weight(s))); } @@ -213,7 +218,7 @@ pub fn assign(user: &mut UserKeys, id: &str, key: &str) -> Result, S replaced.push(other.to_string()); } } - user.insert(id.to_string(), format(s.modifiers, s.logical_key, false)); + user.insert(id.to_string(), format(s.modifiers, s.logical_key)); Ok(replaced) } @@ -315,7 +320,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }); if let Some((k, m)) = pressed { if k != Key::Escape { - note = Some(match assign(&mut app.ui.shortcuts, &id, &format(m, k, mac)) { + note = Some(match assign(&mut app.ui.shortcuts, &id, &format(m, k)) { Ok(lost) if lost.is_empty() => (String::new(), false), Ok(lost) => { let names: Vec = lost.iter().map(|l| label_of(l)).collect(); @@ -446,19 +451,27 @@ mod tests { #[test] fn shortcut_strings_round_trip() { - for s in ["Cmd+Shift+G", "Cmd+4", "F3", "Alt+PageUp", "Cmd+Plus", "Cmd+Minus"] { + for s in ["Cmd+Shift+G", "Cmd+4", "F3", "Alt+PageUp", "Cmd+Plus", "Cmd+Minus", "Ctrl+K", "Cmd+Ctrl+K"] { let k = key(s); - assert_eq!(format(k.modifiers, k.logical_key, false), s); + assert_eq!(format(k.modifiers, k.logical_key), s); } + // Keys as egui reports them: Ctrl on Linux and Windows is the command key; macOS Control + // and Command+Control keep their Control. + let linux_ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let mac_ctrl = Modifiers { ctrl: true, ..Modifiers::NONE }; + let mac_cmd_ctrl = Modifiers { ctrl: true, command: true, mac_cmd: true, ..Modifiers::NONE }; + assert_eq!(format(linux_ctrl, Key::K), "Cmd+K"); + assert_eq!(format(mac_ctrl, Key::K), "Ctrl+K"); + assert_eq!(format(mac_cmd_ctrl, Key::K), "Cmd+Ctrl+K"); assert!(parse("").is_none() && parse("Cmd+").is_none() && parse("Cmd+G+H").is_none() && parse("Hyper+G").is_none()); } #[test] fn typing_keys_clipboard_keys_and_quit_are_never_user_shortcuts() { - for s in ["L", "Shift+L", "Space", "Enter", "Escape", "Cmd+C", "Cmd+V", "Cmd+X", "Cmd+Q", "ArrowUp", "Delete"] { + for s in ["L", "Shift+L", "Space", "Enter", "Escape", "Cmd+C", "Cmd+V", "Cmd+X", "Cmd+Shift+C", "Cmd+Shift+V", "Cmd+Q", "ArrowUp", "Delete"] { assert!(!allowed(&key(s)), "{s}"); } - for s in ["Cmd+L", "Alt+L", "F4", "PageDown", "Cmd+Shift+C"] { + for s in ["Cmd+L", "Alt+L", "F4", "PageDown", "Cmd+Shift+Q", "Ctrl+K"] { assert!(allowed(&key(s)), "{s}"); } } @@ -473,6 +486,22 @@ mod tests { assert_eq!(runs(&UserKeys::new(), "Cmd+L"), None); } + #[test] + fn control_and_command_control_shortcuts_keep_their_control() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Ctrl+K"), Ok(vec![])); + assert_eq!(assign(&mut user, "circle", "Cmd+Ctrl+K"), Ok(vec![])); + assert_eq!(user.get("line").map(String::as_str), Some("Ctrl+K")); + assert_eq!(user.get("circle").map(String::as_str), Some("Cmd+Ctrl+K")); + let eff = effective(&user); + let of = |id: &str| eff.iter().find(|(_, i)| i == id).map(|(s, _)| s.modifiers); + assert_eq!(of("line"), Some(Modifiers::CTRL)); + assert_eq!(of("circle"), Some(Modifiers { ctrl: true, command: true, mac_cmd: true, ..Modifiers::NONE })); + // Command+Control+K is tried before Control+K, which it holds too. + let at = |id: &str| eff.iter().position(|(_, i)| i == id); + assert!(at("circle") < at("line")); + } + #[test] fn a_user_shortcut_wins_over_a_built_in_one_and_says_which() { let mut user = UserKeys::new(); @@ -511,6 +540,7 @@ mod tests { assert!(assign(&mut user, "line", "Cmd+Nothing").is_err()); assert!(assign(&mut user, "line", &"Cmd+".repeat(1000)).is_err()); assert!(assign(&mut user, "copyclip", "Cmd+K").is_err(), "the clipboard keys stay"); + assert!(assign(&mut user, "pasteblock", "Cmd+K").is_err(), "Shift+Cmd+V is a clipboard event too"); assert!(user.is_empty()); } From cdbc32ac8fe29a250a5788c179af145944855448 Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:29:09 +0100 Subject: [PATCH 219/531] Shortcuts: Cmd+Alt+C/X/V stay clipboard keys; one key per command from prefs egui-winit turns Cmd+C, X and V into clipboard events whatever else is held, so Alt variants are refused too. Preferences that give one key to two commands keep it for the first and drop the other, so no menu shows a shortcut that runs something else. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG --- crates/ui-egui/src/keys.rs | 58 ++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs index 6a0bda63b..e1c2944de 100644 --- a/crates/ui-egui/src/keys.rs +++ b/crates/ui-egui/src/keys.rs @@ -94,8 +94,9 @@ pub fn allowed(s: &KeyboardShortcut) -> bool { } let m = s.modifiers; let command = m.command || m.ctrl || m.mac_cmd; - // Shift+Cmd+C and Shift+Cmd+V are clipboard events too (Copy with Base Point, Paste as Block). - let reserved = command && !m.alt && ([Key::C, Key::X, Key::V].contains(&k) || k == Key::Q && !m.shift); + // Cmd+C, X and V arrive as clipboard events whatever else is held (Shift+Cmd+C is Copy with + // Base Point, Shift+Cmd+V Paste as Block). + let reserved = command && ([Key::C, Key::X, Key::V].contains(&k) || k == Key::Q && !m.shift && !m.alt); let alone_ok = matches!(k, Key::PageUp | Key::PageDown | Key::Home | Key::End) || k.name().starts_with('F') && k.name().len() > 1; !reserved && (command || m.alt || alone_ok) } @@ -222,17 +223,30 @@ pub fn assign(user: &mut UserKeys, id: &str, key: &str) -> Result, S Ok(replaced) } -/// The user's shortcuts from saved preferences: unknown commands, bad strings and anything past -/// [`MAX_KEYS`] are dropped. +/// The user's shortcuts from saved preferences: unknown commands, bad strings, a shortcut an +/// earlier command already has (it would show on both, run one) and anything past [`MAX_KEYS`] +/// are dropped. pub fn from_prefs(v: &Value) -> UserKeys { let Some(m) = v.as_object() else { return UserKeys::new() }; - m.iter() - .filter_map(|(id, k)| Some((id, k.as_str()?))) - .filter(|(id, k)| id.len() <= MAX_LEN && k.len() <= MAX_LEN && known(id) && !FIXED.contains(&id.as_str())) - .filter(|(_, k)| k.is_empty() || parse(k).is_some_and(|s| allowed(&s))) - .take(MAX_KEYS) - .map(|(id, k)| (id.clone(), k.to_string())) - .collect() + let mut out = UserKeys::new(); + let mut taken: Vec = Vec::new(); + for (id, k) in m.iter().filter_map(|(id, k)| Some((id, k.as_str()?))) { + if out.len() >= MAX_KEYS { + break; + } + if id.len() > MAX_LEN || k.len() > MAX_LEN || !known(id) || FIXED.contains(&id.as_str()) { + continue; + } + if !k.is_empty() { + let Some(s) = parse(k).filter(allowed) else { continue }; + if taken.iter().any(|o| same(o, &s)) { + continue; + } + taken.push(s); + } + out.insert(id.clone(), k.to_string()); + } + out } /// `ui.shortcuts`: from a menu or typed, the Keyboard Shortcuts dialog; with parameters @@ -468,7 +482,24 @@ mod tests { #[test] fn typing_keys_clipboard_keys_and_quit_are_never_user_shortcuts() { - for s in ["L", "Shift+L", "Space", "Enter", "Escape", "Cmd+C", "Cmd+V", "Cmd+X", "Cmd+Shift+C", "Cmd+Shift+V", "Cmd+Q", "ArrowUp", "Delete"] { + for s in [ + "L", + "Shift+L", + "Space", + "Enter", + "Escape", + "Cmd+C", + "Cmd+V", + "Cmd+X", + "Cmd+Shift+C", + "Cmd+Shift+V", + "Cmd+Alt+C", + "Cmd+Alt+X", + "Cmd+Alt+V", + "Cmd+Q", + "ArrowUp", + "Delete", + ] { assert!(!allowed(&key(s)), "{s}"); } for s in ["Cmd+L", "Alt+L", "F4", "PageDown", "Cmd+Shift+Q", "Ctrl+K"] { @@ -576,6 +607,9 @@ mod tests { c.load_prefs(&json!({ "shortcuts": many }).to_string()); assert!(c.ui.shortcuts.len() <= MAX_KEYS); c.load_prefs(r#"{"shortcuts": "Cmd+K"}"#); + // One key for two commands (an edited file): the first keeps it, the other is dropped. + c.load_prefs(r#"{"shortcuts": {"arc": "Cmd+K", "line": "Cmd+K", "circle": "Cmd+J"}}"#); + assert_eq!(c.ui.shortcuts, UserKeys::from([("arc".to_string(), "Cmd+K".to_string()), ("circle".to_string(), "Cmd+J".to_string())])); } #[test] From 5aa0e2da9e1ee82bf973f3f2ce15c1b5b5bf9bbd Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:16:17 +0100 Subject: [PATCH 220/531] egui 0.37 ids in the Keyboard Shortcuts dialog: Id::unique, as the rest of the UI Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkJ8yA6ibQ4twvHAJjDU3d --- crates/ui-egui/src/keys.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs index e1c2944de..8f7252c49 100644 --- a/crates/ui-egui/src/keys.rs +++ b/crates/ui-egui/src/keys.rs @@ -152,7 +152,7 @@ pub fn effective(user: &UserKeys) -> Vec<(KeyboardShortcut, String)> { /// [`effective`], worked out again only when the user's shortcuts change (the shortcut handler /// asks every frame). pub fn effective_cached(ctx: &egui::Context, user: &UserKeys) -> Vec<(KeyboardShortcut, String)> { - let id = egui::Id::new("user_keys_effective"); + let id = egui::Id::unique("user_keys_effective"); if let Some((k, v)) = ctx.data(|m| m.get_temp::<(UserKeys, Vec<(KeyboardShortcut, String)>)>(id)) && k == *user { @@ -280,11 +280,11 @@ const RECORDING: &str = "user_keys_recording"; /// Whether a shortcut is being recorded (every shortcut stays quiet meanwhile). pub fn recording(ctx: &egui::Context) -> bool { - ctx.data(|m| m.get_temp::(egui::Id::new(RECORDING))).is_some() + ctx.data(|m| m.get_temp::(egui::Id::unique(RECORDING))).is_some() } pub fn stop_recording(ctx: &egui::Context) { - ctx.data_mut(|m| m.remove::(egui::Id::new(RECORDING))); + ctx.data_mut(|m| m.remove::(egui::Id::unique(RECORDING))); } /// The commands the editor lists, sorted by the label shown: (id, label, what tells same labels @@ -318,9 +318,9 @@ fn label_of(id: &str) -> String { pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let t = Tokens::get(); let mac = ctx.os().is_mac(); - let rec_id = egui::Id::new(RECORDING); - let filter_id = egui::Id::new("user_keys_filter"); - let note_id = egui::Id::new("user_keys_note"); + let rec_id = egui::Id::unique(RECORDING); + let filter_id = egui::Id::unique("user_keys_filter"); + let note_id = egui::Id::unique("user_keys_note"); let mut recording: Option = ctx.data(|m| m.get_temp(rec_id)); let mut filter: String = ctx.data(|m| m.get_temp(filter_id)).unwrap_or_default(); let mut note: Option<(String, bool)> = ctx.data(|m| m.get_temp(note_id)); @@ -349,7 +349,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } let mut reset_all = false; egui::Window::new(crate::tl!("Keyboard Shortcuts")) - .id(egui::Id::new("shortcuts_dialog")) + .id(egui::Id::unique("shortcuts_dialog")) .open(open) .collapsible(false) .default_size(vec2(600.0, 520.0)) @@ -648,7 +648,7 @@ mod tests { app.session.cancel(); // Recording in the dialog: F4 becomes the recorded key, nothing runs. app.ui.dialog = Some(DIALOG.into()); - ctx.data_mut(|m| m.insert_temp(egui::Id::new(RECORDING), "circle".to_string())); + ctx.data_mut(|m| m.insert_temp(egui::Id::unique(RECORDING), "circle".to_string())); let mut out = ctx.run_ui(press(Key::F6), |ui| { crate::menus::shortcuts(&mut app, ui.ctx()); let mut open = true; From 789c4e954278504cb3276f455566355ce2cf8870 Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Sat, 31 Oct 2026 04:33:37 +0100 Subject: [PATCH 221/531] Shortcuts: ui.set checks them as the preferences do, and a malformed preference keeps them ui.set took any map: bad keys, unknown or fixed commands and keys taken twice reached the menus. A preference value that isn't an object cleared the shortcuts instead of being ignored. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkJ8y83ji68FwkuL22Qf4n --- crates/ui-egui/src/control.rs | 4 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/shortcuts_checked.rs | 39 ++++++++++++++++++++ 4 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/tests/it/shortcuts_checked.rs diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9c806a96f..e161b2cdf 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -453,7 +453,9 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou } } match serde_json::from_value::(cur) { - Ok(u) => { + Ok(mut u) => { + // Shortcuts are checked as the preferences check them. + u.shortcuts = crate::keys::from_prefs(&json!(u.shortcuts)); if let Err(error) = crate::docking::validate(&u.docking) { return err(error); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7ecb0ae38..c28419086 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -528,7 +528,7 @@ impl CadApp { if let Some(dir) = v.get("lispDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { self.ui.last_lisp_dir = Some(dir.to_string()); } - if let Some(keys) = v.get("shortcuts") { + if let Some(keys) = v.get("shortcuts").filter(|k| k.is_object()) { self.ui.shortcuts = keys::from_prefs(keys); } } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index b80614182..35fa4c7dd 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -29,6 +29,7 @@ mod rapid_clicks; mod selection_cycling; mod shared_controls; mod shortcut_menus; +mod shortcuts_checked; mod status_bar_toggles; mod style_dialogs; mod system_cursor; diff --git a/crates/ui-egui/tests/it/shortcuts_checked.rs b/crates/ui-egui/tests/it/shortcuts_checked.rs new file mode 100644 index 000000000..494160ac0 --- /dev/null +++ b/crates/ui-egui/tests/it/shortcuts_checked.rs @@ -0,0 +1,39 @@ +//! User shortcuts are checked however they arrive: `ui.set` drops what the preferences would, +//! and a malformed preference value leaves the shortcuts as they are. + +use cadcraft_engine::Session; +use cadcraft_ui_egui::control::{ControlRequest, Outcome, handle}; +use cadcraft_ui_egui::{CadApp, Services}; +use serde_json::{Value, json}; + +fn call(app: &mut CadApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _reply) = ControlRequest::new(method, params); + match handle(app, ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("unexpected screenshot"), + } +} + +#[test] +fn ui_set_keeps_only_shortcuts_the_preferences_would() { + let mut app = CadApp::new(Session::new(), Services::default()); + let ctx = egui::Context::default(); + let v = call( + &mut app, + &ctx, + "ui.set", + json!({"shortcuts": {"line": "Ctrl+Shift+L", "circle": "not a key", "nosuchcommand": "Ctrl+Shift+K", "move": "Ctrl+Shift+L"}}), + ); + assert_eq!(v["ok"], true, "{v}"); + let ids: Vec<&String> = app.ui.shortcuts.keys().collect(); + assert_eq!(ids, vec!["line"], "a bad key, an unknown command and a key taken twice are dropped: {:?}", app.ui.shortcuts); +} + +#[test] +fn a_malformed_preference_keeps_the_shortcuts() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.load_prefs(r#"{"shortcuts": {"line": "Ctrl+Shift+L"}}"#); + assert_eq!(app.ui.shortcuts.len(), 1); + app.load_prefs(r#"{"shortcuts": "Ctrl+Shift+L"}"#); + assert_eq!(app.ui.shortcuts.get("line").map(String::as_str), Some("Ctrl+Shift+L"), "not cleared"); +} From d23c5f0182de4c75a9f61f03decefd6cd6260069 Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:18:56 +0100 Subject: [PATCH 222/531] Keyboard Shortcuts: the Chinese label of its menu item, as main's catalog test asks since #2510 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkJ8y75DE7yLZ7utxSRDeP --- crates/ui-egui/src/i18n/zh.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index eae92cc14..9488dcb03 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -361,6 +361,7 @@ Join 合并 Join the ArtCraft Discord… 加入 ArtCraft Discord… Join us on Discord 在 Discord 上加入我们 + Keyboard Shortcuts... 键盘快捷键... Language 语言 Last 最后 Last commit 最后提交 From cce67d27c7fe342212efff8f3a9cbae25fc2c21b Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:45:14 +0100 Subject: [PATCH 223/531] Shortcuts: outside macOS Ctrl and Cmd are one key when checking who has a shortcut One Ctrl press runs a Ctrl and a Cmd shortcut alike on Windows and Linux, so two commands could hold Ctrl+K and Cmd+K and only the first would ever run. same() now compares them as one key there; macOS keeps Control apart. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkJ8y75DE7yLZ7utxSRDeP --- crates/ui-egui/src/keys.rs | 40 +++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs index 8f7252c49..2fd7419bd 100644 --- a/crates/ui-egui/src/keys.rs +++ b/crates/ui-egui/src/keys.rs @@ -30,8 +30,17 @@ const FIXED: &[&str] = &["copyclip", "cutclip", "pasteclip", "copybase", "pasteb /// The dialog name in `UiState::dialog`. pub const DIALOG: &str = "shortcuts"; +/// Whether two shortcuts are one key press. Outside macOS Ctrl is the command key, and one Ctrl +/// press runs a Ctrl and a Cmd shortcut alike, so they are compared as Cmd. fn same(a: &KeyboardShortcut, b: &KeyboardShortcut) -> bool { - a.logical_key == b.logical_key && a.modifiers == b.modifiers + let pressed = |m: Modifiers| { + if !cfg!(target_os = "macos") && (m.ctrl || m.command || m.mac_cmd) { + Modifiers { ctrl: false, command: true, mac_cmd: false, ..m } + } else { + m + } + }; + a.logical_key == b.logical_key && pressed(a.modifiers) == pressed(b.modifiers) } /// A registry shortcut string ("Cmd+Shift+G", "Alt+4", "F3") as a shortcut; `None` when empty or @@ -521,16 +530,20 @@ mod tests { fn control_and_command_control_shortcuts_keep_their_control() { let mut user = UserKeys::new(); assert_eq!(assign(&mut user, "line", "Ctrl+K"), Ok(vec![])); - assert_eq!(assign(&mut user, "circle", "Cmd+Ctrl+K"), Ok(vec![])); - assert_eq!(user.get("line").map(String::as_str), Some("Ctrl+K")); + // Outside macOS both are one Ctrl press, so Circle takes it from Line. + let lost = if cfg!(target_os = "macos") { vec![] } else { vec!["line".to_string()] }; + assert_eq!(assign(&mut user, "circle", "Cmd+Ctrl+K"), Ok(lost)); assert_eq!(user.get("circle").map(String::as_str), Some("Cmd+Ctrl+K")); let eff = effective(&user); let of = |id: &str| eff.iter().find(|(_, i)| i == id).map(|(s, _)| s.modifiers); - assert_eq!(of("line"), Some(Modifiers::CTRL)); assert_eq!(of("circle"), Some(Modifiers { ctrl: true, command: true, mac_cmd: true, ..Modifiers::NONE })); - // Command+Control+K is tried before Control+K, which it holds too. - let at = |id: &str| eff.iter().position(|(_, i)| i == id); - assert!(at("circle") < at("line")); + if cfg!(target_os = "macos") { + assert_eq!(user.get("line").map(String::as_str), Some("Ctrl+K")); + assert_eq!(of("line"), Some(Modifiers::CTRL)); + // Command+Control+K is tried before Control+K, which it holds too. + let at = |id: &str| eff.iter().position(|(_, i)| i == id); + assert!(at("circle") < at("line")); + } } #[test] @@ -549,6 +562,19 @@ mod tests { assert_eq!(assign(&mut user, "line", "Cmd+8"), Ok(vec!["ui.toggle.quickcalc".to_string()])); } + /// On Windows and Linux one Ctrl press runs a Ctrl and a Cmd shortcut alike, so they are one + /// key: giving it takes it from the command that had it, and preferences keep it once. + #[test] + #[cfg(not(target_os = "macos"))] + fn ctrl_and_cmd_are_one_key_outside_macos() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Ctrl+P"), Ok(vec!["plot".to_string()])); + assert_eq!(runs(&user, "Cmd+P").as_deref(), Some("line")); + assert_eq!(assign(&mut user, "circle", "Cmd+P"), Ok(vec!["line".to_string()])); + let user = from_prefs(&json!({"circle": "Cmd+K", "line": "Ctrl+K"})); + assert_eq!(user.values().filter(|k| !k.is_empty()).count(), 1, "{user:?}"); + } + #[test] fn a_new_shortcut_replaces_the_commands_own_and_clear_removes_it() { let mut user = UserKeys::new(); From bd639d320413f76eeb65260e1c8cc1366e77db3e Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:31:03 +0100 Subject: [PATCH 224/531] Properties palette: a text row that holds the separator is shown whole shown_part took off everything after U+001F, so a Contents or dimension text with that character was shown cut off and an edit wrote the cut-off text back. Only a tail that reads as the tagged number is taken off now. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index f6ef6e5a5..ea2deae82 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -773,9 +773,13 @@ fn exact(shown: String, v: f64) -> String { format!("{shown}{EXACT_SEP}{:.11e}", v + 0.0) } -/// What a row shows of a value that [`exact`] tagged (a plain string is shown as it is). +/// What a row shows of a value that [`exact`] tagged (a plain string is shown as it is, also one +/// that holds the separator: only a tail that reads as the tagged number is taken off). fn shown_part(s: &str) -> String { - s.split(EXACT_SEP).next().unwrap_or_default().to_string() + match s.rsplit_once(EXACT_SEP) { + Some((shown, tag)) if tag.parse::().is_ok() => shown.to_string(), + _ => s.to_string(), + } } /// Properties palette: the selection's common properties, or the current defaults when nothing is selected; formats lengths per drawing units and dispatches setter commands. @@ -1490,6 +1494,14 @@ mod tests { use egui::{Color32, Shape}; use egui_kittest::kittest::Queryable; + #[test] + fn shown_part_takes_off_only_the_number_tag() { + assert_eq!(shown_part(&exact("5.00".into(), 5.0)), "5.00"); + assert_eq!(shown_part("plain"), "plain"); + assert_eq!(shown_part("a\u{1f}b"), "a\u{1f}b"); + assert_eq!(shown_part(&format!("a{EXACT_SEP}b")), "a\u{1f}b"); + } + fn contains_swatch(shape: &Shape, color: Color32) -> bool { match shape { Shape::Rect(r) => r.fill == color && (r.rect.width() - 12.0).abs() < 0.01 && (r.rect.height() - 12.0).abs() < 0.01, From d1e6f4df9666cf32ba9697147251e2ddbc9814f7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 17:22:36 -0700 Subject: [PATCH 225/531] XCLIP: invert flag as group 290, extents are the boundary's box, Delete with no boundary asks again; clip on main's new Insert literals --- crates/doc/src/extents.rs | 7 ++- crates/engine/src/cmd/blocks/xclip.rs | 11 +++- crates/engine/src/select.rs | 1 + crates/engine/tests/it/xclip.rs | 25 ++++++++ crates/io/src/dxf_clip.rs | 66 ++++++-------------- crates/io/tests/it/block_expansion.rs | 1 + crates/io/tests/it/dynblock_read.rs | 1 + crates/io/tests/it/roundtrip/cases/blocks.rs | 1 + crates/io/tests/it/roundtrip/compare.rs | 3 +- crates/io/tests/it/xclip_roundtrip.rs | 6 +- 10 files changed, 70 insertions(+), 52 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 548998389..4f40a148c 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -179,12 +179,12 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } }; b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) }; - // XCLIP: what shows is within the boundary (an inverted clip can show anything). + // XCLIP: the reference app takes the boundary's box, also where it reaches past the + // block or misses it (an inverted clip can show anything, so it keeps the block's). if let Some(c) = ins.clip.as_ref().filter(|c| c.active() && !c.inverted) && !b.is_empty() { - let cb = Bounds2::from_points(c.polygon().into_iter().map(|p| m.apply(p))); - b = if b.intersects(&cb) { Bounds2 { min: b.min.max(cb.min), max: b.max.min(cb.max) } } else { Bounds2::EMPTY }; + b = Bounds2::from_points(c.polygon().into_iter().map(|p| m.apply(p))); } if ins.cols > 1 || ins.rows > 1 { let off = @@ -493,6 +493,7 @@ mod tests { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }), ) }; diff --git a/crates/engine/src/cmd/blocks/xclip.rs b/crates/engine/src/cmd/blocks/xclip.rs index b9e1c0e4f..82ee26fb4 100644 --- a/crates/engine/src/cmd/blocks/xclip.rs +++ b/crates/engine/src/cmd/blocks/xclip.rs @@ -280,6 +280,15 @@ impl XclipM { } } + /// Delete: as the reference app, with nothing to delete it says so and asks again. + fn delete(&mut self, s: &mut Session) -> Result { + if !self.any_clipped(s) { + s.echo("No clip boundary found."); + return Ok(Step::Continue); + } + self.apply(s, json!({ "option": "delete" })) + } + fn any_clipped(&self, s: &Session) -> bool { self.refs.iter().any(|h| clip_of(s, *h).is_some()) } @@ -352,7 +361,7 @@ impl Interactive for XclipM { s.echo("Clip depth does not apply to a 2D drawing: front and back clipping planes are ignored."); Ok(Step::Done) } - Some(k) if k.starts_with('d') => self.apply(s, json!({ "option": "delete" })), + Some(k) if k.starts_with('d') => self.delete(s), Some(k) if k.starts_with('p') || k.starts_with('g') => self.apply(s, json!({ "option": "polyline" })), Some(k) if k.starts_with('n') => { self.stage = if self.any_clipped(s) { Stage::DeleteOld } else { Stage::Boundary }; diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 6721cdad8..b92c6b14f 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -527,6 +527,7 @@ mod tests { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap(); (d, h) diff --git a/crates/engine/tests/it/xclip.rs b/crates/engine/tests/it/xclip.rs index 0b1d64443..664acd0bd 100644 --- a/crates/engine/tests/it/xclip.rs +++ b/crates/engine/tests/it/xclip.rs @@ -80,6 +80,23 @@ fn rectangular_clip_cuts_only_that_reference() { assert!(clip(&s, &r1).is_some()); } +#[test] +fn extents_are_the_boundary_box_as_in_the_reference_app() { + let (mut s, r1, _) = setup(); + let bounds = |s: &Session| { + let d = s.doc().unwrap(); + cadcraft_engine::doc::entity_bounds(d, d.entity(Handle::parse_hex(&r1).unwrap()).unwrap(), 0) + }; + // A boundary reaching past the block (0..100 x -50..50): its own box, not the overlap. + s.execute("xclip", &json!({ "handle": r1, "rectangle": [[50, -20], [150, 30]] })).unwrap(); + let b = bounds(&s); + assert!((b.min - Vec2::new(50.0, -20.0)).length() < 1e-9 && (b.max - Vec2::new(150.0, 30.0)).length() < 1e-9, "{b:?}"); + // One that misses the block entirely: still its box. + s.execute("xclip", &json!({ "handle": r1, "rectangle": [[200, 200], [300, 300]] })).unwrap(); + let b = bounds(&s); + assert!((b.min - Vec2::new(200.0, 200.0)).length() < 1e-9 && (b.max - Vec2::new(300.0, 300.0)).length() < 1e-9, "{b:?}"); +} + #[test] fn rotated_and_scaled_reference_gets_a_polygon_in_block_coordinates() { let (mut s, _, r2) = setup(); @@ -189,6 +206,14 @@ fn typed_xclip_follows_the_prompts() { s.input(Input::Enter).unwrap(); s.cmdline("d").unwrap(); assert!(clip(&s, &r1).is_none() && clip(&s, &r2).is_none()); + // Delete with no boundary left says so and asks again. + s.start("xclip").unwrap(); + s.input(pick(&r1)).unwrap(); + s.input(Input::Enter).unwrap(); + s.cmdline("d").unwrap(); + assert!(s.log.iter().any(|l| l.contains("No clip boundary found.")), "{:?}", s.log); + assert!(s.prompt_text().contains("Enter clipping option"), "{}", s.prompt_text()); + s.input(Input::Cancel).unwrap(); // XCLIPFRAME typed. s.cmdline("xclipframe").unwrap(); s.cmdline("1").unwrap(); diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs index fc3d56316..02614b784 100644 --- a/crates/io/src/dxf_clip.rs +++ b/crates/io/src/dxf_clip.rs @@ -4,10 +4,7 @@ //! 10/20 the vertices), whether clipping is on (71), the front and back clip (72/73, 40/41) and //! two 3×4 matrices (group 40, row by row): the inverse of the reference's transform, which takes //! the boundary into the block's coordinates, and the boundary's own transform (identity here). -//! -//! An inverted clip is CADCraft's own entry `CADCRAFT_XCLIP` beside `ACAD_FILTER` in the same -//! extension dictionary: an XRECORD with group 70 = 1. Other programs keep it as unknown data and -//! clip normally. +//! Group 290 is 1 for an inverted clip ("Invert clip"), as the reference app writes it. //! //! Reading takes the planar filters the model can hold out of the kept foreign data and puts them //! on the references ([`read`]); others (front/back clipping, a skewed boundary transform) stay @@ -21,8 +18,6 @@ use cadcraft_doc::foreign::{Foreign, ForeignObject}; use cadcraft_doc::{ClipBoundary, Drawing, EntityKind, Handle, MAX_CLIP_VERTICES, RawTag}; use cadcraft_geom::{Mat3, Vec2}; -/// The extension-dictionary entry of CADCraft's inverted-clip flag. -const INVERT_KEY: &str = "CADCRAFT_XCLIP"; /// Handles above this are not handed out (the DXF handle space is 64-bit, keep a margin). const MAX_HANDLE: u64 = 1 << 48; @@ -125,18 +120,10 @@ fn parse_filter(o: &ForeignObject) -> Option { } points.push(p); } - let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted: false }; + let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted: number(&o.tags, 290).is_some_and(|v| v != 0.0) }; (clip.points.len() == count && cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some()).then_some(clip) } -/// Whether the extension dictionary `xd` marks the clip inverted. -fn inverted(f: &Foreign, xd: Handle) -> bool { - object(f, xd) - .and_then(|o| entry(&o.tags, INVERT_KEY)) - .and_then(|h| object(f, h)) - .is_some_and(|o| o.kind.eq_ignore_ascii_case("XRECORD") && number(&o.tags, 70).is_some_and(|v| v != 0.0)) -} - /// Put the planar filters of the file read into `d` on their references, taking them out of /// the kept foreign data (the model writes them from now on). pub(crate) fn read(d: &mut Drawing) { @@ -148,10 +135,8 @@ pub(crate) fn read(d: &mut Drawing) { .entities .keys() .filter_map(|h| { - let (xd, _, o) = chain(&d.foreign, *h)?; - let mut clip = parse_filter(o)?; - clip.inverted = inverted(&d.foreign, xd); - Some((*h, clip)) + let (_, _, o) = chain(&d.foreign, *h)?; + Some((*h, parse_filter(o)?)) }) .collect(); if found.is_empty() { @@ -188,14 +173,13 @@ pub(crate) fn read(d: &mut Drawing) { } /// Take the clip of entity `h` out of the foreign data: the ACAD_FILTER entry and what it holds, -/// CADCraft's inverted flag, and the extension dictionary when nothing else is left in it. +/// and the extension dictionary when nothing else is left in it. fn forget(f: &mut Foreign, h: Handle) { let Some(xd) = f.entities.get(&h).and_then(|x| x.xdict) else { return }; let mut gone: Vec = Vec::new(); let mut empty = false; if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { gone.extend(remove_entry(&mut o.tags, "ACAD_FILTER")); - gone.extend(remove_entry(&mut o.tags, INVERT_KEY)); empty = !o.tags.iter().any(|t| t.code == 3); } // The filter dictionary's entries go with it. @@ -264,26 +248,10 @@ fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3 for v in matrix_values(inverse).into_iter().chain(matrix_values(&Mat3::IDENTITY)) { tags.push(raw(40, v)); } + tags.push(raw(290, i32::from(clip.inverted))); ForeignObject { handle: h, kind: "SPATIAL_FILTER".into(), tags } } -fn invert_record(h: Handle, owner: Handle) -> ForeignObject { - ForeignObject { - handle: h, - kind: "XRECORD".into(), - tags: vec![ - raw(5, h.hex()), - raw(102, "{ACAD_REACTORS"), - raw(330, owner.hex()), - raw(102, "}"), - raw(330, owner.hex()), - raw(100, "AcDbXrecord"), - raw(280, 1), - raw(70, 1), - ], - } -} - /// A copy of `d` whose foreign data holds the SPATIAL_FILTER of every clipped reference (any /// filter kept from the file for it is replaced). `None` when no reference is clipped. pub(crate) fn prepare(d: &Drawing) -> Option { @@ -328,20 +296,13 @@ pub(crate) fn prepare(d: &Drawing) -> Option { } }; let (fd, sf) = (fresh(&mut next), fresh(&mut next)); - let flag = clip.inverted.then(|| fresh(&mut next)); if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { o.tags.extend([raw(3, "ACAD_FILTER"), raw(360, fd.hex())]); - if let Some(x) = flag { - o.tags.extend([raw(3, INVERT_KEY), raw(360, x.hex())]); - } } let mut filters = dictionary(fd, xd); filters.tags.extend([raw(3, "SPATIAL"), raw(360, sf.hex())]); f.objects.push(filters); f.objects.push(spatial_filter(sf, fd, &clip, &to_world, &inverse)); - if let Some(x) = flag { - f.objects.push(invert_record(x, xd)); - } } Some(out) } @@ -369,6 +330,19 @@ mod tests { assert!(parse_filter(&o(vec![raw(70, 2), raw(10, "nan"), raw(20, 0), raw(10, 1), raw(20, 1)])).is_none()); assert!(parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1), raw(72, 1)])).is_none()); let ok = parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1)])).unwrap(); - assert_eq!(ok.points.len(), 2); + assert_eq!((ok.points.len(), ok.inverted), (2, false)); + } + + #[test] + fn group_290_is_the_inverted_flag() { + let tags = |invert: &str| vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1), raw(290, invert)]; + let o = |invert| ForeignObject { handle: Handle(1), kind: "SPATIAL_FILTER".into(), tags: tags(invert) }; + assert!(parse_filter(&o("1")).unwrap().inverted); + assert!(!parse_filter(&o("0")).unwrap().inverted); + assert!(!parse_filter(&o("junk")).unwrap().inverted); + let clip = ClipBoundary { inverted: true, ..ClipBoundary::new(vec![Vec2::ZERO, Vec2::new(1.0, 1.0)]) }; + let written = spatial_filter(Handle(2), Handle(1), &clip, &Mat3::IDENTITY, &Mat3::IDENTITY); + assert!(written.tags.iter().any(|t| t.code == 290 && t.value == "1")); + assert!(parse_filter(&written).unwrap().inverted); } } diff --git a/crates/io/tests/it/block_expansion.rs b/crates/io/tests/it/block_expansion.rs index 64fca189e..8a6e142a7 100644 --- a/crates/io/tests/it/block_expansion.rs +++ b/crates/io/tests/it/block_expansion.rs @@ -103,6 +103,7 @@ fn an_empty_followup_viewport_does_not_mark_an_exact_budget_truncated() { rows: 1_000, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap(); let viewport = |center: Vec3, view_center: Vec2, frozen_layers| Viewport { diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index dd47c43c9..9c4943350 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -462,6 +462,7 @@ fn door_reference(src: &str) -> (cadcraft_doc::Drawing, Handle) { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(ins)).unwrap(); (d, r) diff --git a/crates/io/tests/it/roundtrip/cases/blocks.rs b/crates/io/tests/it/roundtrip/cases/blocks.rs index a1af6218a..51a8ba0c0 100644 --- a/crates/io/tests/it/roundtrip/cases/blocks.rs +++ b/crates/io/tests/it/roundtrip/cases/blocks.rs @@ -20,6 +20,7 @@ pub(crate) fn insert(block: &str) -> Insert { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, } } diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs index d4bd1541a..e263f47f8 100644 --- a/crates/io/tests/it/roundtrip/compare.rs +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -263,7 +263,7 @@ fn attrib(expected: &Attrib, actual: &Attrib, context: &str) { } fn insert(expected: &Insert, actual: &Insert, context: &str) { - let Insert { block, insert, scale, rotation, attribs, cols, rows, col_spacing, row_spacing } = expected; + let Insert { block, insert, scale, rotation, attribs, cols, rows, col_spacing, row_spacing, clip } = expected; equal(block, &actual.block, context, "insert.block"); equal(insert, &actual.insert, context, "insert.insert"); equal(scale, &actual.scale, context, "insert.scale"); @@ -272,6 +272,7 @@ fn insert(expected: &Insert, actual: &Insert, context: &str) { equal(rows, &actual.rows, context, "insert.rows"); equal(col_spacing, &actual.col_spacing, context, "insert.col_spacing"); equal(row_spacing, &actual.row_spacing, context, "insert.row_spacing"); + equal(clip, &actual.clip, context, "insert.clip"); equal(&attribs.len(), &actual.attribs.len(), context, "insert.attribs.len"); for (index, (a, b)) in attribs.iter().zip(&actual.attribs).enumerate() { attrib(a, b, &format!("{context}.attrib[{index}]")); diff --git a/crates/io/tests/it/xclip_roundtrip.rs b/crates/io/tests/it/xclip_roundtrip.rs index 1e07ecf23..762ac1700 100644 --- a/crates/io/tests/it/xclip_roundtrip.rs +++ b/crates/io/tests/it/xclip_roundtrip.rs @@ -77,7 +77,11 @@ fn clips_round_trip_through_dxf() { let bytes = save(&d, "a.dxf", Version::R2018); let text = String::from_utf8(bytes.clone()).unwrap(); assert_eq!(text.matches("SPATIAL_FILTER").count(), 3, "one filter per clipped reference"); - assert!(text.contains("ACAD_FILTER") && text.contains("CADCRAFT_XCLIP")); + assert!(text.contains("ACAD_FILTER") && !text.contains("CADCRAFT_XCLIP")); + // The inverted triangle is marked on its filter (group 290), as the reference app writes it. + let filters: Vec<&str> = text.split("\r\nSPATIAL_FILTER\r\n").skip(1).map(|f| f.split("\r\n 0\r\n").next().unwrap_or("")).collect(); + assert!(filters.iter().all(|f| f.contains("\r\n290\r\n")), "every filter says whether it is inverted"); + assert_eq!(filters.iter().filter(|f| f.contains("\r\n290\r\n1\r\n")).count(), 1); let first = read(&bytes, "a.dxf").unwrap(); same(&clips(&first), &clips(&d)); // The model owns the filters now: nothing of them is left as foreign data. From e90a19736577ccbd815574a6f2291e9c19cd98b5 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 18:07:00 -0700 Subject: [PATCH 226/531] XCLIP: keep CADCraft's inverted flag beside group 290 for DWG, whose bridge drops 290; the flag is read only when 290 is absent --- crates/engine/tests/it/xclip.rs | 4 +-- crates/io/src/dxf_clip.rs | 49 +++++++++++++++++++++++++-- crates/io/tests/it/xclip_roundtrip.rs | 8 +++-- crates/render/src/viewports.rs | 8 +++++ crates/render/tests/raster_image.rs | 1 + 5 files changed, 62 insertions(+), 8 deletions(-) diff --git a/crates/engine/tests/it/xclip.rs b/crates/engine/tests/it/xclip.rs index 664acd0bd..603640bc1 100644 --- a/crates/engine/tests/it/xclip.rs +++ b/crates/engine/tests/it/xclip.rs @@ -90,11 +90,11 @@ fn extents_are_the_boundary_box_as_in_the_reference_app() { // A boundary reaching past the block (0..100 x -50..50): its own box, not the overlap. s.execute("xclip", &json!({ "handle": r1, "rectangle": [[50, -20], [150, 30]] })).unwrap(); let b = bounds(&s); - assert!((b.min - Vec2::new(50.0, -20.0)).length() < 1e-9 && (b.max - Vec2::new(150.0, 30.0)).length() < 1e-9, "{b:?}"); + assert!((b.min - Vec2::new(50.0, -20.0)).len() < 1e-9 && (b.max - Vec2::new(150.0, 30.0)).len() < 1e-9, "{b:?}"); // One that misses the block entirely: still its box. s.execute("xclip", &json!({ "handle": r1, "rectangle": [[200, 200], [300, 300]] })).unwrap(); let b = bounds(&s); - assert!((b.min - Vec2::new(200.0, 200.0)).length() < 1e-9 && (b.max - Vec2::new(300.0, 300.0)).length() < 1e-9, "{b:?}"); + assert!((b.min - Vec2::new(200.0, 200.0)).len() < 1e-9 && (b.max - Vec2::new(300.0, 300.0)).len() < 1e-9, "{b:?}"); } #[test] diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs index 02614b784..dedc1fd17 100644 --- a/crates/io/src/dxf_clip.rs +++ b/crates/io/src/dxf_clip.rs @@ -6,6 +6,10 @@ //! the boundary into the block's coordinates, and the boundary's own transform (identity here). //! Group 290 is 1 for an inverted clip ("Invert clip"), as the reference app writes it. //! +//! The DWG bridge drops group 290, so an inverted clip is also marked by CADCraft's own entry +//! `CADCRAFT_XCLIP` beside `ACAD_FILTER` (an XRECORD with group 70 = 1), which a DWG keeps. It +//! is read only when the filter has no group 290. +//! //! Reading takes the planar filters the model can hold out of the kept foreign data and puts them //! on the references ([`read`]); others (front/back clipping, a skewed boundary transform) stay //! foreign and are written back untouched. Writing adds the dictionaries and the filter of every @@ -18,6 +22,8 @@ use cadcraft_doc::foreign::{Foreign, ForeignObject}; use cadcraft_doc::{ClipBoundary, Drawing, EntityKind, Handle, MAX_CLIP_VERTICES, RawTag}; use cadcraft_geom::{Mat3, Vec2}; +/// The extension-dictionary entry of CADCraft's inverted-clip flag (for DWG, see above). +const INVERT_KEY: &str = "CADCRAFT_XCLIP"; /// Handles above this are not handed out (the DXF handle space is 64-bit, keep a margin). const MAX_HANDLE: u64 = 1 << 48; @@ -124,6 +130,14 @@ fn parse_filter(o: &ForeignObject) -> Option { (clip.points.len() == count && cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some()).then_some(clip) } +/// Whether the extension dictionary `xd` marks the clip inverted (CADCraft's own flag). +fn inverted_record(f: &Foreign, xd: Handle) -> bool { + object(f, xd) + .and_then(|o| entry(&o.tags, INVERT_KEY)) + .and_then(|h| object(f, h)) + .is_some_and(|o| o.kind.eq_ignore_ascii_case("XRECORD") && number(&o.tags, 70).is_some_and(|v| v != 0.0)) +} + /// Put the planar filters of the file read into `d` on their references, taking them out of /// the kept foreign data (the model writes them from now on). pub(crate) fn read(d: &mut Drawing) { @@ -135,8 +149,12 @@ pub(crate) fn read(d: &mut Drawing) { .entities .keys() .filter_map(|h| { - let (_, _, o) = chain(&d.foreign, *h)?; - Some((*h, parse_filter(o)?)) + let (xd, _, o) = chain(&d.foreign, *h)?; + let mut clip = parse_filter(o)?; + if number(&o.tags, 290).is_none() { + clip.inverted = inverted_record(&d.foreign, xd); + } + Some((*h, clip)) }) .collect(); if found.is_empty() { @@ -173,13 +191,14 @@ pub(crate) fn read(d: &mut Drawing) { } /// Take the clip of entity `h` out of the foreign data: the ACAD_FILTER entry and what it holds, -/// and the extension dictionary when nothing else is left in it. +/// CADCraft's inverted flag, and the extension dictionary when nothing else is left in it. fn forget(f: &mut Foreign, h: Handle) { let Some(xd) = f.entities.get(&h).and_then(|x| x.xdict) else { return }; let mut gone: Vec = Vec::new(); let mut empty = false; if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { gone.extend(remove_entry(&mut o.tags, "ACAD_FILTER")); + gone.extend(remove_entry(&mut o.tags, INVERT_KEY)); empty = !o.tags.iter().any(|t| t.code == 3); } // The filter dictionary's entries go with it. @@ -252,6 +271,23 @@ fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3 ForeignObject { handle: h, kind: "SPATIAL_FILTER".into(), tags } } +fn invert_record(h: Handle, owner: Handle) -> ForeignObject { + ForeignObject { + handle: h, + kind: "XRECORD".into(), + tags: vec![ + raw(5, h.hex()), + raw(102, "{ACAD_REACTORS"), + raw(330, owner.hex()), + raw(102, "}"), + raw(330, owner.hex()), + raw(100, "AcDbXrecord"), + raw(280, 1), + raw(70, 1), + ], + } +} + /// A copy of `d` whose foreign data holds the SPATIAL_FILTER of every clipped reference (any /// filter kept from the file for it is replaced). `None` when no reference is clipped. pub(crate) fn prepare(d: &Drawing) -> Option { @@ -296,13 +332,20 @@ pub(crate) fn prepare(d: &Drawing) -> Option { } }; let (fd, sf) = (fresh(&mut next), fresh(&mut next)); + let flag = clip.inverted.then(|| fresh(&mut next)); if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { o.tags.extend([raw(3, "ACAD_FILTER"), raw(360, fd.hex())]); + if let Some(x) = flag { + o.tags.extend([raw(3, INVERT_KEY), raw(360, x.hex())]); + } } let mut filters = dictionary(fd, xd); filters.tags.extend([raw(3, "SPATIAL"), raw(360, sf.hex())]); f.objects.push(filters); f.objects.push(spatial_filter(sf, fd, &clip, &to_world, &inverse)); + if let Some(x) = flag { + f.objects.push(invert_record(x, xd)); + } } Some(out) } diff --git a/crates/io/tests/it/xclip_roundtrip.rs b/crates/io/tests/it/xclip_roundtrip.rs index 762ac1700..727165d6c 100644 --- a/crates/io/tests/it/xclip_roundtrip.rs +++ b/crates/io/tests/it/xclip_roundtrip.rs @@ -77,11 +77,13 @@ fn clips_round_trip_through_dxf() { let bytes = save(&d, "a.dxf", Version::R2018); let text = String::from_utf8(bytes.clone()).unwrap(); assert_eq!(text.matches("SPATIAL_FILTER").count(), 3, "one filter per clipped reference"); - assert!(text.contains("ACAD_FILTER") && !text.contains("CADCRAFT_XCLIP")); - // The inverted triangle is marked on its filter (group 290), as the reference app writes it. + // The inverted triangle also carries CADCraft's flag, which a DWG keeps. + assert!(text.contains("ACAD_FILTER") && text.matches("CADCRAFT_XCLIP").count() == 1); + // The inverted triangle is marked on its filter (group 290, last), as the reference app writes it. let filters: Vec<&str> = text.split("\r\nSPATIAL_FILTER\r\n").skip(1).map(|f| f.split("\r\n 0\r\n").next().unwrap_or("")).collect(); + assert_eq!(filters.len(), 3); assert!(filters.iter().all(|f| f.contains("\r\n290\r\n")), "every filter says whether it is inverted"); - assert_eq!(filters.iter().filter(|f| f.contains("\r\n290\r\n1\r\n")).count(), 1); + assert_eq!(filters.iter().filter(|f| f.ends_with("\r\n290\r\n1")).count(), 1, "{filters:?}"); let first = read(&bytes, "a.dxf").unwrap(); same(&clips(&first), &clips(&d)); // The model owns the filters now: nothing of them is left as foreign data. diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 6ec10d261..5dbc496c5 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -309,6 +309,14 @@ fn push_clipped_image(dst: &mut DisplayList, p: &DPrim, img: &DImage, corners: & let (outline, area) = match clip { Clip::Rect(rect) => (vec![rect.min, Vec2::new(rect.max.x, rect.min.y), rect.max, Vec2::new(rect.min.x, rect.max.y)], *rect), Clip::Poly(c) => (c.polygon().to_vec(), c.bounds()), + // An image can only be cut to the inside of an outline: under an inverted XCLIP it is + // drawn whole, which shows too much rather than losing any of it. + Clip::Outside(_) => { + let Ok(index) = u32::try_from(dst.images.len()) else { return }; + dst.images.push(img.clone()); + push_raw(dst, p, Kind::Image { index }, corners); + return; + } }; let own = Bounds2::from_points(corners.iter().copied()); if !own.intersects(&area) { diff --git a/crates/render/tests/raster_image.rs b/crates/render/tests/raster_image.rs index bdf03dd44..03016e79d 100644 --- a/crates/render/tests/raster_image.rs +++ b/crates/render/tests/raster_image.rs @@ -219,6 +219,7 @@ fn an_image_in_a_block_follows_the_block_reference() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(ins.clone())).unwrap(); d.rasters.insert("map.png", pixels()); From 01e28fc0d4bf92e28e0cd3923760f4ed6f73721c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 02:12:01 +0100 Subject: [PATCH 227/531] contributors: set names for vangel76 Co-Authored-By: Claude Sonnet 5.5 --- contributors/people.toml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contributors/people.toml b/contributors/people.toml index 8bb73b9ea..a0c46caef 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -37,7 +37,9 @@ display_name = "Tasos Sangiotis" sync_github_name = false [people.vangel76] -sync_github_name = true +real_name = "Valentin Klein" +display_name = "vangel76" +sync_github_name = false [people.WladmirJunior] real_name = "Wladmir Júnior" From 639c2e982576dd654d3df60244575e831c650b52 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 18:20:48 -0700 Subject: [PATCH 228/531] XCLIP: clip on DVIEW's preview reference --- crates/engine/src/cmd/view/dview.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs index 221459c3c..3133fd6fa 100644 --- a/crates/engine/src/cmd/view/dview.rs +++ b/crates/engine/src/cmd/view/dview.rs @@ -409,6 +409,7 @@ impl Interactive for DviewM { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; extra.push(Entity { handle: Handle(0), common, kind: EntityKind::Insert(ins) }); } else { From 510b7283cb2ac71edf75ff88c974f7b16fbd6658 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 19:11:23 -0700 Subject: [PATCH 229/531] XCLIP: Chinese labels for Clip Xref, Xref and Xref Clip Frame --- crates/ui-egui/src/i18n/zh.tsv | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index e44c82864..a07b4f027 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1469,3 +1469,6 @@ menu Dimension 标注 menu Draw 绘图 menu Modify 修改 menu View 视图 + Clip Xref 剪裁外部参照 + Xref 外部参照 + Xref Clip Frame 外部参照剪裁边框 From ef4b4f7e6cd20d2e96172cf9bf76ad698aba3b1d Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 19:34:20 -0700 Subject: [PATCH 230/531] XCLIP: review fixes from CodeRabbit on #2756 - objects are found through a handle index when reading and writing clips, and removed in one pass (no scan per reference) - the writer's handle seed starts past the clip objects, so a drawing with many clipped references gets no duplicate handles - a clipped copy that runs out of the block budget marks the list truncated, like an unclipped one - clipped block contents keep their own layers in plots --- crates/engine/tests/it/xclip.rs | 20 ++++++++ crates/io/src/dxf_clip.rs | 87 ++++++++++++++++++++++++--------- crates/render/src/blocks.rs | 1 + crates/render/src/viewports.rs | 9 +++- 4 files changed, 93 insertions(+), 24 deletions(-) diff --git a/crates/engine/tests/it/xclip.rs b/crates/engine/tests/it/xclip.rs index 603640bc1..97349e782 100644 --- a/crates/engine/tests/it/xclip.rs +++ b/crates/engine/tests/it/xclip.rs @@ -80,6 +80,26 @@ fn rectangular_clip_cuts_only_that_reference() { assert!(clip(&s, &r1).is_some()); } +#[test] +fn a_clipped_reference_plots_its_contents_on_their_own_layers() { + let mut s = Session::new(); + s.doc_mut().unwrap().layers.push(cadcraft_engine::doc::Layer { name: "Walls".into(), ..Default::default() }); + let a = h(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap()); + let b = h(&s.execute("line", &json!({ "points": [[50, -50], [50, 50]] })).unwrap()); + s.doc_mut().unwrap().modify_entity(Handle::parse_hex(&a).unwrap(), |e| e.common.layer = "Walls".into()).unwrap(); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [a, b], "keep": "delete" })).unwrap(); + let r = insert(&mut s, "B", (0.0, 0.0), 1.0, 0.0); + s.execute("setvar", &json!({ "name": "XCLIPFRAME", "value": 0 })).unwrap(); + s.execute("xclip", &json!({ "handle": r, "rectangle": [[20, -10], [70, 10]] })).unwrap(); + let d = s.doc().unwrap(); + let index = |name: &str| d.layers.iter().position(|l| l.name == name).map(|i| i as u32); + let list = render::build_plot(d, &Space::Model, &Options::default()); + assert_eq!(list.prim_layers.len(), list.prims.len()); + // The horizontal line is on Walls, the vertical one (layer 0) takes the reference's layer. + assert!(list.prim_layers.contains(&index("Walls").unwrap()), "{:?}", list.prim_layers); + assert!(list.prim_layers.contains(&index("0").unwrap()), "{:?}", list.prim_layers); +} + #[test] fn extents_are_the_boundary_box_as_in_the_reference_app() { let (mut s, r1, _) = setup(); diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs index dedc1fd17..0e120d9be 100644 --- a/crates/io/src/dxf_clip.rs +++ b/crates/io/src/dxf_clip.rs @@ -16,6 +16,7 @@ //! clipped reference to a copy of the drawing's foreign data ([`prepare`]), which the raw-data //! writer (#528) then places on the reference. +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use cadcraft_doc::foreign::{Foreign, ForeignObject}; @@ -58,16 +59,28 @@ fn number(tags: &[RawTag], code: i32) -> Option { tags.iter().find(|t| t.code == code)?.value.trim().parse::().ok().filter(|n| n.is_finite()) } -fn object(f: &Foreign, h: Handle) -> Option<&ForeignObject> { - f.objects.iter().find(|o| o.handle == h) +/// Where each handle's object is in `Foreign::objects` (the first, as a scan would find it), so +/// a file with many references and objects isn't searched once per reference. +type Index = HashMap; + +fn index(f: &Foreign) -> Index { + let mut idx = Index::with_capacity(f.objects.len()); + for (i, o) in f.objects.iter().enumerate() { + idx.entry(o.handle).or_insert(i); + } + idx +} + +fn object<'a>(f: &'a Foreign, idx: &Index, h: Handle) -> Option<&'a ForeignObject> { + f.objects.get(*idx.get(&h)?) } /// The extension dictionary, ACAD_FILTER dictionary and SPATIAL_FILTER of entity `h`. -fn chain(f: &Foreign, h: Handle) -> Option<(Handle, Handle, &ForeignObject)> { +fn chain<'a>(f: &'a Foreign, idx: &Index, h: Handle) -> Option<(Handle, Handle, &'a ForeignObject)> { let xd = f.entities.get(&h)?.xdict?; - let fd = entry(&object(f, xd)?.tags, "ACAD_FILTER")?; - let sf = entry(&object(f, fd)?.tags, "SPATIAL")?; - Some((xd, fd, object(f, sf).filter(|o| o.kind.eq_ignore_ascii_case("SPATIAL_FILTER"))?)) + let fd = entry(&object(f, idx, xd)?.tags, "ACAD_FILTER")?; + let sf = entry(&object(f, idx, fd)?.tags, "SPATIAL")?; + Some((xd, fd, object(f, idx, sf).filter(|o| o.kind.eq_ignore_ascii_case("SPATIAL_FILTER"))?)) } /// A 3×4 matrix (12 values row by row) as a 2D transform, when it is one (no Z mixing). @@ -131,10 +144,10 @@ fn parse_filter(o: &ForeignObject) -> Option { } /// Whether the extension dictionary `xd` marks the clip inverted (CADCraft's own flag). -fn inverted_record(f: &Foreign, xd: Handle) -> bool { - object(f, xd) +fn inverted_record(f: &Foreign, idx: &Index, xd: Handle) -> bool { + object(f, idx, xd) .and_then(|o| entry(&o.tags, INVERT_KEY)) - .and_then(|h| object(f, h)) + .and_then(|h| object(f, idx, h)) .is_some_and(|o| o.kind.eq_ignore_ascii_case("XRECORD") && number(&o.tags, 70).is_some_and(|v| v != 0.0)) } @@ -144,15 +157,16 @@ pub(crate) fn read(d: &mut Drawing) { if d.foreign.objects.is_empty() { return; } + let idx = index(&d.foreign); let found: Vec<(Handle, ClipBoundary)> = d .foreign .entities .keys() .filter_map(|h| { - let (xd, _, o) = chain(&d.foreign, *h)?; + let (xd, _, o) = chain(&d.foreign, &idx, *h)?; let mut clip = parse_filter(o)?; if number(&o.tags, 290).is_none() { - clip.inverted = inverted_record(&d.foreign, xd); + clip.inverted = inverted_record(&d.foreign, &idx, xd); } Some((*h, clip)) }) @@ -185,18 +199,21 @@ pub(crate) fn read(d: &mut Drawing) { } } let f = Arc::make_mut(&mut d.foreign); + let mut gone = HashSet::new(); for h in taken { - forget(f, h); + forget(f, &idx, h, &mut gone); } + f.objects.retain(|o| !gone.contains(&o.handle)); } /// Take the clip of entity `h` out of the foreign data: the ACAD_FILTER entry and what it holds, -/// CADCraft's inverted flag, and the extension dictionary when nothing else is left in it. -fn forget(f: &mut Foreign, h: Handle) { +/// CADCraft's inverted flag, and the extension dictionary when nothing else is left in it. The +/// objects to remove are added to `gone`; the caller removes them all at once. +fn forget(f: &mut Foreign, idx: &Index, h: Handle, all_gone: &mut HashSet) { let Some(xd) = f.entities.get(&h).and_then(|x| x.xdict) else { return }; let mut gone: Vec = Vec::new(); let mut empty = false; - if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { + if let Some(o) = idx.get(&xd).copied().and_then(|i| f.objects.get_mut(i)) { gone.extend(remove_entry(&mut o.tags, "ACAD_FILTER")); gone.extend(remove_entry(&mut o.tags, INVERT_KEY)); empty = !o.tags.iter().any(|t| t.code == 3); @@ -204,7 +221,7 @@ fn forget(f: &mut Foreign, h: Handle) { // The filter dictionary's entries go with it. let mut i = 0; while let Some(g) = gone.get(i).copied() { - if let Some(o) = object(f, g) + if let Some(o) = object(f, idx, g) && o.kind.eq_ignore_ascii_case("DICTIONARY") { gone.extend(o.tags.windows(2).filter_map(|w| match w { @@ -226,7 +243,7 @@ fn forget(f: &mut Foreign, h: Handle) { f.entities.remove(&h); } } - f.objects.retain(|o| !gone.contains(&o.handle)); + all_gone.extend(gone); } fn dictionary(h: Handle, owner: Handle) -> ForeignObject { @@ -315,17 +332,20 @@ pub(crate) fn prepare(d: &Drawing) -> Option { *next = next.saturating_add(1); h } + let mut idx = index(f); + let mut gone = HashSet::new(); for (insert, clip, to_world) in clips { let Some(inverse) = to_world.inverse() else { continue }; if next.saturating_add(5) >= MAX_HANDLE { break; } // A filter kept from the file for this reference is replaced. - forget(f, insert); - let xd = match f.entities.get(&insert).and_then(|x| x.xdict).filter(|h| object(f, *h).is_some()) { + forget(f, &idx, insert, &mut gone); + let xd = match f.entities.get(&insert).and_then(|x| x.xdict).filter(|h| idx.contains_key(h) && !gone.contains(h)) { Some(h) => h, None => { let h = fresh(&mut next); + idx.insert(h, f.objects.len()); f.objects.push(dictionary(h, insert)); f.entities.entry(insert).or_default().xdict = Some(h); h @@ -333,7 +353,7 @@ pub(crate) fn prepare(d: &Drawing) -> Option { }; let (fd, sf) = (fresh(&mut next), fresh(&mut next)); let flag = clip.inverted.then(|| fresh(&mut next)); - if let Some(o) = f.objects.iter_mut().find(|o| o.handle == xd) { + if let Some(o) = idx.get(&xd).copied().and_then(|i| f.objects.get_mut(i)) { o.tags.extend([raw(3, "ACAD_FILTER"), raw(360, fd.hex())]); if let Some(x) = flag { o.tags.extend([raw(3, INVERT_KEY), raw(360, x.hex())]); @@ -341,12 +361,19 @@ pub(crate) fn prepare(d: &Drawing) -> Option { } let mut filters = dictionary(fd, xd); filters.tags.extend([raw(3, "SPATIAL"), raw(360, sf.hex())]); - f.objects.push(filters); - f.objects.push(spatial_filter(sf, fd, &clip, &to_world, &inverse)); + let mut add = |o: ForeignObject| { + idx.insert(o.handle, f.objects.len()); + f.objects.push(o); + }; + add(filters); + add(spatial_filter(sf, fd, &clip, &to_world, &inverse)); if let Some(x) = flag { - f.objects.push(invert_record(x, xd)); + add(invert_record(x, xd)); } } + f.objects.retain(|o| !gone.contains(&o.handle)); + // The writer hands out handles of its own from the seed on: start it past these. + out.handseed = out.handseed.max(next); Some(out) } @@ -376,6 +403,20 @@ mod tests { assert_eq!((ok.points.len(), ok.inverted), (2, false)); } + #[test] + fn the_writer_starts_its_handles_past_the_clip_objects() { + let mut d = Drawing::new_metric(); + d.blocks.insert("B".into(), Arc::new(cadcraft_doc::Block::new("B"))); + for i in 0..3 { + let clip = ClipBoundary::new(vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)]); + let ins = cadcraft_doc::Insert { block: "B".into(), clip: Some(ClipBoundary { inverted: i == 0, ..clip }), ..Default::default() }; + d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + } + let out = prepare(&d).unwrap(); + let highest = out.foreign.objects.iter().map(|o| o.handle.0).max().unwrap(); + assert!(out.handseed > highest, "seed {} at or below {highest}", out.handseed); + } + #[test] fn group_290_is_the_inverted_flag() { let tags = |invert: &str| vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1), raw(290, invert)]; diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index 6b91c3a09..976840fbd 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -75,6 +75,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: } if let (Some(part), Some((region, inverted))) = (part, &clip) { b.list.expanded = part.list.expanded; + b.list.truncated |= part.list.truncated; append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) }); xclip_frame(b, ctx, region, rgb); } diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 91eda9689..82885b85f 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -1,6 +1,6 @@ #[cfg(not(target_arch = "wasm32"))] use super::display::append; -use super::display::{DImage, DPrim, DisplayList, Kind, PlotText, VIEWPORT_CONTENT}; +use super::display::{DImage, DPrim, DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT}; use super::draw::entity; #[cfg(not(target_arch = "wasm32"))] use super::pipeline::PARALLEL_CHUNK; @@ -221,6 +221,13 @@ pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip for (i, p) in src.prims.iter().enumerate() { let first = dst.prims.len(); clip_prim(dst, src, p, clip); + // Each piece keeps its source's layer (block contents not on layer 0 keep theirs). + if let Some(layer) = src.prim_layers.get(i).copied() { + for k in first..dst.prims.len() { + dst.prim_layers.resize(k, NO_LAYER); + dst.prim_layers.push(layer); + } + } if let Some(pen) = src.pens.get(i).copied().filter(|pen| !pen.is_object()) { for k in first..dst.prims.len() { dst.pens.resize(k, Pen::default()); From 96a9fa615c286f46cbd9ee73ae729e9aad2cbdc8 Mon Sep 17 00:00:00 2001 From: Zaxaerith <189452125+Zaxaerith@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:13:46 +0800 Subject: [PATCH 231/531] fix(engine): clarify JSON TRIM and EXTEND pick diagnostics (#2750) --- crates/engine/src/cmd/modify.rs | 20 ++- crates/engine/src/cmd/modify/trim.rs | 40 +++++ crates/engine/src/cmd/trimextend.rs | 17 ++- crates/engine/tests/it/main.rs | 1 + .../engine/tests/it/trim_extend_json_pick.rs | 144 ++++++++++++++++++ 5 files changed, 214 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/it/trim_extend_json_pick.rs diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index f68d08ebb..5d8661918 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -37,7 +37,7 @@ use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; pub(crate) use transform::transform_entities; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; -pub(crate) use trim::{Edges, extend, trim}; +pub(crate) use trim::{Edges, extend, json_pick_error, trim}; pub fn specs() -> Vec { vec![ @@ -85,14 +85,24 @@ pub fn specs() -> Vec { CommandSpec::new("trim", "Trim", trimextend::run_trim) .menu(&["Modify", "Trim"]) .alias(&["tr"]) - .params( - "{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"}", - ) + .params(concat!( + "{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; ", + "edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\". ", + "For handle+pick: handle is the object to trim; pick selects the portion of that object to remove ", + "(normally a point on it, away from a cutting intersection); edges are the cutting edges. ", + "The JSON default is standard mode." + )) .interactive(|_| Ok(Box::new(TrimM::new(false)))), CommandSpec::new("extend", "Extend", trimextend::run_extend) .menu(&["Modify", "Extend"]) .alias(&["ex"]) - .params("{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\"}") + .params(concat!( + "{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; ", + "edges?: [hex], edgeMode?: \"extend\"|\"none\". ", + "For handle+pick: handle is the object to extend; pick points toward the boundary to extend to ", + "(normally a point on that boundary), selecting the nearer end of the object; ", + "edges are the boundary edges, and the nearest forward intersection is used." + )) .interactive(|_| Ok(Box::new(TrimM::new(true)))), CommandSpec::new("fillet", "Fillet", run_fillet) .menu(&["Modify", "Fillet"]) diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 9f8e856dd..6d60d402b 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -91,6 +91,46 @@ fn prim_to_segments(p: &Prim) -> Vec { } } +/// Explain the generic line failures for JSON handle+pick calls. Other curves retain their +/// own diagnostics: their nearest-parameter rules do not prove that a pick is invalid. +pub(crate) fn json_pick_error(s: &Session, h: Handle, pick: Vec2, edges: Edges, extending: bool, error: EngineError) -> EngineError { + let generic = if extending { "Object does not intersect an edge." } else { "Object does not intersect a cutting edge." }; + if !matches!(&error, EngineError::Other(message) if message == generic) { + return error; + } + let Ok(d) = s.doc() else { return error }; + let Some(e) = d.entity(h) else { return error }; + let EntityKind::Line(l) = &e.kind else { return error }; + let Ok(cut) = edge_segments(s, edges, h) else { return error }; + let ln = Line::new(l.a.xy(), l.b.xy()); + let message = if extending { + // The selected end already failed. Check the opposite end with the same ray and + // forward-intersection rules before attributing the failure to the pick's end choice. + let (fixed, end) = if pick.dist(ln.b) < pick.dist(ln.a) { (ln.b, ln.a) } else { (ln.a, ln.b) }; + let dir = (end - fixed).normalized(); + let ray = Segment::Line(Line::new(end, end + dir * 1e8)); + let opposite_hit = cut.iter().flat_map(|c| intersect_ext(&ray, c, false)).any(|x| (x - end).dot(dir) > 1e-9); + if opposite_hit { + "The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to." + } else { + "No usable boundary intersection was found for either end of the object to extend." + } + } else { + let has_cut = cut.iter().flat_map(|c| intersect_ext(&Segment::Line(ln), c, false)).any(|x| { + let t = ln.param_of(x); + t > 1e-9 && t < 1.0 - 1e-9 + }); + if !has_cut { + "No usable cutting-edge intersection in the interior of the object to trim." + } else if !ln.closest(pick).near(pick, 1e-9) { + "The `pick` point is off the object to trim; pick a removable portion of that object." + } else { + "The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection." + } + }; + EngineError::Other(message.into()) +} + /// Trim `h` at the piece containing `pick`. Returns the handles that replace it. pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result> { if crate::cmd::curves::is_locked(s, h) { diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index ab03d5c31..db90ec300 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -9,7 +9,7 @@ use cadcraft_geom::{Bounds2, Line, Vec2, line_line}; use serde_json::{Value, json}; use super::helpers::{line, lwpoly, rect_vertices}; -use super::modify::{Edges, extend, trim}; +use super::modify::{Edges, extend, json_pick_error, trim}; use super::{bad, point_param, points_param}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; @@ -197,8 +197,19 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result { return Ok(json!({ key: n })); } let h = super::targets(s, p)?.first().copied().ok_or_else(|| bad(cmd, "`handle` is required"))?; - let pick = point_param(p, "pick").ok_or_else(|| bad(cmd, "`pick` ([x, y]) is required"))?; - let r = apply(s, h, pick, extending, edges, quick)?; + let pick = point_param(p, "pick").ok_or_else(|| { + bad( + cmd, + if extending { + "`pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end" + } else { + "`pick` ([x, y]) is required: select the portion of the object to trim away" + }, + ) + })?; + // Diagnose only an existing single-pick JSON failure. Successful calls, Quick-mode + // erasure, fence/crossing and the interactive command keep their existing behavior. + let r = apply(s, h, pick, extending, edges, quick).map_err(|e| json_pick_error(s, h, pick, edges, extending, e))?; if extending { Ok(Value::Null) } else { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 957513621..0003e9202 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -158,6 +158,7 @@ mod text_left_justify; mod tolerance; mod transparent; mod trim_closed_polyline; +mod trim_extend_json_pick; mod trim_extend_options; mod undo_count; mod undo_layout_tab; diff --git a/crates/engine/tests/it/trim_extend_json_pick.rs b/crates/engine/tests/it/trim_extend_json_pick.rs new file mode 100644 index 000000000..1c8cda07a --- /dev/null +++ b/crates/engine/tests/it/trim_extend_json_pick.rs @@ -0,0 +1,144 @@ +//! JSON execute pick roles and diagnostic-only refusals (#2750). + +use cadcraft_doc::{Common, EntityKind, Handle, Line, Space}; +use cadcraft_engine::{Session, find_command}; +use cadcraft_geom::Vec3; +use serde_json::{Value, json}; + +type TestResult = Result>; + +fn fixture(end: f64, edge_x: f64) -> TestResult<(Session, Handle, Handle)> { + let mut s = Session::new(); + let a = s.doc_mut()?.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(end, 0.0, 0.0) }))?; + let b = s.doc_mut()?.add( + &Space::Model, + Common::default(), + EntityKind::Line(Line { a: Vec3::new(edge_x, -20.0, 0.0), b: Vec3::new(edge_x, 20.0, 0.0) }), + )?; + Ok((s, a, b)) +} + +fn assert_line(s: &Session, h: Handle, start: f64, end: f64) -> TestResult { + let e = s.doc()?.entity(h).ok_or("line missing")?; + let EntityKind::Line(l) = &e.kind else { return Err("expected line".into()) }; + assert_eq!((l.a, l.b), (Vec3::new(start, 0.0, 0.0), Vec3::new(end, 0.0, 0.0))); + Ok(()) +} + +fn failure(s: &mut Session, cmd: &str, params: Value, message: &str) -> TestResult { + let before = s.doc()?.clone(); + let selection = s.state()?.selection.clone(); + let error = s.execute(cmd, ¶ms).err().ok_or("expected refusal")?; + assert_eq!(error.to_string(), message); + assert_eq!(s.doc()?, &before, "a failed JSON call must leave the whole drawing unchanged"); + assert_eq!(s.state()?.selection, selection); + Ok(()) +} + +#[test] +fn trim_execute_pick_selects_the_portion_to_remove() -> TestResult { + // Off-object picks that already succeed by projection remain accepted. + for (pick, start, end) in [([5, 0], 25.0, 50.0), ([40, 0], 0.0, 25.0), ([5, 3], 25.0, 50.0)] { + let (mut s, a, b) = fixture(50.0, 25.0)?; + let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?; + let result = s.execute("trim", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?; + let handles = result["handles"].as_array().ok_or("expected handles")?; + assert_eq!(handles.len(), 1); + let h = handles.first().and_then(Value::as_str).and_then(Handle::parse_hex).ok_or("expected replacement handle")?; + assert_line(&s, h, start, end)?; + assert_eq!(s.doc()?.entity(b), Some(&boundary)); + } + Ok(()) +} + +#[test] +fn extend_execute_pick_selects_the_end_toward_the_boundary() -> TestResult { + for pick in [[25, 10], [25, -15], [19, 0], [40, 0]] { + let (mut s, a, b) = fixture(20.0, 25.0)?; + let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?; + let result = s.execute("extend", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?; + assert_eq!(result, Value::Null); + assert_line(&s, a, 0.0, 25.0)?; + assert_eq!(s.doc()?.entity(b), Some(&boundary)); + } + Ok(()) +} + +#[test] +fn trim_execute_distinguishes_a_bad_pick_a_cut_pick_and_no_cut() -> TestResult { + let (mut s, a, b) = fixture(50.0, 25.0)?; + failure( + &mut s, + "trim", + json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 10]}), + "The `pick` point is off the object to trim; pick a removable portion of that object.", + )?; + failure( + &mut s, + "trim", + json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 0], "mode": "standard"}), + "The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection.", + )?; + let (mut s, a, b) = fixture(50.0, 75.0)?; + failure( + &mut s, + "trim", + json!({"handle": a.hex(), "edges": [b.hex()], "pick": [5, 0]}), + "No usable cutting-edge intersection in the interior of the object to trim.", + ) +} + +#[test] +fn extend_execute_distinguishes_the_wrong_end_from_no_boundary_hit() -> TestResult { + let (mut s, a, b) = fixture(20.0, 25.0)?; + failure( + &mut s, + "extend", + json!({"handle": a.hex(), "edges": [b.hex()], "pick": [10, 0]}), + "The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to.", + )?; + s.doc_mut()?.modify_entity(b, |e| { + e.kind = EntityKind::Line(Line { a: Vec3::new(0.0, 20.0, 0.0), b: Vec3::new(25.0, 20.0, 0.0) }); + })?; + failure( + &mut s, + "extend", + json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 20]}), + "No usable boundary intersection was found for either end of the object to extend.", + ) +} + +#[test] +fn quick_erasure_and_unrelated_errors_keep_their_behavior() -> TestResult { + let (mut s, a, b) = fixture(50.0, 25.0)?; + // The current Quick-mode cut-point behavior is preserved, not changed by diagnostics. + let result = s.execute("trim", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 0], "mode": "quick"}))?; + assert_eq!(result["handles"], json!([])); + assert!(s.doc()?.entity(a).is_none()); + assert!(s.doc()?.entity(b).is_some()); + failure(&mut s, "trim", json!({"handle": "DEAD", "pick": [5, 0]}), "no such object") +} + +#[test] +fn command_contracts_and_missing_pick_errors_explain_the_roles() -> TestResult { + let trim = find_command("trim").ok_or("trim not registered")?; + assert!(trim.params.contains("pick selects the portion of that object to remove")); + assert!(trim.params.contains("edges are the cutting edges")); + let extend = find_command("extend").ok_or("extend not registered")?; + assert!(extend.params.contains("pick points toward the boundary to extend to")); + assert!(extend.params.contains("selecting the nearer end")); + assert!(extend.params.contains("edges are the boundary edges")); + let (mut s, a, b) = fixture(20.0, 25.0)?; + failure( + &mut s, + "trim", + json!({"handle": a.hex(), "edges": [b.hex()]}), + "invalid parameters for `trim`: `pick` ([x, y]) is required: select the portion of the object to trim away", + )?; + failure( + &mut s, + "extend", + json!({"handle": a.hex(), "edges": [b.hex()]}), + "invalid parameters for `extend`: `pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end", + ) +} From 064f58f252c9a550d9fce02f43f4e8ad7b0f372f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 21:16:55 -0700 Subject: [PATCH 232/531] XCLIP: write an inverted clip as AutoCAD does in a file (no group 290) AutoCAD 2024 writes no group 290 on a SPATIAL_FILTER in a DXF and discards a file whose filter has one (measured by 2ez4gcx, #2756). An inverted clip's filter now gets an extension dictionary with the ACAD_XREC_ROUNDTRIP XRECORD (ACAD_INVERTEDCLIP_ROUNDTRIP, then ..._COMPARE). Reading takes the ROUNDTRIP list as the boundary while COMPARE matches the filter's vertices, so AutoCAD's keyhole filters read as the clip drawn; 290 is still read when present. The record survives DWG, so CADCraft's own CADCRAFT_XCLIP flag is gone. --- crates/io/src/dxf_clip.rs | 288 +++++++++++++++++--------- crates/io/tests/it/xclip_roundtrip.rs | 15 +- 2 files changed, 203 insertions(+), 100 deletions(-) diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs index 0e120d9be..fcb615a9c 100644 --- a/crates/io/src/dxf_clip.rs +++ b/crates/io/src/dxf_clip.rs @@ -4,11 +4,15 @@ //! 10/20 the vertices), whether clipping is on (71), the front and back clip (72/73, 40/41) and //! two 3×4 matrices (group 40, row by row): the inverse of the reference's transform, which takes //! the boundary into the block's coordinates, and the boundary's own transform (identity here). -//! Group 290 is 1 for an inverted clip ("Invert clip"), as the reference app writes it. //! -//! The DWG bridge drops group 290, so an inverted clip is also marked by CADCraft's own entry -//! `CADCRAFT_XCLIP` beside `ACAD_FILTER` (an XRECORD with group 70 = 1), which a DWG keeps. It -//! is read only when the filter has no group 290. +//! An inverted clip ("Invert clip") is marked as the reference app writes it in a file: the +//! filter has an extension dictionary whose `ACAD_XREC_ROUNDTRIP` entry is an XRECORD holding +//! `102 ACAD_INVERTEDCLIP_ROUNDTRIP` then the boundary (10/20/30), and +//! `102 ACAD_INVERTEDCLIP_ROUNDTRIP_COMPARE` then the filter's own vertices. While the filter +//! still holds those vertices the clip is inverted, with the first list as its boundary. The +//! reference app shows the flag as group 290 on the object but never writes 290 in a DXF file, +//! and discards a file whose filter has one; 290 is read when another program wrote it, never +//! written. The record goes through DWG as it is. //! //! Reading takes the planar filters the model can hold out of the kept foreign data and puts them //! on the references ([`read`]); others (front/back clipping, a skewed boundary transform) stay @@ -23,8 +27,10 @@ use cadcraft_doc::foreign::{Foreign, ForeignObject}; use cadcraft_doc::{ClipBoundary, Drawing, EntityKind, Handle, MAX_CLIP_VERTICES, RawTag}; use cadcraft_geom::{Mat3, Vec2}; -/// The extension-dictionary entry of CADCraft's inverted-clip flag (for DWG, see above). -const INVERT_KEY: &str = "CADCRAFT_XCLIP"; +/// The filter's extension-dictionary entry of the reference app's inverted-clip record. +const ROUNDTRIP_KEY: &str = "ACAD_XREC_ROUNDTRIP"; +const ROUNDTRIP: &str = "ACAD_INVERTEDCLIP_ROUNDTRIP"; +const COMPARE: &str = "ACAD_INVERTEDCLIP_ROUNDTRIP_COMPARE"; /// Handles above this are not handed out (the DXF handle space is 64-bit, keep a margin). const MAX_HANDLE: u64 = 1 << 48; @@ -94,9 +100,70 @@ fn matrix_values(m: &Mat3) -> [f64; 12] { [m.a, m.c, 0.0, m.e, m.b, m.d, 0.0, m.f, 0.0, 0.0, 1.0, 0.0] } -/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates. `None` for anything +/// The `count` vertices (10/20) a SPATIAL_FILTER holds, as written. +fn vertices(tags: &[RawTag], count: usize) -> Option> { + let mut points = Vec::with_capacity(count); + for w in tags.windows(2) { + let [x, y] = w else { continue }; + if x.code != 10 { + continue; + } + if y.code != 20 || points.len() >= count { + return None; + } + points.push(Vec2::new(x.value.trim().parse().ok()?, y.value.trim().parse().ok()?)); + } + (points.len() == count).then_some(points) +} + +/// The handle of an object's own extension dictionary (`102 {ACAD_XDICTIONARY`, 360). +fn own_xdict(tags: &[RawTag]) -> Option { + tags.windows(2) + .find(|w| matches!(w, [k, v] if k.code == 102 && k.value.trim().eq_ignore_ascii_case("{ACAD_XDICTIONARY") && v.code == 360)) + .and_then(|w| w.get(1)) + .and_then(|v| Handle::parse_hex(&v.value)) +} + +/// The boundary of an inverted clip as the reference app marks it on `filter` (see above), when +/// the filter still holds the vertices the mark was made for. +fn roundtrip(f: &Foreign, idx: &Index, filter: &ForeignObject) -> Option> { + let rec = object(f, idx, entry(&object(f, idx, own_xdict(&filter.tags)?)?.tags, ROUNDTRIP_KEY)?)?; + if !rec.kind.eq_ignore_ascii_case("XRECORD") { + return None; + } + let (mut boundary, mut compare) = (Vec::new(), Vec::new()); + // 0 before either list, 1 in the boundary, 2 in the filter's vertices. + let mut list = 0; + for w in rec.tags.windows(2) { + let [x, y] = w else { continue }; + match x.code { + 102 => { + list = match x.value.trim() { + v if v.eq_ignore_ascii_case(ROUNDTRIP) => 1, + v if v.eq_ignore_ascii_case(COMPARE) => 2, + _ => 0, + } + } + 10 if list != 0 && y.code == 20 => { + let into = if list == 1 { &mut boundary } else { &mut compare }; + if into.len() >= MAX_CLIP_VERTICES { + return None; + } + into.push(Vec2::new(x.value.trim().parse().ok()?, y.value.trim().parse().ok()?)); + } + _ => {} + } + } + let own = vertices(&filter.tags, usize::try_from(number(&filter.tags, 70)? as i64).ok()?)?; + let near = |a: f64, b: f64| (a - b).abs() <= 1e-9 * (1.0 + a.abs().max(b.abs())); + let same = own.len() == compare.len() && own.iter().zip(&compare).all(|(p, q)| near(p.x, q.x) && near(p.y, q.y)); + (same && boundary.len() >= 2).then_some(boundary) +} + +/// The boundary a planar SPATIAL_FILTER holds, in the block's coordinates; with `boundary`, the +/// clip is inverted and that is its outline (in the filter's coordinates). `None` for anything /// the model can't hold as it is (it then stays foreign). -fn parse_filter(o: &ForeignObject) -> Option { +fn parse_filter(o: &ForeignObject, boundary: Option<&[Vec2]>) -> Option { let count = usize::try_from(number(&o.tags, 70)? as i64).ok()?; if !(2..=MAX_CLIP_VERTICES).contains(&count) { return None; @@ -124,31 +191,18 @@ fn parse_filter(o: &ForeignObject) -> Option { { return None; } - let mut points = Vec::with_capacity(count); - for w in o.tags.windows(2) { - let [x, y] = w else { continue }; - if x.code != 10 { - continue; - } - if y.code != 20 || points.len() >= count { - return None; - } - let p = inverse.apply(Vec2::new(x.value.trim().parse().ok()?, y.value.trim().parse().ok()?)); - if !p.is_finite() { - return None; - } - points.push(p); + let own = vertices(&o.tags, count)?; + let outline = boundary.unwrap_or(&own); + if !(2..=MAX_CLIP_VERTICES).contains(&outline.len()) { + return None; } - let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted: number(&o.tags, 290).is_some_and(|v| v != 0.0) }; - (clip.points.len() == count && cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some()).then_some(clip) -} - -/// Whether the extension dictionary `xd` marks the clip inverted (CADCraft's own flag). -fn inverted_record(f: &Foreign, idx: &Index, xd: Handle) -> bool { - object(f, idx, xd) - .and_then(|o| entry(&o.tags, INVERT_KEY)) - .and_then(|h| object(f, idx, h)) - .is_some_and(|o| o.kind.eq_ignore_ascii_case("XRECORD") && number(&o.tags, 70).is_some_and(|v| v != 0.0)) + let points: Vec = outline.iter().map(|p| inverse.apply(*p)).collect(); + if !points.iter().all(|p| p.is_finite()) { + return None; + } + let inverted = boundary.is_some() || number(&o.tags, 290).is_some_and(|v| v != 0.0); + let clip = ClipBoundary { points, enabled: number(&o.tags, 71).unwrap_or(1.0) != 0.0, inverted }; + cadcraft_render::clip::PolyClip::new(&clip.polygon()).is_some().then_some(clip) } /// Put the planar filters of the file read into `d` on their references, taking them out of @@ -163,12 +217,9 @@ pub(crate) fn read(d: &mut Drawing) { .entities .keys() .filter_map(|h| { - let (xd, _, o) = chain(&d.foreign, &idx, *h)?; - let mut clip = parse_filter(o)?; - if number(&o.tags, 290).is_none() { - clip.inverted = inverted_record(&d.foreign, &idx, xd); - } - Some((*h, clip)) + let (_, _, o) = chain(&d.foreign, &idx, *h)?; + let boundary = roundtrip(&d.foreign, &idx, o); + Some((*h, parse_filter(o, boundary.as_deref())?)) }) .collect(); if found.is_empty() { @@ -207,7 +258,7 @@ pub(crate) fn read(d: &mut Drawing) { } /// Take the clip of entity `h` out of the foreign data: the ACAD_FILTER entry and what it holds, -/// CADCraft's inverted flag, and the extension dictionary when nothing else is left in it. The +/// and the extension dictionary when nothing else is left in it. The /// objects to remove are added to `gone`; the caller removes them all at once. fn forget(f: &mut Foreign, idx: &Index, h: Handle, all_gone: &mut HashSet) { let Some(xd) = f.entities.get(&h).and_then(|x| x.xdict) else { return }; @@ -215,19 +266,19 @@ fn forget(f: &mut Foreign, idx: &Index, h: Handle, all_gone: &mut HashSet Handle::parse_hex(&v.value), - _ => None, - })); + if let Some(o) = object(f, idx, g) { + if o.kind.eq_ignore_ascii_case("DICTIONARY") { + gone.extend(o.tags.windows(2).filter_map(|w| match w { + [k, v] if k.code == 3 && matches!(v.code, 350 | 360) => Handle::parse_hex(&v.value), + _ => None, + })); + } + gone.extend(own_xdict(&o.tags)); } i += 1; if i > MAX_CLIP_VERTICES { @@ -263,17 +314,14 @@ fn dictionary(h: Handle, owner: Handle) -> ForeignObject { } } -fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3, inverse: &Mat3) -> ForeignObject { - let mut tags = vec![ - raw(5, h.hex()), - raw(102, "{ACAD_REACTORS"), - raw(330, owner.hex()), - raw(102, "}"), - raw(330, owner.hex()), - raw(100, "AcDbFilter"), - raw(100, "AcDbSpatialFilter"), - raw(70, clip.points.len()), - ]; +/// The SPATIAL_FILTER of `clip`; `xdict` is its extension dictionary (an inverted clip's). +/// No group 290: the reference app discards a file whose filter has one. +fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3, inverse: &Mat3, xdict: Option) -> ForeignObject { + let mut tags = vec![raw(5, h.hex()), raw(102, "{ACAD_REACTORS"), raw(330, owner.hex()), raw(102, "}")]; + if let Some(x) = xdict { + tags.extend([raw(102, "{ACAD_XDICTIONARY"), raw(360, x.hex()), raw(102, "}")]); + } + tags.extend([raw(330, owner.hex()), raw(100, "AcDbFilter"), raw(100, "AcDbSpatialFilter"), raw(70, clip.points.len())]); for p in &clip.points { let q = to_world.apply(*p); tags.push(raw(10, q.x)); @@ -284,25 +332,21 @@ fn spatial_filter(h: Handle, owner: Handle, clip: &ClipBoundary, to_world: &Mat3 for v in matrix_values(inverse).into_iter().chain(matrix_values(&Mat3::IDENTITY)) { tags.push(raw(40, v)); } - tags.push(raw(290, i32::from(clip.inverted))); ForeignObject { handle: h, kind: "SPATIAL_FILTER".into(), tags } } -fn invert_record(h: Handle, owner: Handle) -> ForeignObject { - ForeignObject { - handle: h, - kind: "XRECORD".into(), - tags: vec![ - raw(5, h.hex()), - raw(102, "{ACAD_REACTORS"), - raw(330, owner.hex()), - raw(102, "}"), - raw(330, owner.hex()), - raw(100, "AcDbXrecord"), - raw(280, 1), - raw(70, 1), - ], +/// The reference app's inverted-clip record for a filter whose vertices are `points` (drawing +/// coordinates): the boundary and the filter's vertices are the same list. +fn roundtrip_record(h: Handle, owner: Handle, points: &[Vec2]) -> ForeignObject { + let mut tags = vec![raw(5, h.hex()), raw(102, "{ACAD_REACTORS"), raw(330, owner.hex()), raw(102, "}")]; + tags.extend([raw(330, owner.hex()), raw(100, "AcDbXrecord"), raw(280, 1)]); + for name in [ROUNDTRIP, COMPARE] { + tags.push(raw(102, name)); + for p in points { + tags.extend([raw(10, p.x), raw(20, p.y), raw(30, 0.0)]); + } } + ForeignObject { handle: h, kind: "XRECORD".into(), tags } } /// A copy of `d` whose foreign data holds the SPATIAL_FILTER of every clipped reference (any @@ -336,7 +380,7 @@ pub(crate) fn prepare(d: &Drawing) -> Option { let mut gone = HashSet::new(); for (insert, clip, to_world) in clips { let Some(inverse) = to_world.inverse() else { continue }; - if next.saturating_add(5) >= MAX_HANDLE { + if next.saturating_add(6) >= MAX_HANDLE { break; } // A filter kept from the file for this reference is replaced. @@ -352,12 +396,10 @@ pub(crate) fn prepare(d: &Drawing) -> Option { } }; let (fd, sf) = (fresh(&mut next), fresh(&mut next)); - let flag = clip.inverted.then(|| fresh(&mut next)); + // An inverted clip's filter has an extension dictionary and the record in it. + let marks = clip.inverted.then(|| (fresh(&mut next), fresh(&mut next))); if let Some(o) = idx.get(&xd).copied().and_then(|i| f.objects.get_mut(i)) { o.tags.extend([raw(3, "ACAD_FILTER"), raw(360, fd.hex())]); - if let Some(x) = flag { - o.tags.extend([raw(3, INVERT_KEY), raw(360, x.hex())]); - } } let mut filters = dictionary(fd, xd); filters.tags.extend([raw(3, "SPATIAL"), raw(360, sf.hex())]); @@ -366,9 +408,13 @@ pub(crate) fn prepare(d: &Drawing) -> Option { f.objects.push(o); }; add(filters); - add(spatial_filter(sf, fd, &clip, &to_world, &inverse)); - if let Some(x) = flag { - add(invert_record(x, xd)); + add(spatial_filter(sf, fd, &clip, &to_world, &inverse, marks.map(|(x, _)| x))); + if let Some((x, r)) = marks { + let mut own = dictionary(x, sf); + own.tags.extend([raw(3, ROUNDTRIP_KEY), raw(360, r.hex())]); + add(own); + let world: Vec = clip.points.iter().map(|p| to_world.apply(*p)).collect(); + add(roundtrip_record(r, x, &world)); } } f.objects.retain(|o| !gone.contains(&o.handle)); @@ -395,11 +441,11 @@ mod tests { #[test] fn hostile_filters_stay_foreign() { let o = |tags: Vec| ForeignObject { handle: Handle(1), kind: "SPATIAL_FILTER".into(), tags }; - assert!(parse_filter(&o(vec![raw(70, 1_000_000_000)])).is_none()); - assert!(parse_filter(&o(vec![raw(70, 3), raw(10, 0), raw(20, 0)])).is_none()); - assert!(parse_filter(&o(vec![raw(70, 2), raw(10, "nan"), raw(20, 0), raw(10, 1), raw(20, 1)])).is_none()); - assert!(parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1), raw(72, 1)])).is_none()); - let ok = parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1)])).unwrap(); + assert!(parse_filter(&o(vec![raw(70, 1_000_000_000)]), None).is_none()); + assert!(parse_filter(&o(vec![raw(70, 3), raw(10, 0), raw(20, 0)]), None).is_none()); + assert!(parse_filter(&o(vec![raw(70, 2), raw(10, "nan"), raw(20, 0), raw(10, 1), raw(20, 1)]), None).is_none()); + assert!(parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1), raw(72, 1)]), None).is_none()); + let ok = parse_filter(&o(vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1)]), None).unwrap(); assert_eq!((ok.points.len(), ok.inverted), (2, false)); } @@ -418,15 +464,69 @@ mod tests { } #[test] - fn group_290_is_the_inverted_flag() { + fn group_290_is_read_but_never_written() { let tags = |invert: &str| vec![raw(70, 2), raw(10, 0), raw(20, 0), raw(10, 1), raw(20, 1), raw(290, invert)]; let o = |invert| ForeignObject { handle: Handle(1), kind: "SPATIAL_FILTER".into(), tags: tags(invert) }; - assert!(parse_filter(&o("1")).unwrap().inverted); - assert!(!parse_filter(&o("0")).unwrap().inverted); - assert!(!parse_filter(&o("junk")).unwrap().inverted); + assert!(parse_filter(&o("1"), None).unwrap().inverted); + assert!(!parse_filter(&o("0"), None).unwrap().inverted); + assert!(!parse_filter(&o("junk"), None).unwrap().inverted); + // The reference app discards a DXF whose filter has 290. let clip = ClipBoundary { inverted: true, ..ClipBoundary::new(vec![Vec2::ZERO, Vec2::new(1.0, 1.0)]) }; - let written = spatial_filter(Handle(2), Handle(1), &clip, &Mat3::IDENTITY, &Mat3::IDENTITY); - assert!(written.tags.iter().any(|t| t.code == 290 && t.value == "1")); - assert!(parse_filter(&written).unwrap().inverted); + let written = spatial_filter(Handle(2), Handle(1), &clip, &Mat3::IDENTITY, &Mat3::IDENTITY, Some(Handle(3))); + assert!(!written.tags.iter().any(|t| t.code == 290)); + assert_eq!(own_xdict(&written.tags), Some(Handle(3))); + } + + /// The filter, its extension dictionary and the reference app's record, as one foreign set. + fn marked(filter_points: &[(f64, f64)], boundary: &[(f64, f64)], compare: &[(f64, f64)]) -> (Foreign, ForeignObject) { + let mut tags = vec![raw(5, "10"), raw(102, "{ACAD_XDICTIONARY"), raw(360, "11"), raw(102, "}"), raw(70, filter_points.len())]; + for (x, y) in filter_points { + tags.extend([raw(10, x), raw(20, y)]); + } + let filter = ForeignObject { handle: Handle(0x10), kind: "SPATIAL_FILTER".into(), tags }; + let mut f = Foreign::default(); + let mut dict = dictionary(Handle(0x11), Handle(0x10)); + dict.tags.extend([raw(3, ROUNDTRIP_KEY), raw(360, "12")]); + f.objects.push(dict); + let mut rec = vec![raw(100, "AcDbXrecord"), raw(280, 1)]; + for (name, list) in [(ROUNDTRIP, boundary), (COMPARE, compare)] { + rec.push(raw(102, name)); + for (x, y) in list { + rec.extend([raw(10, x), raw(20, y), raw(30, 0)]); + } + } + f.objects.push(ForeignObject { handle: Handle(0x12), kind: "XRECORD".into(), tags: rec }); + f.objects.push(filter.clone()); + (f, filter) + } + + #[test] + fn the_reference_apps_record_marks_an_inverted_clip() { + // As the reference app writes an inverted rectangle: a keyhole filter, the rectangle kept. + let keyhole = [ + (0.0, 0.0), + (100.0, 0.0), + (100.0, 50.0), + (0.0, 50.0), + (0.0, 10.0), + (20.0, 10.0), + (20.0, 40.0), + (80.0, 40.0), + (80.0, 10.0), + (20.0, 10.0), + (0.0, 10.0), + ]; + let (f, filter) = marked(&keyhole, &[(20.0, 10.0), (80.0, 40.0)], &keyhole); + let boundary = roundtrip(&f, &index(&f), &filter).unwrap(); + let clip = parse_filter(&filter, Some(&boundary)).unwrap(); + assert!(clip.inverted); + assert_eq!(clip.points, vec![Vec2::new(20.0, 10.0), Vec2::new(80.0, 40.0)]); + // The simpler form: the filter keeps the boundary itself. + let rect = [(20.0, 10.0), (80.0, 40.0)]; + let (f, filter) = marked(&rect, &rect, &rect); + assert!(roundtrip(&f, &index(&f), &filter).is_some()); + // A filter changed since the record was made (the clip edited elsewhere) isn't inverted. + let (f, filter) = marked(&[(0.0, 0.0), (5.0, 5.0)], &rect, &rect); + assert!(roundtrip(&f, &index(&f), &filter).is_none()); } } diff --git a/crates/io/tests/it/xclip_roundtrip.rs b/crates/io/tests/it/xclip_roundtrip.rs index 727165d6c..a7df6c62b 100644 --- a/crates/io/tests/it/xclip_roundtrip.rs +++ b/crates/io/tests/it/xclip_roundtrip.rs @@ -77,13 +77,15 @@ fn clips_round_trip_through_dxf() { let bytes = save(&d, "a.dxf", Version::R2018); let text = String::from_utf8(bytes.clone()).unwrap(); assert_eq!(text.matches("SPATIAL_FILTER").count(), 3, "one filter per clipped reference"); - // The inverted triangle also carries CADCraft's flag, which a DWG keeps. - assert!(text.contains("ACAD_FILTER") && text.matches("CADCRAFT_XCLIP").count() == 1); - // The inverted triangle is marked on its filter (group 290, last), as the reference app writes it. + assert!(text.contains("ACAD_FILTER")); + // No filter has group 290: the reference app discards a DXF whose filter has one. The + // inverted triangle's filter has its record instead, in the filter's extension dictionary. let filters: Vec<&str> = text.split("\r\nSPATIAL_FILTER\r\n").skip(1).map(|f| f.split("\r\n 0\r\n").next().unwrap_or("")).collect(); assert_eq!(filters.len(), 3); - assert!(filters.iter().all(|f| f.contains("\r\n290\r\n")), "every filter says whether it is inverted"); - assert_eq!(filters.iter().filter(|f| f.ends_with("\r\n290\r\n1")).count(), 1, "{filters:?}"); + assert!(!filters.iter().any(|f| f.contains("\r\n290\r\n")), "{filters:?}"); + assert_eq!(filters.iter().filter(|f| f.contains("{ACAD_XDICTIONARY")).count(), 1, "{filters:?}"); + assert_eq!(text.matches("ACAD_XREC_ROUNDTRIP").count(), 1); + assert!(text.contains("ACAD_INVERTEDCLIP_ROUNDTRIP\r\n") && text.contains("ACAD_INVERTEDCLIP_ROUNDTRIP_COMPARE\r\n")); let first = read(&bytes, "a.dxf").unwrap(); same(&clips(&first), &clips(&d)); // The model owns the filters now: nothing of them is left as foreign data. @@ -95,6 +97,7 @@ fn clips_round_trip_through_dxf() { assert!(!back.foreign.objects.iter().any(|o| o.kind == "SPATIAL_FILTER"), "{}", v.year()); let again = String::from_utf8(save(&back, "a.dxf", v)).unwrap(); assert_eq!(again.matches("SPATIAL_FILTER").count(), 3, "no duplicate filters on resave"); + assert_eq!(again.matches("ACAD_XREC_ROUNDTRIP").count(), 1, "no duplicate records on resave"); } } @@ -124,7 +127,7 @@ fn deleting_a_clip_read_from_a_file_removes_its_filter() { .unwrap(); } let text = String::from_utf8(save(&d, "a.dxf", Version::R2018)).unwrap(); - assert!(!text.contains("SPATIAL_FILTER") && !text.contains("CADCRAFT_XCLIP")); + assert!(!text.contains("SPATIAL_FILTER") && !text.contains("ACAD_XREC_ROUNDTRIP")); assert!(clips(&read(text.as_bytes(), "a.dxf").unwrap()).iter().all(Option::is_none)); } From ff5b55842e1471198d24a390ab1fa5006a973485 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 21:34:23 -0700 Subject: [PATCH 233/531] XCLIP: bound a filter's vertex count before allocating (CodeRabbit on #2756) --- crates/io/src/dxf_clip.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/io/src/dxf_clip.rs b/crates/io/src/dxf_clip.rs index fcb615a9c..5e239e85c 100644 --- a/crates/io/src/dxf_clip.rs +++ b/crates/io/src/dxf_clip.rs @@ -102,6 +102,10 @@ fn matrix_values(m: &Mat3) -> [f64; 12] { /// The `count` vertices (10/20) a SPATIAL_FILTER holds, as written. fn vertices(tags: &[RawTag], count: usize) -> Option> { + // The count is the file's: bound it before allocating. + if count > MAX_CLIP_VERTICES { + return None; + } let mut points = Vec::with_capacity(count); for w in tags.windows(2) { let [x, y] = w else { continue }; @@ -529,4 +533,19 @@ mod tests { let (f, filter) = marked(&[(0.0, 0.0), (5.0, 5.0)], &rect, &rect); assert!(roundtrip(&f, &index(&f), &filter).is_none()); } + + #[test] + fn a_hostile_vertex_count_beside_the_record_does_not_allocate() { + let rect = [(20.0, 10.0), (80.0, 40.0)]; + for count in ["9223372036854775807", "1000000000", "1e300"] { + let (mut f, mut filter) = marked(&rect, &rect, &rect); + for t in filter.tags.iter_mut().filter(|t| t.code == 70) { + t.value = count.into(); + } + f.objects.retain(|o| o.handle != filter.handle); + f.objects.push(filter.clone()); + assert!(roundtrip(&f, &index(&f), &filter).is_none(), "{count}"); + assert!(parse_filter(&filter, None).is_none(), "{count}"); + } + } } From 371e8b9e02a72496d23996df9fd4b65ad72fac1a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 21:56:58 -0700 Subject: [PATCH 234/531] XCLIP: ON/OFF checks every selected reference before changing any (CodeRabbit on #2756) --- crates/engine/src/cmd/blocks/xclip.rs | 7 ++++++- crates/engine/tests/it/xclip.rs | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/blocks/xclip.rs b/crates/engine/src/cmd/blocks/xclip.rs index 82ee26fb4..b9a638827 100644 --- a/crates/engine/src/cmd/blocks/xclip.rs +++ b/crates/engine/src/cmd/blocks/xclip.rs @@ -116,10 +116,15 @@ fn run(s: &mut Session, p: &Value) -> Result { } "on" | "off" => { let on = option == "on"; + // Every reference is checked before any changes: an error leaves the drawing as it was. + let mut clips = Vec::with_capacity(hs.len()); for h in &hs { let mut c = clip_of(s, *h).ok_or_else(|| bad("xclip", "no clipping boundary on the selected reference"))?; c.enabled = on; - set_clip(s, *h, Some(c))?; + clips.push((*h, c)); + } + for (h, c) in clips { + set_clip(s, h, Some(c))?; } } "delete" | "d" => { diff --git a/crates/engine/tests/it/xclip.rs b/crates/engine/tests/it/xclip.rs index 97349e782..c49f20377 100644 --- a/crates/engine/tests/it/xclip.rs +++ b/crates/engine/tests/it/xclip.rs @@ -80,6 +80,16 @@ fn rectangular_clip_cuts_only_that_reference() { assert!(clip(&s, &r1).is_some()); } +#[test] +fn off_on_a_selection_with_an_unclipped_reference_changes_nothing() { + let (mut s, r1, r2) = setup(); + s.execute("xclip", &json!({ "handle": r1, "rectangle": [[20, -10], [70, 10]] })).unwrap(); + // r2 has no boundary: the command fails, and r1 keeps its clip on. + assert!(s.execute("xclip", &json!({ "handles": [r1, r2], "option": "off" })).is_err()); + assert!(clip(&s, &r1).unwrap().enabled); + assert!(clip(&s, &r2).is_none()); +} + #[test] fn a_clipped_reference_plots_its_contents_on_their_own_layers() { let mut s = Session::new(); From f91d5ad38f0e56998ea3136c3cbde826becfe5da Mon Sep 17 00:00:00 2001 From: wovadi <350371346+wovadi@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:52:45 +0100 Subject: [PATCH 235/531] Images: refuse oversized data before decoding, and say what to do with a relative path in an unsaved drawing Follow-up to #2505: imageattach checks the length of base64 data against the 256 MB image limit before decoding it, and a relative path in an unsaved drawing reports "save the drawing first, or give a full path". Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image.rs | 16 ++++++++++++++-- crates/engine/tests/image_attach.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index daf46557b..56f2979b4 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -18,8 +18,9 @@ use crate::{Result, Session}; /// Most image files loaded per drawing. const MAX_IMAGE_FILES: usize = 1000; /// Largest image file read (bytes). -#[cfg(not(target_arch = "wasm32"))] const MAX_IMAGE_BYTES: u64 = 256 << 20; +/// Longest base64 text taken for `data`: what a file of [`MAX_IMAGE_BYTES`] encodes to. +const MAX_IMAGE_BASE64: u64 = MAX_IMAGE_BYTES.div_ceil(3) * 4; /// Most decoded pixel bytes kept per drawing; images past it stay unloaded. const MAX_LOADED_BYTES: u64 = 2 << 30; /// Most image files decoded at the same time when a drawing opens. @@ -74,7 +75,14 @@ fn paths(d: &Drawing) -> Vec { fn read_file(path: &str, host: Option<&str>) -> std::result::Result, String> { #[cfg(not(target_arch = "wasm32"))] { - let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?; + let file = super::blocks::xref::find_file(path, host).ok_or_else(|| { + // An unsaved drawing has no folder for a relative path to be relative to. + if host.is_none() && std::path::Path::new(path).is_relative() { + "file not found (save the drawing first, or give a full path)" + } else { + "file not found" + } + })?; let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len(); if len > MAX_IMAGE_BYTES { return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20)); @@ -304,6 +312,10 @@ fn pixels(s: &Session, p: &Value, path: &str) -> Result> { let bytes = match p.get("data") { Some(data) => { let text = data.as_str().ok_or_else(|| bad(ID, "`data` must be base64 text"))?; + // Refused before decoding, which would hold all of it in memory. + if u64::try_from(text.len()).unwrap_or(u64::MAX) > MAX_IMAGE_BASE64 { + return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20))); + } base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))? } None => { diff --git a/crates/engine/tests/image_attach.rs b/crates/engine/tests/image_attach.rs index 864d968a5..64245b1ab 100644 --- a/crates/engine/tests/image_attach.rs +++ b/crates/engine/tests/image_attach.rs @@ -142,6 +142,33 @@ fn bad_input_is_refused_and_changes_nothing() { assert_eq!(listed(&mut s), json!([])); } +/// `data` longer than the largest image file encodes to is refused before it is decoded. +#[test] +fn oversized_data_is_refused_before_decoding() { + hooks(); + const LIMIT: u64 = 256 << 20; + let mut s = Session::new(); + let too_long = "A".repeat(usize::try_from(LIMIT.div_ceil(3) * 4 + 1).unwrap()); + let e = s.execute("imageattach", &json!({ "path": "a.png", "data": too_long })).unwrap_err().to_string(); + assert!(e.contains("`data` is larger than 256 MB"), "{e}"); + assert!(images(&s).is_empty()); +} + +/// A relative path in an unsaved drawing has nothing to be relative to, and the error says so. +#[test] +fn a_relative_path_in_an_unsaved_drawing_says_what_to_do() { + hooks(); + let mut s = Session::new(); + let e = s.execute("imageattach", &json!({ "path": "missing.png" })).unwrap_err().to_string(); + assert!(e.contains("save the drawing first, or give a full path"), "{e}"); + + let dir = folder("unsaved"); + let full = dir.join("missing.png"); + let e = s.execute("imageattach", &json!({ "path": full.to_string_lossy() })).unwrap_err().to_string(); + assert!(e.contains("file not found") && !e.contains("save the drawing"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn an_image_among_many_objects_keeps_its_pixels() { // More objects than one build task takes: the display list is built in parts and joined, From f998f2f663071647b52a852983bc5ece96a709b6 Mon Sep 17 00:00:00 2001 From: wovadi <350371346+wovadi@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:35:33 +0100 Subject: [PATCH 236/531] Images: check the decoded size of data too Review follow-up on #2765: the longest base64 text allowed can hold one or two bytes more than the 256 MB limit (it is not a multiple of three), so the decoded bytes are checked against the limit as well. The length check before decoding stays, to bound the allocation. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/image.rs | 7 ++++++- crates/engine/tests/image_attach.rs | 7 +++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index 56f2979b4..6fd2e8154 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -316,7 +316,12 @@ fn pixels(s: &Session, p: &Value, path: &str) -> Result> { if u64::try_from(text.len()).unwrap_or(u64::MAX) > MAX_IMAGE_BASE64 { return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20))); } - base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))? + let bytes = base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?; + // The longest text allowed can still hold a byte or two more than the limit. + if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_IMAGE_BYTES { + return Err(bad(ID, format!("`data` is larger than {} MB", MAX_IMAGE_BYTES >> 20))); + } + bytes } None => { if let Some(loaded) = s.doc()?.rasters.get(path) { diff --git a/crates/engine/tests/image_attach.rs b/crates/engine/tests/image_attach.rs index 64245b1ab..ec2c35f36 100644 --- a/crates/engine/tests/image_attach.rs +++ b/crates/engine/tests/image_attach.rs @@ -151,6 +151,13 @@ fn oversized_data_is_refused_before_decoding() { let too_long = "A".repeat(usize::try_from(LIMIT.div_ceil(3) * 4 + 1).unwrap()); let e = s.execute("imageattach", &json!({ "path": "a.png", "data": too_long })).unwrap_err().to_string(); assert!(e.contains("`data` is larger than 256 MB"), "{e}"); + + // The longest text allowed, holding one byte more than the limit, is refused once decoded. + let groups = usize::try_from(LIMIT / 3).unwrap(); + let one_over = format!("{}AAA=", "AAAA".repeat(groups)); + assert_eq!(u64::try_from(one_over.len()).unwrap(), LIMIT.div_ceil(3) * 4, "as long as the text for the limit itself"); + let e = s.execute("imageattach", &json!({ "path": "a.png", "data": one_over })).unwrap_err().to_string(); + assert!(e.contains("`data` is larger than 256 MB"), "{e}"); assert!(images(&s).is_empty()); } From 23c55fc1a8649853569e9827e1efdba96667d1c6 Mon Sep 17 00:00:00 2001 From: zwork Date: Wed, 4 Nov 2026 17:51:09 +0300 Subject: [PATCH 237/531] io: drop the renumbering plumbing the handle fix no longer needs --- crates/io/src/dxf_read.rs | 7 ------- crates/io/src/dxf_read/dimassoc.rs | 18 ++++++++---------- crates/io/src/dxf_read/objects.rs | 3 +-- 3 files changed, 9 insertions(+), 19 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 55af28344..2dcb14fc0 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -61,9 +61,6 @@ struct Rx { block_arrays: HashMap, /// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers). layers: HashMap, - /// Entities the reader renumbered (a handle at the top of the range): the file's handle → - /// the fresh one. References that name the file's handle follow the entity. - renamed: HashMap, } /// Read a DXF file into a drawing. @@ -129,10 +126,6 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { let (paper_block_for, first_layout) = setup_layouts(&mut d, &mut layout_objs, &rx); place_blocks(&mut d, blocks, &mut rx, &paper_block_for, &first_layout); place_entities(&mut d, entities, &rx, &paper_block_for, &first_layout); - // A sortents table orders by the file's entity handles; those follow a renumbered entity. - for (_, order) in &mut objs.sortents { - *order = order.iter().map(|(h, o)| (rx.renamed.get(h).copied().unwrap_or(*h), *o)).collect(); - } apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); crate::dxf_image::resolve(&secs, &mut d); diff --git a/crates/io/src/dxf_read/dimassoc.rs b/crates/io/src/dxf_read/dimassoc.rs index d38eae921..fb4fc5aa1 100644 --- a/crates/io/src/dxf_read/dimassoc.rs +++ b/crates/io/src/dxf_read/dimassoc.rs @@ -1,5 +1,5 @@ use super::common::T; -use super::{Arc, AssocSnap, Circle, DimAssoc, DimKind, Dimension, Drawing, EntityKind, Handle, Rx, Tag, Vec2, Vec3}; +use super::{Arc, AssocSnap, Circle, DimAssoc, DimKind, Dimension, Drawing, EntityKind, Handle, Tag, Vec2, Vec3}; /// Associativity from a DIMASSOC object (files from other writers). The dimension kind decides /// which definition points the references name, in the order AutoCAD writes them: `p13`/`p14` @@ -7,19 +7,17 @@ use super::{Arc, AssocSnap, Circle, DimAssoc, DimKind, Dimension, Drawing, Entit /// angular dimensions, the three points of an angular-3-point dimension, `p13` for ordinate /// dimensions, and for radial or diametric dimensions the single circle reference /// ([`radial_links`]). CADCraft's own xdata links, when present, win. -pub(super) fn dimassoc(d: &mut Drawing, tags: &[Tag], rx: &Rx) { - // The entity handles a reference names follow the entity when the reader renumbered it. - let renamed = |h: Handle| rx.renamed.get(&h).copied().unwrap_or(h); +pub(super) fn dimassoc(d: &mut Drawing, tags: &[Tag]) { let start = tags.iter().position(|x| x.code == 100 && x.str() == "AcDbDimAssoc").unwrap_or(0); let tail = tags.get(start..).unwrap_or(&[]); - let Some(dim_h) = tail.iter().find(|x| x.code == 330).and_then(|x| Handle::parse_hex(&x.str())).map(renamed) else { return }; + let Some(dim_h) = tail.iter().find(|x| x.code == 330).and_then(|x| Handle::parse_hex(&x.str())) else { return }; let Some(EntityKind::Dimension(dm)) = d.entity(dim_h).map(|e| &e.kind) else { return }; if !dm.assoc.is_empty() { return; } // A radial or diametric dimension names its circle once, by its centre. if matches!(dm.kind, DimKind::Radius | DimKind::Diameter) { - let links = radial_links(d, dm, tail, rx); + let links = radial_links(d, dm, tail); if !links.is_empty() { let _ = d.modify_entity(dim_h, |e| { if let EntityKind::Dimension(dm) = &mut e.kind { @@ -46,8 +44,8 @@ pub(super) fn dimassoc(d: &mut Drawing, tags: &[Tag], rx: &Rx) { let Some(point) = used.get(k) else { break }; let end = starts.get(k + 1).copied().unwrap_or(tail.len()); let r = T(tail.get(s + 1..end).unwrap_or(&[])); - let Some(main) = r.s(331).and_then(|h| Handle::parse_hex(&h)).map(renamed) else { continue }; - let other = r.s(332).and_then(|h| Handle::parse_hex(&h)).map(renamed); + let Some(main) = r.s(331).and_then(|h| Handle::parse_hex(&h)) else { continue }; + let other = r.s(332).and_then(|h| Handle::parse_hex(&h)); let at = r.p(10).xy(); // A polyline's segment (subentity type 73 = 2, edge; 91 its 1-based index). let segment = r.i(91).filter(|k| *k >= 1 && r.i(73) == Some(2)); @@ -67,7 +65,7 @@ pub(super) fn dimassoc(d: &mut Drawing, tags: &[Tag], rx: &Rx) { /// Associations of a radial or diametric dimension from its one standard reference: the circle /// or arc it measures, by its centre (osnap 3). The definition points are then on that circle, /// so the dimension follows its radius or diameter. -fn radial_links(d: &Drawing, dm: &Dimension, tail: &[Tag], rx: &Rx) -> Vec { +fn radial_links(d: &Drawing, dm: &Dimension, tail: &[Tag]) -> Vec { let starts: Vec = tail.iter().enumerate().filter(|(_, x)| x.code == 1 && x.str() == "AcDbOsnapPointRef").map(|(i, _)| i).take(8).collect(); for (k, s) in starts.iter().enumerate() { let end = starts.get(k + 1).copied().unwrap_or(tail.len()); @@ -75,7 +73,7 @@ fn radial_links(d: &Drawing, dm: &Dimension, tail: &[Tag], rx: &Rx) -> Vec Date: Mon, 2 Nov 2026 08:49:01 -0800 Subject: [PATCH 238/531] mcp: port the automation roots onto the clap CLI The CLI's argument parsing moved to clap on main, so the hand-rolled parser and its McpTarget change are rebuilt as two options, a usage error naming to the modules main split out (wblock, import, export, plot, saveas, compare, template, the LISP file builtins). --- README.md | 2 + apps/cadcraft-cli/src/args.rs | 44 ++- apps/cadcraft-cli/src/error.rs | 3 + apps/cadcraft-cli/src/mcp.rs | 9 +- apps/cadcraft-cli/tests/mcp_roots.rs | 279 ++++++++++++++ crates/engine/src/cmd/audit.rs | 5 + crates/engine/src/cmd/blocks/extract.rs | 1 + crates/engine/src/cmd/blocks/insert_file.rs | 1 + crates/engine/src/cmd/blocks/wblock.rs | 2 + crates/engine/src/cmd/blocks/xref/load.rs | 1 + crates/engine/src/cmd/exchange.rs | 2 + crates/engine/src/cmd/file.rs | 4 + crates/engine/src/cmd/file/compare.rs | 6 +- crates/engine/src/cmd/file/template.rs | 2 + crates/engine/src/cmd/helpers.rs | 1 + crates/engine/src/cmd/layout.rs | 1 + crates/engine/src/cmd/layout/plotstyle.rs | 2 + crates/engine/src/cmd/layout/saveas.rs | 1 + crates/engine/src/cmd/plotters.rs | 1 + crates/engine/src/cmd/table/breaks.rs | 1 + crates/engine/src/cmd/table/cells.rs | 1 + crates/engine/src/file_access.rs | 387 ++++++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/lisp/builtins/files.rs | 8 +- crates/mcp/src/backend.rs | 32 +- docs/mcp.md | 38 ++ 26 files changed, 817 insertions(+), 18 deletions(-) create mode 100644 apps/cadcraft-cli/tests/mcp_roots.rs create mode 100644 crates/engine/src/file_access.rs diff --git a/README.md b/README.md index 611110c3c..7d733348d 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,8 @@ The logger is `apps/cadcraft/src/logging.rs`; the web build logs to the browser cadcraft-cli mcp # …or bridged to the running app (start it with --control 7979): cadcraft-cli mcp --connect 127.0.0.1:7979 +# …or headless, with the agent confined to a work folder: +cadcraft-cli mcp --automation-read-root ~/work --automation-write-root ~/work/out # One-shot headless runs: cadcraft-cli run --sample --script 'CIRCLE 22,3 1\n' --save out.dxf --export out.png diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index f3b70fdc8..9e7a0c3ed 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -276,6 +276,12 @@ pub(crate) struct McpArgs { /// port first (macOS) #[arg(long, requires = "connect")] pub(crate) launch: bool, + /// The only folder the agent's commands may read from (headless only) + #[arg(long, value_name = "DIR")] + pub(crate) automation_read_root: Option, + /// The only folder the agent's commands may write to (headless only) + #[arg(long, value_name = "DIR")] + pub(crate) automation_write_root: Option, #[command(flatten)] pub(crate) settings: Settings, } @@ -408,12 +414,17 @@ enum UsageError { /// The output is one of the input files, so writing it would replace the original. #[error("{} is an input file, so the result would replace the original: choose another output, or pass --in-place to overwrite it", .0.display())] OutIsInput(PathBuf), + /// The automation roots confine the headless server; a running app enforces its own access. + #[error( + "--automation-read-root and --automation-write-root confine the headless MCP server; a running app enforces its own file access (not yet available: see issue #1585)" + )] + AutomationRootsNeedHeadless, } impl UsageError { fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { let kind = match self { - Self::FramingNeedsImage { .. } | Self::OutIsInput(_) => ErrorKind::ArgumentConflict, + Self::FramingNeedsImage { .. } | Self::OutIsInput(_) | Self::AutomationRootsNeedHeadless => ErrorKind::ArgumentConflict, }; cmd.error(kind, self) } @@ -485,6 +496,13 @@ fn framing_error(cli: &Cli) -> Option { (!cadcraft_io::is_image(out)).then(|| UsageError::FramingNeedsImage { flag, out: out.to_path_buf() }) } +/// The automation roots confine the headless server only, as the other Craft apps' do. +fn roots_need_headless(cli: &Cli) -> Option { + let Command::Mcp(m) = &cli.command else { return None }; + (m.connect.is_some() && (m.automation_read_root.is_some() || m.automation_write_root.is_some())) + .then_some(UsageError::AutomationRootsNeedHeadless) +} + /// An output that is the same file as an input, without `--in-place`. An output that doesn't exist /// can't be an input, and an I/O error in the comparison is left to the open or write that follows. fn out_is_input(cli: &Cli) -> Option { @@ -503,8 +521,8 @@ fn out_is_input(cli: &Cli) -> Option { /// The backend `cadcraft-cli mcp` serves from. #[derive(Debug, PartialEq, Eq)] pub(crate) enum McpTarget { - /// An in-process drawing session (no `--connect`). - Headless, + /// An in-process drawing session (no `--connect`), optionally confined to the two folders. + Headless { read_root: Option, write_root: Option }, /// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call; /// `launch`: opened then if it isn't running. Connect { addr: String, lazy: bool, launch: bool }, @@ -515,7 +533,7 @@ impl McpArgs { match &self.connect { // `--launch` connects at the first call too (the app opens then). Some(addr) => McpTarget::Connect { addr: addr.clone(), lazy: self.lazy || self.launch, launch: self.launch }, - None => McpTarget::Headless, + None => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() }, } } } @@ -588,7 +606,7 @@ fn parse_with(mut cmd: clap::Command, args: &[OsString]) -> Result = std::result::Result; diff --git a/apps/cadcraft-cli/src/mcp.rs b/apps/cadcraft-cli/src/mcp.rs index 960c80a5e..4727d29c1 100644 --- a/apps/cadcraft-cli/src/mcp.rs +++ b/apps/cadcraft-cli/src/mcp.rs @@ -8,7 +8,14 @@ pub(crate) fn mcp(a: &McpArgs) -> Result { Ok(r) => Box::new(r), Err(source) => return Err(CliError::McpConnect { addr, source }), }, - McpTarget::Headless => Box::new(cadcraft_mcp::Headless::default()), + McpTarget::Headless { read_root, write_root } => { + let roots = cadcraft_engine::file_access::AutomationRoots::new( + read_root.as_deref().map(std::path::Path::new), + write_root.as_deref().map(std::path::Path::new), + ) + .map_err(CliError::AutomationRoots)?; + Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots)) + } }; let stdin = std::io::stdin(); let stdout = std::io::stdout(); diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs new file mode 100644 index 000000000..67f205041 --- /dev/null +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -0,0 +1,279 @@ +//! `cadcraft-cli mcp --automation-read-root --automation-write-root ` (#1472): through +//! the MCP protocol, files open only from inside the read root and are saved, exported, plotted and +//! rendered only inside the write root; `..` and links that leave a root are refused, and nothing is +//! written outside. Without roots nothing changes. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Never crash). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; + +use serde_json::{Value, json}; + +const INIT: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#; + +/// A folder holding `in` (the read root, with `a.dxf`), `out` (the write root), `outside` (with +/// `b.dxf`) and `in2` (a sibling with the same prefix as `in`). +fn folders(tag: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("cc-mcp-roots-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in", "out", "outside", "in2"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + for p in ["in/a.dxf", "outside/b.dxf", "in2/c.dxf"] { + let drawing = cadcraft_engine::doc::Drawing::new_imperial(); + std::fs::write(base.join(p), cadcraft_io::write(&drawing, "x.dxf").unwrap()).unwrap(); + } + base +} + +fn s(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +/// One tool call's result: `isError` and its first text block. +struct Tool { + error: bool, + text: String, +} + +/// Run `cadcraft-cli mcp` with `args`, initialise, then make each call in order. +fn run(args: &[&str], calls: &[(&str, Value)]) -> (Output, Vec) { + let mut input = format!("{INIT}\n"); + for (i, (name, arguments)) in calls.iter().enumerate() { + let req = json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}}); + input.push_str(&req.to_string()); + input.push('\n'); + } + let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) + .arg("mcp") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn cadcraft-cli"); + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(input.as_bytes()).unwrap(); + } + let out = child.wait_with_output().expect("wait for cadcraft-cli"); + let replies: Vec = String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).collect(); + let tools = calls + .iter() + .enumerate() + .map(|(i, (name, arguments))| { + let id = (i + 2) as u64; + let reply = replies.iter().find(|v| v["id"] == id).unwrap_or_else(|| panic!("no reply to {name} {arguments}: {replies:?}")); + let result = &reply["result"]; + Tool { error: result["isError"] == true, text: result["content"][0]["text"].as_str().unwrap_or_default().to_string() } + }) + .collect(); + (out, tools) +} + +fn ok(t: &Tool) { + assert!(!t.error, "should be allowed: {}", t.text); +} + +fn refused(t: &Tool, why: &str) { + assert!(t.error, "should be refused ({why}): {}", t.text); + assert!(t.text.contains(why), "should say `{why}`: {}", t.text); +} + +#[test] +fn files_open_only_from_inside_the_read_root() { + let base = folders("open"); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + ("open", json!({"path": s(&base.join("outside/b.dxf"))})), + ("open", json!({"path": s(&base.join("in2/c.dxf"))})), + ("open", json!({"path": format!("{}/../outside/b.dxf", s(&base.join("in")))})), + ("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})), + ], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + refused(&t[1], "outside the read root"); + refused(&t[2], "outside the read root"); + refused(&t[3], "outside the read root"); + // A refused path is an ordinary tool error; the session keeps working. + ok(&t[4]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { + let base = folders("write"); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + ("save", json!({"path": s(&base.join("out/saved.dxf"))})), + ("save", json!({"path": s(&base.join("outside/saved.dxf"))})), + ("save", json!({"path": s(&base.join("in/a.dxf"))})), + ("save", json!({"path": format!("{}/../outside/up.dxf", s(&base.join("out")))})), + ("execute", json!({"command": "export", "params": {"path": s(&base.join("out/art.png")), "format": "png"}})), + ("execute", json!({"command": "export", "params": {"path": s(&base.join("outside/art.png")), "format": "png"}})), + ("render", json!({"path": s(&base.join("out/view.png"))})), + ("render", json!({"path": s(&base.join("outside/view.png"))})), + ("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})), + ], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + ok(&t[1]); + assert!(base.join("out/saved.dxf").is_file()); + refused(&t[2], "outside the write root"); + refused(&t[3], "outside the write root"); + refused(&t[4], "outside the write root"); + ok(&t[5]); + assert!(base.join("out/art.png").is_file()); + refused(&t[6], "outside the write root"); + ok(&t[7]); + assert!(base.join("out/view.png").is_file()); + refused(&t[8], "outside the write root"); + ok(&t[9]); + + assert!(!base.join("outside/saved.dxf").exists()); + assert!(!base.join("outside/art.png").exists()); + assert!(!base.join("outside/view.png").exists()); + // The save's temporary file is beside the destination, inside the root; none is outside. + assert!(!base.join("outside/saved.dxf.cadcraft-tmp").exists()); + assert!(!base.join("outside/up.dxf.cadcraft-tmp").exists()); + let leftovers: Vec = + std::fs::read_dir(base.join("outside")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(leftovers, ["b.dxf"], "nothing was written outside the roots"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_root_left_out_grants_none_of_its_access() { + let base = folders("left-out"); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in"))], + &[("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/a.dxf"))})), ("save", json!({}))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + refused(&t[1], "write authority is absent"); + // QSAVE writes over the opened drawing's own path, which is not writable either. + refused(&t[2], "write authority is absent"); + + let (out, t) = run( + &["--automation-write-root", &s(&base.join("out"))], + &[("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/new.dxf"))}))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + refused(&t[0], "read authority is absent"); + ok(&t[1]); + assert!(base.join("out/new.dxf").is_file()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn without_roots_files_are_reachable_as_before() { + let base = folders("none"); + let (out, t) = + run(&[], &[("open", json!({"path": s(&base.join("outside/b.dxf"))})), ("save", json!({"path": s(&base.join("outside/new.dxf"))}))]); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + ok(&t[1]); + assert!(base.join("outside/new.dxf").is_file()); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn links_out_of_a_root_are_refused() { + let base = folders("links"); + std::os::unix::fs::symlink(base.join("outside"), base.join("out/away")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/b.dxf"), base.join("in/leak.dxf")).unwrap(); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[("open", json!({"path": s(&base.join("in/leak.dxf"))})), ("save", json!({"path": s(&base.join("out/away/new.dxf"))}))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + refused(&t[0], "outside the read root"); + refused(&t[1], "outside the write root"); + assert!(!base.join("outside/new.dxf").exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn every_file_a_command_touches_is_held_to_the_roots() { + let base = folders("commands"); + let drawing = cadcraft_engine::doc::Drawing::new_imperial(); + std::fs::write(base.join("in/x.dxf"), cadcraft_io::write(&drawing, "x.dxf").unwrap()).unwrap(); + std::fs::write(base.join("in/ok.scr"), "CIRCLE 0,0 1\n").unwrap(); + std::fs::write(base.join("outside/bad.scr"), "CIRCLE 0,0 1\n").unwrap(); + let (out, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + // SCRIPT + ("execute", json!({"command": "script", "params": {"path": s(&base.join("in/ok.scr"))}})), + ("execute", json!({"command": "script", "params": {"path": s(&base.join("outside/bad.scr"))}})), + // XATTACH reads the referenced drawing, INSERT and IMPORT read their files. + ("execute", json!({"command": "xattach", "params": {"path": s(&base.join("in/x.dxf")), "name": "ok"}})), + ("execute", json!({"command": "xattach", "params": {"path": s(&base.join("outside/b.dxf")), "name": "bad"}})), + ("execute", json!({"command": "insert", "params": {"name": "blk", "file": s(&base.join("outside/b.dxf")), "at": [0, 0]}})), + ("execute", json!({"command": "import", "params": {"path": s(&base.join("outside/b.dxf"))}})), + // Support files (a linetype file here) and a plot style table. + ("execute", json!({"command": "linetype", "params": {"file": s(&base.join("outside/b.dxf"))}})), + ("execute", json!({"command": "stylesmanager", "params": {"action": "load", "path": s(&base.join("outside/b.dxf"))}})), + // PLOT writes only inside the write root; the inside plot works. + ("execute", json!({"command": "plot", "params": {"path": s(&base.join("out/plot.pdf"))}})), + ("execute", json!({"command": "plot", "params": {"path": s(&base.join("outside/plot.pdf"))}})), + ], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + ok(&t[0]); + ok(&t[1]); + refused(&t[2], "outside the read root"); + ok(&t[3]); + refused(&t[4], "outside the read root"); + refused(&t[5], "outside the read root"); + refused(&t[6], "outside the read root"); + refused(&t[7], "outside the read root"); + refused(&t[8], "outside the read root"); + ok(&t[9]); + assert!(base.join("out/plot.pdf").is_file()); + refused(&t[10], "outside the write root"); + assert!(!base.join("outside/plot.pdf").exists()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn missing_roots_and_roots_with_connect_fail_at_startup() { + let base = folders("bad-roots"); + let input = format!("{INIT}\n"); + let start = |args: &[&str]| { + let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) + .arg("mcp") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn cadcraft-cli"); + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(input.as_bytes()); + } + child.wait_with_output().expect("wait for cadcraft-cli") + }; + let out = start(&["--automation-read-root", &s(&base.join("nope"))]); + assert!(!out.status.success() && out.stdout.is_empty()); + assert!(String::from_utf8_lossy(&out.stderr).contains("cannot open the automation read root")); + + let out = start(&["--automation-write-root", &s(&base.join("in/a.dxf"))]); + assert!(!out.status.success() && out.stdout.is_empty()); + assert!(String::from_utf8_lossy(&out.stderr).contains("cannot open the automation write root")); + + let out = start(&["--connect", "127.0.0.1:1", "--automation-read-root", &s(&base.join("in"))]); + assert!(!out.status.success() && out.stdout.is_empty()); + assert!(String::from_utf8_lossy(&out.stderr).contains("headless MCP server")); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index fa3cc2f98..d7b2813b8 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -143,6 +143,10 @@ fn write_audit_log(s: &Session, report: &crate::audit::Report) { // An unsaved drawing has no folder of its own to hold the log. let Some(path) = &path_str else { return }; let adt_path = std::path::PathBuf::from(path).with_extension("adt"); + if let Err(e) = crate::file_access::check_write(&adt_path.to_string_lossy()) { + log::warn!("AUDITCTL: not writing audit log {}: {e}", adt_path.display()); + return; + } let content = report.format_adt(&title, path_str.as_deref()); // Write through an exclusively-created temporary and rename over the companion path, so a // planted `.adt` symlink beside the drawing cannot redirect the report onto another file @@ -157,6 +161,7 @@ fn write_audit_log(_: &Session, _: &crate::audit::Report) {} #[cfg(not(target_arch = "wasm32"))] fn read_path(cmd: &str, path: &str) -> Result> { + crate::file_access::check_read(path).map_err(|e| bad(cmd, e))?; std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}"))) } diff --git a/crates/engine/src/cmd/blocks/extract.rs b/crates/engine/src/cmd/blocks/extract.rs index 10785f08f..ecb2ca540 100644 --- a/crates/engine/src/cmd/blocks/extract.rs +++ b/crates/engine/src/cmd/blocks/extract.rs @@ -203,6 +203,7 @@ fn csv(columns: &[String], rows: &[Vec], sep: char) -> String { fn write_file(path: &str, text: &str) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(path).map_err(EngineError::Other)?; std::fs::write(path, text).map_err(|e| EngineError::Other(format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 7a0492fad..650bf9468 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -85,6 +85,7 @@ fn read_drawing(path: &str) -> Result { fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(_path).map_err(|e| bad("insert", e))?; std::fs::read(_path).map_err(|e| bad("insert", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 373e471bf..79b9955b2 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -105,6 +105,8 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi let bytes = (hooks.write)(&d, path).map_err(|e| bad(cmd, e))?; // Through a temporary file, as SAVE writes, so a failed write keeps the file it replaces. #[cfg(not(target_arch = "wasm32"))] + crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?; + #[cfg(not(target_arch = "wasm32"))] crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() }; Ok((d.model.len(), bytes.len(), lost)) diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 981df918d..6522e8e18 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -261,6 +261,7 @@ fn read(file: &Path, cx: &mut Ctx) -> Result { #[cfg(not(target_arch = "wasm32"))] { use std::io::Read; + crate::file_access::check_read(&file.to_string_lossy())?; let left = MAX_XREF_TOTAL_BYTES.saturating_sub(cx.bytes); let limit = MAX_XREF_BYTES.min(left); let mut f = std::fs::File::open(file).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index b90fa5e67..9f586978c 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -82,6 +82,7 @@ fn write_file(cmd: &str, path: &str, bytes: &[u8]) -> Result<()> { { // Exclusively create a fresh temporary file and rename it into place so a planted // `.cadcraft-tmp` symlink cannot redirect the export write (CWE-59). + crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?; crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), bytes).map_err(|e| bad(cmd, format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] @@ -204,6 +205,7 @@ fn import_drawing(s: &mut Session, src: &Drawing, at: Vec2, scale: f64, file: &s fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(_path).map_err(|e| bad("import", e))?; std::fs::read(_path).map_err(|e| bad("import", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 606ad4e28..2b298e889 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -224,6 +224,7 @@ fn run_script(s: &mut Session, p: &Value) -> Result { let path = _path; #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(path).map_err(|e| bad("script", e))?; let bytes = crate::capped_read::read_capped(std::path::Path::new(path), MAX_SCRIPT_BYTES).map_err(|e| bad("script", format!("{path}: {e}")))?; String::from_utf8_lossy(&bytes).into_owned() @@ -304,6 +305,7 @@ pub fn read_file(path: &std::path::Path) -> std::result::Result Result { let path = _path; #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(path).map_err(|e| bad("open", e))?; let bytes = crate::capped_read::read_capped(std::path::Path::new(path), MAX_DRAWING_BYTES).map_err(|e| bad("open", format!("{path}: {e}")))?; let i = open_bytes(s, &bytes, path, Some(path.to_string()))?; @@ -462,6 +465,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result Result<()> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(path).map_err(|e| bad("save", e))?; // A file in a folder still to be made has nothing to back up. if is_drawing_file(path) && crate::autosave::isavebak() && crate::atomic_write::missing_folder(std::path::Path::new(path)).is_none() { backup(std::path::Path::new(path)) diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 295b472b1..3af713cd4 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -110,7 +110,11 @@ fn other_drawing(s: &Session, p: &Value) -> Result<(Arc, String)> { fn read_path(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { - std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) + crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; + { + crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; + std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) + } } #[cfg(target_arch = "wasm32")] Err(bad("compare", "paths are not available on the web: open the other drawing and compare with it by name (`document`)")) diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 11d6f2926..7608eb124 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -74,6 +74,8 @@ fn read_template(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_bytes(path: &str) -> Result> { + crate::file_access::check_read(path).map_err(|e| bad("new", e))?; + crate::file_access::check_read(path).map_err(|e| bad("new", e))?; std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) } diff --git a/crates/engine/src/cmd/helpers.rs b/crates/engine/src/cmd/helpers.rs index ed5891203..b68990048 100644 --- a/crates/engine/src/cmd/helpers.rs +++ b/crates/engine/src/cmd/helpers.rs @@ -117,6 +117,7 @@ pub fn support_text(cmd: &str, p: &serde_json::Value, path_key: &str, text_key: #[cfg(not(target_arch = "wasm32"))] fn read_support_file(cmd: &str, path: &str) -> crate::Result { use std::io::Read; + crate::file_access::check_read(path).map_err(|e| super::bad(cmd, e))?; let f = std::fs::File::open(path).map_err(|e| super::bad(cmd, format!("{path}: {e}")))?; let mut bytes = Vec::new(); f.take(MAX_SUPPORT_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(|e| super::bad(cmd, format!("{path}: {e}")))?; diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f6b519a3c..8abddba52 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -841,6 +841,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { let path = _path; // Exclusively create a fresh temporary file and rename it into place so a planted // `.cadcraft-tmp` symlink cannot redirect the plot write (CWE-59). + crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?; let folder = super::file::new_folder(path); crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages }); diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index d432343c2..ef6c2edab 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -303,6 +303,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { (None, Some(_path)) => { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(_path).map_err(|e| bad(cmd, e))?; let meta = std::fs::metadata(_path).map_err(|e| bad(cmd, format!("{_path}: {e}")))?; if meta.len() > cadcraft_doc::MAX_TABLE_FILE as u64 { return Err(bad(cmd, format!("{_path}: the plot style table file is too large"))); @@ -333,6 +334,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { Some(_path) => { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(_path).map_err(|e| bad(cmd, e))?; crate::atomic_write::write_atomic(std::path::Path::new(_path), text.as_bytes()) .map_err(|e| bad(cmd, format!("{_path}: {e}")))?; Ok(json!({ "name": name, "path": _path, "bytes": text.len() })) diff --git a/crates/engine/src/cmd/layout/saveas.rs b/crates/engine/src/cmd/layout/saveas.rs index 0a0b2b5f8..f697285c5 100644 --- a/crates/engine/src/cmd/layout/saveas.rs +++ b/crates/engine/src/cmd/layout/saveas.rs @@ -126,6 +126,7 @@ fn store(path: &str, bytes: &[u8]) -> Result<()> { { // Exclusively create a fresh temporary file and rename it into place so a planted // `.cadcraft-tmp` symlink cannot redirect the write (CWE-59). + crate::file_access::check_write(path).map_err(|e| bad("layout.saveas", e))?; crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), bytes).map_err(|e| bad("layout.saveas", format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 95ead78fc..d5f738233 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -598,6 +598,7 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result { Some(_path) => { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(_path).map_err(|e| bad(cmd, e))?; std::fs::write(_path, &text).map_err(|e| bad(cmd, format!("{_path}: {e}")))?; Ok(json!({ "name": name, "path": _path })) } diff --git a/crates/engine/src/cmd/table/breaks.rs b/crates/engine/src/cmd/table/breaks.rs index 6f207ec50..63504de55 100644 --- a/crates/engine/src/cmd/table/breaks.rs +++ b/crates/engine/src/cmd/table/breaks.rs @@ -238,6 +238,7 @@ fn read_link(id: &str, file: &std::path::Path) -> Result { let path = file.display(); #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_read(&file.to_string_lossy()).map_err(|e| bad(id, e))?; let meta = std::fs::metadata(file).map_err(|e| bad(id, format!("{path}: {e}")))?; if meta.len() > MAX_LINK_BYTES { return Err(bad(id, format!("{path}: larger than {} MB", MAX_LINK_BYTES >> 20))); diff --git a/crates/engine/src/cmd/table/cells.rs b/crates/engine/src/cmd/table/cells.rs index d020758d8..f7c695036 100644 --- a/crates/engine/src/cmd/table/cells.rs +++ b/crates/engine/src/cmd/table/cells.rs @@ -514,6 +514,7 @@ pub(crate) fn table_csv(t: &Table, sep: char) -> String { fn write_text(path: &str, text: &str) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { + crate::file_access::check_write(path).map_err(|e| bad("tableexport", e))?; std::fs::write(path, text).map_err(|e| bad("tableexport", format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs new file mode 100644 index 000000000..78e237ad4 --- /dev/null +++ b/crates/engine/src/file_access.rs @@ -0,0 +1,387 @@ +//! The folders automation may read and write (#1472). +//! +//! `cadcraft-cli mcp --automation-read-root --automation-write-root ` confines the files +//! an agent's commands reach. [`AutomationRoots`] holds the two folders. While they are in force, +//! every path a command reads goes through [`check_read`] and every path it writes through +//! [`check_write`]: +//! +//! - The path is made absolute against the working directory, as the file system reads it. Its +//! links are followed: for a file that doesn't exist yet, the links of its nearest existing +//! folder, the rest of the path being plain names (`..` below a missing folder is refused, and so +//! is a link that leads nowhere). +//! - The result must lie inside the root, compared by whole components (`/work2` isn't inside +//! `/work`), without regard to case on Windows. +//! - Read and write access are separate: a root given alone grants only its own kind of access. +//! A root left out grants none of that access. +//! +//! Roots are in force on a thread inside [`confine`]. The MCP headless backend runs every call in +//! it; without roots nothing is checked, so the app and the command line keep working everywhere. +//! +//! A path is checked, then opened: a process that can change the folders in between (swapping in +//! a link) can still win that race. The roots keep an agent to the files it was given; they don't +//! guard against other programs on the computer. + +use std::cell::RefCell; +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; + +/// Read access or write access. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Access { + Read, + Write, +} + +/// The folders automation may read and write; a root left out grants no access of its kind. +#[derive(Debug)] +pub struct AutomationRoots { + read: Option, + write: Option, +} + +#[derive(Debug)] +struct Root { + /// The folder made absolute, links followed: what paths are compared with. + resolved: PathBuf, + /// The same path, for people. + shown: PathBuf, +} + +impl Root { + /// The folder at `path`, which must exist. + fn open(path: &Path, access: Access) -> Result { + let kind = match access { + Access::Read => "read", + Access::Write => "write", + }; + let resolved = std::fs::canonicalize(path) + .and_then(|p| if p.is_dir() { Ok(p) } else { Err(std::io::ErrorKind::NotADirectory.into()) }) + .map_err(|e| format!("cannot open the automation {kind} root `{}`: {e}", path.display()))?; + Ok(Self { shown: resolved.clone(), resolved }) + } +} + +impl AutomationRoots { + /// The roots `read` and `write`, which must be existing folders; `None` when neither is given + /// (nothing is confined then). + pub fn new(read: Option<&Path>, write: Option<&Path>) -> Result>, String> { + if read.is_none() && write.is_none() { + return Ok(None); + } + let read = read.map(|p| Root::open(p, Access::Read)).transpose()?; + let write = write.map(|p| Root::open(p, Access::Write)).transpose()?; + Ok(Some(Arc::new(Self { read, write }))) + } + + /// The read root, absolute with its links followed. + pub fn read_root(&self) -> Option<&Path> { + self.read.as_ref().map(|r| r.shown.as_path()) + } + + /// The write root, absolute with its links followed. + pub fn write_root(&self) -> Option<&Path> { + self.write.as_ref().map(|r| r.shown.as_path()) + } + + /// May the file or folder at `path` be read (or written)? `Err` says why not. + pub fn check(&self, path: &str, access: Access) -> Result<(), String> { + let root = match access { + Access::Read => self.read.as_ref(), + Access::Write => self.write.as_ref(), + }; + let Some(Root { resolved: folder, shown }) = root else { + return match access { + Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")), + Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), + }; + }; + if inside(&resolve(path)?, folder) { + return Ok(()); + } + let root = shown.display(); + match access { + Access::Read => Err(format!("automation path rejected: outside the read root {root}: {path}")), + Access::Write => Err(format!("automation path rejected: outside the write root {root}: {path}")), + } + } +} + +thread_local! { + /// The roots in force on this thread. + static ROOTS: RefCell>> = const { RefCell::new(None) }; +} + +/// Puts the roots it replaced back when dropped (also when `f` panics). +struct Restore(Option>); + +impl Drop for Restore { + fn drop(&mut self) { + ROOTS.with(|r| *r.borrow_mut() = self.0.take()); + } +} + +/// Run `f` with `roots` in force on this thread (`None`: as things stand). +pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) -> T { + let previous = ROOTS.with(|r| r.replace(roots.cloned())); + let _restore = Restore(previous); + f() +} + +/// This thread's roots, if any. +pub fn current() -> Option> { + ROOTS.with(|r| r.borrow().clone()) +} + +/// May `path` be read here? Always, without roots in force. +pub fn check_read(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Read)) +} + +/// May `path` be written here? Always, without roots in force. +pub fn check_write(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write)) +} + +/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest +/// existing folder's links followed and the rest appended. +fn resolve(path: &str) -> Result { + if path.is_empty() { + return Err("automation path rejected: path is empty".into()); + } + // Checked as given: making `…\NUL` absolute gives the device path `\\.\NUL` on Windows. + if cfg!(windows) && Path::new(path).components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) { + return Err(format!("automation path rejected: reserved device names are not allowed: {path}")); + } + let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {path}: {e}"))?; + // The names below the nearest existing folder, last first. + let mut missing: Vec = vec![]; + let mut at = absolute.as_path(); + loop { + match std::fs::canonicalize(at) { + Ok(mut found) => { + found.extend(missing.iter().rev()); + return Ok(found); + } + Err(e) => match std::fs::symlink_metadata(at) { + Ok(m) if m.file_type().is_symlink() => return Err(format!("automation path rejected: a link that leads nowhere: {path}")), + // There, yet its real path can't be had (no permission): nothing to compare. + Ok(_) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("automation path rejected: cannot resolve {path}: {e}")), + }, + } + let parent = at.parent(); + match (at.components().next_back(), parent) { + (Some(Component::Normal(name)), Some(parent)) => { + missing.push(name.to_os_string()); + at = parent; + } + (Some(Component::ParentDir), _) => { + return Err(format!("automation path rejected: parent traversal below a folder that doesn't exist: {path}")); + } + // Down to the root (or drive) and it doesn't exist either. + _ => { + let e = std::io::Error::from(std::io::ErrorKind::NotFound); + return Err(format!("automation path rejected: cannot resolve {path}: {e}")); + } + } + } +} + +/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on +/// Windows, whose file systems ignore it)? +fn inside(path: &Path, root: &Path) -> bool { + let mut path = path.components(); + root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) +} + +fn same_component(a: Component, b: Component) -> bool { + if a == b { + return true; + } + if !cfg!(windows) { + return false; + } + match (a.as_os_str().to_str(), b.as_os_str().to_str()) { + (Some(a), Some(b)) => a.to_lowercase() == b.to_lowercase(), + _ => false, + } +} + +/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. +fn is_device_name(component: &str) -> bool { + let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); + let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")); + matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A fresh folder holding `in` (read root), `out` (write root) and `outside`. + fn folders(name: &str) -> (PathBuf, Arc) { + let base = std::env::temp_dir().join(format!("cc-file-access-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in/sub", "out", "outside", "in2"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + std::fs::write(base.join("in/a.dxf"), "0\nEOF\n").unwrap(); + std::fs::write(base.join("outside/secret.dxf"), "0\nEOF\n").unwrap(); + let roots = AutomationRoots::new(Some(&base.join("in")), Some(&base.join("out"))).unwrap().unwrap(); + (base, roots) + } + + fn s(p: PathBuf) -> String { + p.to_string_lossy().into_owned() + } + + #[test] + fn paths_inside_the_roots_pass_and_others_dont() { + let (base, roots) = folders("inside"); + assert_eq!(roots.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); + assert_eq!(roots.check(&s(base.join("in")), Access::Read), Ok(()), "the root itself"); + assert_eq!(roots.check(&s(base.join("in/sub/new.dxf")), Access::Read), Ok(()), "missing files are checked by their folder"); + assert_eq!(roots.check(&s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder"); + let e = roots.check(&s(base.join("outside/secret.dxf")), Access::Read).unwrap_err(); + assert!(e.starts_with("automation path rejected: outside the read root"), "{e}"); + // Read and write access are separate. + let e = roots.check(&s(base.join("in/a.dxf")), Access::Write).unwrap_err(); + assert!(e.contains("outside the write root"), "{e}"); + assert!(roots.check(&s(base.join("out/x.png")), Access::Read).unwrap_err().contains("outside the read root")); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn a_sibling_with_the_same_prefix_is_outside() { + let (base, roots) = folders("prefix"); + std::fs::write(base.join("in2/b.dxf"), "0\nEOF\n").unwrap(); + assert!(roots.check(&s(base.join("in2/b.dxf")), Access::Read).is_err(), "in2 is not inside in"); + assert!(roots.check(&format!("{}2/c.dxf", s(base.join("in"))), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn parent_traversal_is_resolved_or_refused() { + let (base, roots) = folders("dotdot"); + let sep = std::path::MAIN_SEPARATOR; + let up = format!("{}{sep}..{sep}outside{sep}secret.dxf", s(base.join("in"))); + assert!(roots.check(&up, Access::Read).unwrap_err().contains("outside the read root"), "`..` out of the root"); + let back = format!("{}{sep}..{sep}a.dxf", s(base.join("in/sub"))); + assert_eq!(roots.check(&back, Access::Read), Ok(()), "`..` that stays inside"); + let missing = format!("{}{sep}nope{sep}..{sep}..{sep}outside{sep}x.dxf", s(base.join("out"))); + let e = roots.check(&missing, Access::Write).unwrap_err(); + // Windows resolves `..` by name first (so does opening the file there): then it's outside. + assert!(e.contains("parent traversal below a folder that doesn't exist") || e.contains("outside the write root"), "{e}"); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn relative_paths_resolve_against_the_working_directory() { + let (base, roots) = folders("relative"); + // The tests' working directory is the crate's folder: not inside the roots. + assert!(roots.check("a.dxf", Access::Read).unwrap_err().contains("outside the read root")); + assert!(roots.check("", Access::Read).unwrap_err().contains("path is empty")); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn a_missing_root_is_an_error_and_none_is_no_confinement() { + let (base, _) = folders("missing"); + let e = AutomationRoots::new(Some(&base.join("nope")), None).unwrap_err(); + assert!(e.starts_with("cannot open the automation read root"), "{e}"); + let e = AutomationRoots::new(None, Some(&base.join("in/a.dxf"))).unwrap_err(); + assert!( + e.starts_with("cannot open the automation write root") + && e.ends_with(&std::io::Error::from(std::io::ErrorKind::NotADirectory).to_string()), + "{e}" + ); + assert!(AutomationRoots::new(Some(Path::new("")), None).unwrap_err().starts_with("cannot open the automation read root ``")); + assert!(AutomationRoots::new(None, None).unwrap().is_none()); + // One root alone grants only its own access. + let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); + let e = read_only.check(&s(base.join("in/x.dxf")), Access::Write).unwrap_err(); + assert!(e.contains("write authority is absent"), "{e}"); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn links_are_followed_before_comparing() { + let (base, roots) = folders("links"); + #[cfg(unix)] + let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + let made = |target: &Path, link: &Path| { + let made = + if target.is_dir() { std::os::windows::fs::symlink_dir(target, link) } else { std::os::windows::fs::symlink_file(target, link) }; + made.is_ok() + }; + #[cfg(not(any(unix, windows)))] + let made = |_: &Path, _: &Path| false; + // Windows needs Developer Mode or elevation to make links: nothing to test without them. + if !made(&base.join("outside/secret.dxf"), &base.join("in/leak.dxf")) { + eprintln!("skipped: symbolic links can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + assert!(roots.check(&s(base.join("in/leak.dxf")), Access::Read).unwrap_err().contains("outside the read root"), "a file link out"); + assert!(made(&base.join("outside"), &base.join("out/away"))); + let e = roots.check(&s(base.join("out/away/new.png")), Access::Write).unwrap_err(); + assert!(e.contains("outside the write root"), "a folder link out: {e}"); + assert!(made(&base.join("outside/gone.dxf"), &base.join("out/dangling.png"))); + let e = roots.check(&s(base.join("out/dangling.png")), Access::Write).unwrap_err(); + assert!(e.contains("a link that leads nowhere"), "writing would create the file outside: {e}"); + // A link to a folder inside the root stays inside. + assert!(made(&base.join("in/sub"), &base.join("in/alias"))); + assert_eq!(roots.check(&s(base.join("in/alias/x.dxf")), Access::Read), Ok(())); + // A root given through a link is the folder it leads to. + assert!(made(&base.join("in"), &base.join("in-link"))); + let linked = AutomationRoots::new(Some(&base.join("in-link")), None).unwrap().unwrap(); + assert_eq!(linked.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + #[cfg(windows)] + #[test] + fn windows_ignores_case_and_refuses_devices() { + let (base, roots) = folders("case"); + let upper = s(base.join("IN/A.DXF")); + assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}"); + assert_eq!(roots.check(&s(base.join("In/Sub/New.dxf")), Access::Read), Ok(())); + let e = roots.check(&s(base.join("out/NUL")), Access::Write).unwrap_err(); + assert!(e.contains("reserved device names"), "{e}"); + assert!(roots.check(&s(base.join("out/com1.txt")), Access::Write).is_err()); + assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn scopes_nest_and_restore_after_a_panic() { + let (base, roots) = folders("scopes"); + let outside = s(base.join("outside/secret.dxf")); + assert_eq!(check_read(&outside), Ok(()), "nothing is confined by default"); + confine(Some(&roots), || { + assert!(check_read(&outside).is_err()); + // A nested scope replaces the outer one and gives it back on the way out. + confine(None, || assert_eq!(check_read(&outside), Ok(()))); + assert!(check_read(&outside).is_err(), "restored after the inner scope"); + }); + assert_eq!(check_read(&outside), Ok(()), "restored after confine"); + let r = std::panic::catch_unwind(|| confine(Some(&roots), || panic!("boom"))); + assert!(r.is_err()); + assert_eq!(check_read(&outside), Ok(()), "restored after a panic"); + assert_eq!(confine(None, || check_read(&outside)), Ok(())); + let _ = std::fs::remove_dir_all(base); + } + + #[test] + fn device_names() { + for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.svg", "NUL "] { + assert!(is_device_name(d), "{d}"); + } + for f in ["console", "com10", "COM0", "lpt", "a.svg", "nul-x"] { + assert!(!is_device_name(f), "{f}"); + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ccb93ef4f..809e1fa8a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,6 +18,7 @@ pub mod blockedit; pub mod capped_read; pub mod cmd; pub mod doc_path; +pub mod file_access; mod finite; pub mod grip_dims; pub mod grips; diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index 44452ae89..00c8788fa 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -32,7 +32,7 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec) -> Result } None => return Ok(Flow::Value(Value::Nil)), } - } else if !can_write(&path) { + } else if !can_write(&path) || crate::file_access::check_write(&path).is_err() { return Ok(Flow::Value(Value::Nil)); } let id = ctx.env.next_file; @@ -77,6 +77,7 @@ pub fn read_text_file(path: impl AsRef) -> Option { // Read through a byte-limited, regular-file-only reader so a path naming an endless device // cannot exhaust memory before the 64 MiB cap is enforced (CWE-400). const MAX: usize = 64 * 1024 * 1024; + crate::file_access::check_read(&path.as_ref().to_string_lossy()).ok()?; let bytes = crate::capped_read::read_capped(path.as_ref(), MAX).ok()?; Some(String::from_utf8_lossy(&bytes).into_owned()) } @@ -100,6 +101,9 @@ fn can_write(_path: &str) -> bool { #[cfg(not(target_arch = "wasm32"))] fn write_text_file(path: &str, text: &str, append: bool) { use std::io::Write; + if crate::file_access::check_write(path).is_err() { + return; + } let f = std::fs::OpenOptions::new().create(true).write(true).append(append).truncate(!append).open(path); if let Ok(mut f) = f { let _ = f.write_all(text.as_bytes()); @@ -111,7 +115,7 @@ fn write_text_file(_path: &str, _text: &str, _append: bool) {} #[cfg(not(target_arch = "wasm32"))] fn file_exists(path: &str) -> bool { - std::path::Path::new(path).is_file() + crate::file_access::check_read(path).is_ok() && std::path::Path::new(path).is_file() } #[cfg(target_arch = "wasm32")] diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 913569e82..af2e9bc9e 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -2,9 +2,11 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; +use std::sync::Arc; use std::time::Duration; use cadcraft_engine::Session; +use cadcraft_engine::file_access::{self, AutomationRoots}; use serde_json::{Value, json}; /// Something that answers control-channel methods (`engine.execute`, `cmdline.input`, @@ -308,13 +310,19 @@ const HEADLESS_METHODS: &[(&str, &str, &str)] = &[ ]; /// An in-process headless session (no window). +#[derive(Default)] pub struct Headless { pub session: Session, + /// The folders its methods may read and write (`--automation-read-root`, + /// `--automation-write-root`); `None`: anywhere. + roots: Option>, } -impl Default for Headless { - fn default() -> Self { - Headless { session: Session::new() } +impl Headless { + /// Confine the files every method reads and writes to `roots` ([`file_access`]). + pub fn with_automation_roots(mut self, roots: Option>) -> Self { + self.roots = roots; + self } } @@ -333,8 +341,8 @@ fn state(s: &Session) -> Value { }) } -impl Backend for Headless { - fn call(&mut self, method: &str, p: Value) -> Result { +impl Headless { + fn answer(&mut self, method: &str, p: &Value) -> Result { let s = &mut self.session; let str_p = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); match method { @@ -394,12 +402,12 @@ impl Backend for Headless { "engine.commands" => { Ok(Value::Array(cadcraft_engine::command_specs().iter().map(|c| serde_json::to_value(c.info(s)).unwrap_or_default()).collect())) } - "drawing.inspect" | "document.inspect" => s.execute("drawing.inspect", &p).map_err(|e| e.to_string()), + "drawing.inspect" | "document.inspect" => s.execute("drawing.inspect", p).map_err(|e| e.to_string()), "ui.render" => { let w = p.get("width").and_then(Value::as_f64).unwrap_or(1600.0).clamp(16.0, 8192.0) as u32; let h = p.get("height").and_then(Value::as_f64).unwrap_or(1000.0).clamp(16.0, 8192.0) as u32; let st = s.state().map_err(|e| e.to_string())?; - let window = render_window(&p); + let window = render_window(p); let opts = cadcraft_render::Options { view: window, transparency: s.settings.transparency_display, ..Default::default() }; let list = cadcraft_render::build(&st.doc, &st.space, &opts); let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(true); @@ -418,6 +426,7 @@ impl Backend for Headless { let mut r = json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "truncated": list.truncated}); if let Some(path) = str_p("path") { + file_access::check_write(&path)?; let file = std::path::Path::new(&path); let folder = cadcraft_engine::atomic_write::missing_folder(file); cadcraft_engine::atomic_write::write_atomic_making_folders(file, &png).map_err(|e| format!("{path}: {e}"))?; @@ -433,7 +442,7 @@ impl Backend for Headless { } "app.save" => { let id = if p.get("path").is_some() { "saveas" } else { "qsave" }; - s.execute(id, &p).map_err(|e| e.to_string()) + s.execute(id, p).map_err(|e| e.to_string()) } "ui.screenshot" => Err("no UI in headless mode; use render".into()), "control.methods" => Ok(HEADLESS_METHODS @@ -444,6 +453,13 @@ impl Backend for Headless { other => Err(format!("unknown method `{other}`; `control.methods` lists them (docs/control-protocol.md)")), } } +} + +impl Backend for Headless { + fn call(&mut self, method: &str, p: Value) -> Result { + let roots = self.roots.clone(); + file_access::confine(roots.as_ref(), || self.answer(method, &p)) + } fn has_ui(&self) -> bool { false } diff --git a/docs/mcp.md b/docs/mcp.md index ecdc53d09..fa76d3452 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -32,6 +32,44 @@ Example client configuration (Claude Code / Claude Desktop): { "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp"] } } } ``` +## Confining file access + +```sh +cadcraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project/out +``` + +The two flags (PhotoCraft, VectorCraft and the other Craft apps take the same ones, so one client +configuration works across the suite) keep the agent to the folders you give it: + +- Every file a command **reads** must lie inside the **read root**: `open`, `recover`, `compare`, + `script`, `import`, `insert`, `xattach` and every xref it loads, `new` templates, `appload` and + LISP `load`/`open`, support files (`linetype`, `hatch.patterns`, `aliasedit`, `reinit`), data + links, and plot style and plotter configuration files named by a path. +- Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas` + (including the temporary file written beside the destination), `export`, `plot`, `publish`, + `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, and + `render {path}`. +- Read and write access are separate. Give the same folder twice for both; a root left out grants + none of its access (with only `--automation-read-root`, nothing can be written to disk). Without + either flag nothing changes. +- A path is made absolute against the server's working directory, then its links are followed: a + file or folder link that leads out of a root is outside it. For a file that doesn't exist yet, + its nearest existing folder's links are followed and the rest must be plain names, so `..` below + a folder that doesn't exist is refused, as is a link that leads nowhere. The result is compared + with the root by whole folder names: `/work2/x` is not inside `/work`. On Windows case is ignored, + UNC paths are resolved like drive-letter ones, and device names (`CON`, `NUL`, `COM1`…) are + refused. +- A refused path is an ordinary tool error with `isError: true` that the agent can read and + correct, for example `automation path rejected: outside the write root + /work/project/out: /etc/x.png` or `automation filesystem access is not granted: write authority + is absent: /work/project/out/x.png`. +- The roots must be existing folders; a missing one stops the server with an error. Each flag is + given once (`--flag ` or `--flag=`). + +The flags confine the headless server. `--connect` with them is an error, since the server would +otherwise talk to an app that isn't confined; the app's control channel does not take them yet +(#1585). Without `--connect` the server writes the files itself, so every check happens here. + ## Tools | Tool | What it does | From 2872c051622fb370dc872059c560ae8b4a457878 Mon Sep 17 00:00:00 2001 From: assamaral <217119886+assamaral@users.noreply.github.com> Date: Wed, 4 Nov 2026 13:47:19 -0300 Subject: [PATCH 239/531] fix(io): read VIEWPORT ids outside 1..=32767 as unknown Group 69 is a 16-bit code. Large values passed the filter and `as u32` truncated them, so 69 = 4294967297 read as a second id 1. Also drop the docs/file-format-parity.md row: PRs name affected rows in the description. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/dxf_read/entities.rs | 3 ++- crates/io/src/tests.rs | 19 ++++++++++++++++++- docs/file-format-parity.md | 1 - 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 1a9e6c98e..eb0e4a397 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -254,7 +254,8 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef view_center: t.view_center(12, 17, twist), view_height: t.fd(45, 1.0), // ZWCAD writes -1 (unknown): 0 here, numbered in order by the reader (#1463). - id: t.i(69).filter(|i| *i > 0).unwrap_or(0) as u32, + // Group 69 is 16-bit: other out-of-range values are unknown too, never truncated. + id: t.i(69).filter(|i| (1..=32767).contains(i)).unwrap_or(0) as u32, locked: t.i(90).unwrap_or(0) & 16384 != 0, frozen_layers: crate::dxf_ext::read_frozen(tags), layer_colors: crate::dxf_ext::read_layer_colors(tags), diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 623c09900..c943ee9a7 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -669,6 +669,11 @@ fn viewport_frozen_layers_roundtrip() { /// `Layout1` with viewports 1 (the sheet), 2 and 3, written to DXF and read back with the id (69) /// of every viewport `blank` names replaced by -1 (ZWCAD's "unknown"): the ids and widths read. fn viewport_ids_read_back(blank: impl Fn(&str) -> bool) -> (Drawing, Vec<(u32, f64)>) { + viewport_ids_read_back_as(blank, "-1") +} + +/// [`viewport_ids_read_back`], with `value` in place of the id of every viewport `blank` names. +fn viewport_ids_read_back_as(blank: impl Fn(&str) -> bool, value: &str) -> (Drawing, Vec<(u32, f64)>) { let mut d = sample(); let paper = Space::Paper("Layout1".into()); for (id, w) in [(1, 420.0), (2, 8.0), (3, 4.0)] { @@ -687,7 +692,7 @@ fn viewport_ids_read_back(blank: impl Fn(&str) -> bool) -> (Drawing, Vec<(u32, f let mut lines: Vec = text.lines().map(String::from).collect(); for i in (0..lines.len() - 1).step_by(2) { if lines[i].trim() == "69" && blank(lines[i + 1].trim()) { - lines[i + 1] = "-1".into(); + lines[i + 1] = value.into(); } } let back = read_dxf(lines.join("\n").as_bytes()).unwrap(); @@ -723,6 +728,18 @@ fn viewport_ids_unknown_sheet_becomes_one() { assert!(!write_dxf(&back).contains("PAPERVIEW"), "the first viewport is the sheet"); } +/// Group 69 is a 16-bit code: an id outside 1..=32767 reads as unknown (0), and is never truncated +/// into a real id (4294967297 would become a second id 1, a second paper-space viewport). +#[test] +fn viewport_ids_out_of_range_read_as_unknown() { + for bad in ["4294967297", "65537", "32768"] { + let (_, ids) = viewport_ids_read_back_as(|v| v == "2", bad); + assert_eq!(ids, [(1, 420.0), (0, 8.0), (3, 4.0)], "69 = {bad}"); + } + let (_, ids) = viewport_ids_read_back_as(|v| v == "2", "32767"); + assert_eq!(ids, [(1, 420.0), (32767, 8.0), (3, 4.0)]); +} + /// A layout whose only viewport has id 0 (entmake, MCP): the writer adds the PAPERVIEW sheet ahead /// of it and the reader drops that sheet again. The id-0 viewport must not be numbered 1, or the /// next save takes it as the sheet and the generated sheet is lost (#2107). diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 8234b79e1..8085f422c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -144,7 +144,6 @@ our output in AutoCAD black-box. | 2026-10-29 | minor | R2000 DXF: CLASS records written without group 91 (instance count), which came with the 2004 format; AutoCAD LT 2026 stopped responding on every R2000 DXF CADCraft saved (checked black-box in AutoCAD LT 2026) | | 2026-10-26 | minor | CC-046: ATTEDIT and -ATTEDIT value changes invalidate derived justified baselines before DXF/DWG export; preserve alignment anchors, unchanged values and Aligned/Fit endpoints. Review follow-up: baseline recomputation preserves insertion elevation independently of alignment elevation. The shared writer correction also applies to justified TEXT. Independent of attribute editor UI; reverting the follow-up restores elevation loss on recomputation, while reverting the value setter restores stale XY baselines. | | 2026-10-25 | minor | LAYOUT SAveas (`layout.saveas`) writes a layout as a drawing template: its page setup and paper space objects, no model space objects or other layouts, and only the named objects they use | -| 2026-10-24 | minor | DXF read: a layout whose VIEWPORTs all carry id (69) -1 (ZWCAD writes no ids) gets them numbered in file order, the first being the paper-space viewport, so a save no longer adds a second sheet viewport that turns the real one into a model viewport and inflates the drawing extents (#1463) | | 2026-10-22 | minor | DXF/DWG save: angular, diametric and radial dimensions get standard DIMASSOC objects (one centre reference to the circle for radial/diametric, the definition points for angular), so AutoCAD follows their geometry; the standard objects of those kinds are read back too, without CADCraft's xdata (#1651) | | 2026-10-19 | minor | DXF/DWG save: angular dimension block text honors DIMDSEP, including per-dimension overrides (#1646) | | 2026-10-19 | minor | A file's own arrowhead blocks with standard names (AutoCAD's `_Dot`, `_DotSmall`), named only by a dimension style, are kept and saved as they were instead of being replaced by CADCraft's solids; PURGE keeps arrowhead blocks dimension styles name | From 0f33f430a75a28145b24f540e4f5b553f7070012 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 05:50:44 -0700 Subject: [PATCH 240/531] security: confine plotter settings I/O and refuse the write root itself - PLOTTERMANAGER's settings store now checks read access to the settings folder and each file, write access to the target before the folder is created, and write access before deletion (#1472 review). list surfaces a refused folder as an ordinary error. - Reads are allowed under the read or the write root; writes stay under the write root. A write to the write root itself is refused, since its temporary file would land beside the root, outside it. - Tests cover reads under either root, refusing the root as a write target, no temporary file outside the root, and every plotter action refused when the shared settings folder is outside the roots. - Docs and CLI help describe the same rules. This is 72961da from the #1904 branch, which the 2 Nov rebase dropped, ported to main's atomic_write. Main's writers now use a fresh temporary file beside the target, so the separate temporary-path checks are gone. --- apps/cadcraft-cli/src/args.rs | 5 +- apps/cadcraft-cli/tests/mcp_roots.rs | 86 +++++++++++++++++++++++++--- crates/engine/src/cmd/plotters.rs | 35 ++++++++++- crates/engine/src/file_access.rs | 85 ++++++++++++++++++++------- docs/mcp.md | 26 +++++---- 5 files changed, 192 insertions(+), 45 deletions(-) diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index 9e7a0c3ed..5d3864e0e 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -276,10 +276,11 @@ pub(crate) struct McpArgs { /// port first (macOS) #[arg(long, requires = "connect")] pub(crate) launch: bool, - /// The only folder the agent's commands may read from (headless only) + /// The only folder the agent's commands may read from; reads are also allowed under the write + /// root (headless only) #[arg(long, value_name = "DIR")] pub(crate) automation_read_root: Option, - /// The only folder the agent's commands may write to (headless only) + /// The only folder the agent's commands may write to, never the folder itself (headless only) #[arg(long, value_name = "DIR")] pub(crate) automation_write_root: Option, #[command(flatten)] diff --git a/apps/cadcraft-cli/tests/mcp_roots.rs b/apps/cadcraft-cli/tests/mcp_roots.rs index 67f205041..71e38adc0 100644 --- a/apps/cadcraft-cli/tests/mcp_roots.rs +++ b/apps/cadcraft-cli/tests/mcp_roots.rs @@ -40,6 +40,11 @@ struct Tool { /// Run `cadcraft-cli mcp` with `args`, initialise, then make each call in order. fn run(args: &[&str], calls: &[(&str, Value)]) -> (Output, Vec) { + run_env(args, calls, &[]) +} + +/// [`run`], with `env` set for the server process (a private settings folder). +fn run_env(args: &[&str], calls: &[(&str, Value)], env: &[(&str, &str)]) -> (Output, Vec) { let mut input = format!("{INIT}\n"); for (i, (name, arguments)) in calls.iter().enumerate() { let req = json!({"jsonrpc": "2.0", "id": i + 2, "method": "tools/call", "params": {"name": name, "arguments": arguments}}); @@ -49,6 +54,7 @@ fn run(args: &[&str], calls: &[(&str, Value)]) -> (Output, Vec) { let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) .arg("mcp") .args(args) + .envs(env.iter().copied()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -104,17 +110,21 @@ fn files_open_only_from_inside_the_read_root() { let _ = std::fs::remove_dir_all(base); } +/// Writes stay inside the write root, the root itself is refused, and no temporary file is left outside. #[test] fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { let base = folders("write"); - let (out, t) = run( - &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + let out = s(&base.join("out")); + let (out_run, t) = run( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &out], &[ ("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/saved.dxf"))})), ("save", json!({"path": s(&base.join("outside/saved.dxf"))})), ("save", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": format!("{}/../outside/up.dxf", s(&base.join("out")))})), + ("save", json!({"path": out})), + ("save", json!({"path": format!("{out}/../out")})), ("execute", json!({"command": "export", "params": {"path": s(&base.join("out/art.png")), "format": "png"}})), ("execute", json!({"command": "export", "params": {"path": s(&base.join("outside/art.png")), "format": "png"}})), ("render", json!({"path": s(&base.join("out/view.png"))})), @@ -122,20 +132,22 @@ fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { ("execute", json!({"command": "circle", "params": {"center": [0, 0], "radius": 1}})), ], ); - assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + assert!(out_run.status.success(), "stderr: {}", String::from_utf8_lossy(&out_run.stderr)); ok(&t[0]); ok(&t[1]); assert!(base.join("out/saved.dxf").is_file()); refused(&t[2], "outside the write root"); refused(&t[3], "outside the write root"); refused(&t[4], "outside the write root"); - ok(&t[5]); - assert!(base.join("out/art.png").is_file()); - refused(&t[6], "outside the write root"); + refused(&t[5], "the write root itself cannot be written"); + refused(&t[6], "the write root itself cannot be written"); ok(&t[7]); - assert!(base.join("out/view.png").is_file()); + assert!(base.join("out/art.png").is_file()); refused(&t[8], "outside the write root"); ok(&t[9]); + assert!(base.join("out/view.png").is_file()); + refused(&t[10], "outside the write root"); + ok(&t[11]); assert!(!base.join("outside/saved.dxf").exists()); assert!(!base.join("outside/art.png").exists()); @@ -143,12 +155,17 @@ fn writes_go_only_into_the_write_root_and_leave_no_temp_file_outside() { // The save's temporary file is beside the destination, inside the root; none is outside. assert!(!base.join("outside/saved.dxf.cadcraft-tmp").exists()); assert!(!base.join("outside/up.dxf.cadcraft-tmp").exists()); + assert!(!base.join("out.cadcraft-tmp").exists(), "writing to the root must not leave its temporary file beside it"); let leftovers: Vec = std::fs::read_dir(base.join("outside")).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); assert_eq!(leftovers, ["b.dxf"], "nothing was written outside the roots"); + let temps: Vec = + std::fs::read_dir(&base).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).filter(|n| n.ends_with(".cadcraft-tmp")).collect(); + assert!(temps.is_empty(), "no temporary file beside or outside the roots: {temps:?}"); let _ = std::fs::remove_dir_all(base); } +/// A root left out grants none of its own access: a read root allows no writes, while a write root also allows reads. #[test] fn a_root_left_out_grants_none_of_its_access() { let base = folders("left-out"); @@ -164,12 +181,63 @@ fn a_root_left_out_grants_none_of_its_access() { let (out, t) = run( &["--automation-write-root", &s(&base.join("out"))], - &[("open", json!({"path": s(&base.join("in/a.dxf"))})), ("save", json!({"path": s(&base.join("out/new.dxf"))}))], + &[ + ("open", json!({"path": s(&base.join("in/a.dxf"))})), + ("save", json!({"path": s(&base.join("out/new.dxf"))})), + // Reads are allowed under the write root: the agent can reopen what it saved. + ("open", json!({"path": s(&base.join("out/new.dxf"))})), + ], ); assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); - refused(&t[0], "read authority is absent"); + refused(&t[0], "outside the read root (or the write root)"); ok(&t[1]); assert!(base.join("out/new.dxf").is_file()); + ok(&t[2]); + let _ = std::fs::remove_dir_all(base); +} + +/// The shared plotter settings folder is outside the roots: every action refuses and it is unchanged. +#[test] +fn plotter_settings_outside_the_roots_are_refused() { + let base = folders("plotters"); + let config = base.join("config"); + let settings = config.join("plotters"); + std::fs::create_dir_all(&settings).unwrap(); + let device = cadcraft_engine::doc::PlotterConfig { + name: "Office".into(), + description: "not the agent's".into(), + papers: vec![cadcraft_engine::doc::DevicePaper { name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }], + ..Default::default() + }; + let file = settings.join("Office.plotter.json"); + let original = device.to_file_text(); + std::fs::write(&file, &original).unwrap(); + + let text = original.clone(); + let (out, t) = run_env( + &["--automation-read-root", &s(&base.join("in")), "--automation-write-root", &s(&base.join("out"))], + &[ + ("execute", json!({"command": "plottermanager", "params": {}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "get", "name": "Office"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "new", "name": "Leak", "output": "pdf"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "set", "name": "Office", "description": "changed"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "load", "text": text, "name": "Leaked Copy"}})), + ("execute", json!({"command": "plottermanager", "params": {"action": "delete", "name": "Office"}})), + ], + &[("CADCRAFT_CONFIG_DIR", &s(&config))], + ); + assert!(out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr)); + refused(&t[0], "outside the read root (or the write root)"); + refused(&t[1], "unknown plotter"); + refused(&t[2], "outside the write root"); + refused(&t[3], "unknown plotter"); + refused(&t[4], "outside the write root"); + refused(&t[5], "unknown plotter"); + + assert_eq!(std::fs::read_to_string(&file).unwrap(), original, "the shared file is unchanged"); + let names: Vec = std::fs::read_dir(&settings).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["Office.plotter.json"], "nothing was created or deleted in the settings folder"); + assert!(!settings.join("Office.plotter.json.cadcraft-tmp").exists()); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index d5f738233..fce04acfe 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -77,9 +77,27 @@ impl PlotterStore { } Ok(dir()?.join(n)) } + /// Refuse a settings path automation may not read (always allowed without roots). + fn check_read(path: &std::path::Path) -> std::result::Result<(), String> { + if crate::file_access::current().is_none() { + return Ok(()); + } + let path = path.to_str().ok_or_else(|| "the plotter settings path is not valid UTF-8".to_string())?; + crate::file_access::check_read(path) + } + /// Refuse a settings path automation may not write (always allowed without roots). + fn check_write(path: &std::path::Path) -> std::result::Result<(), String> { + if crate::file_access::current().is_none() { + return Ok(()); + } + let path = path.to_str().ok_or_else(|| "the plotter settings path is not valid UTF-8".to_string())?; + crate::file_access::check_write(path) + } PlotterStore { list: || { - let rd = match std::fs::read_dir(dir()?) { + let d = dir()?; + check_read(&d)?; + let rd = match std::fs::read_dir(d) { Ok(rd) => rd, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e.to_string()), @@ -92,6 +110,7 @@ impl PlotterStore { }, read: |n| { let p = file(n)?; + check_read(&p)?; let len = std::fs::metadata(&p).map_err(|e| format!("{n}: {e}"))?.len(); if len > cadcraft_doc::MAX_PLOTTER_FILE as u64 { return Err(format!("{n}: the plotter configuration file is too large")); @@ -100,10 +119,16 @@ impl PlotterStore { }, write: |n, t| { let p = file(n)?; + // Checked before the folder it lives in is created. The temporary file sits beside it. + check_write(&p)?; std::fs::create_dir_all(dir()?).map_err(|e| e.to_string())?; crate::atomic_write::write_atomic(&p, t.as_bytes()).map_err(|e| format!("{n}: {e}")) }, - delete: |n| std::fs::remove_file(file(n)?).map_err(|e| format!("{n}: {e}")), + delete: |n| { + let p = file(n)?; + check_write(&p)?; + std::fs::remove_file(p).map_err(|e| format!("{n}: {e}")) + }, } } } @@ -513,7 +538,11 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result { let cmd = "plottermanager"; let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase(); match action.as_str() { - "list" => Ok(json!({ "devices": devices().iter().map(summary).collect::>() })), + "list" => { + // A refused settings folder is an error, not a short list: show the refusal. + (store().list)().map_err(|e| bad(cmd, e))?; + Ok(json!({ "devices": devices().iter().map(summary).collect::>() })) + } "get" => { let n = device_name(cmd, p)?; let c = find_device(&n).ok_or_else(|| unknown_device(cmd, &n))?; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 78e237ad4..35ed5f9ec 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -11,8 +11,9 @@ //! is a link that leads nowhere). //! - The result must lie inside the root, compared by whole components (`/work2` isn't inside //! `/work`), without regard to case on Windows. -//! - Read and write access are separate: a root given alone grants only its own kind of access. -//! A root left out grants none of that access. +//! - Reads may lie under either root; writes only under the write root, and never at the write +//! root itself (its save-style temporary file would be outside). A root given alone grants +//! reads under it even when it is the write root; a read root grants no writes. //! //! Roots are in force on a thread inside [`confine`]. The MCP headless backend runs every call in //! it; without roots nothing is checked, so the app and the command line keep working everywhere. @@ -85,25 +86,33 @@ impl AutomationRoots { } /// May the file or folder at `path` be read (or written)? `Err` says why not. + /// + /// A read may lie under either root: the read root, or the write root (files the agent may + /// write it may also read back). A write may lie only under the write root, and not at the + /// root itself, whose save-style temporary file would sit beside it. pub fn check(&self, path: &str, access: Access) -> Result<(), String> { - let root = match access { - Access::Read => self.read.as_ref(), - Access::Write => self.write.as_ref(), - }; - let Some(Root { resolved: folder, shown }) = root else { - return match access { - Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")), - Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), - }; - }; - if inside(&resolve(path)?, folder) { - return Ok(()); + let target = resolve(path)?; + if access == Access::Read { + let roots = [self.read.as_ref(), self.write.as_ref()]; + if roots.iter().flatten().any(|r| inside(&target, &r.resolved)) { + return Ok(()); + } + if roots.iter().all(|r| r.is_none()) { + return Err(format!("automation filesystem access is not granted: read authority is absent: {path}")); + } + return Err(format!("automation path rejected: outside the read root (or the write root): {path}")); } - let root = shown.display(); - match access { - Access::Read => Err(format!("automation path rejected: outside the read root {root}: {path}")), - Access::Write => Err(format!("automation path rejected: outside the write root {root}: {path}")), + let Some(Root { resolved: folder, shown }) = self.write.as_ref() else { + return Err(format!("automation filesystem access is not granted: write authority is absent: {path}")); + }; + if !inside(&target, folder) { + return Err(format!("automation path rejected: outside the write root {}: {path}", shown.display())); } + // A write to the root itself would put its temporary file beside the root, outside it. + if same(&target, folder) { + return Err(format!("automation path rejected: the write root itself cannot be written: {path}")); + } + Ok(()) } } @@ -196,6 +205,11 @@ fn inside(path: &Path, root: &Path) -> bool { root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) } +/// Is `path` (resolved) exactly `root`, compared like [`inside`] does? +fn same(path: &Path, root: &Path) -> bool { + path.components().count() == root.components().count() && path.components().zip(root.components()).all(|(p, r)| same_component(p, r)) +} + fn same_component(a: Component, b: Component) -> bool { if a == b { return true; @@ -233,10 +247,12 @@ mod tests { (base, roots) } + /// `p` as a string a command would pass. fn s(p: PathBuf) -> String { p.to_string_lossy().into_owned() } + /// Paths under either root may be read; writes stay inside the write root. #[test] fn paths_inside_the_roots_pass_and_others_dont() { let (base, roots) = folders("inside"); @@ -246,10 +262,39 @@ mod tests { assert_eq!(roots.check(&s(base.join("out/new/deeper/x.png")), Access::Write), Ok(()), "and by their nearest folder"); let e = roots.check(&s(base.join("outside/secret.dxf")), Access::Read).unwrap_err(); assert!(e.starts_with("automation path rejected: outside the read root"), "{e}"); - // Read and write access are separate. + // Reads are allowed under the write root too; writes are not allowed under the read root. + assert_eq!(roots.check(&s(base.join("out/x.png")), Access::Read), Ok(()), "the write root also grants reads"); let e = roots.check(&s(base.join("in/a.dxf")), Access::Write).unwrap_err(); assert!(e.contains("outside the write root"), "{e}"); - assert!(roots.check(&s(base.join("out/x.png")), Access::Read).unwrap_err().contains("outside the read root")); + let _ = std::fs::remove_dir_all(base); + } + + /// A write-only root still permits reads inside it; reads outside both roots are refused. + #[test] + fn reads_are_allowed_under_either_root() { + let (base, _) = folders("either"); + let write_only = AutomationRoots::new(None, Some(&base.join("out"))).unwrap().unwrap(); + assert_eq!(write_only.check(&s(base.join("out/new.dxf")), Access::Read), Ok(()), "a file to read back"); + let e = write_only.check(&s(base.join("in/a.dxf")), Access::Read).unwrap_err(); + assert!(e.contains("outside the read root (or the write root)"), "{e}"); + let read_only = AutomationRoots::new(Some(&base.join("in")), None).unwrap().unwrap(); + assert_eq!(read_only.check(&s(base.join("in/a.dxf")), Access::Read), Ok(())); + assert!(read_only.check(&s(base.join("out/new.dxf")), Access::Read).is_err(), "a read root alone grants no read of another folder"); + let _ = std::fs::remove_dir_all(base); + } + + /// A write to the write root itself would put its `.cadcraft-tmp` file beside the root: refused. + #[test] + fn writing_to_the_write_root_itself_is_refused() { + let (base, roots) = folders("write-root"); + let out = s(base.join("out")); + let sep = std::path::MAIN_SEPARATOR; + for p in [out.clone(), format!("{out}{sep}."), format!("{out}{sep}..{sep}out")] { + let e = roots.check(&p, Access::Write).unwrap_err(); + assert!(e.contains("the write root itself cannot be written"), "{p}: {e}"); + } + assert_eq!(roots.check(&out, Access::Read), Ok(()), "reading the root stays allowed"); + assert_eq!(roots.check(&s(base.join("out/new/x.png")), Access::Write), Ok(()), "a normal save inside still works"); let _ = std::fs::remove_dir_all(base); } diff --git a/docs/mcp.md b/docs/mcp.md index fa76d3452..7b64dffa5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -41,17 +41,19 @@ cadcraft-cli mcp --automation-read-root /work/project --automation-write-root /w The two flags (PhotoCraft, VectorCraft and the other Craft apps take the same ones, so one client configuration works across the suite) keep the agent to the folders you give it: -- Every file a command **reads** must lie inside the **read root**: `open`, `recover`, `compare`, - `script`, `import`, `insert`, `xattach` and every xref it loads, `new` templates, `appload` and - LISP `load`/`open`, support files (`linetype`, `hatch.patterns`, `aliasedit`, `reinit`), data - links, and plot style and plotter configuration files named by a path. +- Every file a command **reads** must lie inside the **read root or the write root**: `open`, + `recover`, `compare`, `script`, `import`, `insert`, `xattach` and every xref it loads, `new` + templates, `appload` and LISP `load`/`open`, support files (`linetype`, `hatch.patterns`, + `aliasedit`, `reinit`), data links, plot style and plotter configuration files named by a path, + and the shared plotter settings folder. - Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas` (including the temporary file written beside the destination), `export`, `plot`, `publish`, - `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, and - `render {path}`. -- Read and write access are separate. Give the same folder twice for both; a root left out grants - none of its access (with only `--automation-read-root`, nothing can be written to disk). Without - either flag nothing changes. + `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, the shared + plotter settings folder, and `render {path}`. The write root itself is refused: a save's + temporary file would sit beside it, outside the root. +- Give the same folder twice for both. A root left out grants none of its *own* access: a read + root allows no writes, while a write root still allows reads inside it (files the agent wrote it + can read back). Without either flag nothing changes. - A path is made absolute against the server's working directory, then its links are followed: a file or folder link that leads out of a root is outside it. For a file that doesn't exist yet, its nearest existing folder's links are followed and the rest must be plain names, so `..` below @@ -61,8 +63,10 @@ configuration works across the suite) keep the agent to the folders you give it: refused. - A refused path is an ordinary tool error with `isError: true` that the agent can read and correct, for example `automation path rejected: outside the write root - /work/project/out: /etc/x.png` or `automation filesystem access is not granted: write authority - is absent: /work/project/out/x.png`. + /work/project/out: /etc/x.png`, `automation path rejected: outside the read root (or the write + root): /etc/x.png`, `automation path rejected: the write root itself cannot be written: + /work/project/out`, or `automation filesystem access is not granted: write authority is absent: + /work/project/out/x.png`. - The roots must be existing folders; a missing one stops the server with an error. Each flag is given once (`--flag ` or `--flag=`). From 2c979eb14b20aedafd0946f9f6d5463949f30b0e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 20:21:02 +0200 Subject: [PATCH 241/531] Fonts: user font folders, Hebrew SHX fonts, redraw when fonts change (on #1944's SHX) Rebuilt on main after #1944 (SHX shape fonts, big fonts, unifonts) landed: this part now keeps only what #1944 doesn't do. - User font folders (Options > Fonts, fontFolders): TrueType and OpenType files in them are found before the system's and listed first (ttf::set_font_dirs, installed, available, rescan); a face is found by its family name in any file there. SHX files in them, or in a folder under them, are found by the SHX font table too (shx::set_font_dirs), after the drawings' folders and before the search path. Folders are cleaned and capped, links to folders are not followed. - Hebrew SHX fonts: a one-byte font with the letters at their Windows-1255 or DOS 862 places draws Hebrew text from them; a Cyrillic font with letters at those places is not taken for Hebrew. In a DOS 862 font, %%d %%p %%c come from shapes 256-258 only. - The canvas draws text again when the TrueType or SHX font set changes (a font folder, a rescan, a drawing folder), the active viewport's model space included. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/fonts/src/shx/mod.rs | 20 +- crates/fonts/src/shx/parse.rs | 1 + crates/fonts/src/shx/table.rs | 16 +- crates/fonts/src/shx/tests.rs | 32 +++ crates/fonts/src/shx/text.rs | 9 + crates/fonts/src/ttf.rs | 340 ++++++++++++++++++++++++- crates/fonts/tests/shx_font_folders.rs | 32 +++ crates/ui-egui/src/canvas.rs | 3 + crates/ui-egui/src/canvas/list.rs | 10 + 9 files changed, 445 insertions(+), 18 deletions(-) create mode 100644 crates/fonts/tests/shx_font_folders.rs diff --git a/crates/fonts/src/shx/mod.rs b/crates/fonts/src/shx/mod.rs index 9ad352a2e..559621b70 100644 --- a/crates/fonts/src/shx/mod.rs +++ b/crates/fonts/src/shx/mod.rs @@ -41,8 +41,8 @@ use cadcraft_geom::Vec2; pub use compile::compile; pub use table::{ - FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, register, search_path, set_font_map, set_provider, - set_search_path, + FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, register, search_path, set_font_dirs, set_font_map, + set_provider, set_search_path, }; pub use text::ShxText; pub(crate) use text::{shape, width}; @@ -128,6 +128,9 @@ pub struct ShxFont { data: Vec, records: HashMap, cache: RwLock, + /// Whether a one-byte font holds Hebrew letters at their Windows-1255 / DOS 862 places, + /// worked out on first use ([`ShxFont::hebrew_places`]). + hebrew: std::sync::OnceLock<(bool, bool)>, } impl std::fmt::Debug for ShxFont { @@ -194,6 +197,19 @@ impl ShxFont { pub fn has_shape(&self, number: u16) -> bool { number != 0 && self.records.contains_key(&number) } + /// Whether this one-byte font draws Hebrew letters at their Windows-1255 places (0xE0..0xFA) + /// and at their DOS 862 places (0x80..0x9A), as Israeli SHX fonts do. A Cyrillic font fills + /// the same places with its letters, so it must not also fill 0xC0..0xDF (Windows-1251) or + /// 0xA0..0xAF (DOS 866): Hebrew text never turns into Russian. + pub fn hebrew_places(&self) -> (bool, bool) { + *self.hebrew.get_or_init(|| { + if self.kind != ShxKind::Shapes { + return (false, false); + } + let count = |r: std::ops::RangeInclusive| r.filter(|c| self.has_shape(*c)).count(); + (count(0xE0..=0xFA) >= 20 && count(0xC0..=0xDF) < 16, count(0x80..=0x9A) >= 20 && count(0xA0..=0xAF) < 8) + }) + } /// The shape numbers in the file, sorted (not shape 0). pub fn shape_numbers(&self) -> Vec { let mut v: Vec = self.records.keys().copied().filter(|n| *n != 0).collect(); diff --git a/crates/fonts/src/shx/parse.rs b/crates/fonts/src/shx/parse.rs index b10e8142e..086857af0 100644 --- a/crates/fonts/src/shx/parse.rs +++ b/crates/fonts/src/shx/parse.rs @@ -127,6 +127,7 @@ impl Font { data, records: self.records, cache: RwLock::default(), + hebrew: std::sync::OnceLock::new(), }) } } diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 4b44927d7..859ff0d3c 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -5,8 +5,8 @@ //! Order: the font map ([`set_font_map`]) renames the file; then fonts registered by the app //! ([`register`]: the web build's files opened alongside a drawing, tests); then the app's //! [`FontProvider`]; then, natively, the folders of opened drawings ([`add_drawing_dir`], most -//! recent first) and the support search path ([`set_search_path`], from `CADCRAFT_SHXPATH` at -//! start). Results, found or not, are cached until one of these changes ([`generation`] +//! recent first), the user's font folders ([`set_font_dirs`], from Options) and the support +//! search path ([`set_search_path`], from `CADCRAFT_SHXPATH` at start). Results, found or not, are cached until one of these changes ([`generation`] //! counts the changes, so a viewer knows to regenerate). use std::collections::HashMap; @@ -38,6 +38,7 @@ struct Table { loaded_bytes: usize, provider: Option>, drawing_dirs: Vec, + font_dirs: Vec, search_path: Vec, map: Vec<(String, String)>, generation: u64, @@ -135,6 +136,15 @@ pub fn drawing_dirs() -> Vec { table().drawing_dirs.clone() } +/// Search the user's font folders (and the folders under them that hold SHX files, as the +/// font list finds them) after the drawings' folders. Looks again even when the folders are the +/// same: files may have been added. +pub fn set_font_dirs(dirs: Vec) { + let mut t = table(); + t.font_dirs = dirs.into_iter().filter(|d| !d.as_os_str().is_empty()).take(MAX_DIRS).collect(); + t.changed(); +} + /// Set the support search path for SHX files: folders separated by `;` (or the platform's /// path separator). Empty clears it. pub fn set_search_path(list: &str) { @@ -196,7 +206,7 @@ pub fn find(name: &str) -> Option> { if let Some(r) = t.resolved.get(&k) { return r.clone(); } - let dirs: Vec = t.drawing_dirs.iter().chain(t.search_path.iter()).cloned().collect(); + let dirs: Vec = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect(); (t.provider.clone(), dirs, t.generation) }; let font = provider diff --git a/crates/fonts/src/shx/tests.rs b/crates/fonts/src/shx/tests.rs index a6ab40c99..f918e4645 100644 --- a/crates/fonts/src/shx/tests.rs +++ b/crates/fonts/src/shx/tests.rs @@ -448,3 +448,35 @@ fn arcs_follow_the_circle() { assert!(close(g.advance, (dir(135.0 + 180.0) - dir(135.0)) * 5.0)); let _ = PI; } + +/// A one-byte font with Hebrew letters at `codes`, each shape advancing by a different amount +/// (its code's low byte in units), and a font record 6 units high. +fn hebrew_font(codes: impl Iterator) -> ShxFont { + let mut src = String::from("*0,4,hebrew\n6,2,0,0\n"); + for c in codes { + src.push_str(&format!("*0{c:X},3,h\n8,({},0),0\n", c & 0x1F)); + } + font(&src) +} + +/// Israeli SHX fonts keep Hebrew letters at their Windows-1255 (0xE0..0xFA) or DOS 862 +/// (0x80..0x9A) places: Hebrew text draws from them, while a Cyrillic font with letters at the +/// same places is not taken for Hebrew (#2316, rebuilt on #1944). +#[test] +fn hebrew_letters_draw_from_their_one_byte_places() { + let draws = |f: ShxFont, c: char| { + let t = ShxText::new(Some(std::sync::Arc::new(f)), None, "", false); + super::text::width(&t, &c.to_string(), 6.0, 1.0) + }; + // Windows-1255: alef at 0xE0 advances 0xE0 & 0x1F = 0 units; bet at 0xE1 one unit. + assert!((draws(hebrew_font(0xE0..=0xFA), 'ב') - 1.0).abs() < 1e-9); + // DOS 862: bet at 0x81 advances one unit. + assert!((draws(hebrew_font(0x80..=0x9A), 'ב') - 1.0).abs() < 1e-9); + assert_eq!(hebrew_font(0x80..=0x9A).hebrew_places(), (false, true)); + // A Cyrillic-style font (0xC0..0xFF all drawn) is not read as Hebrew: the letter comes + // from the built-in stroke font instead of a Cyrillic shape. + let cyr = hebrew_font(0xC0..=0xFF); + assert_eq!(cyr.hebrew_places(), (false, false)); + let stroke = crate::stroke_advance('ב', 6.0, 1.0); + assert!((draws(cyr, 'ב') - stroke).abs() < 1e-9); +} diff --git a/crates/fonts/src/shx/text.rs b/crates/fonts/src/shx/text.rs index 0e7e6513e..82ef71a0b 100644 --- a/crates/fonts/src/shx/text.rs +++ b/crates/fonts/src/shx/text.rs @@ -88,6 +88,10 @@ fn candidates(c: char, font: &ShxFont) -> [Option; 4] { _ => None, }; if let Some((s, latin, old)) = special { + // In a DOS 862 Hebrew font 127–129 are letters and 0xB0.. box drawing: shape 256–258 only. + if !unicode && font.kind() == ShxKind::Shapes && font.hebrew_places().1 { + return [Some(s), None, None, None]; + } return if unicode { [code(u), code(if c == '⌀' { 0x2205 } else { latin }), Some(s), Some(old)] } else { @@ -97,6 +101,11 @@ fn candidates(c: char, font: &ShxFont) -> [Option; 4] { if unicode || u < 0x80 { return [code(u), None, None, None]; } + // A Hebrew letter in an Israeli one-byte font: its Windows-1255 or DOS 862 place. + if (0x05D0..=0x05EA).contains(&u) && font.kind() == ShxKind::Shapes { + let (win, dos) = font.hebrew_places(); + return [win.then(|| code(u - 0x05D0 + 0xE0)).flatten(), dos.then(|| code(u - 0x05D0 + 0x80)).flatten(), None, None]; + } // A single-byte font: the Windows Latin-1 code of the character (not the old special // codes 127–129). let mut buf = [0u8; 4]; diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index bcf610e0a..085f46ad5 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -17,6 +17,10 @@ //! lacks (CJK in an SHX big font, for example), before the automatic system font search. //! //! Both start empty; the host sets its starting values ([`set_font_alt`], [`set_fallback_fonts`]). +//! +//! Besides the system font folders, the user's own font folders ([`set_font_dirs`], Options ▸ +//! Fonts) are searched first: a font placed there wins over an installed one with the same file +//! name. use std::collections::HashMap; use std::path::PathBuf; @@ -79,6 +83,16 @@ impl Face { pub fn has_glyph(&self, c: char) -> bool { self.font().is_some_and(|f| f.charmap().map(c).is_some()) } + /// The family name, as the font gives it. + pub fn family_name(&self) -> Option { + let f = self.font()?; + [skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME] + .into_iter() + .find_map(|id| f.localized_strings(id).next().map(|s| s.to_string())) + .map(|s| s.chars().filter(|c| !c.is_control()).take(80).collect::()) + .filter(|s| !s.trim().is_empty()) + } + /// The glyph ids the face's character map gives `chars` (`None` for an unmapped one). pub(crate) fn glyph_ids(&self, chars: &[char]) -> Vec> { let Some(f) = self.font() else { return vec![None; chars.len()] }; @@ -236,6 +250,20 @@ struct Db { fallback: Fallback, /// Bytes of font files loaded from disk so far (bounded by `MAX_LOADED_BYTES`). loaded_bytes: usize, + /// Stems of the fonts found in the user's font folders. + user: std::collections::HashSet, + /// 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>, +} + +/// The names inside one font file. +#[derive(Default)] +struct FaceNames { + /// The first face's family name. + family: Option, + /// Each face's normalized names (family, typographic family, full name). + faces: Vec>, } /// State of the missing-glyph search. @@ -266,10 +294,18 @@ fn lock() -> MutexGuard<'static, Db> { let mut g = DB.get_or_init(|| Mutex::new(Db::default())).lock().unwrap_or_else(PoisonError::into_inner); if !g.scanned { g.scanned = true; - g.paths = scan().into_iter().map(|(stem, p)| (stem, Source::File(p))).collect(); - // Embedded craft-fonts fonts take the place of an installed file with the same stem. + let user = scan_dirs(&user_dirs(), true); + g.user = user.keys().cloned().collect(); + let mut all = scan(); + all.extend(user); + g.paths = all.into_iter().map(|(stem, p)| (stem, Source::File(p))).collect(); + // Embedded craft-fonts fonts take the place of an installed file with the same stem, + // but not of a font in the user's own folders (which they chose to use). for f in crate::CRAFT_FONTS { - g.paths.insert(f.stem(), Source::Static(f.bytes)); + let stem = f.stem(); + if !g.user.contains(&stem) { + g.paths.insert(stem, Source::Static(f.bytes)); + } } } g @@ -277,7 +313,7 @@ fn lock() -> MutexGuard<'static, Db> { /// The platform's system font directories, in search order. #[cfg(not(target_arch = "wasm32"))] -fn font_dirs() -> Vec { +fn system_font_dirs() -> Vec { let mut dirs: Vec = Vec::new(); if cfg!(target_os = "macos") { dirs.extend(["/System/Library/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts"].map(Into::into)); @@ -304,11 +340,18 @@ fn font_dirs() -> Vec { dirs } -/// Every font file under [`font_dirs`], by lower-case file stem. +/// Every font file under [`system_font_dirs`], by lower-case file stem. #[cfg(not(target_arch = "wasm32"))] fn scan() -> HashMap { + scan_dirs(&system_font_dirs(), false) +} + +/// Font files under `dirs` by lower-case stem; the first file found with a stem wins +/// (`in_order`: a folder listed earlier wins over a later one). +#[cfg(not(target_arch = "wasm32"))] +fn scan_dirs(dirs: &[PathBuf], in_order: bool) -> HashMap { let mut out = HashMap::new(); - let mut stack = font_dirs(); + let mut stack: Vec = if in_order { dirs.iter().rev().cloned().collect() } else { dirs.to_vec() }; let mut seen = 0usize; while let Some(d) = stack.pop() { let Ok(rd) = std::fs::read_dir(&d) else { continue }; @@ -318,10 +361,15 @@ fn scan() -> HashMap { return out; } let p = e.path(); - if p.is_dir() { + // Real folders only: a link to a folder could lead in a circle. + let Ok(ft) = e.file_type() else { continue }; + if ft.is_dir() { stack.push(p); continue; } + if ft.is_symlink() && p.is_dir() { + continue; + } let ext = p.extension().map(|x| x.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); if !matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") { continue; @@ -339,6 +387,176 @@ fn scan() -> HashMap { HashMap::new() } +#[cfg(target_arch = "wasm32")] +fn scan_dirs(_dirs: &[PathBuf], _in_order: bool) -> HashMap { + HashMap::new() +} + +/// Most user font folders. +pub const MAX_FONT_DIRS: usize = 16; +/// The longest font folder path kept. +const MAX_DIR_CHARS: usize = 1024; + +fn dirs_lock() -> MutexGuard<'static, Vec> { + static DIRS: OnceLock>> = OnceLock::new(); + DIRS.get_or_init(|| Mutex::new(Vec::new())).lock().unwrap_or_else(PoisonError::into_inner) +} + +fn user_dirs() -> Vec { + dirs_lock().clone() +} + +/// Counts changes to the set of fonts ([`set_font_dirs`], [`rescan`]): text drawn before a change +/// may have been drawn with another font. +static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The font set's change count (see [`GENERATION`]). +pub fn generation() -> u64 { + GENERATION.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The user's font folders, searched before the system's. +pub fn font_dirs() -> Vec { + user_dirs().iter().map(|p| p.to_string_lossy().to_string()).collect() +} + +/// Clean a font folder list: trimmed, without empty, repeated or over-long entries, at most +/// [`MAX_FONT_DIRS`]. +pub fn clean_dirs>(dirs: &[S]) -> Vec { + let mut out: Vec = Vec::new(); + for d in dirs.iter().take(MAX_FONT_DIRS * 4) { + let d = d.as_ref().trim(); + if d.is_empty() || d.chars().count() > MAX_DIR_CHARS || d.chars().any(char::is_control) || out.iter().any(|o| o == d) { + continue; + } + out.push(d.to_string()); + if out.len() >= MAX_FONT_DIRS { + break; + } + } + out +} + +/// Set the user's font folders (Options ▸ Fonts) and look for fonts again. +pub fn set_font_dirs>(dirs: &[S]) { + let dirs: Vec = clean_dirs(dirs).into_iter().map(PathBuf::from).collect(); + { + let mut current = dirs_lock(); + if *current == dirs { + return; + } + *current = dirs; + } + rescan(); +} + +/// Forget what was found and look for fonts again (files added to a font folder). +pub fn rescan() { + let mut g = lock(); + // Fonts registered by name (no file behind them) stay. + let paths = std::mem::take(&mut g.paths); + g.files.retain(|k, _| !paths.contains_key(k)); + g.scanned = false; + g.resolved.clear(); + g.fallback = Fallback::default(); + g.loaded_bytes = 0; + g.user.clear(); + g.face_names.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. + crate::shx::set_font_dirs(shx_dirs(&user_dirs())); +} + +/// The folders under `dirs` (them included) that hold SHX files, in order, bounded like the +/// font scan. +#[cfg(not(target_arch = "wasm32"))] +fn shx_dirs(dirs: &[PathBuf]) -> Vec { + let mut out: Vec = Vec::new(); + let mut stack: Vec = dirs.iter().rev().cloned().collect(); + let mut seen = 0usize; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { continue }; + let mut subs = Vec::new(); + let mut has_shx = false; + for e in rd.flatten() { + seen += 1; + if seen > 20_000 { + return out; + } + let Ok(ft) = e.file_type() else { continue }; + if ft.is_dir() { + subs.push(e.path()); + } else if e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("shx")) { + has_shx = true; + } + } + if has_shx && !out.contains(&d) { + out.push(d); + } + stack.extend(subs.into_iter().rev()); + } + out +} + +#[cfg(target_arch = "wasm32")] +fn shx_dirs(_dirs: &[PathBuf]) -> Vec { + Vec::new() +} + +/// A font file CADCraft can use, for font lists. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FontFile { + /// The name a text style stores: the file name (`arial.ttf`), or the name of a font built + /// into CADCraft. + pub name: String, + /// The family name inside the file, read for fonts in the user's folders. + pub family: Option, + /// Found in one of the user's font folders. + pub user: bool, +} + +/// The fonts CADCraft can use: those in the user's folders first (with their family names), +/// then the installed and built-in ones, by name. +pub fn installed() -> Vec { + /// Fonts whose family name is read for the list. + const MAX_NAMED: usize = 200; + let mut g = lock(); + let mut list: Vec<(String, String, bool)> = g + .paths + .iter() + .map(|(stem, src)| { + let name = match src { + Source::File(p) => p.file_name().map_or_else(|| stem.clone(), |n| n.to_string_lossy().to_string()), + Source::Static(_) => stem.clone(), + }; + (stem.clone(), name, g.user.contains(stem)) + }) + .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; + 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 { + None + }; + FontFile { name, family, user } + }) + .collect() +} + +/// Whether a text style font is drawn as named: a font CADCraft found, or its own stroke font. +/// Other names (an SHX file, a missing TTF) are drawn with a substitute ([`crate::TextFont::resolve`]). +pub fn available(name: &str) -> bool { + let k = key(name); + // The built-in stroke font is CADCraft's own stand-in for the basic stroke fonts. + let stand_in = matches!(k.trim_end_matches(".shx"), "txt" | "simplex" | "romans"); + k.is_empty() || stand_in || k == crate::BUILTIN_FONT.to_ascii_lowercase() || crate::shx::find(name).is_some() || find(name).is_some() +} + #[cfg(not(target_arch = "wasm32"))] fn read_file(path: &std::path::Path) -> Option> { /// Font files larger than this are never read. @@ -363,15 +581,35 @@ impl Db { if self.loaded_bytes >= MAX_LOADED_BYTES { return None; } - let bytes = Arc::new(match self.paths.get(stem)? { - Source::File(path) => read_file(path)?, - Source::Static(bytes) => bytes.to_vec(), - }); + let bytes = self.peek(stem)?; self.loaded_bytes = self.loaded_bytes.saturating_add(bytes.len()); self.files.insert(stem.to_string(), bytes.clone()); Some(bytes) } + /// Bytes of the font file with this stem, without keeping them or charging the load budget. + fn peek(&self, stem: &str) -> Option>> { + if let Some(b) = self.files.get(stem) { + return Some(b.clone()); + } + Some(Arc::new(match self.paths.get(stem)? { + Source::File(path) => read_file(path)?, + Source::Static(bytes) => bytes.to_vec(), + })) + } + + /// 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) { + return Some(n.clone()); + } + let bytes = self.peek(stem)?; + let all = faces(&bytes); + let names = Arc::new(FaceNames { family: all.first().and_then(Face::family_name), faces: all.iter().map(Face::names).collect() }); + self.face_names.insert(stem.to_string(), names.clone()); + Some(names) + } + fn lookup(&mut self, k: &str) -> Option { let candidates = [k.to_string(), k.replace(' ', ""), format!("{k} regular"), format!("{}-regular", k.replace(' ', ""))]; for c in &candidates { @@ -379,7 +617,28 @@ impl Db { return Some(face); } } - self.by_family(k) + self.by_family(k).or_else(|| self.user_family(k)) + } + + /// A face in the user's font folders whose family or full name is `k`, whatever its file is + /// called (the folders are small; at most 200 files are looked at). + fn user_family(&mut self, k: &str) -> Option { + let want = norm(k); + if want.is_empty() { + return None; + } + let mut stems: Vec = self.user.iter().cloned().collect(); + stems.sort(); + for stem in stems.into_iter().take(200) { + let Some(names) = self.face_names(&stem) else { continue }; + let Some(i) = names.faces.iter().position(|f| f.iter().any(|n| *n == want || format!("{n}regular") == want)) else { continue }; + // Only the file that has the face is kept (and charged to the load budget). + // A file that cannot be read now (deleted, too large, budget used) does not end the + // search: another file in the folders may hold the same family. + let Some(bytes) = self.file(&stem).or_else(|| self.peek(&stem)) else { continue }; + return faces(&bytes).into_iter().nth(i); + } + None } /// A face whose family or full name is `k`, among files with a similar stem, then among the @@ -986,6 +1245,61 @@ pub fn layout_line(face: &Face, s: &str, height: f64, width_factor: f64, oblique mod family_tests { use super::*; + #[test] + fn font_folders_are_cleaned_and_unknown_shx_names_are_not_available() { + let long = "x".repeat(MAX_DIR_CHARS + 1); + let many: Vec = (0..40).map(|i| format!("/fonts/{i}")).collect(); + assert_eq!(clean_dirs(&[" /a ", "", "/a", "/b", long.as_str(), "bad\u{0}dir"]), vec!["/a".to_string(), "/b".to_string()]); + assert_eq!(clean_dirs(&many).len(), MAX_FONT_DIRS); + assert!(!available("gost_cadcraft.shx")); + assert!(available("txt.shx") && available("SIMPLEX.SHX"), "the built-in stroke font stands in for these"); + assert!(available("")); + assert!(available(crate::BUILTIN_FONT)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_font_in_a_user_folder_is_found_listed_and_dropped_with_the_folder() { + let Some(src) = scan().into_values().find(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("ttf"))) else { return }; + let dir = std::env::temp_dir().join(format!("cadcraft-fontdir-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let Ok(_) = std::fs::copy(&src, dir.join("CadcraftTestFace.ttf")) else { return }; + let before = generation(); + set_font_dirs(&[dir.to_string_lossy().to_string()]); + assert!(generation() > before); + // Listing reads the family name without keeping the file (or using up the load budget). + let early = installed(); + assert!(early.iter().any(|f| f.name == "CadcraftTestFace.ttf" && f.family.is_some())); + assert!(!lock().files.contains_key("cadcrafttestface"), "listing keeps no font bytes"); + assert!(find("CadcraftTestFace.ttf").is_some()); + let listed = installed(); + let entry = listed.iter().find(|f| f.name == "CadcraftTestFace.ttf"); + assert!(entry.is_some_and(|f| f.user && f.family.is_some()), "{entry:?}"); + assert!(listed.first().is_some_and(|f| f.user), "the user's fonts come first"); + if let Some(family) = entry.and_then(|f| f.family.clone()) { + assert!(find(&family).is_some(), "found by its family name: {family}"); + } + set_font_dirs::<&str>(&[]); + assert!(find("CadcraftTestFace.ttf").is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// One unreadable user font file with the family does not stop the search: the next file + /// that has the family is still read. + #[test] + fn an_unreadable_user_font_does_not_end_the_family_search() { + let mut db = Db::default(); + let names = || Arc::new(FaceNames { family: Some("Foo".into()), faces: vec![vec!["foo".into()]] }); + for stem in ["a", "b"] { + db.user.insert(stem.into()); + db.face_names.insert(stem.into(), names()); + } + // "a" has no file left on disk; "b" can be read. + db.paths.insert("b".into(), Source::Static(b"not a font")); + let _ = db.user_family("Foo"); + assert!(db.files.contains_key("b"), "the second file with the family was tried"); + } + #[test] fn thai_looks_in_thai_fonts_before_the_general_search() { // Letters, vowels, tone marks and digits: the general search loads a bounded number of @@ -1107,7 +1421,7 @@ mod scan_tests { /// here rather than discovered by a drawing full of missing-glyph boxes. #[test] fn the_platforms_system_font_directory_is_searched() { - let dirs = font_dirs(); + let dirs = system_font_dirs(); #[cfg(target_os = "macos")] assert!(dirs.iter().any(|d| d == std::path::Path::new("/System/Library/Fonts")), "{dirs:?}"); #[cfg(target_os = "android")] diff --git a/crates/fonts/tests/shx_font_folders.rs b/crates/fonts/tests/shx_font_folders.rs new file mode 100644 index 000000000..a1fa69ed8 --- /dev/null +++ b/crates/fonts/tests/shx_font_folders.rs @@ -0,0 +1,32 @@ +//! SHX files in the user's font folders (Options ▸ Fonts): found by name, in the folder itself +//! or a folder under it, and gone again when the folder is removed. Process-wide settings, so +//! one test in its own binary. The font is compiled here from shape source written for it. + +use cadcraft_fonts::{shx, ttf}; + +#[test] +fn shx_fonts_in_the_users_font_folders_are_found() { + let bytes = shx::compile("*0,4,folder test\n6,2,0,0\n*65,4,UCA\n1,064,0\n").unwrap(); + let dir = std::env::temp_dir().join(format!("cadcraft-shx-folders-{}", std::process::id())); + let sub = dir.join("shx").join("old"); + std::fs::create_dir_all(&sub).unwrap(); + std::fs::write(dir.join("cadcraft-top.shx"), &bytes).unwrap(); + std::fs::write(sub.join("cadcraft-deep.shx"), &bytes).unwrap(); + assert!(shx::find("cadcraft-top.shx").is_none() && shx::find("cadcraft-deep").is_none()); + + let g = shx::generation(); + ttf::set_font_dirs(&[dir.to_string_lossy().to_string()]); + assert_ne!(shx::generation(), g, "viewers draw the text again"); + assert!(shx::find("cadcraft-top.shx").is_some_and(|f| f.has_shape(65))); + assert!(shx::find("CADCRAFT-DEEP").is_some(), "in a folder under the font folder"); + assert!(ttf::available("cadcraft-deep.shx")); + + // A file added later is found after Look for Fonts Again. + std::fs::write(dir.join("cadcraft-later.shx"), &bytes).unwrap(); + ttf::rescan(); + assert!(shx::find("cadcraft-later.shx").is_some()); + + ttf::set_font_dirs::<&str>(&[]); + assert!(shx::find("cadcraft-top.shx").is_none()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5d3bc449d..612dfa738 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -101,6 +101,9 @@ fn same_content(a: &ListKey, b: &ListKey) -> bool { #[derive(Default)] pub struct CanvasState { pub list: Option, + /// The font set the list was drawn with ([`cadcraft_fonts::ttf::generation`] and + /// [`cadcraft_fonts::shx::generation`]): a new font folder redraws the text. + font_generation: u64, key: ListKey, /// The area `list` was built for (hatch patterns exist only inside it); a view leaving it /// rebuilds the list. diff --git a/crates/ui-egui/src/canvas/list.rs b/crates/ui-egui/src/canvas/list.rs index 6a3360409..a02a0bbd6 100644 --- a/crates/ui-egui/src/canvas/list.rs +++ b/crates/ui-egui/src/canvas/list.rs @@ -65,6 +65,16 @@ pub(super) fn rebuilt_preview<'a>(doc: &cadcraft_doc::Drawing, ents: impl IntoIt /// yet, is built at once. pub(super) fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], ctx: &egui::Context) { let px = 1.0 / xf.scale; + // TrueType fonts (font folders, rescans) and SHX fonts (drawing folders, font folders, + // the search path) can each change what text looks like. + let fonts = cadcraft_fonts::ttf::generation().wrapping_add(cadcraft_fonts::shx::generation() << 32); + if app.canvas.font_generation != fonts { + app.canvas.font_generation = fonts; + app.canvas.list = None; + app.canvas.job = None; + // The model space seen through a layout's active viewport is drawn apart: rebuilt too. + app.canvas.vp.key = None; + } let Ok(st) = app.session.state() else { return }; // Rebuild when the drawing changes, the zoom moves by more than 2x (tessellation band) or a // view leaves the area the list was built for. From f09c50d6b84d4590d7b38726cedab5e21318db12 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:56:13 +0530 Subject: [PATCH 242/531] mcp: refuse unclassified commands under the automation roots and walk the registry Bring the rest of the file access under the roots: - Image references had no check at all, and the loader threads lost the roots, which are per thread. Both are held to them now. - The xref and image search looked outside the roots before any check, listing folders and answering whether a file exists. It now skips those places. - setvar SAVEFILEPATH could point autosave and recovery anywhere, so it is refused under roots, and so is drawingrecovery. - A command runs under roots only if file_access/commands.rs classifies it. Anything else is refused, whichever route starts it. every_command_is_classified walks the registry for the table. mcp_roots_walk.rs walks it through the real server with paths outside the roots, seeing reads by access time and writes by metadata. The same walk with no roots is the control: it has to find the same commands escaping. Also drops two duplicated checks the rebase left in template.rs and compare.rs. --- apps/cadcraft-cli/tests/mcp_roots_walk.rs | 535 +++++++++++++++++++++ crates/engine/src/cmd/blocks/xref.rs | 3 + crates/engine/src/cmd/blocks/xref/load.rs | 20 +- crates/engine/src/cmd/file/compare.rs | 5 +- crates/engine/src/cmd/file/template.rs | 1 - crates/engine/src/cmd/image.rs | 19 +- crates/engine/src/file_access.rs | 2 + crates/engine/src/file_access/commands.rs | 537 ++++++++++++++++++++++ crates/engine/src/lisp/builtins/files.rs | 2 +- crates/engine/src/session/execute.rs | 3 + crates/engine/src/session/interactive.rs | 3 + crates/engine/src/sysvars.rs | 4 + docs/mcp.md | 14 +- 13 files changed, 1128 insertions(+), 20 deletions(-) create mode 100644 apps/cadcraft-cli/tests/mcp_roots_walk.rs create mode 100644 crates/engine/src/file_access/commands.rs diff --git a/apps/cadcraft-cli/tests/mcp_roots_walk.rs b/apps/cadcraft-cli/tests/mcp_roots_walk.rs new file mode 100644 index 000000000..cfe237a6e --- /dev/null +++ b/apps/cadcraft-cli/tests/mcp_roots_walk.rs @@ -0,0 +1,535 @@ +//! Walks every command in the registry through the real MCP server with paths outside the +//! automation roots (#1472). Reads show as a changed access time and writes as a changed size, +//! modification time or folder, whatever the command does with the path. The same walk without +//! roots has to find escapes, or finding none under roots would prove nothing. +#![cfg(unix)] +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Never crash). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{File, FileTimes}; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{Receiver, channel}; +use std::time::{Duration, SystemTime}; + +use serde_json::{Value, json}; + +/// Longest a call may take before the server counts as hung. +const CALL_TIMEOUT: Duration = Duration::from_secs(60); +/// The extensions commands choose their behaviour by. +const EXTENSIONS: &[&str] = &["dxf", "dwg", "dwt", "scr", "lsp", "lin", "pat", "pgp", "csv", "txt", "png", "pdf", "svg", "ctb"]; +/// The parameter names a command might take a path under. +const PATH_KEYS: &[&str] = + &["path", "file", "template", "patternFile", "from", "to", "source", "target", "output", "folder", "dir", "filename", "document"]; +/// A valid 1x1 PNG. +const PNG: &[u8] = &[ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0, 0x1F, 0x15, 0xC4, + 0x89, 0, 0, 0, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0, 1, 0, 0, 5, 0, 1, 0x0D, 0x0A, 0x2D, 0xB4, 0, 0, 0, 0, 0x49, 0x45, 0x4E, 0x44, + 0xAE, 0x42, 0x60, 0x82, +]; + +fn s(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +/// A running `cadcraft-cli mcp`. +struct Server { + child: Child, + stdin: ChildStdin, + replies: Receiver, + next: u64, +} + +impl Server { + fn start(args: &[String], cwd: &Path, config: &Path) -> Self { + let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) + .arg("mcp") + .args(args) + .current_dir(cwd) + .env("CADCRAFT_CONFIG_DIR", config) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn cadcraft-cli"); + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (tx, replies) = channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if let Ok(v) = serde_json::from_str::(&line) + && tx.send(v).is_err() + { + break; + } + } + }); + let mut server = Self { child, stdin, replies, next: 1 }; + server.request("initialize", json!({"protocolVersion": "2025-06-18"})).expect("initialize"); + server + } + + fn request(&mut self, method: &str, params: Value) -> Option { + let id = self.next; + self.next += 1; + let req = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + writeln!(self.stdin, "{req}").ok()?; + loop { + let reply = self.replies.recv_timeout(CALL_TIMEOUT).ok()?; + if reply["id"] == id { + return Some(reply); + } + } + } + + /// A tool's first text block, or `None` when the server hung or stopped. + fn tool(&mut self, name: &str, arguments: Value) -> Option { + let reply = self.request("tools/call", json!({"name": name, "arguments": arguments}))?; + Some(reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string()) + } + + fn execute(&mut self, command: &str, params: Value) -> Option { + self.tool("execute", json!({"command": command, "params": params})) + } +} + +impl Drop for Server { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// The folders of one walk: `in` and `out` are the roots, nothing under `outside` may be touched. +struct Fixture { + base: PathBuf, + outside: PathBuf, + /// Each path under `outside`, with its size, modification time and access time. + baseline: BTreeMap, + /// Whether this file system records reads at all (`noatime` doesn't). + sees_reads: bool, +} + +impl Fixture { + fn new(tag: &str) -> Self { + let base = std::env::temp_dir().join(format!("cc-walk-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for d in ["in", "out"] { + std::fs::create_dir_all(base.join(d)).unwrap(); + } + let probe = base.join("probe"); + std::fs::write(&probe, "x").unwrap(); + age_access_time(&probe); + let before = std::fs::metadata(&probe).unwrap().accessed().unwrap(); + std::fs::read(&probe).unwrap(); + let sees_reads = std::fs::metadata(&probe).unwrap().accessed().unwrap() != before; + let outside = base.join("outside"); + let mut f = Self { base, outside, baseline: BTreeMap::new(), sees_reads }; + f.reset(); + f + } + + /// Lay out `outside` afresh and start watching it. + fn reset(&mut self) { + let o = self.outside.clone(); + let _ = std::fs::remove_dir_all(&o); + for d in ["cwd", "config/plotters", "recover"] { + std::fs::create_dir_all(o.join(d)).unwrap(); + } + let dxf = cadcraft_io::write(&cadcraft_engine::doc::Drawing::new_imperial(), "x.dxf").unwrap(); + for ext in EXTENSIONS { + let body: &[u8] = match *ext { + "dxf" | "dwg" | "dwt" => &dxf, + "scr" => b"CIRCLE 0,0 5\n", + "lsp" => b"(princ 1)\n", + "lin" => b"*WALK,walk\nA,1,-1\n", + "pat" => b"*WALK,walk\n0,0,0,0,1\n", + "pgp" => b"W,*LINE\n", + "csv" | "txt" => b"a,b\n1,2\n", + "png" => PNG, + _ => b"canary", + }; + std::fs::write(o.join(format!("canary.{ext}")), body).unwrap(); + } + // Two images, so that a drawing naming both loads them on threads of their own. + std::fs::write(o.join("second.png"), PNG).unwrap(); + let device = cadcraft_engine::doc::PlotterConfig { name: "Office".into(), ..Default::default() }; + std::fs::write(o.join("config/plotters/Office.plotter.json"), device.to_file_text()).unwrap(); + self.baseline.clear(); + for p in tree(&o) { + age_access_time(&p); + let m = std::fs::metadata(&p).unwrap(); + self.baseline.insert(p, (m.len(), m.modified().unwrap(), m.accessed().unwrap())); + } + } + + /// What happened under `outside` since [`Self::reset`]. Only metadata is read: this leaves + /// the access times as they are. + fn touched(&self) -> Vec { + let mut seen = Vec::new(); + for (p, (len, modified, accessed)) in &self.baseline { + let name = p.strip_prefix(&self.outside).unwrap().display(); + match std::fs::metadata(p) { + Err(_) => seen.push(format!("removed {name}")), + Ok(m) if m.modified().unwrap() != *modified || (!m.is_dir() && m.len() != *len) => seen.push(format!("wrote {name}")), + Ok(m) if self.sees_reads && m.accessed().unwrap() != *accessed => seen.push(format!("read {name}")), + Ok(_) => {} + } + } + seen + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.base); + } +} + +fn tree(dir: &Path) -> Vec { + let mut out = vec![dir.to_path_buf()]; + for e in std::fs::read_dir(dir).unwrap().flatten() { + if e.path().is_dir() { + out.extend(tree(&e.path())); + } else { + out.push(e.path()); + } + } + out +} + +/// Put `p`'s access time in the past, so that the next read updates it even under `relatime`. +fn age_access_time(p: &Path) { + let past = SystemTime::now() - Duration::from_secs(3 * 24 * 3600); + File::open(p).unwrap().set_times(FileTimes::new().set_accessed(past)).unwrap(); +} + +/// The `action` or `option` values a parameter doc lists: `action?: list|open|discard (…)`. +fn actions(doc: &str) -> Vec { + let mut out = Vec::new(); + for key in ["action", "option"] { + let Some(at) = doc.find(key) else { continue }; + let rest = doc[at + key.len()..].trim_start_matches(['?', ':', ' ']); + let end = rest.find([',', '}', '(']).unwrap_or(rest.len()); + out.extend(rest[..end].split('|').map(|w| w.trim().trim_matches('"').to_string()).filter(|w| !w.is_empty())); + } + out +} + +/// The calls to try for command `id`: every path-like key set to `target`, with each action. +fn variants(doc: &str, target: &str, handle: &str, table: &str) -> Vec { + let mut base = json!({"handle": table, "handles": [handle], "at": [0, 0], "name": "walk"}); + for key in PATH_KEYS { + base[*key] = json!(target); + } + let mut named = base.clone(); + named["name"] = json!(target); + let mut device = base.clone(); + device["name"] = json!("Office"); + // Commands refuse parameters that don't go together, so each key the doc names goes on its own too. + let lower = doc.to_ascii_lowercase(); + let documented = PATH_KEYS.iter().filter(|key| **key == "path" || lower.contains(&key.to_ascii_lowercase())); + let alone = documented.flat_map(|key| { + [ + json!({*key: target}), + json!({*key: target, "handles": [handle]}), + json!({*key: target, "handle": table}), + json!({*key: target, "name": "Office"}), + ] + }); + let mut out = Vec::new(); + for v in [base, named, device].into_iter().chain(alone) { + out.push(v.clone()); + for a in actions(doc) { + let mut with = v.clone(); + with["action"] = json!(a); + with["option"] = json!(a); + out.push(with); + } + } + out +} + +/// Whether a command's doc says it takes a file. These get every extension; the rest, one. +fn takes_a_file(doc: &str) -> bool { + let d = doc.to_ascii_lowercase(); + ["path", "file", "template", "folder", "action", "option"].iter().any(|w| d.contains(w)) +} + +/// A fresh drawing with a circle and a table, selected; the circle's and table's handles. +fn seed(server: &mut Server) -> Option<(String, String)> { + // Closed first: the walk starts tens of thousands of drawings, and they would all stay open. + server.execute("closeall", json!({}))?; + server.execute("new", json!({}))?; + let handle_of = |text: &str| serde_json::from_str::(text).ok().and_then(|v| v["handle"].as_str().map(str::to_string)).unwrap_or_default(); + let circle = server.execute("circle", json!({"center": [0, 0], "radius": 1}))?; + let table = server.execute("table", json!({"at": [5, 5], "rows": 2, "columns": 2}))?; + server.execute("selectall", json!({}))?; + Some((handle_of(&circle), handle_of(&table))) +} + +/// What one walk saw. +struct Walk { + /// The command and the call that touched each file outside. + escapes: BTreeMap>, + calls: usize, + commands: usize, + /// Calls that hung or stopped the server. + lost: Vec, + sees_reads: bool, +} + +/// Run the walk, under `in` and `out` as roots or with no roots at all. +fn walk(tag: &str, roots: bool) -> Walk { + let mut f = Fixture::new(tag); + let args = if roots { + vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))] + } else { + vec![] + }; + let cwd = f.outside.join("cwd"); + let config = f.outside.join("config"); + let start = |f: &mut Fixture| { + let server = Server::start(&args, &cwd, &config); + f.reset(); + server + }; + let mut server = start(&mut f); + let listed = server.tool("list_commands", json!({})).expect("list_commands"); + let specs: Vec = serde_json::from_str(&listed).expect("the command list"); + assert!(specs.len() > 400, "the walk has to see the registry: {} commands", specs.len()); + let mut result = Walk { escapes: BTreeMap::new(), calls: 0, commands: specs.len(), lost: Vec::new(), sees_reads: f.sees_reads }; + + let mut steps: Vec<(String, Value)> = Vec::new(); + let o = f.outside.clone(); + let canary = |ext: &str| s(&o.join(format!("canary.{ext}"))); + let (circle, table) = seed(&mut server).expect("seed"); + assert!(!table.is_empty(), "the seed table has no handle"); + for spec in &specs { + let id = spec["id"].as_str().unwrap().to_string(); + let doc = spec["params"].as_str().unwrap_or_default(); + let mut targets: Vec = if takes_a_file(doc) { EXTENSIONS.iter().map(|e| canary(e)).collect() } else { vec![canary("dxf")] }; + if takes_a_file(doc) { + // A file that isn't there yet, in a folder that isn't there yet, and a relative path. + targets.extend(["dxf", "png", "pdf", "csv"].iter().map(|e| s(&o.join(format!("fresh/x.{e}"))))); + targets.push("../canary.dxf".to_string()); + } + for target in targets { + for v in variants(doc, &target, &circle, &table) { + steps.push((id.clone(), v)); + } + } + } + + let run_step = + |server: &mut Server, f: &mut Fixture, result: &mut Walk, id: &str, label: String, call: &mut dyn FnMut(&mut Server) -> Option| { + result.calls += 1; + let done = call(server); + let touched = f.touched(); + if !touched.is_empty() { + for what in touched { + result.escapes.entry(id.to_string()).or_default().push(format!("{what}: {label}")); + } + } + if done.is_none() { + result.lost.push(format!("{id}: {label}")); + } + done.is_some() + }; + + for (id, params) in &steps { + let label = params.to_string(); + let params = params.clone(); + let alive = run_step(&mut server, &mut f, &mut result, id, label, &mut |sv| sv.execute(id, params.clone())); + let dirty = !f.touched().is_empty(); + if !alive { + server = start(&mut f); + } else if dirty { + f.reset(); + } + // A command can stop the server without its own reply being lost. + if seed(&mut server).is_none() { + result.lost.push(format!("after {id}: {params}")); + server = start(&mut f); + seed(&mut server); + } + } + + // The ways in that aren't one command with a path parameter. + let dxf = canary("dxf"); + let png = canary("png"); + let scr = canary("scr"); + let lsp = canary("lsp"); + let tools: Vec<(&str, &str, Value)> = vec![ + ("tool:open", "open", json!({"path": dxf})), + ("tool:save", "save", json!({"path": dxf})), + ("tool:save-new", "save", json!({"path": s(&o.join("fresh/y.dxf"))})), + ("tool:render", "render", json!({"path": png})), + ("tool:command_line", "command_line", json!({"text": format!("SCRIPT {scr}")})), + ("tool:command_line", "command_line", json!({"text": format!("OPEN {dxf}")})), + ("tool:command_line", "command_line", json!({"text": format!("SAVEAS {dxf}")})), + ("tool:script", "script", json!({"text": format!("OPEN {dxf}\n")})), + ]; + for (label, name, a) in tools { + let text = a.to_string(); + let a = a.clone(); + let alive = run_step(&mut server, &mut f, &mut result, label, text, &mut |sv| sv.tool(name, a.clone())); + if alive { + f.reset(); + } else { + server = start(&mut f); + } + seed(&mut server); + } + let lisp = [ + format!("(setq f (open {dxf:?} \"r\")) (read-line f) (close f)"), + format!("(setq f (open {dxf:?} \"w\")) (write-line \"x\" f) (close f)"), + format!("(setq f (open {:?} \"w\")) (write-line \"x\" f) (close f)", s(&o.join("new.txt"))), + format!("(load {lsp:?})"), + ]; + for code in lisp { + let label = code.clone(); + run_step(&mut server, &mut f, &mut result, "lisp:code", label, &mut |sv| sv.execute("lisp", json!({"code": code}))); + f.reset(); + seed(&mut server); + } + // Settings that name a file or a folder, then the commands that use them. + let chained: Vec<(&str, Vec<(&str, Value)>)> = vec![ + ( + "stylesmanager", + vec![ + ("stylesmanager", json!({"action": "new", "name": "walk.ctb"})), + ("stylesmanager", json!({"action": "save", "name": "walk.ctb", "path": canary("ctb")})), + ("stylesmanager", json!({"action": "load", "path": canary("ctb")})), + ], + ), + ( + "pdfbook", + vec![("pline", json!({"points": [[0, 0], [210, 0], [210, 297], [0, 297]], "closed": true})), ("pdfbook", json!({"path": canary("pdf")}))], + ), + ("setvar:SAVEFILEPATH", vec![("setvar", json!({"name": "SAVEFILEPATH", "value": s(&o.join("recover"))})), ("drawingrecovery", json!({}))]), + ("setvar:QNEWTEMPLATE", vec![("setvar", json!({"name": "QNEWTEMPLATE", "value": dxf})), ("new", json!({}))]), + ]; + for (label, calls) in chained { + for (id, params) in calls { + run_step(&mut server, &mut f, &mut result, label, format!("{id} {params}"), &mut |sv| sv.execute(id, params.clone())); + } + f.reset(); + seed(&mut server); + } + result +} + +fn summary(w: &Walk) -> String { + format!( + "{} commands, {} calls, reads seen: {}, {} commands touched files outside, {} calls lost the server", + w.commands, + w.calls, + w.sees_reads, + w.escapes.len(), + w.lost.len() + ) +} + +/// Under roots, nothing in the registry reaches a file outside them. +#[test] +fn no_command_escapes_the_roots() { + let w = walk("roots", true); + println!("under roots: {}", summary(&w)); + let found: Vec = w.escapes.iter().flat_map(|(id, what)| what.iter().take(3).map(move |l| format!("{id}: {l}"))).collect(); + assert!(found.is_empty(), "escapes under the roots:\n{}", found.join("\n")); + assert!(w.lost.is_empty(), "calls that lost the server: {:?}", w.lost); +} + +/// The control: without roots the same walk finds these commands reaching the same files. If this +/// fails, the walk has stopped reaching them and [`no_command_escapes_the_roots`] proves nothing. +#[test] +fn the_walk_finds_escapes_without_roots() { + let w = walk("control", false); + println!("without roots: {}", summary(&w)); + let found: BTreeSet<&str> = w.escapes.keys().map(String::as_str).collect(); + println!("touched files outside: {}", found.iter().copied().collect::>().join(" ")); + let writers = [ + "saveas", + "export", + "plot", + "exportpdf", + "publish", + "pdfbook", + "wblock", + "-wblock", + "layout.saveas", + "layout", + "stylesmanager", + "plottermanager", + "tableexport", + "dataextraction", + "tool:save", + "tool:save-new", + "tool:render", + "lisp:code", + ]; + for id in writers { + assert!(found.contains(id), "the walk no longer finds `{id}` writing outside: {found:?}"); + } + if w.sees_reads { + for id in [ + "open", + "new", + "recover", + "script", + "import", + "insert", + "minsert", + "xattach", + "-xref", + "compare", + "imageattach", + "attach", + "aliasedit", + "linetype", + "hatch.patterns", + "appload", + "datalink", + "tool:open", + "setvar:QNEWTEMPLATE", + "setvar:SAVEFILEPATH", + ] { + assert!(found.contains(id), "the walk no longer finds `{id}` reading outside: {found:?}"); + } + } +} + +/// A drawing inside the roots can't bring in what it names outside them: an image or an xref saved +/// with a path outside stays unloaded, and nothing outside is read. +#[test] +fn a_drawing_cannot_reach_files_it_names_outside_the_roots() { + let mut f = Fixture::new("named"); + let host = f.base.join("in/host.dxf"); + { + // Made without roots: a drawing someone hands the agent. + let mut free = Server::start(&[], &f.outside.join("cwd"), &f.outside.join("config")); + free.execute("new", json!({})).unwrap(); + let image = free.execute("imageattach", json!({"path": s(&f.outside.join("canary.png"))})).unwrap(); + assert!(image.contains("handle"), "the image attaches: {image}"); + let second = free.execute("imageattach", json!({"path": s(&f.outside.join("second.png"))})).unwrap(); + assert!(second.contains("handle"), "the second image attaches: {second}"); + let xref = free.execute("xattach", json!({"path": s(&f.outside.join("canary.dxf")), "name": "walk"})).unwrap(); + assert!(xref.contains("handle"), "the xref attaches: {xref}"); + free.execute("saveas", json!({"path": s(&host)})).unwrap(); + } + let roots = vec!["--automation-read-root".into(), s(&f.base.join("in")), "--automation-write-root".into(), s(&f.base.join("out"))]; + let mut server = Server::start(&roots, &f.outside.join("cwd"), &f.outside.join("config")); + f.reset(); + let opened = server.tool("open", json!({"path": s(&host)})).unwrap(); + let images = server.execute("image", json!({})).unwrap(); + let xrefs = server.execute("xref", json!({})).unwrap(); + server.tool("render", json!({})).unwrap(); + let touched = f.touched(); + assert!(touched.is_empty(), "{touched:?}\nopen: {opened}\nimage: {images}\nxref: {xrefs}"); + assert!(images.contains("canary.png") && !images.contains("\"Loaded\""), "the image stays unloaded: {images}"); + assert!(images.contains("\"foundAt\": null") || images.contains("\"foundAt\":null"), "and it isn't said to exist: {images}"); + assert!(!xrefs.contains("\"Loaded\""), "the xref stays unloaded: {xrefs}"); +} diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index 18da7fa0f..602d43b17 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -374,6 +374,9 @@ fn run_xopen(s: &mut Session, p: &Value) -> Result { let file = load::find(&path, host.as_deref().map(std::path::Path::new), false).map_err(|m| match m { load::Missing::NotFound => bad("xopen", format!("{path}: file not found")), load::Missing::Refused(r) => bad("xopen", format!("{path}: not opened, {r}")), + load::Missing::OutsideRoots => { + bad("xopen", format!("{path}: not opened, automation path rejected: outside the read root (or the write root)")) + } })?; s.execute("open", &json!({ "path": file.to_string_lossy() })) } diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index 6522e8e18..5735f6699 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -145,6 +145,8 @@ pub(crate) enum Missing { NotFound, /// The saved path isn't followed, and there is no file of its name beside the host. Refused(Refused), + /// The automation roots don't reach the file ([`crate::file_access`]). + OutsideRoots, } impl Missing { @@ -155,6 +157,9 @@ impl Missing { (XrefStatus::NotFound, format!("{path}: {why}")) } Self::Refused(r) => (XrefStatus::Unresolved, format!("{path}: not opened, {r}")), + Self::OutsideRoots => { + (XrefStatus::Unresolved, format!("{path}: not opened, automation path rejected: outside the read root (or the write root)")) + } } } } @@ -208,14 +213,17 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result = files.into_iter().filter(allowed).collect(); + let outside = files.len() < looked_for; #[cfg(not(target_arch = "wasm32"))] - let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p))); + let found = files.iter().find(|p| p.is_file()).cloned().or_else(|| files.iter().find_map(|p| case_insensitive(p))).filter(allowed); #[cfg(target_arch = "wasm32")] - let found: Option = { - let _ = files; - None - }; - found.ok_or(refused.map_or(Missing::NotFound, Missing::Refused)) + let found: Option = None; + found.ok_or(if outside { Missing::OutsideRoots } else { refused.map_or(Missing::NotFound, Missing::Refused) }) } /// Upper bound on directory entries scanned per path component by [`case_insensitive`]. diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 3af713cd4..2b0b2678a 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -111,10 +111,7 @@ fn read_path(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; - { - crate::file_access::check_read(_path).map_err(|e| bad("compare", e))?; - std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) - } + std::fs::read(_path).map_err(|e| bad("compare", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("compare", "paths are not available on the web: open the other drawing and compare with it by name (`document`)")) diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 7608eb124..0134f2e9f 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -74,7 +74,6 @@ fn read_template(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_bytes(path: &str) -> Result> { - crate::file_access::check_read(path).map_err(|e| bad("new", e))?; crate::file_access::check_read(path).map_err(|e| bad("new", e))?; std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) } diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index daf46557b..7cc1eac3a 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -75,6 +75,7 @@ fn read_file(path: &str, host: Option<&str>) -> std::result::Result, Str #[cfg(not(target_arch = "wasm32"))] { let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?; + crate::file_access::check_read(&file.to_string_lossy())?; let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len(); if len > MAX_IMAGE_BYTES { return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20)); @@ -180,14 +181,18 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec 1 { // Each loader takes the next file nobody has started. let next = AtomicUsize::new(0); + // The automation roots are per thread, so they go along with each loader. + let roots = crate::file_access::current(); let work = || { - let mut done = Vec::new(); - loop { - let index = next.fetch_add(1, Ordering::Relaxed); - let Some(path) = paths.get(index) else { break }; - done.push((index, load(path))); - } - done + crate::file_access::confine(roots.as_ref(), || { + let mut done = Vec::new(); + loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(path) = paths.get(index) else { break }; + done.push((index, load(path))); + } + done + }) }; let finished: Vec<_> = std::thread::scope(|scope| { let started: Vec<_> = (0..loaders).filter_map(|_| std::thread::Builder::new().spawn_scoped(scope, work).ok()).collect(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 35ed5f9ec..589866f16 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -22,6 +22,8 @@ //! a link) can still win that race. The roots keep an agent to the files it was given; they don't //! guard against other programs on the computer. +pub mod commands; + use std::cell::RefCell; use std::ffi::OsString; use std::path::{Component, Path, PathBuf}; diff --git a/crates/engine/src/file_access/commands.rs b/crates/engine/src/file_access/commands.rs new file mode 100644 index 000000000..f2b673a82 --- /dev/null +++ b/crates/engine/src/file_access/commands.rs @@ -0,0 +1,537 @@ +//! Which commands automation may run while the automation roots are in force ([`super`]). +//! +//! The checks that hold a path to the roots sit where the file is touched, and a new command that +//! touches a file through a new route would get past them. So a command runs under the roots only +//! if it is listed here: anything else is refused, whatever it does. Adding a command to the +//! registry means adding it to one of these lists (`every_command_is_classified` says so). + +/// Commands that read or write files, each path held to the roots where the file is touched. +pub const FILES: &[&str] = &[ + "-linetype", + "-plottermanager", + "-wblock", + "-xref", + "aliasedit", + "appload", + "attach", + "audit", + "compare", + "compareexport", + "dataextraction", + "datalink", + "datalinkupdate", + "eattext", + "export", + "exportpdf", + "hatch", + "hatch.patterns", + "image", + "imageattach", + "import", + "insert", + "layout", + "layout.saveas", + "linetype", + "lisp", + "minsert", + "new", + "open", + "options", + "pagesetup", + "pdfbook", + "plot", + "plotstyle", + "plottermanager", + "preview", + "publish", + "qsave", + "recover", + "reinit", + "saveas", + "script", + "setvar", + "share", + "stylesmanager", + "tableexport", + "wblock", + "xattach", + "xbind", + "xopen", + "xref", +]; + +/// Commands that can't be held to the roots, and why. +pub const REFUSED: &[(&str, &str)] = &[("drawingrecovery", "it works on the autosave folder (SAVEFILEPATH), which is the server's own")]; + +/// Commands that touch no file. +pub const NO_FILES: &[&str] = &[ + "close", + "closeall", + "document.switch", + "document.bytes", + "u", + "undo", + "redo", + "mredo", + "cutclip", + "cutbase", + "copyclip", + "copybase", + "pasteclip", + "pasteblock", + "pasteorig", + "erase.selection", + "selectall", + "ai_deselect", + "select", + "qselect", + "qselect.info", + "selectsimilar", + "isolateobjects", + "hideobjects", + "unisolateobjects", + "zoom", + "zoom.realtime", + "zoom.dynamic", + "zoom.previous", + "zoom.window", + "zoom.in", + "zoom.out", + "zoom.all", + "zoom.extents", + "zoom.object", + "pan", + "pan.left", + "pan.right", + "pan.up", + "pan.down", + "regen", + "regenall", + "redraw", + "dview", + "view.set", + "view.get", + "layout.set", + "view", + "-vports", + "vports.activate", + "vports.named", + "line", + "pline", + "circle", + "arc", + "rectang", + "polygon", + "ellipse", + "point", + "point.multiple", + "xline", + "ray", + "spline", + "donut", + "solid", + "text", + "mtext", + "arc.sce", + "arc.sca", + "arc.scl", + "arc.sea", + "arc.sed", + "arc.ser", + "arc.cse", + "arc.csa", + "arc.csl", + "arc.continue", + "circle.cd", + "circle.2p", + "circle.3p", + "circle.ttr", + "circle.ttt", + "ellipse.axis", + "ellipse.arc", + "divide", + "measure", + "revcloud", + "revcloud.polygonal", + "revcloud.freehand", + "wipeout", + "3dpoly", + "helix", + "spline.cv", + "centermark", + "centerline", + "mline", + "mlstyle", + "mledit", + "breakline", + "dimlinear", + "dimaligned", + "dimradius", + "dimdiameter", + "dimangular", + "dimarc", + "dimordinate", + "dimcontinue", + "dimbaseline", + "qdim", + "dim", + "mleader", + "leader", + "dimstyle.update", + "dimoverride", + "dimreassociate", + "dimdisassociate", + "dimtedit.home", + "dimtedit.angle", + "dimtedit.left", + "dimtedit.center", + "dimtedit.right", + "dimtedit", + "dimspace", + "dimedit", + "dimedit.oblique", + "dimjogged", + "dimjogline", + "dimbreak", + "diminspect", + "mleaderedit", + "mleaderedit.add", + "mleaderedit.remove", + "mleaderalign", + "mleadercollect", + "scalelistedit", + "objectscale", + "aiobjectscaleadd", + "aiobjectscaleremove", + "annoreset", + "annoupdate", + "annovisible.current", + "annovisible.all", + "annovisible.toggle", + "gradient", + "boundary", + "region", + "hatchedit", + "hatchpick", + "overkill", + "block", + "-block", + "attdef", + "attedit", + "-attedit", + "base", + "blocks.dynamic", + "blocks.reference", + "blocks.reference.set", + "blocks.reference.grips", + "blocks.reference.grip", + "purge", + "blocks.list", + "battman", + "attdisp", + "attsync", + "burst", + "blockreplace", + "blocks.description", + "attdisp.normal", + "attdisp.on", + "attdisp.off", + "refedit", + "refset", + "refclose", + "bedit", + "bsave", + "bsaveas", + "bclose", + "erase", + "oops", + "move", + "copy", + "rotate", + "scale", + "mirror", + "stretch", + "offset", + "trim", + "extend", + "fillet", + "chamfer", + "explode", + "break", + "breakatpoint", + "join", + "draworder", + "draworder.front", + "draworder.back", + "draworder.above", + "draworder.under", + "texttofront", + "texttofront.text", + "texttofront.dimensions", + "texttofront.leaders", + "texttofront.all", + "hatchtoback", + "array", + "arrayrect", + "arraypolar", + "-array", + "arrayedit", + "arrayclose", + "pedit", + "splinedit", + "lengthen", + "align", + "blend", + "reverse", + "ncopy", + "mocoro", + "chspace", + "flatten", + "arraypath", + "textedit", + "group", + "ungroup", + "groupedit", + "groups.list", + "-group", + "pickstyle", + "grip.move", + "grip.stretch", + "grip.rotate", + "grip.scale", + "grip.mirror", + "grip.option", + "grip", + "compare.next", + "compare.previous", + "compareclose", + "layer", + "layer.new", + "layer.set", + "layer.current", + "layer.delete", + "laymcur", + "laymch", + "laycur", + "layiso", + "layuniso", + "layfrz", + "layoff", + "laylck", + "layulk", + "layon", + "laythw", + "layerp", + "layerstate.save", + "layerstate.restore", + "layerstate.list", + "layerstate.delete", + "layerstate.rename", + "laymrg", + "laydel", + "layout.new", + "layout.delete", + "layout.rename", + "layout.copy", + "layout.list", + "mview", + "mview.polygonal", + "vpclip", + "vports", + "vports.1", + "vports.2", + "vports.3", + "vports.4", + "viewport.set", + "vplayer", + "mspace", + "pspace", + "plotwindow", + "3dorbit", + "properties", + "properties.set", + "chprop", + "change", + "matchprop", + "color", + "lweight", + "ltscale", + "units", + "-units", + "thickness", + "limits", + "style", + "style.list", + "style.rename", + "style.delete", + "style.current", + "dimstyle", + "dimstyle.dimension", + "dimstyle.list", + "dimstyle.rename", + "dimstyle.delete", + "dimstyle.current", + "dimstyle.override", + "tablestyle", + "mleaderstyle", + "ddptype", + "rename", + "dist", + "id", + "list", + "area", + "time", + "status", + "drawing.inspect", + "entities", + "shapes", + "usage", + "loops", + "texts", + "countlist", + "counttable", + "count", + "union", + "subtract", + "intersect", + "massprop", + "ortho", + "grid", + "snap", + "polar", + "otrack", + "dynmode", + "lwdisplay", + "isodraft", + "isoplane", + "transparencydisplay", + "qpmode", + "selectioncycling", + "osnap", + "dsettings", + "getvar", + "sysvars", + "cal", + "quickcalc.pick", + "find", + "measuregeom", + "radius.measure", + "angle.measure", + "volume.measure", + "table", + "table.set", + "table.insertrow", + "table.deleterow", + "table.insertcol", + "table.deletecol", + "table.merge", + "table.unmerge", + "tablestyle.cellstyle", + "table.cellstyle", + "table.formula", + "table.recalc", + "tabledit", + "table.break", + "tolerance", + "txt2mtxt", + "geomconstraint", + "gccoincident", + "gcperpendicular", + "gcparallel", + "gctangent", + "gchorizontal", + "gcvertical", + "gccollinear", + "gcconcentric", + "gcsmooth", + "gcsymmetric", + "gcequal", + "gcfix", + "autoconstrain", + "constraintbar", + "constraintbar.showall", + "constraintbar.hideall", + "dimconstraint", + "dcaligned", + "dchorizontal", + "dcvertical", + "dcangular", + "dcradius", + "dcdiameter", + "dclinear", + "dcdisplay", + "dcdisplay.showall", + "dcdisplay.hideall", + "delconstraint", + "parameters", + "constraintsettings", + "constraintinfer", + "constraints.inspect", + "constraints.dof", +]; + +/// Why command `id` may not run here; `None` when it may. Without roots in force everything may. +pub fn refusal(id: &str) -> Option { + super::current()?; + if let Some((_, why)) = REFUSED.iter().find(|(c, _)| *c == id) { + return Some(format!("automation command refused: {why}")); + } + if FILES.contains(&id) || NO_FILES.contains(&id) { + return None; + } + Some("automation command refused: it is not classified for the automation roots".to_string()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::panic)] +mod tests { + use super::super::{AutomationRoots, confine}; + use super::*; + use std::collections::BTreeSet; + + /// Words in a command's parameter doc that usually name a file. In these commands they don't: + /// `array` and `arraypath` follow a path of objects, and `blocks.reference.grips` reports a + /// direction. + const NOT_FILES: &[&str] = &["array", "arraypath", "blocks.reference.grips"]; + + fn words(doc: &str) -> BTreeSet { + doc.to_ascii_lowercase().split(|c: char| !c.is_ascii_alphanumeric()).map(str::to_string).collect() + } + + /// Walks the registry: every command is on exactly one list, and the lists name no command + /// that is gone. A command whose parameters name a file can't be on the no-files list. + #[test] + fn every_command_is_classified() { + let refused: Vec<&str> = REFUSED.iter().map(|(c, _)| *c).collect(); + let lists = [FILES, refused.as_slice(), NO_FILES]; + let specs = crate::command_specs(); + for spec in specs { + let on = lists.iter().filter(|l| l.contains(&spec.id)).count(); + assert_eq!(on, 1, "`{}` is on {on} lists: add it to one in file_access/commands.rs", spec.id); + let doc = words(spec.params); + let names_a_file = ["path", "file", "template", "patternfile", "folder", "dir"].iter().any(|w| doc.contains(*w)); + if names_a_file && NO_FILES.contains(&spec.id) && !NOT_FILES.contains(&spec.id) { + panic!("`{}` takes a file ({}): it belongs on FILES, with its paths checked", spec.id, spec.params); + } + } + for id in lists.iter().flat_map(|l| l.iter()) { + assert!(specs.iter().any(|s| s.id == *id), "`{id}` is listed but no longer a command"); + } + } + + /// Under roots a command nobody classified is refused; without roots it isn't this table's business. + #[test] + fn an_unclassified_command_fails_closed() { + let base = std::env::temp_dir().join(format!("cc-commands-{}", std::process::id())); + std::fs::create_dir_all(&base).unwrap(); + let roots = AutomationRoots::new(Some(&base), None).unwrap(); + assert_eq!(refusal("made.up"), None); + confine(roots.as_ref(), || { + assert!(refusal("made.up").unwrap().contains("not classified")); + assert!(refusal("drawingrecovery").unwrap().contains("autosave")); + assert_eq!(refusal("open"), None); + assert_eq!(refusal("line"), None); + }); + let _ = std::fs::remove_dir_all(base); + } +} diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index 00c8788fa..1f19c71af 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -32,7 +32,7 @@ pub(super) fn open(ctx: &mut Ctx<'_>, a: Vec) -> Result } None => return Ok(Flow::Value(Value::Nil)), } - } else if !can_write(&path) || crate::file_access::check_write(&path).is_err() { + } else if crate::file_access::check_write(&path).is_err() || !can_write(&path) { return Ok(Flow::Value(Value::Nil)); } let id = ctx.env.next_file; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 230422e09..6f71b2537 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -26,6 +26,9 @@ impl Session { fn execute_guarded(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if let Some(why) = crate::file_access::commands::refusal(spec.id) { + return Err(EngineError::Disabled(spec.id.into(), why)); + } (spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?; if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) { return Err(EngineError::Disabled(spec.id.into(), why)); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 273ce0890..dc1c30fb7 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -39,6 +39,9 @@ impl Session { } return Err(EngineError::UnknownCommand(name.to_string())); }; + if let Some(why) = crate::file_access::commands::refusal(spec.id) { + return Err(EngineError::Disabled(spec.id.into(), why)); + } if transparent && spec.transparent && self.running.is_some() { // Transparent commands (zoom, pan…) run without cancelling the active one. if spec.interactive.is_none() { diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index e98836446..0cd902021 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -382,6 +382,10 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { "SAVETIME" => crate::autosave::set_savetime( as_f64(v).filter(|m| *m >= 0.0 && *m <= f64::from(crate::autosave::MAX_SAVETIME)).ok_or_else(bad)?.round() as u32, ), + // A folder autosave and recovery would use without any further check. + "SAVEFILEPATH" if crate::file_access::current().is_some() => { + return Err(EngineError::Other("SAVEFILEPATH cannot be changed under the automation roots".into())); + } "SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?), "ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?), // A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line). diff --git a/docs/mcp.md b/docs/mcp.md index 7b64dffa5..76ddba61e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -47,7 +47,7 @@ configuration works across the suite) keep the agent to the folders you give it: `aliasedit`, `reinit`), data links, plot style and plotter configuration files named by a path, and the shared plotter settings folder. - Every file a command **writes** must lie inside the **write root**: `save`/`qsave`/`saveas` - (including the temporary file written beside the destination), `export`, `plot`, `publish`, + (including the temporary file and `.bak` written beside the destination), `export`, `plot`, `publish`, `pdfbook`, `wblock`, data extraction, table export, plot style and plotter saves, the shared plotter settings folder, and `render {path}`. The write root itself is refused: a save's temporary file would sit beside it, outside the root. @@ -67,6 +67,14 @@ configuration works across the suite) keep the agent to the folders you give it: root): /etc/x.png`, `automation path rejected: the write root itself cannot be written: /work/project/out`, or `automation filesystem access is not granted: write authority is absent: /work/project/out/x.png`. +- A file a drawing names is held to the roots too: an image or xref saved with a path outside them + stays unloaded, and the answer doesn't say whether the file exists. +- A command runs under the roots only if it is classified (`crates/engine/src/file_access/commands.rs`): + one nobody classified is refused, whatever it does. `drawingrecovery` is refused, and SAVEFILEPATH + can't be changed, because both work on the server's autosave folder. +- The server itself still reads the system's fonts, from the system font folders and + `CADCRAFT_SHXPATH`. Their paths come from the server's setup, never from the agent, but a font file + named by a drawing can decide which of them is read. - The roots must be existing folders; a missing one stops the server with an error. Each flag is given once (`--flag ` or `--flag=`). @@ -74,6 +82,10 @@ The flags confine the headless server. `--connect` with them is an error, since otherwise talk to an app that isn't confined; the app's control channel does not take them yet (#1585). Without `--connect` the server writes the files itself, so every check happens here. +A path is checked, then opened: another program on the computer that swaps in a link between the two +can still win that race, and a hard link can't be told from a file. Use the operating system's +sandbox as well if other programs can change these folders. + ## Tools | Tool | What it does | From f554de28b5380ef69a6d47c3330cb76fbac86404 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 13:02:38 -0700 Subject: [PATCH 243/531] XCLIP: ON/OFF checks without copying boundaries and sets each reference once (CodeRabbit on #2756) --- crates/engine/src/cmd/blocks/xclip.rs | 22 +++++++++++++++------- crates/engine/tests/it/xclip.rs | 4 ++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/blocks/xclip.rs b/crates/engine/src/cmd/blocks/xclip.rs index b9a638827..067932127 100644 --- a/crates/engine/src/cmd/blocks/xclip.rs +++ b/crates/engine/src/cmd/blocks/xclip.rs @@ -117,14 +117,22 @@ fn run(s: &mut Session, p: &Value) -> Result { "on" | "off" => { let on = option == "on"; // Every reference is checked before any changes: an error leaves the drawing as it was. - let mut clips = Vec::with_capacity(hs.len()); - for h in &hs { - let mut c = clip_of(s, *h).ok_or_else(|| bad("xclip", "no clipping boundary on the selected reference"))?; - c.enabled = on; - clips.push((*h, c)); + let d = s.doc()?; + if !hs.iter().all(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Insert(i)) if i.clip.is_some())) { + return Err(bad("xclip", "no clipping boundary on the selected reference")); } - for (h, c) in clips { - set_clip(s, h, Some(c))?; + // Only the flag changes, once per reference (a selection may name one many times). + let mut seen = std::collections::HashSet::new(); + for h in hs.iter().filter(|h| seen.insert(**h)) { + s.doc_mut()? + .modify_entity(*h, |e| { + if let EntityKind::Insert(i) = &mut e.kind + && let Some(c) = &mut i.clip + { + c.enabled = on; + } + }) + .map_err(|e| bad("xclip", e.to_string()))?; } } "delete" | "d" => { diff --git a/crates/engine/tests/it/xclip.rs b/crates/engine/tests/it/xclip.rs index c49f20377..10b551716 100644 --- a/crates/engine/tests/it/xclip.rs +++ b/crates/engine/tests/it/xclip.rs @@ -88,6 +88,10 @@ fn off_on_a_selection_with_an_unclipped_reference_changes_nothing() { assert!(s.execute("xclip", &json!({ "handles": [r1, r2], "option": "off" })).is_err()); assert!(clip(&s, &r1).unwrap().enabled); assert!(clip(&s, &r2).is_none()); + // A reference named many times is turned off once, its boundary kept. + s.execute("xclip", &json!({ "handles": vec![r1.clone(); 1000], "option": "off" })).unwrap(); + let c = clip(&s, &r1).unwrap(); + assert!(!c.enabled && c.points.len() == 2); } #[test] From 7ea06a86dbed9b34a8148e4de74dd20ddeef5755 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 22:43:42 +0200 Subject: [PATCH 244/531] SHX fonts: list the ones in the user's font folders, for font lists Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/fonts/src/shx/mod.rs | 4 ++-- crates/fonts/src/shx/table.rs | 26 ++++++++++++++++++++++++++ crates/fonts/tests/shx_font_folders.rs | 4 ++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/fonts/src/shx/mod.rs b/crates/fonts/src/shx/mod.rs index 559621b70..016fe9821 100644 --- a/crates/fonts/src/shx/mod.rs +++ b/crates/fonts/src/shx/mod.rs @@ -41,8 +41,8 @@ use cadcraft_geom::Vec2; pub use compile::compile; pub use table::{ - FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, register, search_path, set_font_dirs, set_font_map, - set_provider, set_search_path, + FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, installed, register, search_path, set_font_dirs, + set_font_map, set_provider, set_search_path, }; pub use text::ShxText; pub(crate) use text::{shape, width}; diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 859ff0d3c..efcca16b6 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -238,6 +238,32 @@ pub fn find(name: &str) -> Option> { #[cfg(not(target_arch = "wasm32"))] const MAX_DIR_ENTRIES: usize = 10_000; +/// The SHX fonts in the user's font folders ([`set_font_dirs`]) and the registered ones, by file +/// stem, sorted without repeats (for font lists). Not read: only their names are listed. +pub fn installed() -> Vec { + let (dirs, mut out): (Vec, Vec) = { + let t = table(); + (t.font_dirs.clone(), t.registered.keys().map(|k| k.trim_end_matches(".shx").to_string()).collect()) + }; + #[cfg(not(target_arch = "wasm32"))] + for d in &dirs { + let Ok(entries) = std::fs::read_dir(d) else { continue }; + for e in entries.take(MAX_DIR_ENTRIES).filter_map(Result::ok) { + let p = e.path(); + if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("shx")) + && let Some(stem) = p.file_stem().and_then(|s| s.to_str()) + { + out.push(stem.to_string()); + } + } + } + #[cfg(target_arch = "wasm32")] + let _ = dirs; + out.sort_by_key(|n| n.to_lowercase()); + out.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + out +} + /// The file `name` (a lower-case key) in the first of `dirs` that has it, whatever the case of /// its name: lower-case, upper-case, else any other case found in the directory (`Simplex.shx` /// on a case-sensitive file system). diff --git a/crates/fonts/tests/shx_font_folders.rs b/crates/fonts/tests/shx_font_folders.rs index a1fa69ed8..a911b9382 100644 --- a/crates/fonts/tests/shx_font_folders.rs +++ b/crates/fonts/tests/shx_font_folders.rs @@ -20,6 +20,9 @@ fn shx_fonts_in_the_users_font_folders_are_found() { assert!(shx::find("cadcraft-top.shx").is_some_and(|f| f.has_shape(65))); assert!(shx::find("CADCRAFT-DEEP").is_some(), "in a folder under the font folder"); assert!(ttf::available("cadcraft-deep.shx")); + // Font lists name them. + let names = shx::installed(); + assert!(names.iter().any(|n| n == "cadcraft-top") && names.iter().any(|n| n == "cadcraft-deep"), "{names:?}"); // A file added later is found after Look for Fonts Again. std::fs::write(dir.join("cadcraft-later.shx"), &bytes).unwrap(); @@ -28,5 +31,6 @@ fn shx_fonts_in_the_users_font_folders_are_found() { ttf::set_font_dirs::<&str>(&[]); assert!(shx::find("cadcraft-top.shx").is_none()); + assert!(!shx::installed().iter().any(|n| n.starts_with("cadcraft-"))); let _ = std::fs::remove_dir_all(&dir); } From fb6178b1787de3f38f87d3896cf871020ea2f899 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 14:31:19 -0700 Subject: [PATCH 245/531] fix(doc): a rotated MINSERT array's extents reach its side copies The extents took the first copy and the far corner copy only. Turned, the grid's other two corner copies lie outside that box, so ZOOM Extents cut them off. All four corner copies count now, and the counts are clamped to the 10,000 columns and rows the renderer draws. Found by CodeRabbit on #2756. --- crates/doc/src/extents.rs | 44 +++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 4f40a148c..e2a748606 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -187,10 +187,15 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< b = Bounds2::from_points(c.polygon().into_iter().map(|p| m.apply(p))); } if ins.cols > 1 || ins.rows > 1 { - let off = - Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1))) - .rotate(ins.rotation); - b = b.union(&Bounds2::from_points(b.corners().map(|c| c + off))); + // The grid's four corner copies (as many as are drawn): turned, the far corner + // alone misses the side ones. + let (cols, rows) = + (f64::from(ins.cols.clamp(1, 10_000).saturating_sub(1)), f64::from(ins.rows.clamp(1, 10_000).saturating_sub(1))); + let one = b; + for (c, r) in [(cols, 0.0), (0.0, rows), (cols, rows)] { + let off = Vec2::new(ins.col_spacing * c, ins.row_spacing * r).rotate(ins.rotation); + b = b.union(&Bounds2::from_points(one.corners().map(|p| p + off))); + } } } for a in &ins.attribs { @@ -522,4 +527,35 @@ mod tests { assert!(extents.width() > drawn.width()); } } + + /// A turned array of references reaches its side copies, not only the first and the last; + /// a hostile count measures only the copies that are drawn. + #[test] + fn a_rotated_array_counts_every_corner_copy() { + let mut d = Drawing::new_metric(); + let mut b = crate::Block::new("B"); + b.entities.push(Entity::new(crate::Handle(1), EntityKind::Line(crate::Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }))); + d.blocks.insert("B".into(), std::sync::Arc::new(b)); + let array = |cols: u32, rows: u32, rotation: f64| { + let ins = crate::Insert { + block: "B".into(), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation, + cols, + rows, + col_spacing: 10.0, + row_spacing: 10.0, + ..crate::Insert::default() + }; + Entity::new(crate::Handle(2), EntityKind::Insert(ins)) + }; + // Turned 45°: the copies sit at (0, 0), (7.07, 7.07), (-7.07, 7.07) and (0, 14.14). + let b = entity_bounds(&d, &array(2, 2, std::f64::consts::FRAC_PI_4), 0); + let side = 10.0 * std::f64::consts::FRAC_1_SQRT_2; + assert!((b.min.x + side).abs() < 1e-9 && b.max.x >= side, "{b:?}"); + assert!((b.max.y - 2.0 * side - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{b:?}"); + // The renderer draws at most 10,000 columns. + let b = entity_bounds(&d, &array(u32::MAX, 1, 0.0), 0); + assert!((b.max.x - (10.0 * 9_999.0 + 1.0)).abs() < 1e-6, "{b:?}"); + } } From 594c30ae2d2acc87249ab85157110086d36b76f1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 17:45:46 -0500 Subject: [PATCH 246/531] Pass the Linux signing key to the release workflow (#2798) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index dc9c462db..c2cf475e8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -85,3 +85,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} From 935e13cc5277c46e2dbbaab07114077309614419 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 12:24:02 +1100 Subject: [PATCH 247/531] UCS: LISP picks, selection points, deferred polar and angtof use the right frame (review) entsel's pick point passed to (command ...) and ssget's W/C/F/WP/CP/pick points were read as world points though getpoint/getcorner answer in the UCS; the deferred-tangent polar text ignored the UCS; angtof depended on it. Convert UCS to world there, read @d, a: Vec) -> Result { feed(ctx.s, Input::Point(w)); } else if let Value::Ename(h) = arg.car() { // An `entsel` result: (ename point). - named(ctx.s, h, arg.cdr().car().as_point().map(|p| Vec2::new(p[0], p[1]))); + // The pick point is what `entsel` gave: a UCS point, like the ones above. + let frame = ctx.s.input_ucs(); + named(ctx.s, h, arg.cdr().car().as_point().map(|p| frame.to_wcs(Vec2::new(p[0], p[1])))); } else { return Err(LispError::bad_arg("command argument", arg)); } @@ -617,10 +619,13 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec) -> Result { } _ => (rest, None), }; + // The points are UCS points, as `getpoint` and `getcorner` give them: the selection runs in + // the world. + let frame = ctx.s.input_ucs(); let point = |i: usize| -> Result { let v = pts.get(i).ok_or_else(|| args_err(true))?; let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", v))?; - Ok(Vec2::new(p[0], p[1])) + Ok(frame.to_wcs(Vec2::new(p[0], p[1]))) }; let s = &mut *ctx.s; let all = |s: &Session, all_spaces: bool| -> Vec { @@ -652,7 +657,7 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec) -> Result { } Some("F") | Some("WP") | Some("CP") => { let poly: Vec = - pts.first().map(|l| l.iter().filter_map(|p| p.as_point().map(|q| Vec2::new(q[0], q[1]))).collect()).unwrap_or_default(); + pts.first().map(|l| l.iter().filter_map(|p| p.as_point().map(|q| frame.to_wcs(Vec2::new(q[0], q[1])))).collect()).unwrap_or_default(); let s = &*ctx.s; let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) }; match mode.as_deref() { @@ -1097,7 +1102,8 @@ pub fn distof(_ctx: &mut Ctx<'_>, a: Vec) -> Result { pub fn angtof(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 2)?; let s = string(&a[0])?; - let mut settings = ctx.s.angle_settings(); + // A pure string-to-angle conversion: ANGBASE and ANGDIR apply, the UCS does not. + let mut settings = ctx.s.angle_settings().world(); // AUNITS 0..=4; any other units argument is an error in AutoCAD, nil here. match a.get(1) { None | Some(Value::Nil) => {} diff --git a/crates/engine/src/lisp/ucs_tests.rs b/crates/engine/src/lisp/ucs_tests.rs index bf2dbf4ef..072a4f3e7 100644 --- a/crates/engine/src/lisp/ucs_tests.rs +++ b/crates/engine/src/lisp/ucs_tests.rs @@ -176,3 +176,53 @@ fn getangle_and_getdist_measure_in_the_ucs() { assert!(close(pt(&ok(&mut s, "(getvar \"UCSXDIR\")")), [0.0, 1.0, 0.0])); assert_eq!(ok(&mut s, "(getvar \"WORLDUCS\")"), "0"); } + +fn model_lines(s: &Session) -> Vec<(Vec2, Vec2)> { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| if let cadcraft_doc::EntityKind::Line(l) = &e.kind { Some((l.a.xy(), l.b.xy())) } else { None }) + .collect() +} + +/// The pick point of an `entsel` result handed to `command` is a UCS point, like the others. +#[test] +fn command_with_entsel_converts_the_pick_point_to_world() { + let mut s = session(); + turned(&mut s); + // World (100, 50) to (100, 150): UCS (0, 0) to (100, 0). + s.execute("line", &json!({"points": [[100, 50], [100, 150]]})).unwrap(); + ok(&mut s, "(setq e (entlast))"); + // Break it from UCS (30, 0) to UCS (60, 0), picked the way `entsel` answers: (ename point). + ok(&mut s, "(command \"_.BREAK\" (list e '(30 0)) '(60 0))"); + let mut l = model_lines(&s); + l.sort_by(|a, b| a.0.y.total_cmp(&b.0.y)); + assert_eq!(l.len(), 2, "{l:?}"); + assert!(l[0].0.dist(Vec2::new(100.0, 50.0)) < 1e-9 && l[0].1.dist(Vec2::new(100.0, 80.0)) < 1e-9, "{l:?}"); + assert!(l[1].0.dist(Vec2::new(100.0, 110.0)) < 1e-9 && l[1].1.dist(Vec2::new(100.0, 150.0)) < 1e-9, "{l:?}"); +} + +/// `ssget` windows, fences, polygons and single picks take UCS points, as `getpoint` gives them. +#[test] +fn ssget_window_takes_ucs_points() { + let mut s = session(); + s.execute("ucs", &json!({"option": "origin", "origin": [1000, 1000]})).unwrap(); + s.execute("circle", &json!({"center": [1005, 1005], "radius": 1})).unwrap(); + s.execute("circle", &json!({"center": [5, 5], "radius": 1})).unwrap(); + assert_eq!(ok(&mut s, "(sslength (ssget \"W\" '(0 0) '(10 10)))"), "1"); + let found = ok(&mut s, "(cdr (assoc 10 (entget (ssname (ssget \"W\" '(0 0) '(10 10)) 0))))"); + assert!(close(pt(&found), [1005.0, 1005.0, 0.0]), "{found}"); + assert_eq!(ok(&mut s, "(sslength (ssget \"C\" '(-1 -1) '(11 11)))"), "1"); + assert_eq!(ok(&mut s, "(sslength (ssget \"WP\" '((0 0) (10 0) (10 10) (0 10))))"), "1"); + assert_eq!(ok(&mut s, "(sslength (ssget \"F\" '((0 0) (10 10))))"), "1"); +} + +/// `angtof` converts text to radians: ANGBASE and ANGDIR apply, the UCS does not. +#[test] +fn angtof_ignores_the_ucs() { + let mut s = session(); + turned(&mut s); + assert_eq!(ok(&mut s, "(angtof \"0\")"), "0.0"); + assert_eq!(ok(&mut s, "(angtos (angtof \"45\"))"), "\"45\""); +} diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index b3d77f763..75f1c0a86 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -109,7 +109,10 @@ pub fn parse_polar_text(text: &str, angles: &crate::units::AngleSettings) -> Opt let body = text.trim().strip_prefix('@')?; // relative form only let (d, a) = body.split_once('<')?; let dist = d.trim().parse::().ok()?; - let angle = angles.amount(a.trim())?; + // The direction `@d 9.999 && (b.x - a.x).abs() < 1e-9 && (b.y - a.y - 10.0).abs() < 1e-9, "{a:?} {b:?}"); +} From d75bc7fa60998448d77bc517cc7eda2255e08ef8 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 12:24:14 +1100 Subject: [PATCH 248/531] UCS: UCSICON is saved with the drawing; deleting a named UCS clears it everywhere (review) UCSICON became a drawing setting but the DXF header did not carry it, so it came back on after a save; write and read it (group 70). The menu toggle is disabled with no drawing open and no longer fails on doc_mut. UCS NAmed Delete cleared the name only in the current space; clear it in model space and every layout. Tests: ucsicon_survives_a_dxf_round_trip, deleting_a_named_ucs_clears_it_in_every_space. --- crates/engine/src/cmd/ucs.rs | 12 ++++++++++++ crates/engine/tests/ucs.rs | 21 +++++++++++++++++++++ crates/io/src/dxf_write/header.rs | 2 ++ crates/io/tests/ucs_roundtrip.rs | 15 +++++++++++++++ crates/ui-egui/src/menus.rs | 8 +++++++- 5 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/ucs.rs b/crates/engine/src/cmd/ucs.rs index cdc950d3d..a87e32f4c 100644 --- a/crates/engine/src/cmd/ucs.rs +++ b/crates/engine/src/cmd/ucs.rs @@ -332,6 +332,18 @@ fn delete(s: &mut Session, patterns: &str) -> Result { if gone.iter().any(|g| g.eq_ignore_ascii_case(¤t)) { s.set_ucs(frame, "")?; } + // The other spaces whose current UCS carries a deleted name keep their axes and lose the name + // too (model space's UCSNAME, every layout's UCS). + let d = s.doc_mut()?; + let is_gone = |n: &str| gone.iter().any(|g| g.eq_ignore_ascii_case(n.trim())); + if is_gone(&d.header.str("UCSNAME", "")) { + d.header.set_str("UCSNAME", ""); + } + for l in &mut d.layouts { + if let Some(u) = l.ucs.as_mut().filter(|u| is_gone(&u.name)) { + u.name.clear(); + } + } Ok(gone.len()) } diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs index f3a7bca8b..a342c0425 100644 --- a/crates/engine/tests/ucs.rs +++ b/crates/engine/tests/ucs.rs @@ -587,3 +587,24 @@ fn deferred_line_polar_follows_the_ucs() { let (a, b) = last_line(&s); assert!((b - a).len() > 9.999 && (b.x - a.x).abs() < 1e-9 && (b.y - a.y - 10.0).abs() < 1e-9, "{a:?} {b:?}"); } + +/// Deleting a named UCS clears its name wherever it is the current UCS: model space and every +/// layout, not only the space deleted from. +#[test] +fn deleting_a_named_ucs_clears_it_in_every_space() { + let mut s = session(); + turned(&mut s); + s.execute("ucs", &json!({"option": "named", "action": "save", "name": "SITE"})).unwrap(); + let layout = s.doc().unwrap().layouts[0].name.clone(); + s.execute("layout.set", &json!({"name": layout})).unwrap(); + s.execute("ucs", &json!({"option": "named", "action": "restore", "name": "SITE"})).unwrap(); + assert_eq!(s.ucs_named().1, "SITE"); + // Delete from paper space: model space is still named SITE. + s.execute("ucs", &json!({"option": "named", "action": "delete", "name": "SITE"})).unwrap(); + assert_eq!(s.ucs_named().1, "", "the current space"); + assert_eq!(s.doc().unwrap().header.str("UCSNAME", ""), "", "model space"); + assert!(s.doc().unwrap().layouts.iter().all(|l| l.ucs.as_ref().is_none_or(|u| u.name.is_empty())), "every layout"); + // The axes stay. + s.execute("layout.set", &json!({"name": "Model"})).unwrap(); + assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0))); +} diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index bb8fb296e..86eba574c 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -42,6 +42,8 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("UCSORG", -3), ("UCSXDIR", -3), ("UCSYDIR", -3), + // Whether the UCS icon is shown (bit 1) and at the UCS origin (bit 2). + ("UCSICON", 70), ("PDMODE", 70), ("PDSIZE", 40), ("PLINEWID", 40), diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index a79e5db94..5707e7e3f 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -413,3 +413,18 @@ fn a_stale_ucs_name_copy_is_not_brought_back() { } assert_eq!(cadcraft_io::read_dxf(same.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE"); } + +/// UCSICON is a setting of the drawing: icon off (bit 1 clear) comes back off after a DXF save. +#[test] +fn ucsicon_survives_a_dxf_round_trip() { + let mut d = Drawing::default(); + d.header.set_i64("UCSICON", 0); + let text = cadcraft_io::write_dxf(&d); + assert_eq!(group(&header_var(&text, "UCSICON"), "70"), Some("0"), "written to the header"); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + assert_eq!(back.header.i64("UCSICON", 3), 0); + // And a value with the origin bit only. + d.header.set_i64("UCSICON", 2); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(back.header.i64("UCSICON", 3), 2); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 63e431880..bdbc863b4 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -242,6 +242,10 @@ fn run_ui_toggle_command(app: &mut CadApp, id: &str, params: &Value) -> Option { + // The icon is a setting of the drawing: with none open there is nothing to toggle. + if app.session.doc().is_err() { + return Some(Err("No drawing open.".into())); + } let (key, bit) = if id == "ui.toggle.ucsicon" { ("on", 1) } else { ("origin", 2) }; let mut on = app.session.ucsicon_bits() & bit != 0; toggle(&mut on, params); @@ -620,7 +624,9 @@ pub fn tree(app: &CadApp) -> Vec<(String, Vec)> { } for (id, label, menu, sc) in UI_COMMANDS { if !menu.is_empty() { - add(menu, label, id, *sc, true); + // The UCS icon is a setting of the drawing: off the menu's reach when none is open. + let enabled = !id.starts_with("ui.toggle.ucsicon") || app.session.doc().is_ok(); + add(menu, label, id, *sc, enabled); } } if let Some((_, file)) = out.iter_mut().find(|(m, _)| m == "File") { From 404988f67af1ec353450583dc7972cfe8d8aa15a Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 12:24:15 +1100 Subject: [PATCH 249/531] UCS: DIST JSON matches its message; no allocation per angle; origin prompt default (review) DIST's JSON angle and deltas were world values while its message is in the UCS; they now match the message and the world values sit under "world". Session::ucs() went through ucs_named() and allocated the name on every angle and point; a name-free current_frame() serves it. The origin prompt showed the world origin although input is read in the UCS; it shows 0,0,0. Tests: dist_json_matches_its_message_in_a_ucs, pressing_enter_at_the_origin_prompt_keeps_the_origin. --- crates/engine/src/cmd/inquiry.rs | 23 +++++++++++++++------ crates/engine/src/cmd/ucs.rs | 4 ++-- crates/engine/src/ucs.rs | 35 ++++++++++++++++++++------------ crates/engine/tests/ucs.rs | 32 +++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index dcfbf6e4f..1278c7656 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { CommandSpec::new("dist", "Distance", run_dist) .menu(&["Tools", "Inquiry", "Distance"]) .alias(&["di"]) - .params("{p1, p2}") + .params("{p1, p2} -> {distance, angle, angleFromXY, dx, dy, dz (in the current UCS, as the message), world: {angle, angleFromXY, dx, dy, dz}, message}") .noundo() .transparent() .interactive(|_| Ok(Box::new(DistM::default()))), @@ -224,13 +224,24 @@ fn run_dist(s: &mut Session, p: &Value) -> Result { } s.distance = d.len(); s.last_point = a.xy(); + // `angle`, `angleFromXY` and the deltas are measured in the current UCS, as the message says + // them; `world` has the same numbers along the world axes. + let u = s.input_ucs(); + let du = u.to_ucs3(b) - u.to_ucs3(a); Ok(json!({ "distance": d.len(), - "angle": d.xy().angle().to_degrees(), - "angleFromXY": angle_from_xy(d).to_degrees(), - "dx": d.x, - "dy": d.y, - "dz": d.z, + "angle": du.xy().angle().to_degrees(), + "angleFromXY": angle_from_xy(du).to_degrees(), + "dx": du.x, + "dy": du.y, + "dz": du.z, + "world": { + "angle": d.xy().angle().to_degrees(), + "angleFromXY": angle_from_xy(d).to_degrees(), + "dx": d.x, + "dy": d.y, + "dz": d.z, + }, "message": dist_text(s, a, b), })) } diff --git a/crates/engine/src/cmd/ucs.rs b/crates/engine/src/cmd/ucs.rs index a87e32f4c..44590f485 100644 --- a/crates/engine/src/cmd/ucs.rs +++ b/crates/engine/src/cmd/ucs.rs @@ -435,8 +435,8 @@ impl Interactive for UcsM { match &self.stage { Stage::Main => Prompt::new("Specify origin of UCS", Accept::POINT).kw(OPTIONS).default("World"), Stage::OriginOnly | Stage::ThreePoint => { - let o = s.ucs().origin; - Prompt::new("Specify new origin point", Accept::POINT).default(format!("{},{},{}", o.x, o.y, o.z)) + // Input here is read in the current UCS, where the UCS's own origin is 0,0,0. + Prompt::new("Specify new origin point", Accept::POINT).default("0,0,0") } Stage::XPoint(o) => Prompt::new("Specify point on X-axis", Accept::POINT).default("Accept").base(o.xy()), Stage::XyPoint(o, _) => Prompt::new("Specify point on the XY plane", Accept::POINT).default("Accept").base(o.xy()), diff --git a/crates/engine/src/ucs.rs b/crates/engine/src/ucs.rs index bf6eeb78b..36be65b71 100644 --- a/crates/engine/src/ucs.rs +++ b/crates/engine/src/ucs.rs @@ -155,29 +155,38 @@ impl UcsFrame { } } -/// The current UCS of `space` in `d` and its name (empty when it isn't a named UCS). A missing -/// or unusable one is the World UCS. -pub fn current(d: &Drawing, space: &Space) -> (UcsFrame, String) { +/// The usable current UCS of `space` in `d`, if it has one. +fn frame_of(d: &Drawing, space: &Space) -> Option { match space { Space::Model => { let h = &d.header; - let frame = match (h.point("UCSORG"), h.point("UCSXDIR"), h.point("UCSYDIR")) { + match (h.point("UCSORG"), h.point("UCSXDIR"), h.point("UCSYDIR")) { (Some(o), Some(x), Some(y)) => UcsFrame::new(o, x, y), (o, None, None) => o.filter(|o| o.is_finite()).map(|o| UcsFrame::WORLD.with_origin(o)), _ => None, - }; - match frame { - Some(f) => (f, h.str("UCSNAME", "").trim().to_string()), - None => (UcsFrame::WORLD, String::new()), } } - Space::Paper(name) => match d.layout(name).and_then(|l| l.ucs.as_ref()).and_then(|u| Some((UcsFrame::of(u)?, u.name.trim().to_string()))) { - Some(x) => x, - None => (UcsFrame::WORLD, String::new()), - }, + Space::Paper(name) => d.layout(name).and_then(|l| l.ucs.as_ref()).and_then(UcsFrame::of), } } +/// The current UCS of `space` in `d` without its name, so nothing is allocated: what the +/// per-point and per-angle paths need. A missing or unusable one is the World UCS. +pub fn current_frame(d: &Drawing, space: &Space) -> UcsFrame { + frame_of(d, space).unwrap_or(UcsFrame::WORLD) +} + +/// The current UCS of `space` in `d` and its name (empty when it isn't a named UCS). A missing +/// or unusable one is the World UCS. +pub fn current(d: &Drawing, space: &Space) -> (UcsFrame, String) { + let Some(frame) = frame_of(d, space) else { return (UcsFrame::WORLD, String::new()) }; + let name = match space { + Space::Model => d.header.str("UCSNAME", "").trim().to_string(), + Space::Paper(name) => d.layout(name).and_then(|l| l.ucs.as_ref()).map(|u| u.name.trim().to_string()).unwrap_or_default(), + }; + (frame, name) +} + /// Make `frame` (named `name`, empty for an unnamed one) the current UCS of `space`. pub fn set_current(d: &mut Drawing, space: &Space, frame: &UcsFrame, name: &str) { match space { @@ -219,7 +228,7 @@ impl Session { /// The current UCS of the space commands act on. pub fn ucs(&self) -> UcsFrame { - self.ucs_named().0 + self.doc().map(|d| current_frame(d, &self.space())).unwrap_or_default() } /// The UCS points are typed in and shown in: the current one, or the World UCS while the diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs index a342c0425..f1d3f4d4d 100644 --- a/crates/engine/tests/ucs.rs +++ b/crates/engine/tests/ucs.rs @@ -608,3 +608,35 @@ fn deleting_a_named_ucs_clears_it_in_every_space() { s.execute("layout.set", &json!({"name": "Model"})).unwrap(); assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0))); } + +/// The origin prompt offers the origin in the UCS's own terms (0,0,0), so Enter, or the default +/// typed back, keeps the origin. +#[test] +fn pressing_enter_at_the_origin_prompt_keeps_the_origin() { + let mut s = session(); + s.execute("ucs", &json!({"option": "origin", "origin": [100, 50]})).unwrap(); + s.execute("ucs", &json!({"option": "z", "angle": 30})).unwrap(); + let before = s.ucs(); + s.start("ucs.origin").unwrap(); + let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default(); + s.cmdline(&shown).unwrap(); + assert!(near3(s.ucs().origin, before.origin), "typing the default {shown:?} back: {:?}", s.ucs().origin); + s.start("ucs.origin").unwrap(); + s.cmdline("").unwrap(); + assert!(near3(s.ucs().origin, before.origin)); +} + +/// DIST's JSON says what its message says: angle and deltas in the current UCS, the world ones +/// under `world`. +#[test] +fn dist_json_matches_its_message_in_a_ucs() { + let mut s = session(); + turned(&mut s); + // Points are given in the world: UCS (0,0) and (10,0). + let r = s.execute("dist", &json!({"p1": [100, 50], "p2": [100, 60]})).unwrap(); + let f = |v: &Value, k: &str| v[k].as_f64().unwrap(); + assert!((f(&r, "dx") - 10.0).abs() < 1e-9 && f(&r, "dy").abs() < 1e-9 && f(&r, "angle").abs() < 1e-9, "{r}"); + assert!(r["message"].as_str().unwrap().contains("Delta X = 10"), "{r}"); + let w = &r["world"]; + assert!(f(w, "dx").abs() < 1e-9 && (f(w, "dy") - 10.0).abs() < 1e-9 && (f(w, "angle") - 90.0).abs() < 1e-9, "{r}"); +} From b2ded208881f0fed4aa8a96cfe20ec7f9da7a7c6 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 12:36:59 +1100 Subject: [PATCH 250/531] OLE2FRAME: the axis-aligned check scales its tolerance with the matrix (review on #2587) ALIGN builds its matrix from two angles that agree only to rounding, so a large scale leaves a rotation part of about scale * 1e-16 that an absolute 1e-12 bound refused as a turn. The bound now grows with the scale; a real turn is still refused. Test: ole_frame_accepts_a_large_scale_with_rounding_noise_in_its_rotation. --- crates/doc/src/extents.rs | 19 +++++++++++++- crates/engine/tests/ole_frame_transform.rs | 29 ++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 7713395a4..55138649d 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -161,7 +161,10 @@ pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) /// upper-left. pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool { const T: f64 = 1e-12; - m.b.abs() < T && m.c.abs() < T && m.a > 0.0 && (m.a - m.d).abs() <= T * m.a.abs().max(1.0) + // The tolerance grows with the scale: a matrix built from two angles (ALIGN) leaves rounding noise + // in b and c of about `scale * 1e-16`. + let t = T * m.a.abs().max(1.0); + m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t } /// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification @@ -767,6 +770,20 @@ mod tests { assert!(!ole_frame_accepts(&Mat3::rotate_about(p, 0.5))); assert!(!ole_frame_accepts(&Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)))); } + /// ALIGN with a scale builds its matrix from two angles that agree only to rounding, so a large + /// scale leaves a rotation part of about `scale * 1e-16`. That is a scale, not a turn: the + /// tolerance for it grows with the scale, while a real turn is still refused (review on #2587). + #[test] + fn ole_frame_accepts_a_large_scale_with_rounding_noise_in_its_rotation() { + use cadcraft_geom::Mat3; + let p = Vec2::new(3.0, -4.0); + let noisy = Mat3::scale_about(p, 1e6).then_before(Mat3::rotate_about(p, 2e-16)); + assert!(noisy.b.abs() > 1e-12, "the setup must exceed an absolute tolerance: {}", noisy.b); + assert!(ole_frame_accepts(&noisy)); + let turned = Mat3::scale_about(p, 1e6).then_before(Mat3::rotate_about(p, 1e-6)); + assert!(!ole_frame_accepts(&turned)); + } + /// The corners (x, y) in the OLE data header of a frame built by [`big_frame`]-style tags. fn header_corners(tags: &[crate::RawTag]) -> Vec<(f64, f64)> { let hex: String = tags.iter().filter(|t| t.code == 310).map(|t| t.value.as_str()).collect(); diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index 3569d39e5..afe138ff9 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -236,3 +236,32 @@ fn arraypath_refuses_before_adding_any_copy() { assert_eq!(s.doc().unwrap().model.len(), count, "no copy was added"); assert_eq!(corners(&s), before); } + +/// A refused command leaves the drawing and its undo history alone: UNDO afterwards takes back the +/// earlier MOVE, not a phantom step (review on #2587). +#[test] +fn a_refused_rotation_adds_no_undo_step() { + let (mut s, h) = session(); + let original = corners(&s); + s.execute("move", &json!({ "handles": [h.clone()], "delta": [10, 5] })).unwrap(); + let undo = s.state().unwrap().undo.len(); + s.execute("rotate", &json!({ "handles": [h], "base": [0, 0], "angle": 30 })).expect_err("rotate"); + assert_eq!(s.state().unwrap().undo.len(), undo); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(corners(&s), original); +} + +/// The classic -ARRAY makes separate copies: a polar array that turns its items refuses an OLE +/// frame before the first copy, and one that keeps the items upright carries it. +#[test] +fn classic_polar_array_refuses_a_turned_frame_but_not_an_upright_one() { + let (mut s, h) = session(); + let before = corners(&s); + let turned = json!({ "handles": [h.clone()], "type": "polar", "center": [0, 0], "count": 4, "rotate": true }); + let e = s.execute("-array", &turned).expect_err("turned items"); + assert!(e.to_string().contains("OLE object"), "{e}"); + assert_eq!((s.doc().unwrap().model.len(), corners(&s)), (1, before)); + let upright = json!({ "handles": [h], "type": "polar", "center": [0, 0], "count": 4, "rotate": false }); + s.execute("-array", &upright).unwrap(); + assert_eq!(s.doc().unwrap().model.len(), 4); +} From d12c87ca56bf51a6f6d622d7d04e55d28606aa4c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 18:48:06 -0700 Subject: [PATCH 251/531] Fonts: review fixes on #2316 (load budget, linked font folders, a test in its own binary) - A face found by family name in the user's font folders is loaded within the font-byte budget: no uncharged read past it (CodeRabbit on #2316). - Linked font folders are followed again, as before #2316, in the system scan, the user scan and the SHX folder search; each real folder is read once, so a circle of links can't use up the scan's entry budget (CodeRabbit on #2316). - The user-font-folder test changes process-wide font settings and emptied the font table under tests running beside it (2 of 3 runs failed): it moves to its own test binary, tests/ttf_font_folders.rs; that a list keeps no font bytes is checked on a local table. --- crates/fonts/src/ttf.rs | 96 +++++++++++++++++--------- crates/fonts/tests/ttf_font_folders.rs | 59 ++++++++++++++++ 2 files changed, 121 insertions(+), 34 deletions(-) create mode 100644 crates/fonts/tests/ttf_font_folders.rs diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 085f46ad5..c45c0118b 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -353,7 +353,11 @@ fn scan_dirs(dirs: &[PathBuf], in_order: bool) -> HashMap { let mut out = HashMap::new(); let mut stack: Vec = if in_order { dirs.iter().rev().cloned().collect() } else { dirs.to_vec() }; let mut seen = 0usize; + let mut visited = std::collections::HashSet::new(); while let Some(d) = stack.pop() { + if !first_visit(&mut visited, &d) { + continue; + } let Ok(rd) = std::fs::read_dir(&d) else { continue }; for e in rd.flatten() { seen += 1; @@ -361,15 +365,12 @@ fn scan_dirs(dirs: &[PathBuf], in_order: bool) -> HashMap { return out; } let p = e.path(); - // Real folders only: a link to a folder could lead in a circle. - let Ok(ft) = e.file_type() else { continue }; - if ft.is_dir() { + // Linked folders are followed (font folders often are links); `first_visit` keeps a + // circle of links from reading a folder twice. + if p.is_dir() { stack.push(p); continue; } - if ft.is_symlink() && p.is_dir() { - continue; - } let ext = p.extension().map(|x| x.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); if !matches!(ext.as_str(), "ttf" | "otf" | "ttc" | "otc") { continue; @@ -468,6 +469,13 @@ pub fn rescan() { crate::shx::set_font_dirs(shx_dirs(&user_dirs())); } +/// Whether folder `d` is read for the first time (by its real path: a link to a folder already +/// read, or a circle of links, is not read again). +#[cfg(not(target_arch = "wasm32"))] +fn first_visit(visited: &mut std::collections::HashSet, d: &std::path::Path) -> bool { + visited.insert(std::fs::canonicalize(d).unwrap_or_else(|_| d.to_path_buf())) +} + /// The folders under `dirs` (them included) that hold SHX files, in order, bounded like the /// font scan. #[cfg(not(target_arch = "wasm32"))] @@ -475,7 +483,11 @@ fn shx_dirs(dirs: &[PathBuf]) -> Vec { let mut out: Vec = Vec::new(); let mut stack: Vec = dirs.iter().rev().cloned().collect(); let mut seen = 0usize; + let mut visited = std::collections::HashSet::new(); while let Some(d) = stack.pop() { + if !first_visit(&mut visited, &d) { + continue; + } let Ok(rd) = std::fs::read_dir(&d) else { continue }; let mut subs = Vec::new(); let mut has_shx = false; @@ -484,8 +496,7 @@ fn shx_dirs(dirs: &[PathBuf]) -> Vec { if seen > 20_000 { return out; } - let Ok(ft) = e.file_type() else { continue }; - if ft.is_dir() { + if e.path().is_dir() { subs.push(e.path()); } else if e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("shx")) { has_shx = true; @@ -632,10 +643,10 @@ impl Db { for stem in stems.into_iter().take(200) { let Some(names) = self.face_names(&stem) else { continue }; let Some(i) = names.faces.iter().position(|f| f.iter().any(|n| *n == want || format!("{n}regular") == want)) else { continue }; - // Only the file that has the face is kept (and charged to the load budget). - // A file that cannot be read now (deleted, too large, budget used) does not end the - // search: another file in the folders may hold the same family. - let Some(bytes) = self.file(&stem).or_else(|| self.peek(&stem)) else { continue }; + // Only the file that has the face is kept, charged to the load budget like any other + // (once it is used up, no more faces are loaded). A file that cannot be read now + // (deleted, too large) does not end the search: another file may hold the family. + let Some(bytes) = self.file(&stem) else { continue }; return faces(&bytes).into_iter().nth(i); } None @@ -1257,31 +1268,17 @@ mod family_tests { assert!(available(crate::BUILTIN_FONT)); } + /// Reading a user font's names for a list keeps none of its bytes and uses none of the load + /// budget. (Font folders themselves are process-wide: `tests/ttf_font_folders.rs`.) #[cfg(not(target_arch = "wasm32"))] #[test] - fn a_font_in_a_user_folder_is_found_listed_and_dropped_with_the_folder() { + fn reading_a_user_fonts_names_keeps_no_font_bytes() { let Some(src) = scan().into_values().find(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("ttf"))) else { return }; - let dir = std::env::temp_dir().join(format!("cadcraft-fontdir-{}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); - let Ok(_) = std::fs::copy(&src, dir.join("CadcraftTestFace.ttf")) else { return }; - let before = generation(); - set_font_dirs(&[dir.to_string_lossy().to_string()]); - assert!(generation() > before); - // Listing reads the family name without keeping the file (or using up the load budget). - let early = installed(); - assert!(early.iter().any(|f| f.name == "CadcraftTestFace.ttf" && f.family.is_some())); - assert!(!lock().files.contains_key("cadcrafttestface"), "listing keeps no font bytes"); - assert!(find("CadcraftTestFace.ttf").is_some()); - let listed = installed(); - let entry = listed.iter().find(|f| f.name == "CadcraftTestFace.ttf"); - assert!(entry.is_some_and(|f| f.user && f.family.is_some()), "{entry:?}"); - assert!(listed.first().is_some_and(|f| f.user), "the user's fonts come first"); - if let Some(family) = entry.and_then(|f| f.family.clone()) { - assert!(find(&family).is_some(), "found by its family name: {family}"); - } - set_font_dirs::<&str>(&[]); - assert!(find("CadcraftTestFace.ttf").is_none()); - let _ = std::fs::remove_dir_all(&dir); + let mut db = Db::default(); + db.user.insert("face".into()); + db.paths.insert("face".into(), Source::File(src)); + assert!(db.face_names("face").is_some_and(|n| n.family.is_some())); + assert!(db.files.is_empty() && db.loaded_bytes == 0); } /// One unreadable user font file with the family does not stop the search: the next file @@ -1300,6 +1297,37 @@ mod family_tests { assert!(db.files.contains_key("b"), "the second file with the family was tried"); } + /// A face found by family name is loaded within the font-byte budget: once it is used up, + /// none is read past it (#2316 review). + #[test] + fn a_family_search_keeps_to_the_load_budget() { + let mut db = Db::default(); + db.user.insert("b".into()); + db.face_names.insert("b".into(), Arc::new(FaceNames { family: Some("Foo".into()), faces: vec![vec!["foo".into()]] })); + db.paths.insert("b".into(), Source::Static(b"not a font")); + db.loaded_bytes = MAX_LOADED_BYTES; + assert!(db.user_family("Foo").is_none()); + assert!(db.files.is_empty(), "nothing read past the budget"); + } + + /// Linked font folders are followed, and a circle of links reads each folder once. + #[cfg(unix)] + #[test] + fn linked_font_folders_are_followed_once() { + let root = std::env::temp_dir().join(format!("cadcraft-fontlinks-{}", std::process::id())); + let real = root.join("real"); + let _ = std::fs::create_dir_all(&real); + let Ok(()) = std::fs::write(real.join("LinkedFace.ttf"), b"x") else { return }; + let _ = std::fs::write(real.join("linked.shx"), b"x"); + let _ = std::os::unix::fs::symlink(&real, root.join("link")); + // A link back up: a circle. + let _ = std::os::unix::fs::symlink(&root, real.join("up")); + let found = scan_dirs(&[root.join("link")], true); + assert!(found.contains_key("linkedface"), "{found:?}"); + assert_eq!(shx_dirs(&[root.clone()]).len(), 1, "the folder with the SHX file, once"); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn thai_looks_in_thai_fonts_before_the_general_search() { // Letters, vowels, tone marks and digits: the general search loads a bounded number of diff --git a/crates/fonts/tests/ttf_font_folders.rs b/crates/fonts/tests/ttf_font_folders.rs new file mode 100644 index 000000000..6ad257788 --- /dev/null +++ b/crates/fonts/tests/ttf_font_folders.rs @@ -0,0 +1,59 @@ +//! TrueType fonts in the user's font folders (Options ▸ Fonts): found by file and family name, +//! listed first, and gone again when the folder is removed. Font folders are process-wide and a +//! change looks for fonts again, so this is one test in its own binary (run beside other tests, +//! it would empty the font table under them). + +use std::path::{Path, PathBuf}; + +use cadcraft_fonts::ttf; + +/// A TrueType file from the system's fonts to copy, if there is one (a bounded walk). +fn a_system_ttf() -> Option { + let mut stack: Vec = + ["C:/Windows/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts", "/usr/share/fonts", "/usr/local/share/fonts"] + .map(PathBuf::from) + .to_vec(); + let mut seen = 0; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { + seen += 1; + if seen > 5_000 { + return None; + } + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("ttf")) { + return Some(p); + } + } + } + None +} + +fn copy_into(src: &Path, dir: &Path) -> bool { + std::fs::create_dir_all(dir).is_ok() && std::fs::copy(src, dir.join("CadcraftTestFace.ttf")).is_ok() +} + +#[test] +fn a_font_in_a_user_folder_is_found_listed_and_dropped_with_the_folder() { + let Some(src) = a_system_ttf() else { return }; + let dir = std::env::temp_dir().join(format!("cadcraft-fontdir-{}", std::process::id())); + if !copy_into(&src, &dir) { + return; + } + let before = ttf::generation(); + ttf::set_font_dirs(&[dir.to_string_lossy().to_string()]); + assert!(ttf::generation() > before); + assert!(ttf::find("CadcraftTestFace.ttf").is_some()); + let listed = ttf::installed(); + let entry = listed.iter().find(|f| f.name == "CadcraftTestFace.ttf"); + assert!(entry.is_some_and(|f| f.user && f.family.is_some()), "{entry:?}"); + assert!(listed.first().is_some_and(|f| f.user), "the user's fonts come first"); + if let Some(family) = entry.and_then(|f| f.family.clone()) { + assert!(ttf::find(&family).is_some(), "found by its family name: {family}"); + } + ttf::set_font_dirs::<&str>(&[]); + assert!(ttf::find("CadcraftTestFace.ttf").is_none()); + let _ = std::fs::remove_dir_all(&dir); +} From 3c123fd61cdedafa4e154b353c5f5486097c45f3 Mon Sep 17 00:00:00 2001 From: Luminati Date: Thu, 5 Nov 2026 03:56:40 +0200 Subject: [PATCH 252/531] New and redrawn icons (drawn in code); clicks on painted controls keep the keyboard with the drawing (#2319) * New and redrawn icons (drawn in code); a click on a painted control leaves the keyboard with the drawing Split out of #2034. No image files: every icon is drawn in code. - New: Zoom In / Zoom Out / Zoom to Fit, Move to Top / Up / Down / Bottom, Text Style and Dimension Style (with a small gear); redrawn: Undo, Redo, Plot, Preview, the dimension tools and others. - icons::button_bare: a button without its hover text, for callers that show a richer tooltip. - Clicking a painted control (a file tab) no longer takes keyboard focus, so Ctrl+C in one drawing and Ctrl+V in another keep working; Tab still reaches it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V * Undo/Redo icons of our own design; the clipboard test requires the copied text Review (CodeRabbit): the Undo/Redo comment named another product's icons as the model. The icons are redrawn to our own design (a straight run and a half-turn back, in the icon colour) and the reference is gone. The cross-drawing clipboard test no longer falls back to placeholder text: it installs a DXF writer and requires the copy to reach the system clipboard. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V * Icons: fit upstream's split icon painter (the pen's painter, theme colours, dim flag) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V * Icons: drop the dangling tool_button doc link; describe the tab click focus as it behaves --------- Co-authored-by: Claude Co-authored-by: FredApps --- crates/ui-egui/src/icons.rs | 227 ++++++++++++++---- .../tests/it/clipboard_between_drawings.rs | 89 +++++++ crates/ui-egui/tests/it/main.rs | 1 + 3 files changed, 265 insertions(+), 52 deletions(-) create mode 100644 crates/ui-egui/tests/it/clipboard_between_drawings.rs diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 8e0f89963..8a6e67368 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -149,6 +149,15 @@ pub enum Icon { PickAdd, SelectObjects, QuickSelect, + ZoomIn, + ZoomOut, + MoveTop, + MoveUp, + MoveDown, + MoveBottom, + ZoomFit, + TextStyle, + DimStyle, } struct Pen<'a> { @@ -219,6 +228,14 @@ impl Pen<'_> { let (nx, ny) = (-uy, ux); self.tri([(x, y), (x - ux * 3.0 + nx * 1.4, y - uy * 3.0 + ny * 1.4), (x - ux * 3.0 - nx * 1.4, y - uy * 3.0 - ny * 1.4)], c); } + /// A larger arrowhead than [`Pen::arrow_tip`]: `len` long, `half` wide either side. + #[allow(clippy::too_many_arguments)] + fn big_arrow(&self, x: f32, y: f32, dx: f32, dy: f32, len: f32, half: f32, c: Color32) { + let l = (dx * dx + dy * dy).sqrt().max(1e-3); + let (ux, uy) = (dx / l, dy / l); + let (nx, ny) = (-uy, ux); + self.tri([(x, y), (x - ux * len + nx * half, y - uy * len + ny * half), (x - ux * len - nx * half, y - uy * len - ny * half)], c); + } fn text(&self, x: f32, y: f32, s: &str, size: f32, c: Color32) { self.p.text(self.at(x, y), egui::Align2::CENTER_CENTER, s, egui::FontId::proportional(size * self.sc()), c); } @@ -242,7 +259,7 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { paint_constraints(&pen, icon, b, a, dim); } -fn paint_file_view(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: bool) { +fn paint_file_view(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, dim: bool) { use Icon::*; match icon { New => { @@ -258,26 +275,48 @@ fn paint_file_view(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: bool pen.rect(8.0, 4.0, 8.0, 5.0, b); pen.rect(7.0, 13.0, 10.0, 7.0, b); if icon == SaveAs { - pen.la(15.0, 22.0, 22.0, 15.0); - pen.fill_c(15.0, 22.0, 1.2, a); + // A large pencil across the lower-right corner: body, ferrule line and a filled tip. + pen.p.add(egui::Shape::convex_polygon( + [(12.6, 19.4), (20.6, 11.4), (23.6, 14.4), (15.6, 22.4)].iter().map(|(x, y)| pen.at(*x, *y)).collect(), + Tokens::get().panel, + Stroke::NONE, + )); + pen.poly(&[(12.6, 19.4), (20.6, 11.4), (23.6, 14.4), (15.6, 22.4)], true, a); + pen.la(19.0, 13.0, 22.0, 16.0); + pen.tri([(12.6, 19.4), (15.6, 22.4), (10.8, 24.0)], a); } } - Undo => { - pen.arc(12.0, 13.0, 7.0, 150.0, -40.0, b); - pen.arrow_tip(5.0, 9.0, -1.0, 2.5, b); + Undo | Redo => { + // CADCraft's own: a step back along the drawing's path. A short straight run with a + // half-turn above it, the arrowhead at the free end pointing back (Undo: to the + // left, Redo: mirrored to the right), in the icon colour. + let m = |x: f32| if icon == Undo { x } else { 24.0 - x }; + let col = if dim { a } else { b }; + // The straight run along the bottom, then a half circle up and back over it. + let (cx, cy, r) = (13.0_f32, 12.0_f32, 5.0_f32); + let mut pts: Vec = vec![pen.at(m(6.0), cy + r)]; + pts.extend((0..=20).map(|i| { + let ang = (-90.0 + 180.0 * i as f32 / 20.0).to_radians(); + pen.at(m(cx + r * ang.cos()), cy - r * ang.sin()) + })); + pts.push(pen.at(m(7.5), cy - r)); + pen.p.add(egui::Shape::line(pts, Stroke::new(pen.w * 1.8, col))); + // The arrowhead at the free end, pointing back along the top run. + let dx = if icon == Undo { -1.0 } else { 1.0 }; + pen.big_arrow(m(5.0), cy - r, dx, 0.0, 5.0, 4.6, col); } - Redo => { - pen.arc(12.0, 13.0, 7.0, 30.0, 220.0, b); - pen.arrow_tip(19.0, 9.0, 1.0, 2.5, b); - } - Plot | Preview => { + Plot => { pen.rect(4.0, 9.0, 16.0, 8.0, b); pen.rect(7.0, 4.0, 10.0, 5.0, b); pen.rect(7.0, 14.0, 10.0, 7.0, b); - if icon == Preview { - pen.c(17.0, 17.0, 3.0, a); - pen.la(19.0, 19.0, 22.0, 22.0); - } + } + Preview => { + // A smaller printer on the left and the magnifier clear of it on the right. + pen.rect(1.5, 8.0, 12.0, 6.5, b); + pen.rect(3.8, 4.0, 7.4, 4.0, b); + pen.rect(3.8, 12.0, 7.4, 6.0, b); + pen.c(17.5, 13.0, 4.0, a); + pen.p.line_segment([pen.at(20.4, 15.9), pen.at(23.0, 18.5)], Stroke::new(pen.w * 1.8, a)); } Publish => { pen.rect(3.0, 10.0, 13.0, 7.0, b); @@ -291,12 +330,14 @@ fn paint_file_view(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: bool } Import | Export => { pen.poly(&[(5.0, 3.0), (14.0, 3.0), (18.0, 7.0), (18.0, 21.0), (5.0, 21.0)], true, b); + // A large, thick arrow: into the page for Import, out of it for Export. + let thick = Stroke::new(pen.w * 2.0, a); if icon == Import { - pen.la(1.0, 13.0, 11.0, 13.0); - pen.arrow_tip(12.0, 13.0, 1.0, 0.0, a); + pen.p.line_segment([pen.at(0.5, 13.0), pen.at(8.0, 13.0)], thick); + pen.big_arrow(14.5, 13.0, 1.0, 0.0, 7.0, 5.0, a); } else { - pen.la(11.0, 13.0, 21.0, 13.0); - pen.arrow_tip(23.0, 13.0, 1.0, 0.0, a); + pen.p.line_segment([pen.at(9.0, 13.0), pen.at(17.0, 13.0)], thick); + pen.big_arrow(24.0, 13.0, 1.0, 0.0, 7.0, 5.0, a); } } Attach => { @@ -520,20 +561,24 @@ fn paint_edit_tools(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: boo use Icon::*; match icon { Move => { - pen.la(12.0, 3.0, 12.0, 21.0); - pen.la(3.0, 12.0, 21.0, 12.0); - pen.arrow_tip(12.0, 2.0, 0.0, -1.0, a); - pen.arrow_tip(12.0, 22.0, 0.0, 1.0, a); - pen.arrow_tip(2.0, 12.0, -1.0, 0.0, a); - pen.arrow_tip(22.0, 12.0, 1.0, 0.0, a); + pen.la(12.0, 6.0, 12.0, 18.0); + pen.la(6.0, 12.0, 18.0, 12.0); + pen.big_arrow(12.0, 1.5, 0.0, -1.0, 5.5, 3.3, a); + pen.big_arrow(12.0, 22.5, 0.0, 1.0, 5.5, 3.3, a); + pen.big_arrow(1.5, 12.0, -1.0, 0.0, 5.5, 3.3, a); + pen.big_arrow(22.5, 12.0, 1.0, 0.0, 5.5, 3.3, a); } Copy => { pen.rect(3.0, 3.0, 11.0, 13.0, b); pen.rect(10.0, 8.0, 11.0, 13.0, a); } Rotate => { - pen.arc(12.0, 12.0, 8.0, 100.0, 380.0, a); - pen.arrow_tip(10.6, 4.1, -1.0, 0.1, a); + // Most of a circle, counter-clockwise, ending in an arrowhead along it. + pen.arc(12.0, 12.0, 8.0, 50.0, 300.0, a); + let end = 300f32.to_radians(); + let (px, py) = (12.0 + 8.0 * end.cos(), 12.0 - 8.0 * end.sin()); + let (ux, uy) = (-end.sin(), -end.cos()); + pen.big_arrow(px + ux * 4.5, py + uy * 4.5, ux, uy, 5.5, 3.3, a); pen.dot(12.0, 12.0); } Scale => { @@ -558,20 +603,22 @@ fn paint_edit_tools(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: boo pen.la(4.0, 18.0, 4.0, 22.0); } Trim => { - pen.l(8.0, 2.0, 8.0, 22.0); - pen.l(16.0, 2.0, 16.0, 22.0); - pen.l(2.0, 12.0, 8.0, 12.0); - pen.l(16.0, 12.0, 22.0, 12.0); - for x in [9.5, 12.0, 14.5] { - pen.la(x, 12.0, x + 1.0, 12.0); - } - pen.poly(&[(10.0, 17.0), (12.0, 15.0), (14.0, 17.0)], false, a); + // Scissors cutting a line in two: the line's halves apart under the blades. + pen.l(1.5, 20.0, 9.0, 20.0); + pen.l(15.0, 20.0, 22.5, 20.0); + pen.c(7.5, 4.5, 3.0, a); + pen.c(16.5, 4.5, 3.0, a); + pen.poly(&[(9.3, 6.9), (14.6, 18.5)], false, a); + pen.poly(&[(14.7, 6.9), (9.4, 18.5)], false, a); + pen.tri([(14.6, 18.5), (13.0, 13.5), (11.8, 14.6)], a); + pen.tri([(9.4, 18.5), (11.0, 13.5), (12.2, 14.6)], a); + pen.fill_c(12.0, 12.6, 1.3, pen.pt); } Extend => { - pen.l(20.0, 2.0, 20.0, 22.0); - pen.l(3.0, 12.0, 11.0, 12.0); - pen.la(11.0, 12.0, 19.0, 12.0); - pen.arrow_tip(19.5, 12.0, 1.0, 0.0, a); + pen.l(21.0, 2.0, 21.0, 22.0); + pen.l(2.0, 12.0, 9.0, 12.0); + pen.la(9.0, 12.0, 14.0, 12.0); + pen.big_arrow(20.5, 12.0, 1.0, 0.0, 7.0, 4.0, a); } Fillet => { pen.l(4.0, 20.0, 4.0, 12.0); @@ -645,7 +692,21 @@ fn paint_edit_tools(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: boo fn paint_dimensions(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: bool) { use Icon::*; match icon { - DimLinear | DimAligned | DimBaseline | DimContinue | QDim => { + DimAligned => { + // The linear dimension's figure turned 13° counter-clockwise, as an aligned + // dimension follows a slanted object. + let (sin, cos) = 13f32.to_radians().sin_cos(); + let r = |x: f32, y: f32| (12.0 + (x - 12.0) * cos + (y - 12.0) * sin, 12.0 - (x - 12.0) * sin + (y - 12.0) * cos); + let line = |x1: f32, y1: f32, x2: f32, y2: f32, c: Color32| pen.poly(&[r(x1, y1), r(x2, y2)], false, c); + let (y0, y1) = (9.0, 19.0); + line(4.0, y1, 4.0, 6.0, b); + line(20.0, y1, 20.0, 6.0, b); + line(4.0, y0, 20.0, y0, a); + let ((ax, ay), (bx, by)) = (r(4.0, y0), r(20.0, y0)); + pen.arrow_tip(ax, ay, -cos, sin, a); + pen.arrow_tip(bx, by, cos, -sin, a); + } + DimLinear | DimBaseline | DimContinue | QDim => { let (y0, y1) = (8.0, 18.0); pen.l(4.0, y1, 4.0, 5.0); pen.l(20.0, y1, 20.0, 5.0); @@ -658,7 +719,6 @@ fn paint_dimensions(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: boo pen.l(12.0, y1, 12.0, 5.0); } QDim => pen.text(12.0, 15.0, "Q", 7.0, b), - DimAligned => {} _ => pen.text(12.0, 14.5, "1.5", 6.0, b), } } @@ -845,15 +905,20 @@ fn paint_display_toggles(pen: &Pen<'_>, icon: Icon, b: Color32, _a: Color32, dim pen.l(17.0, 13.0, 17.0, 21.0); } Gear => { - pen.c(12.0, 12.0, 4.0, b); + // A gear wheel: eight square teeth on a rim, and the hole in the middle. + let mut outline = Vec::new(); for i in 0..8 { - let ang = (i as f32 * 45.0).to_radians(); - pen.p.line_segment( - [pen.at(12.0 + 6.0 * ang.cos(), 12.0 + 6.0 * ang.sin()), pen.at(12.0 + 9.0 * ang.cos(), 12.0 + 9.0 * ang.sin())], - Stroke::new(2.2 * pen.sc(), b), - ); + let c = i as f32 * 45.0; + for (da, rr) in [(-17.0, 7.0), (-11.0, 9.6), (11.0, 9.6), (17.0, 7.0)] { + let a = (c + da).to_radians(); + outline.push(pen.at(12.0 + rr * a.cos(), 12.0 + rr * a.sin())); + } } - pen.c(12.0, 12.0, 6.5, b); + if let Some(f) = outline.first().copied() { + outline.push(f); + } + pen.p.add(egui::Shape::line(outline, Stroke::new(pen.w * 1.2, b))); + pen.c(12.0, 12.0, 3.2, b); } Annotation => { pen.poly(&[(12.0, 3.0), (21.0, 20.0), (3.0, 20.0)], true, b); @@ -885,6 +950,59 @@ fn paint_navigation_controls(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, pen.fill_rect(x, y, 8.0, 8.0, if x == 3.0 && y == 3.0 { a } else { b }); } } + ZoomIn | ZoomOut => { + pen.c(10.0, 10.0, 7.0, b); + pen.p.line_segment([pen.at(15.0, 15.0), pen.at(21.5, 21.5)], Stroke::new(pen.w * 2.2, b)); + pen.la(6.5, 10.0, 13.5, 10.0); + if icon == ZoomIn { + pen.la(10.0, 6.5, 10.0, 13.5); + } + } + MoveTop | MoveBottom => { + // A bar at the end the arrow points to. + let (bar, tip, tail, dir) = if icon == MoveTop { (4.0, 7.0, 21.0, -1.0) } else { (20.0, 17.0, 3.0, 1.0) }; + pen.p.line_segment([pen.at(5.0, bar), pen.at(19.0, bar)], Stroke::new(pen.w * 1.6, a)); + pen.l(12.0, tail, 12.0, tip - 5.0 * dir); + pen.big_arrow(12.0, tip, 0.0, dir, 6.0, 4.5, b); + } + MoveUp | MoveDown => { + let dir = if icon == MoveUp { -1.0 } else { 1.0 }; + pen.l(12.0, 12.0 - 8.0 * dir, 12.0, 12.0 + 2.0 * dir); + pen.big_arrow(12.0, 12.0 + 8.0 * dir, 0.0, dir, 7.0, 5.0, b); + } + ZoomFit => { + // Four right-angle corners framing a rectangle. + let s = Stroke::new(pen.w * 1.6, b); + for (x, y, dx, dy) in [(3.0, 5.0, 1.0, 1.0), (21.0, 5.0, -1.0, 1.0), (3.0, 19.0, 1.0, -1.0), (21.0, 19.0, -1.0, -1.0)] { + pen.p.line(vec![pen.at(x + dx * 5.0, y), pen.at(x, y), pen.at(x, y + dy * 4.5)], s); + } + pen.rect(8.0, 9.0, 8.0, 6.0, a); + } + TextStyle | DimStyle => { + if icon == TextStyle { + pen.text(9.5, 10.5, "A", 15.0, b); + } else { + pen.l(2.0, 4.0, 2.0, 12.0); + pen.l(15.0, 4.0, 15.0, 12.0); + pen.l(2.0, 8.0, 15.0, 8.0); + pen.arrow_tip(2.0, 8.0, -1.0, 0.0, b); + pen.arrow_tip(15.0, 8.0, 1.0, 0.0, b); + } + // A small gear: the style's settings. + let mut outline = Vec::new(); + for i in 0..6 { + let c = i as f32 * 60.0; + for (da, rr) in [(-20.0, 3.6), (-12.0, 5.0), (12.0, 5.0), (20.0, 3.6)] { + let ang = (c + da).to_radians(); + outline.push(pen.at(17.5 + rr * ang.cos(), 17.5 + rr * ang.sin())); + } + } + if let Some(f) = outline.first().copied() { + outline.push(f); + } + pen.p.add(egui::Shape::line(outline, Stroke::new(pen.w, a))); + pen.c(17.5, 17.5, 1.5, a); + } Close => { pen.l(6.0, 6.0, 18.0, 18.0); pen.l(18.0, 6.0, 6.0, 18.0); @@ -1025,6 +1143,11 @@ fn paint_constraints(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, dim: boo /// A shared button interaction with CADCraft's original multicolor icon painting. pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: bool) -> egui::Response { + button_bare(ui, icon, size, tooltip, selected).on_hover_text(crate::i18n::t(tooltip)) +} + +/// [`button`] without its hover text, for callers that show a richer tooltip of their own. +pub fn button_bare(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: bool) -> egui::Response { let t = Tokens::get(); let visuals = |fill| ButtonVisuals { fill, stroke: Stroke::NONE, icon: t.icon }; let style = IconButtonStyle { @@ -1041,7 +1164,7 @@ pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: paint(ui.painter(), rect.shrink(size * 0.08), icon, !ui.is_enabled()); }); crate::control::record_widget(ui, &resp, tooltip, "button", Some(selected)); - resp.on_hover_text(crate::i18n::t(tooltip)) + resp } /// Labels and focus outlines for controls whose existing geometry is painted by the app. @@ -1060,9 +1183,9 @@ pub fn describe_control(ui: &egui::Ui, response: &egui::Response, label: &str, s node.set_selected(selected); } }); - if response.clicked() { - response.request_focus(); - } + // A click leaves the keyboard with the drawing (shortcuts such as Ctrl+V and typed + // commands keep working after switching drawings), as the drafting buttons already do. + // Keyboard focus still shows its outline below when the tab gets it another way. } if response.has_focus() && response.rect.width() > 4.0 && response.rect.height() > 4.0 { ui.painter().rect_stroke(response.rect.shrink(2.0), 2.0, Stroke::new(1.0, Tokens::get().accent), egui::StrokeKind::Inside); diff --git a/crates/ui-egui/tests/it/clipboard_between_drawings.rs b/crates/ui-egui/tests/it/clipboard_between_drawings.rs new file mode 100644 index 000000000..fbb2944eb --- /dev/null +++ b/crates/ui-egui/tests/it/clipboard_between_drawings.rs @@ -0,0 +1,89 @@ +//! Ctrl+C in one open drawing, Ctrl+V in another: the objects are pasted there. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session}; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::{Event, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn harness(app: CadApp) -> Harness<'static, CadApp> { + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(5); + h +} + +#[test] +fn copy_in_one_drawing_and_paste_in_another() { + // A DXF writer for the clipboard text (the app installs the real one). + cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks { + read: |_, _| Ok(cadcraft_engine::doc::Drawing::new_metric()), + write: |_, _| Ok(b"0\nSECTION\n0\nENDSEC\n0\nEOF\n".to_vec()), + plot: None, + }); + let mut app = CadApp::new(Session::new(), Services::default()); + app.run("line", json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + app.run("circle", json!({ "center": [5, 5], "radius": 2 })).unwrap(); + app.run("block", json!({ "name": "DOT", "base": [5, 5], "handles": [app.session.doc().unwrap().model.iter().nth(1).unwrap().handle.hex()], "keep": "convert" })) + .unwrap(); + let first = app.session.active; + let all: Vec<_> = app.session.doc().unwrap().model.iter().map(|e| e.handle).collect(); + app.session.set_selection(all); + let mut h = harness(app); + h.event(Event::Copy); + h.run_steps(2); + // The copy is mirrored to the system clipboard as text (what another drawing or another + // CADCraft window pastes): checked on a frame of its own, where egui's output is kept. + let text = { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| cadcraft_ui_egui::clipboard::mirror(h.state(), ui.ctx())); + out.textures_delta.clear(); + out.platform_output.commands.iter().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) + }; + let text = text.expect("the copy is on the system clipboard as text"); + assert_eq!( + h.state().session.clipboard.len(), + 2, + "{:?}", + h.state().session.doc().unwrap().model.iter().map(|e| e.kind.type_name()).collect::>() + ); + // Another drawing, made active by clicking its tab (which must not keep the keyboard). + h.state_mut().run("new", json!({})).unwrap(); + h.run_steps(3); + let second = h.state().session.active; + let title = h.state().session.docs[second].title.clone(); + h.state_mut().run("document.switch", json!({ "index": first })).unwrap(); + h.run_steps(3); + h.get_by_label(&title).click(); + h.run_steps(3); + assert_eq!(h.state().session.active, second); + assert_ne!(second, first); + assert!(h.state().session.doc().unwrap().model.is_empty()); + assert!(!h.ctx.egui_wants_keyboard_input(), "the clicked tab doesn't hold the keyboard"); + // Ctrl+V: egui reports it as a Paste event with the system clipboard's text. + h.event(Event::Paste(text)); + h.run_steps(3); + assert_eq!( + h.state().session.running.as_ref().map(|r| r.id.as_str()), + Some("pasteclip"), + "{:?}", + h.state().session.log.iter().rev().take(5).collect::>() + ); + h.state_mut().session.input(Input::Point(Vec2::new(100.0, 100.0))).unwrap(); + h.run_steps(2); + let d = h.state().session.doc().unwrap(); + assert_eq!(d.model.len(), 2); + assert!(d.model.iter().any(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block == "DOT"))); + assert!(d.block("DOT").is_some()); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index b80614182..6cc883a66 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,6 +1,7 @@ mod animation_effects; mod block_description_palette; mod chrome_geometry; +mod clipboard_between_drawings; mod context_menu; mod context_menus; mod control_cmdline; From 1947e4e09e9b326a16faf9bb13b29eb0690e97d2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 19:13:39 -0700 Subject: [PATCH 253/531] Fonts: review fixes on #2803 (Unix clippy, the degree sign in DOS Hebrew fonts, font-keyed caches) - The linked-folder test (Unix only) passes a slice without a clone (clippy cloned_ref_to_slice_refs, which failed the Linux gate). - In a DOS 862 Hebrew SHX font, %%d still draws from the old degree shape 127: only 128-129 are letters there. - The viewport highlight, drag preview and command preview caches key on the font set too, so text in them is drawn again when fonts change. --- crates/fonts/src/shx/tests.rs | 3 +++ crates/fonts/src/shx/text.rs | 5 +++-- crates/fonts/src/ttf.rs | 2 +- crates/ui-egui/src/canvas/draw.rs | 2 +- crates/ui-egui/src/canvas/list.rs | 14 ++++++++++---- crates/ui-egui/src/canvas/viewport.rs | 3 ++- 6 files changed, 20 insertions(+), 9 deletions(-) diff --git a/crates/fonts/src/shx/tests.rs b/crates/fonts/src/shx/tests.rs index f918e4645..bb7436b64 100644 --- a/crates/fonts/src/shx/tests.rs +++ b/crates/fonts/src/shx/tests.rs @@ -473,6 +473,9 @@ fn hebrew_letters_draw_from_their_one_byte_places() { // DOS 862: bet at 0x81 advances one unit. assert!((draws(hebrew_font(0x80..=0x9A), 'ב') - 1.0).abs() < 1e-9); assert_eq!(hebrew_font(0x80..=0x9A).hebrew_places(), (false, true)); + // The old degree sign at 127 isn't a letter in DOS 862: `%%d` still draws from it + // (127 & 0x1F = 31 units). + assert!((draws(hebrew_font((0x80..=0x9A).chain([127])), '°') - 31.0).abs() < 1e-9); // A Cyrillic-style font (0xC0..0xFF all drawn) is not read as Hebrew: the letter comes // from the built-in stroke font instead of a Cyrillic shape. let cyr = hebrew_font(0xC0..=0xFF); diff --git a/crates/fonts/src/shx/text.rs b/crates/fonts/src/shx/text.rs index 82ef71a0b..c7da188ed 100644 --- a/crates/fonts/src/shx/text.rs +++ b/crates/fonts/src/shx/text.rs @@ -88,9 +88,10 @@ fn candidates(c: char, font: &ShxFont) -> [Option; 4] { _ => None, }; if let Some((s, latin, old)) = special { - // In a DOS 862 Hebrew font 127–129 are letters and 0xB0.. box drawing: shape 256–258 only. + // In a DOS 862 Hebrew font 128–129 are letters and 0xB0.. box drawing: shape 256–258, + // and the old degree sign 127 (not a letter there). if !unicode && font.kind() == ShxKind::Shapes && font.hebrew_places().1 { - return [Some(s), None, None, None]; + return [Some(s), (old == 127).then_some(old), None, None]; } return if unicode { [code(u), code(if c == '⌀' { 0x2205 } else { latin }), Some(s), Some(old)] diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index c45c0118b..5125d0a24 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -1324,7 +1324,7 @@ mod family_tests { let _ = std::os::unix::fs::symlink(&root, real.join("up")); let found = scan_dirs(&[root.join("link")], true); assert!(found.contains_key("linkedface"), "{found:?}"); - assert_eq!(shx_dirs(&[root.clone()]).len(), 1, "the folder with the SHX file, once"); + assert_eq!(shx_dirs(std::slice::from_ref(&root)).len(), 1, "the folder with the SHX file, once"); let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index 34316374a..17da084f7 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -226,7 +226,7 @@ pub(super) fn draw_drag_gpu( let key = { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - (c.key, band, bg.0, bg.1, bg.2, &drag.handles, transparency).hash(&mut h); + (c.key, band, bg.0, bg.1, bg.2, &drag.handles, transparency, super::list::font_generation()).hash(&mut h); if drag.clipboard { clipboard.1.hash(&mut h); } diff --git a/crates/ui-egui/src/canvas/list.rs b/crates/ui-egui/src/canvas/list.rs index a02a0bbd6..6b4aefa9a 100644 --- a/crates/ui-egui/src/canvas/list.rs +++ b/crates/ui-egui/src/canvas/list.rs @@ -63,11 +63,16 @@ pub(super) fn rebuilt_preview<'a>(doc: &cadcraft_doc::Drawing, ents: impl IntoIt /// A rebuild only the view asks for (a new zoom band, a pan out of the built area) runs in the /// background while the current list is drawn (see [`rebuild`]); a changed drawing, or no list /// yet, is built at once. +/// The font set text is drawn with: TrueType fonts (font folders, rescans) and SHX fonts +/// (drawing folders, font folders, the search path) can each change what text looks like. Every +/// cache of drawn geometry keys on it. +pub(super) fn font_generation() -> u64 { + cadcraft_fonts::ttf::generation().wrapping_add(cadcraft_fonts::shx::generation() << 32) +} + pub(super) fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], ctx: &egui::Context) { let px = 1.0 / xf.scale; - // TrueType fonts (font folders, rescans) and SHX fonts (drawing folders, font folders, - // the search path) can each change what text looks like. - let fonts = cadcraft_fonts::ttf::generation().wrapping_add(cadcraft_fonts::shx::generation() << 32); + let fonts = font_generation(); if app.canvas.font_generation != fonts { app.canvas.font_generation = fonts; app.canvas.list = None; @@ -189,7 +194,8 @@ impl OnlyList { let key = { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, band, &only.handles, format!("{:?}", only.extra)).hash(&mut h); + (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, band, &only.handles, format!("{:?}", only.extra), font_generation()) + .hash(&mut h); outline.into_iter().flatten().for_each(|q| (q.x.to_bits(), q.y.to_bits()).hash(&mut h)); h.finish() }; diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index 3e065f810..202fab8c2 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -286,7 +286,8 @@ impl VpHighlight { let key = { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); - (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), handles).hash(&mut h); + (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), handles, super::list::font_generation()) + .hash(&mut h); h.finish() }; if self.key != Some(key) { From 56246049bcb123594dca11d3d335f91308d61133 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 13:15:29 +1100 Subject: [PATCH 254/531] UCS: point filters take their coordinates in the UCS (review) .X/.Y/.XY combined the two points' world coordinates, so in a turned UCS the result was not the point the user meant. Combine them in the UCS and convert back. Test point_filters_and_ortho_follow_the_ucs (ortho and tracking were already done in this PR). --- crates/engine/src/pointmod.rs | 9 ++++++++- crates/engine/tests/ucs_drafting.rs | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/pointmod.rs b/crates/engine/src/pointmod.rs index dcbd861bc..5d8762beb 100644 --- a/crates/engine/src/pointmod.rs +++ b/crates/engine/src/pointmod.rs @@ -61,6 +61,13 @@ impl Axes { pub fn combine(self, first: Vec2, second: Vec2) -> Vec2 { Vec2::new(if self.x { first.x } else { second.x }, if self.y { first.y } else { second.y }) } + + /// [`Axes::combine`] with the coordinates read in the UCS `ucs`, where the user typed and saw + /// the points: `.X` takes the first point's X along the UCS X axis, not the world's. + pub fn combine_in(self, ucs: &crate::ucs::UcsFrame, first: Vec2, second: Vec2) -> Vec2 { + let r = ucs.to_wcs(self.combine(ucs.to_ucs(first), ucs.to_ucs(second))); + if r.is_finite() { r } else { self.combine(first, second) } + } } /// A pending point modifier. @@ -336,7 +343,7 @@ impl Session { // The offset point is already measured from the base (`@` reads the last point). Frame::From { base: Some(_) } => {} Frame::Mid { first: Some(f) } => p = (f + p) * 0.5, - Frame::Filter { keep, first: Some(f) } => p = keep.combine(f, p), + Frame::Filter { keep, first: Some(f) } => p = keep.combine_in(&self.input_ucs(), f, p), Frame::Angle { base, dir } => p = base + dir * (p - base).dot(dir), Frame::Snap { mode: 0 } => {} Frame::Snap { mode } => { diff --git a/crates/engine/tests/ucs_drafting.rs b/crates/engine/tests/ucs_drafting.rs index acb7715f9..0231c7998 100644 --- a/crates/engine/tests/ucs_drafting.rs +++ b/crates/engine/tests/ucs_drafting.rs @@ -221,3 +221,19 @@ fn dimlinear_horizontal_and_vertical_follow_the_ucs() { s.cmdline("dimlinear 0,0 0,10 5,5").unwrap(); assert!(ang_eq(last_dim_rotation(&s), 90.0 * DEG)); } + +/// A point filter takes its coordinates in the UCS: `.X` of one point and `YZ` of another make +/// the point with the first's UCS X and the second's UCS Y. +#[test] +fn point_filters_and_ortho_follow_the_ucs() { + let mut s = session(); + turned(&mut s, 90.0); + s.cmdline("line 0,0").unwrap(); + s.cmdline(".x").unwrap(); + s.cmdline("3,4").unwrap(); + s.cmdline("7,9").unwrap(); + s.cmdline("").unwrap(); + let l = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap(); + // UCS (3, 9): the UCS at (5, 5) turned 90° puts it at world (5 - 9, 5 + 3). + assert!(near(l.b.xy(), -4.0, 8.0), "{l:?}"); +} From 5b2c7bb0fbd48c632480f885a39b840ce5cf5d08 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 19:34:32 -0700 Subject: [PATCH 255/531] Fonts: a font's family name falls back to the family when the typographic one is blank (CodeRabbit on #2803) --- crates/fonts/src/ttf.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 5125d0a24..29a8b686c 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -83,14 +83,14 @@ impl Face { pub fn has_glyph(&self, c: char) -> bool { self.font().is_some_and(|f| f.charmap().map(c).is_some()) } - /// The family name, as the font gives it. + /// The family name, as the font gives it (the typographic family, else the family when that + /// is missing or blank). pub fn family_name(&self) -> Option { let f = self.font()?; - [skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME] - .into_iter() - .find_map(|id| f.localized_strings(id).next().map(|s| s.to_string())) - .map(|s| s.chars().filter(|c| !c.is_control()).take(80).collect::()) - .filter(|s| !s.trim().is_empty()) + [skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME].into_iter().find_map(|id| { + let s = f.localized_strings(id).next()?.to_string(); + Some(s.chars().filter(|c| !c.is_control()).take(80).collect::()).filter(|s| !s.trim().is_empty()) + }) } /// The glyph ids the face's character map gives `chars` (`None` for an unmapped one). From c397ab1e9e1f212887ae243084794c59cf78971e Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 13:55:27 +1100 Subject: [PATCH 256/531] OLE2FRAME: the frame can be picked by its edges (review on #2587) An OLE2FRAME is drawn but prims() gave nothing for it, so hit testing never saw it and a click on its outline picked nothing. prims() now returns the frame's four edges from the same corner helper the extents use, so the extents arm is gone. The renderer keeps its closed-polyline arm (one joined outline, not four segments). Test: clicking_an_ole_frame_edge_selects_it. --- crates/doc/src/entity.rs | 4 ++++ crates/doc/src/extents.rs | 2 -- crates/engine/src/select.rs | 15 +++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 1237463f1..d24f7f49b 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -264,6 +264,10 @@ impl EntityKind { EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())], EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())], EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())], + // An OLE object's content is not drawn, but its frame is: the edges between its corners. + EntityKind::Unknown(u) if u.is_ole_frame() => crate::ole_frame(&u.tags) + .map(|q| q.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect()) + .unwrap_or_default(), EntityKind::Unknown(_) => Vec::new(), } } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 55138649d..6584980ac 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -429,8 +429,6 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< Bounds2::from_points([o, o + u, o + v, o + u + v]) } EntityKind::LwPolyline(p) => lwpolyline_bounds(p), - // An OLE object's content is not drawn, but its frame is, so the frame counts (#2422). - EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points), kind => { let mut b = Bounds2::EMPTY; for p in kind.prims() { diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 6721cdad8..a3d361e84 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -507,6 +507,21 @@ mod tests { assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line)); } + /// An OLE2FRAME draws as its frame, so a click on an edge picks it (review on #2587); a click in + /// the middle of the frame, or on a frame without both corners, does not. + #[test] + fn clicking_an_ole_frame_edge_selects_it() { + let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() }; + let frame = |tags: Vec| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags }); + let mut d = Drawing::new_metric(); + let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap(); + d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap(); + assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -19.0), 0.2), Some(h), "top edge"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(35.0, -20.5), 0.2), Some(h), "right edge"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -20.5), 0.2), None, "inside the frame"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(80.0, 80.0), 0.2), None, "a frame without a second corner"); + } + /// A block holding a diagonal dashed line, inserted at `scale`. fn dashed_block(length: f64, scale: f64) -> (Drawing, Handle) { let mut d = Drawing::new_imperial(); From a779dadad597b0821f7d6ba1f3ba665dba9cb711 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 13:57:06 +1100 Subject: [PATCH 257/531] OLE2FRAME: corner match and rotation bound scale with the coordinates; hex keeps its case (review on #2587) The corner match was capped at 1e-6, under one ulp above about 8.6e9, so a frame there never matched its header; a few ulps of the larger value now also match. The rotation bound had a floor of 1 on the scale, so a small real turn at a tiny scale passed; it is now purely relative. Hex digits are re-encoded in the case of the digit at the same place, so untouched bytes keep their text. Tests: ole_frame_moves_at_2e10_with_a_one_ulp_text_corner, ole_frame_refuses_a_small_turn_at_a_tiny_scale, moving_an_ole_frame_keeps_each_hex_digits_case. --- crates/doc/src/extents.rs | 102 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 98 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 6584980ac..2e3f16a48 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -96,7 +96,12 @@ fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4 // other header is not ours to rewrite. let [x1, y1, x2, y2] = frame; let want = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]; - let near = |a: f64, b: f64| (a - b).abs() <= (1e-9 * a.abs().max(b.abs()).max(1.0)).min(CORNER_EPS); + // The floor is the fixed-ceiling match; above about 8.6e9 one ulp exceeds it, so a few ulps of the + // larger value also match. + let near = |a: f64, b: f64| { + let m = a.abs().max(b.abs()); + (a - b).abs() <= (1e-9 * m.max(1.0)).min(CORNER_EPS).max(4.0 * f64::EPSILON * m) + }; for (c, (wx, wy)) in want.iter().enumerate() { let at = OLE_HEADER + c * 24; let rd = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes); @@ -117,15 +122,39 @@ fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4 let mut pos = 0; for (i, n) in spans { let (Some(t), Some(chunk)) = (tags.get_mut(i), bytes.get(pos..pos + n)) else { return }; - let lower = t.value.bytes().any(|b| b.is_ascii_lowercase()); - let hex: String = chunk.iter().map(|b| if lower { format!("{b:02x}") } else { format!("{b:02X}") }).collect(); // Leave any padding around the digits, and the digits after the header, as they were. let start = t.value.len() - t.value.trim_start().len(); + let hex = recase(chunk, t.value.get(start..).unwrap_or_default()); t.value.replace_range(start..start + 2 * n, &hex); pos += n; } } +/// The hex of `chunk`, each digit in the case of the digit at the same place in `old`. A digit that +/// was a number and becomes a letter takes the case of the nearest letter in `old`, upper when there +/// is none, so bytes that did not change keep their exact text. +fn recase(chunk: &[u8], old: &str) -> String { + let old = old.as_bytes(); + let lower_at = |i: usize| -> bool { + if let Some(c) = old.get(i).filter(|c| c.is_ascii_alphabetic()) { + return c.is_ascii_lowercase(); + } + let nearest = (1..=old.len()).find_map(|d| { + let before = i.checked_sub(d).and_then(|j| old.get(j)).filter(|c| c.is_ascii_alphabetic()); + before.or_else(|| old.get(i + d).filter(|c| c.is_ascii_alphabetic())) + }); + nearest.is_some_and(|c| c.is_ascii_lowercase()) + }; + let mut out = String::with_capacity(chunk.len() * 2); + for (k, b) in chunk.iter().enumerate() { + for (j, d) in [b >> 4, b & 15].into_iter().enumerate() { + let digit = char::from_digit(d.into(), 16).unwrap_or('0'); + out.push(if lower_at(2 * k + j) { digit } else { digit.to_ascii_uppercase() }); + } + } + out +} + /// Ceiling for the tolerance when matching the corners in the OLE data to the frame's. The header /// holds the same f64 the frame groups print, so they agree to a few ulps; a fixed ceiling keeps /// distinct geometry from matching at large coordinates, where a relative tolerance would grow to @@ -163,7 +192,7 @@ pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool { const T: f64 = 1e-12; // The tolerance grows with the scale: a matrix built from two angles (ALIGN) leaves rounding noise // in b and c of about `scale * 1e-16`. - let t = T * m.a.abs().max(1.0); + let t = T * m.a.abs(); m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t } @@ -868,4 +897,69 @@ mod tests { assert_eq!(after, rest, "every group after the first is string-identical"); assert_eq!(tags.get(4).map(|t| t.value.len()), Some(254), "the first group keeps its length"); } + + /// Above about 8.6e9 one ulp of an f64 is more than the fixed ceiling on the corner match, so a + /// text corner one ulp from the header double must still count as the same corner (review on + /// #2587). + #[test] + fn ole_frame_moves_at_2e10_with_a_one_ulp_text_corner() { + let mut tags = big_frame(0.0); + // Rebuild the frame at 2e10: the header keeps the exact corners, the text is one ulp off. + let (x1, y1, x2, y2) = (2e10f64, 2e10f64, 2e10 + 10.0, 2e10 + 5.0); + let mut blob = vec![1u8, 0]; + for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] { + for v in [x, y, 7.0] { + blob.extend_from_slice(&v.to_le_bytes()); + } + } + let text_x1 = f64::from_bits(x1.to_bits() + 1); + tags[0].value = text_x1.to_string(); + tags[1].value = y1.to_string(); + tags[2].value = x2.to_string(); + tags[3].value = y2.to_string(); + if let Some(t) = tags.last_mut() { + t.value = blob.iter().map(|b| format!("{b:02X}")).collect(); + } + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1e4, 1e4))); + assert_eq!(header_corners(&tags)[0].0, text_x1 + 1e4, "the header moved with the frame"); + } + + /// Below scale 1 the rotation bound is still relative to the scale: a small real turn at a tiny + /// scale is refused, and so is a non-uniform scale whose two factors differ by more than a + /// relative 1e-12 (review on #2587). + #[test] + fn ole_frame_refuses_a_small_turn_at_a_tiny_scale() { + use cadcraft_geom::Mat3; + let p = Vec2::new(3.0, -4.0); + let turned = Mat3::scale_about(p, 1e-9).then_before(Mat3::rotate_about(p, 0.05f64.to_radians())); + assert!(!ole_frame_accepts(&turned)); + assert!(ole_frame_accepts(&Mat3::scale_about(p, 1e-9))); + assert!(!ole_frame_accepts(&Mat3::scale(1e-6, 1e-6 + 5e-13))); + } + + /// Hex digits keep the case they had: bytes the transform does not change come back as the + /// identical text, also in a group that mixes upper and lower case (review on #2587). + #[test] + fn moving_an_ole_frame_keeps_each_hex_digits_case() { + let mut tags = small_frame(); + let old = tags.last().map(|t| t.value.clone()).unwrap_or_default(); + let mixed: String = old.chars().enumerate().map(|(i, c)| if i < 24 { c.to_ascii_lowercase() } else { c }).collect(); + assert_ne!(mixed, old); + if let Some(t) = tags.last_mut() { + t.value = mixed.clone(); + } + ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0))); + let new = tags.last().map(|t| t.value.clone()).unwrap_or_default(); + assert_eq!(new.len(), mixed.len()); + let byte = |s: &str, i: usize| s.get(2 * i..2 * i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); + let mut same = 0; + for i in 0..mixed.len() / 2 { + if byte(&mixed, i) == byte(&new, i) { + same += 1; + assert_eq!(mixed.get(2 * i..2 * i + 2), new.get(2 * i..2 * i + 2), "byte {i}"); + } + } + assert!(same > 40, "most of the header is unchanged: {same}"); + assert_eq!(header_corners(&tags)[0], (40.0, -14.0)); + } } From 843ffb6507ed37185282eead34d0f75cb9e746ef Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 19:58:44 -0700 Subject: [PATCH 258/531] Fonts: a registered font outlives a rescan, also beside a file of the same stem (CodeRabbit on #2803) --- crates/fonts/src/ttf.rs | 14 +++++++++++--- crates/fonts/tests/ttf_font_folders.rs | 6 ++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 29a8b686c..2f4ffab24 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -245,6 +245,9 @@ struct Db { paths: HashMap, /// Loaded or registered font file bytes, by lower-case file stem. files: HashMap>>, + /// The keys of `files` given by [`register`]: kept over a file of the same stem, and by a + /// rescan. + registered: std::collections::HashSet, /// Name lookups already answered, found or not. resolved: HashMap>, fallback: Fallback, @@ -454,9 +457,11 @@ pub fn set_font_dirs>(dirs: &[S]) { /// Forget what was found and look for fonts again (files added to a font folder). pub fn rescan() { let mut g = lock(); - // Fonts registered by name (no file behind them) stay. + // Fonts registered by name stay, also where a found file has the same stem; bytes read + // from found files go. let paths = std::mem::take(&mut g.paths); - g.files.retain(|k, _| !paths.contains_key(k)); + let Db { files, registered, .. } = &mut *g; + files.retain(|k, _| registered.contains(k) || !paths.contains_key(k)); g.scanned = false; g.resolved.clear(); g.fallback = Fallback::default(); @@ -797,7 +802,9 @@ pub(crate) fn rank_fallback(stems: &[String]) -> Vec { /// Register font bytes under a name (web builds and tests). pub fn register(name: &str, bytes: Vec) { let mut g = lock(); - g.files.insert(key(name), Arc::new(bytes)); + let k = key(name); + g.files.insert(k.clone(), Arc::new(bytes)); + g.registered.insert(k); g.resolved.clear(); g.fallback = Fallback::default(); } @@ -809,6 +816,7 @@ pub(crate) fn register_static(name: &str, bytes: &'static [u8]) { let mut g = lock(); let k = key(name); g.files.remove(&k); + g.registered.remove(&k); g.paths.insert(k, Source::Static(bytes)); g.resolved.clear(); g.fallback = Fallback::default(); diff --git a/crates/fonts/tests/ttf_font_folders.rs b/crates/fonts/tests/ttf_font_folders.rs index 6ad257788..e8e3debda 100644 --- a/crates/fonts/tests/ttf_font_folders.rs +++ b/crates/fonts/tests/ttf_font_folders.rs @@ -42,6 +42,11 @@ fn a_font_in_a_user_folder_is_found_listed_and_dropped_with_the_folder() { if !copy_into(&src, &dir) { return; } + // A font registered by name, with a file of the same stem in the folder: looking for fonts + // again (twice, as the folder comes and goes) keeps the registered bytes. + let Ok(bytes) = std::fs::read(&src) else { return }; + let _ = std::fs::copy(&src, dir.join("CadcraftRegistered.ttf")); + ttf::register("CadcraftRegistered.ttf", bytes); let before = ttf::generation(); ttf::set_font_dirs(&[dir.to_string_lossy().to_string()]); assert!(ttf::generation() > before); @@ -55,5 +60,6 @@ fn a_font_in_a_user_folder_is_found_listed_and_dropped_with_the_folder() { } ttf::set_font_dirs::<&str>(&[]); assert!(ttf::find("CadcraftTestFace.ttf").is_none()); + assert!(ttf::find("CadcraftRegistered.ttf").is_some(), "a registered font outlives a rescan"); let _ = std::fs::remove_dir_all(&dir); } From 485c74da6b7bb798805c743b636ebd2e9b0d6411 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 13:58:15 +1100 Subject: [PATCH 259/531] ARRAY: check OLE frames once (review on #2587) copy_all scanned the selection for an OLE frame once per matrix before copying. It now looks at the objects once and then only tests each matrix. Covered by the existing refusal tests (classic_polar_array_refuses_a_turned_frame_but_not_an_upright_one). --- crates/engine/src/cmd/array.rs | 5 +++-- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/transform.rs | 26 ++++++++++++++--------- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 5fc16b310..c4948c9e0 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -250,8 +250,9 @@ fn copy_all(s: &mut Session, hs: &[Handle], mats: impl Iterator) -> // Every copy is checked before the first is made: a refusal part way would leave the copies // already added in the drawing (a failed command is not rolled back). let mats: Vec = mats.collect(); - for m in &mats { - super::modify::refuse_ole_frames(s, hs, m, true)?; + // The objects are looked at once; then a matrix only needs its own check. + if super::modify::holds_ole_frame(s, hs, true)? && mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) { + return Err(super::modify::ole_refusal()); } let mut n = 0; for m in &mats { diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 825add837..f9fae40e2 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -35,7 +35,7 @@ use oops::run_oops; pub(crate) use oops::{Erased, erase_kept}; use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; -pub(crate) use transform::{refuse_ole_frames, transform_entities}; +pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities}; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; pub(crate) use trim::{Edges, extend, trim}; diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 219468f93..df43f782c 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -24,23 +24,29 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, /// An OLE2FRAME only translates or scales uniformly (its corners stay axis aligned): refuse any other `m` before anything /// changes, instead of reporting success and leaving the frame where it was. pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<()> { - if cadcraft_doc::ole_frame_accepts(m) { + if cadcraft_doc::ole_frame_accepts(m) || !holds_ole_frame(s, hs, copy)? { return Ok(()); } + Err(ole_refusal()) +} + +/// The refusal for a transform an OLE2FRAME cannot take. +pub(crate) fn ole_refusal() -> crate::EngineError { + crate::EngineError::Other( + "An OLE object can only be moved, copied or scaled uniformly; other transforms (rotation, mirroring, non-uniform scale, alignment) are not supported.".into(), + ) +} + +/// Whether `hs` holds an OLE2FRAME a transform would touch. An in-place edit (`copy` false) skips +/// an object on a locked layer (see edit_entities), so such a frame cannot be refused. +pub(crate) fn holds_ole_frame(s: &Session, hs: &[Handle], copy: bool) -> Result { let d = s.doc()?; - let ole = |h: &Handle| { + Ok(hs.iter().any(|h| { d.entity(*h).is_some_and(|e| { - // An in-place edit skips an object on a locked layer (see edit_entities), so it cannot be refused. let locked = !copy && d.layer(&e.common.layer).is_some_and(|l| l.locked); !locked && matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.is_ole_frame()) }) - }; - if hs.iter().any(ole) { - return Err(crate::EngineError::Other( - "An OLE object can only be moved, copied or scaled uniformly; other transforms (rotation, mirroring, non-uniform scale, alignment) are not supported.".into(), - )); - } - Ok(()) + })) } /// `p` at the current elevation (ELEVATION), the Z AutoCAD gives a point entered without one. From c4d9e6ac64bea4bb54b23fcbf32c21dc997f279c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:33:26 +0100 Subject: [PATCH 260/531] fix(ui): About credits tables fit without side-scrolling and their columns resize (#2747) * fix(ui): About credits tables fit without side-scrolling and their columns resize The Contributors table and the Models table were egui Grids inside a two-way scroll area: they opened wider than the dialog, so they scrolled sideways, and Company and Model sat almost touching. Both are now egui_extras tables. Each column opens at the width of its header and widest cell, the spare width goes to the text columns (Name; Company and Model), and every column edge can be dragged. Widening a column grows the table like a spreadsheet, and only then does it scroll sideways; the header stays put while the rows scroll. Counts and dates are right-aligned and every cell is vertically centred. The sorted column stays highlighted and its direction shows on the toolbar's sort-order button, so headers no longer reserve room for an arrow. The opening widths come from fit_widths, a pure function with unit tests that a fitted table fills its room exactly and that only the text columns give way when room is short. The About dialog opens 820 points wide, so every column fits at its natural width. Co-Authored-By: Claude Opus 5.5 * Let every credits column be dragged, and refit changed tables The last column was egui's remainder column, which has no drag handle, so it could only be resized from the edge before it. It is now an ordinary column with its own handle. A table keeps its column widths, so switching to a longer name left the Name column at its old width and clipped the text. The table now goes back to the opening fit whenever that fit changes: a longer widest cell or a resized window. Dragged widths are dropped at that point. fit_widths could overflow the room when one column hit the minimum, because the other columns did not take up its share. Columns now give way in proportion to their width above the minimum. Co-Authored-By: Claude Opus 5.5 * Refit credits tables on what they measure, not the fitted widths Comparing the fitted widths missed the case it was meant for. Name is the only growing column, so a longer name takes its extra width from the spare room and the fit comes out the same: a dragged Name width stayed, clipping the longer name. It could also drop dragged widths by accident. The fit comes from the available width inside the scroll area, which scrolling can nudge, so scrolling a widened table could reset it. The table now compares the natural widths and the clip rect's width, which scrolling does not move. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 39 +++- Cargo.toml | 2 + crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/credits.rs | 376 +++++++++++++++++++++++++++++----- crates/ui-egui/src/dialogs.rs | 2 +- 5 files changed, 359 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 78591de23..c08b8f4bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -808,6 +808,7 @@ dependencies = [ "craft-window", "egui", "egui-wgpu", + "egui_extras", "egui_kittest", "image", "log", @@ -1513,6 +1514,19 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools", + "log", + "profiling", +] + [[package]] name = "egui_glow" version = "0.37.0" @@ -1581,6 +1595,26 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -6253,11 +6287,6 @@ name = "egui_demo_lib" version = "0.37.0" source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - [[patch.unused]] name = "egui_inspection" version = "0.37.0" diff --git a/Cargo.toml b/Cargo.toml index 605fd484f..f2112a517 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -63,6 +63,8 @@ quick-xml = "0.42" craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] } craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] } +# Resizable table columns (About ▸ Contributors / Models); no image loaders. +egui_extras = { version = "0.37", default-features = false } egui_kittest = "0.37" eframe = { version = "0.37", default-features = false } egui-wgpu = "0.37" diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index d21c2d8ca..916ab6456 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -19,6 +19,7 @@ cadcraft-engine = { workspace = true } cadcraft-fonts = { workspace = true } craft-window = { workspace = true } egui = { workspace = true } +egui_extras = { workspace = true } # GPU canvas paint callback (same egui-wgpu/wgpu eframe uses with its "wgpu" feature). egui-wgpu = { workspace = true } serde = { workspace = true } diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index 6ebcb362e..fe31fcfa0 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -253,12 +253,14 @@ pub fn contributors_ui(ui: &mut egui::Ui) { .weak(), ); ui.separator(); - egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { - if list.is_empty() { - ui.label(crate::tl!("No contributor data was built into this copy.")); - } else if v.table { - table(ui, &list, &mut v); - } else { + if list.is_empty() { + ui.label(crate::tl!("No contributor data was built into this copy.")); + } else if v.table { + // The table scrolls vertically itself, under a fixed header; it only scrolls sideways + // once its columns are dragged wider than the dialog. + egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| table(ui, &list, &mut v)); + } else { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.horizontal_wrapped(|ui| { for (i, c) in list.iter().enumerate() { if i > 0 { @@ -267,43 +269,154 @@ pub fn contributors_ui(ui: &mut egui::Ui) { ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary()); } }); - } - }); + }); + } ui.data_mut(|d| d.insert_temp(id, v)); } -fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { - egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| { - for k in SortKey::ALL { - let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" }; - if ui - .button(RichText::new(format!("{}{arrow}", crate::i18n::t(k.label().1))).strong()) - .on_hover_text(crate::i18n::t(k.label().0)) - .clicked() - { - if v.key == k { - v.ascending = !v.ascending; - } else { - v.key = k; - v.ascending = k.default_ascending(); - } +/// How the contributor table's spare width is shared out: all of it to Name. +const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + +/// How the model table's spare width is shared out: to Company and Model, the text columns. +const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0]; + +/// The narrowest a column can be dragged. +const MIN_COLUMN: f32 = 28.0; + +/// The width a column needs for its header and its widest cell. +fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator) -> f32 { + let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; + let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max); + widest + 2.0 * ui.spacing().button_padding.x +} + +/// Opening column widths: each column's natural width, with the spare room shared out by `grow`, +/// so the columns fill `room` exactly. When there is too little room, only the growing columns +/// give way, each in proportion to its width above [`MIN_COLUMN`], and none goes below that. +fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec { + let spare = room - natural.iter().sum::(); + let weight = grow.iter().sum::(); + let slack = |w: f32| (w - MIN_COLUMN).max(0.0); + let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| slack(*w)).sum(); + natural + .iter() + .zip(grow) + .map(|(w, g)| { + if *g > 0.0 && spare >= 0.0 { + w + spare * g / weight + } else if *g > 0.0 && flexible > 0.0 { + w - (-spare).min(flexible) * slack(*w) / flexible + } else { + *w } - } - ui.end_row(); - for c in list { - ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary()); - ui.label(group(c.prs)); - ui.label(group(c.commits)); - ui.label(group(c.lines_added)); - ui.label(group(c.lines_deleted)); - ui.label(signed(c.lines_delta())); - ui.label(group(c.binary_added)); - ui.label(group(c.binary_deleted)); - ui.label(day(c.first_commit)); - ui.label(day(c.last_commit)); - ui.end_row(); - } - }); + }) + .collect() +} + +/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls +/// sideways. Every column, the last included, can be dragged wider or narrower at its right edge: +/// only a table dragged wider than the window scrolls sideways. Text too long for its column is +/// clipped. When a column's natural width or the window changes, the columns go back to a new fit, +/// dropping any dragged widths. +fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> { + // Every cell is followed by the item gap, and the vertical scrollbar keeps its margins. + let s = ui.spacing(); + let gaps = s.item_spacing.x * natural.len() as f32; + let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin; + let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0)); + // The table keeps its own column widths, so a change in what they were fitted to has to clear + // them. A longer name can leave the fit itself unchanged, and scrolling can nudge the available + // width, so this compares the natural widths and the clip rect, which scrolling never moves. + let fit = egui::Id::unique(("credits_fit", id)); + let measured = (natural.to_vec(), ui.clip_rect().width()); + let refit = ui.data_mut(|d| d.get_temp::<(Vec, f32)>(fit)).as_ref() != Some(&measured); + ui.data_mut(|d| d.insert_temp(fit, measured)); + let mut t = + egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY); + if refit { + t.reset(); + } + for w in widths { + t = t.column(egui_extras::Column::initial(w).at_least(MIN_COLUMN).clip(true)); + } + t +} + +/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred. +fn aligned(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }; + ui.with_layout(layout, add).inner +} + +fn row_height(ui: &egui::Ui) -> f32 { + ui.text_style_height(&egui::TextStyle::Body) + 6.0 +} + +/// One contributor's table cells after the name, in `SortKey::ALL` order. +fn cells(c: &Contributor) -> [String; 9] { + [ + group(c.prs), + group(c.commits), + group(c.lines_added), + group(c.lines_deleted), + signed(c.lines_delta()), + group(c.binary_added), + group(c.binary_deleted), + day(c.first_commit).to_string(), + day(c.last_commit).to_string(), + ] +} + +/// A contributor-table header. The sorted column is highlighted; its direction shows on the +/// toolbar's sort-order button, so no arrow widens the column. +fn header_text(k: SortKey) -> RichText { + RichText::new(crate::i18n::t(k.label().1)).strong() +} + +fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { + let h = row_height(ui); + let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect(); + let widths: Vec = SortKey::ALL + .iter() + .enumerate() + .map(|(i, &k)| match i.checked_sub(1) { + None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))), + Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())), + }) + .collect(); + fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW) + .header(h + 4.0, |mut header| { + for k in SortKey::ALL { + header.col(|ui| { + let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))) + .on_hover_text(crate::i18n::t(k.label().0)); + + if r.clicked() { + if v.key == k { + v.ascending = !v.ascending; + } else { + v.key = k; + v.ascending = k.default_ascending(); + } + } + }); + } + }) + .body(|mut body| { + for (c, cells) in list.iter().zip(rows) { + body.row(h, |mut row| { + row.col(|ui| { + aligned(ui, false, |ui| ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login))) + .on_hover_text(c.summary()); + }); + for text in cells { + row.col(|ui| { + aligned(ui, true, |ui| ui.label(text)); + }); + } + }); + } + }); } /// About ▸ Models: AI models credited in Co-Authored-By trailers. @@ -313,22 +426,48 @@ pub fn models_ui(ui: &mut egui::Ui) { return; } let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1); - egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { - egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| { - for h in ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"] { - ui.label(RichText::new(crate::i18n::t(h)).strong()); - } - ui.end_row(); - for m in MODELS { - ui.label(m.company); - ui.label(m.model); - ui.label(m.version); - ui.label(group(m.commits)); - ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64)); - ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted))); - ui.end_row(); - } - }); + let h = row_height(ui); + let titles = ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"]; + // Company, Model and Version read as text; the counts line up on the right. + let right = [false, false, false, true, true, true]; + let rows: Vec<[String; 6]> = MODELS + .iter() + .map(|m| { + [ + m.company.to_string(), + m.model.to_string(), + m.version.to_string(), + group(m.commits), + format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64), + format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)), + ] + }) + .collect(); + let widths: Vec = titles + .iter() + .enumerate() + .map(|(i, title)| natural(ui, RichText::new(crate::i18n::t(title)).strong(), rows.iter().filter_map(|r| r.get(i).cloned()))) + .collect(); + egui::ScrollArea::horizontal().id_salt("credits_models").auto_shrink([false, false]).show(ui, |ui| { + fitted_table(ui, "credits_models", &widths, &MODEL_GROW) + .header(h + 4.0, |mut header| { + for (title, r) in titles.into_iter().zip(right) { + header.col(|ui| { + aligned(ui, r, |ui| ui.label(RichText::new(crate::i18n::t(title)).strong())); + }); + } + }) + .body(|mut body| { + for cells in rows { + body.row(h, |mut row| { + for (text, r) in cells.into_iter().zip(right) { + row.col(|ui| { + aligned(ui, r, |ui| ui.label(text)); + }); + } + }); + } + }); }); } @@ -408,4 +547,131 @@ mod tests { assert_eq!(day("2026-10-07T18:45:23Z"), "2026-10-07"); assert_eq!(day(""), "—"); } + + #[test] + fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]); + let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0); + assert!((w.iter().sum::() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}"); + } + + #[test] + fn too_little_room_shrinks_only_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]); + } + + #[test] + fn a_column_at_the_minimum_leaves_the_shortfall_to_the_others() { + let w = fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 140.0); + assert!((w.iter().sum::() - 140.0).abs() < 0.01, "the columns still fit the room: {w:?}"); + assert!(w.iter().all(|c| *c >= MIN_COLUMN), "no column goes below the minimum: {w:?}"); + assert_eq!(fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 0.0), [MIN_COLUMN, MIN_COLUMN, 50.0]); + } + + const WINDOW: f32 = 640.5; + const NATURAL: [f32; 3] = [120.0, 80.0, 80.0]; + const GROW: [f32; 3] = [1.0, 0.0, 0.0]; + + /// One frame of a table long enough to scroll; the rects of its header cells. + fn table_frame(ctx: &egui::Context, width: f32, natural: &[f32], events: Vec) -> Vec { + scrolled_frame(ctx, width, natural, 0.0, events) + } + + /// [`table_frame`], scrolled `offset` points sideways. + fn scrolled_frame(ctx: &egui::Context, width: f32, natural: &[f32], offset: f32, events: Vec) -> Vec { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0))); + let raw = egui::RawInput { screen_rect, events, ..Default::default() }; + let mut cells = Vec::new(); + let out = ctx.run_ui(raw, |ui| { + cells.clear(); + egui::ScrollArea::horizontal().auto_shrink([false, false]).horizontal_scroll_offset(offset).show(ui, |ui| { + fitted_table(ui, "test", natural, &GROW) + .header(20.0, |mut header| { + for _ in natural { + header.col(|ui| cells.push(ui.max_rect())); + } + }) + .body(|mut body| { + for _ in 0..40 { + body.row(20.0, |mut row| { + for _ in natural { + row.col(|ui| { + ui.label("x"); + }); + } + }); + } + }); + }); + }); + out.drop_without_applying_deltas(); + cells + } + + /// A new context with the table open and settled, and the rects of its header cells. + fn opened_table() -> (egui::Context, Vec) { + let ctx = egui::Context::default(); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let cells = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + (ctx, cells) + } + + /// Drags a column's right edge, which runs midway through the gap after `cell`, then lets go. + fn drag_edge(ctx: &egui::Context, cell: egui::Rect, by: f32) { + use egui::{Event, Modifiers, PointerButton}; + let start = egui::pos2(cell.right() + 4.0, cell.center().y); + let halfway = start + egui::vec2(by / 2.0, 0.0); + let end = start + egui::vec2(by, 0.0); + let moved = Event::PointerMoved; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + for event in [moved(start), button(start, true), moved(halfway), moved(end), button(end, false)] { + table_frame(ctx, WINDOW, &NATURAL, vec![event]); + } + } + + #[test] + fn every_column_can_be_dragged_at_its_right_edge_and_stays_there() { + let (_, opened) = opened_table(); + for (dragged, cell) in opened.iter().enumerate() { + let (ctx, _) = opened_table(); + drag_edge(&ctx, *cell, -30.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let after = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + for (column, (was, now)) in opened.iter().zip(&after).enumerate() { + let want = if column == dragged { was.width() - 30.0 } else { was.width() }; + assert!((now.width() - want).abs() < 1.0, "dragging column {dragged}: column {column} is {now:?}, was {was:?}"); + } + } + } + + #[test] + fn a_changed_fit_replaces_the_column_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], -30.0); + let longer_name = table_frame(&ctx, WINDOW, &[200.0, 80.0, 80.0], Vec::new()); + assert!((longer_name[0].width() - opened[0].width()).abs() < 1.0, "a longer name drops a dragged width: {longer_name:?}"); + let wider = table_frame(&ctx, WINDOW, &[120.0, 200.0, 80.0], Vec::new()); + let widths: Vec = wider.iter().map(|c| c.width().round()).collect(); + assert!(widths.ends_with(&[200.0, 80.0]), "a longer cell widens its column: {widths:?}"); + assert!(wider[2].right() < WINDOW, "the table still fits the window: {wider:?}"); + let narrower = table_frame(&ctx, 400.0, &NATURAL, Vec::new()); + assert!(narrower[2].right() < 400.0, "a narrower window refits the table: {narrower:?}"); + } + + #[test] + fn scrolling_sideways_keeps_dragged_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], 100.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let dragged = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + assert!((dragged[0].width() - opened[0].width() - 100.0).abs() < 1.0, "the drag took: {dragged:?}"); + for offset in [13.3, 27.77, 41.1, 0.6] { + scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + let scrolled = scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + assert!((scrolled[0].width() - dragged[0].width()).abs() < 1.0, "scrolled {offset}: {scrolled:?}"); + } + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1f8035434..0132ea219 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -325,7 +325,7 @@ fn about(ctx: &egui::Context, open: &mut bool) { egui::Window::new(crate::tl!("About CADCraft")) .id(egui::Id::unique("About CADCraft")) .open(open) - .default_size(vec2(640.0, 420.0)) + .default_size(vec2(820.0, 420.0)) .collapsible(false) .show(ctx, |ui| { let mut tab = ui.data_mut(|d| d.get_temp::(tab_id)).unwrap_or(0); From 5b622c3d323b7af68ab4eed3911fe970151a1fbb Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 14:38:43 +1100 Subject: [PATCH 261/531] UCS: ssget windows in a turned UCS; UCS Previous after a delete; origin defaults (review) ssget W/C built a world-aligned box from two converted corners (zero width at 45 degrees); it now selects with the four converted corners as a polygon. Deleting the current named UCS pushed the old frame under the deleted name onto UCS Previous; the name is now cleared there and in every layout's history. Enter at the 3 Point origin prompt went on to nothing; it keeps the origin and asks for the X axis. The origin default is shown in the frame input is read in (world while the UCS is tilted). Tests for each. --- crates/engine/src/cmd/ucs.rs | 33 +++++++++++------- crates/engine/src/lisp/drawing.rs | 17 +++++++-- crates/engine/src/lisp/ucs_tests.rs | 17 +++++++++ crates/engine/tests/ucs.rs | 54 +++++++++++++++++++++++++++++ 4 files changed, 107 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/ucs.rs b/crates/engine/src/cmd/ucs.rs index 44590f485..4379d0185 100644 --- a/crates/engine/src/cmd/ucs.rs +++ b/crates/engine/src/cmd/ucs.rs @@ -6,7 +6,7 @@ //! UCS out of the XY plane, which CADCraft doesn't draw in yet; they say so. A UCS change is part //! of the command's undo step, as an edit is. -use cadcraft_doc::{Drawing, EntityKind}; +use cadcraft_doc::{Drawing, EntityKind, Ucs}; use cadcraft_geom::{Vec2, Vec3}; use serde_json::{Value, json}; @@ -327,22 +327,23 @@ fn delete(s: &mut Session, patterns: &str) -> Result { if gone.is_empty() { return Ok(0); } - let (frame, current) = s.ucs_named(); s.doc_mut()?.ucss.retain(|u| !gone.iter().any(|g| g == &u.name)); - if gone.iter().any(|g| g.eq_ignore_ascii_case(¤t)) { - s.set_ucs(frame, "")?; - } - // The other spaces whose current UCS carries a deleted name keep their axes and lose the name - // too (model space's UCSNAME, every layout's UCS). + // Wherever a deleted name is current (model space's UCSNAME, every layout's UCS) the UCS keeps + // its axes and loses the name; the UCS Previous histories keep their frames the same way. let d = s.doc_mut()?; let is_gone = |n: &str| gone.iter().any(|g| g.eq_ignore_ascii_case(n.trim())); if is_gone(&d.header.str("UCSNAME", "")) { d.header.set_str("UCSNAME", ""); } - for l in &mut d.layouts { - if let Some(u) = l.ucs.as_mut().filter(|u| is_gone(&u.name)) { + let unname = |u: &mut Ucs| { + if is_gone(&u.name) { u.name.clear(); } + }; + d.ucs_previous.iter_mut().for_each(unname); + for l in &mut d.layouts { + l.ucs.iter_mut().for_each(unname); + l.ucs_previous.iter_mut().for_each(unname); } Ok(gone.len()) } @@ -435,8 +436,11 @@ impl Interactive for UcsM { match &self.stage { Stage::Main => Prompt::new("Specify origin of UCS", Accept::POINT).kw(OPTIONS).default("World"), Stage::OriginOnly | Stage::ThreePoint => { - // Input here is read in the current UCS, where the UCS's own origin is 0,0,0. - Prompt::new("Specify new origin point", Accept::POINT).default("0,0,0") + // The origin as input is read: in the UCS where that is the current one (so 0,0,0), + // in the world while the current UCS is tilted out of the XY plane. + let o = s.ucs().origin; + let (p, z) = if s.input_ucs().is_planar() { (s.input_ucs().to_ucs(o.xy()), 0.0) } else { (o.xy(), o.z) }; + Prompt::new("Specify new origin point", Accept::POINT).default(format!("{},{},{}", p.x, p.y, z)) } Stage::XPoint(o) => Prompt::new("Specify point on X-axis", Accept::POINT).default("Accept").base(o.xy()), Stage::XyPoint(o, _) => Prompt::new("Specify point on the XY plane", Accept::POINT).default("Accept").base(o.xy()), @@ -502,7 +506,12 @@ impl Interactive for UcsM { s.set_ucs(f, "")?; Ok(Step::Done) } - (Stage::OriginOnly | Stage::ThreePoint, Input::Enter) => Ok(Step::Done), + (Stage::OriginOnly, Input::Enter) => Ok(Step::Done), + // Enter keeps the origin and goes on to the axes, as a typed point would. + (Stage::ThreePoint, Input::Enter) => { + self.stage = Stage::XPoint(s.ucs().origin); + Ok(Step::Continue) + } (Stage::XPoint(o), Input::Enter) => { set_by_points(s, o, None, None)?; Ok(Step::Done) diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 133347815..8762f7d3a 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -650,10 +650,23 @@ pub fn ssget(ctx: &mut Ctx<'_>, a: Vec) -> Result { Some("P") => ctx.s.state().map(|st| st.previous_selection.clone()).unwrap_or_default(), Some("I") => ctx.s.selection(), Some("W") | Some("C") => { - let (p1, p2) = (point(0)?, point(1)?); + let corner = |i: usize| -> Result<[f64; 3], LispError> { + let v = pts.get(i).ok_or_else(|| args_err(true))?; + v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", v)) + }; + let (u1, u2) = (corner(0)?, corner(1)?); + let crossing = mode.as_deref() == Some("C"); let s = &*ctx.s; let Ok(d) = s.doc() else { return Ok(Flow::Value(Value::Nil)) }; - crate::select::select_window(d, &space, cadcraft_geom::Bounds2::from_points([p1, p2]), mode.as_deref() == Some("C")) + if frame.rotation() == 0.0 { + let (p1, p2) = (frame.to_wcs(Vec2::new(u1[0], u1[1])), frame.to_wcs(Vec2::new(u2[0], u2[1]))); + crate::select::select_window(d, &space, cadcraft_geom::Bounds2::from_points([p1, p2]), crossing) + } else { + // A window drawn in a turned UCS is a turned rectangle in the world: all four + // corners, not the box around two of them. + let corners = [(u1[0], u1[1]), (u2[0], u1[1]), (u2[0], u2[1]), (u1[0], u2[1])].map(|(x, y)| frame.to_wcs(Vec2::new(x, y))); + crate::select::select_polygon(d, &space, &corners, crossing) + } } Some("F") | Some("WP") | Some("CP") => { let poly: Vec = diff --git a/crates/engine/src/lisp/ucs_tests.rs b/crates/engine/src/lisp/ucs_tests.rs index 072a4f3e7..d2006d11b 100644 --- a/crates/engine/src/lisp/ucs_tests.rs +++ b/crates/engine/src/lisp/ucs_tests.rs @@ -226,3 +226,20 @@ fn angtof_ignores_the_ucs() { assert_eq!(ok(&mut s, "(angtof \"0\")"), "0.0"); assert_eq!(ok(&mut s, "(angtos (angtof \"45\"))"), "\"45\""); } + +/// A window in a UCS turned 45 degrees is a turned rectangle in the world, not the box around +/// its two corners. +#[test] +fn ssget_window_in_a_45_degree_ucs() { + let mut s = session(); + s.execute("ucs", &json!({"option": "z", "angle": 45})).unwrap(); + // UCS (5, 5) is on the world Y axis, inside the window. + s.execute("circle", &json!({"center": [0.0, 5.0 * std::f64::consts::SQRT_2], "radius": 1})).unwrap(); + // World (5, 3) is UCS (5.66, -1.41): in the world box of the window, below the UCS window. + s.execute("circle", &json!({"center": [5.0, 3.0], "radius": 0.5})).unwrap(); + assert_eq!(ok(&mut s, "(sslength (ssget \"W\" '(0 0) '(10 10)))"), "1"); + let found = ok(&mut s, "(cdr (assoc 10 (entget (ssname (ssget \"W\" '(0 0) '(10 10)) 0))))"); + let f = pt(&found); + assert!(f[0].abs() < 1e-4 && (f[1] - 5.0 * std::f64::consts::SQRT_2).abs() < 1e-4, "{found}"); + assert_eq!(ok(&mut s, "(sslength (ssget \"C\" '(0 0) '(10 10)))"), "1"); +} diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs index f1d3f4d4d..42143a30a 100644 --- a/crates/engine/tests/ucs.rs +++ b/crates/engine/tests/ucs.rs @@ -640,3 +640,57 @@ fn dist_json_matches_its_message_in_a_ucs() { let w = &r["world"]; assert!(f(w, "dx").abs() < 1e-9 && (f(w, "dy") - 10.0).abs() < 1e-9 && (f(w, "angle") - 90.0).abs() < 1e-9, "{r}"); } + +/// Deleting the current named UCS leaves no trace of its name: UCS Previous goes back to the axes +/// before it, unnamed, and does not bring the deleted name back. +#[test] +fn ucs_previous_after_deleting_the_current_named_ucs() { + let mut s = session(); + typed(&mut s, &["ucs na s SITE"]); + turned(&mut s); + typed(&mut s, &["ucs na r SITE"]); + typed(&mut s, &["ucs na d SITE"]); + assert_eq!(s.ucs_named().1, ""); + assert!(s.doc().unwrap().ucs_previous.iter().all(|u| u.name.is_empty()), "{:?}", s.doc().unwrap().ucs_previous); + typed(&mut s, &["ucs p"]); + assert_eq!(s.ucs_named().1, "", "the deleted name does not come back"); + assert!(near3(s.ucs().x, Vec3::new(0.0, 1.0, 0.0)), "back to the axes before SITE: {:?}", s.ucs()); + assert_eq!(s.doc().unwrap().header.str("UCSNAME", ""), ""); +} + +/// Enter at the 3 Point origin prompt keeps the origin and asks for the X axis point. +#[test] +fn three_point_ucs_enter_keeps_the_origin() { + let mut s = session(); + turned(&mut s); + let before = s.ucs(); + s.start("ucs.3point").unwrap(); + s.cmdline("").unwrap(); + assert!(s.current_prompt().is_some_and(|p| p.message.contains("X-axis")), "{:?}", s.current_prompt().map(|p| p.message)); + // A point 10 along the UCS X axis, then Enter for the XY point: the origin is kept. + s.cmdline("10,0").unwrap(); + s.cmdline("").unwrap(); + assert!(near3(s.ucs().origin, before.origin) && near3(s.ucs().x, before.x), "{:?}", s.ucs()); +} + +/// With the current UCS tilted, points are read in the World UCS: the origin prompt shows the +/// origin there, so Enter, or the default typed back, keeps it. +#[test] +fn tilted_ucs_origin_default_keeps_the_origin() { + let mut s = session(); + { + let h = &mut s.doc_mut().unwrap().header; + h.set("UCSORG", HVal::Point(Vec3::new(50.0, 20.0, 0.0))); + h.set("UCSXDIR", HVal::Point(Vec3::new(1.0, 0.0, 0.0))); + h.set("UCSYDIR", HVal::Point(Vec3::new(0.0, 0.0, 1.0))); + } + let before = s.ucs().origin; + s.start("ucs.origin").unwrap(); + let shown = s.current_prompt().and_then(|p| p.default).unwrap_or_default(); + assert_eq!(shown, "50,20,0"); + s.cmdline(&shown).unwrap(); + assert!(near3(s.ucs().origin, before), "typed {shown:?}: {:?}", s.ucs().origin); + s.start("ucs.origin").unwrap(); + s.cmdline("").unwrap(); + assert!(near3(s.ucs().origin, before)); +} From 026f7d906b8372694c00221678992b9fb6b85cfb Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 14:38:44 +1100 Subject: [PATCH 262/531] UCS: UCSICON in the active VPORT record; DIST keeps world values with a ucs object (review) The public DXF reference has no UCSICON header variable; the setting is group 74 of the *ACTIVE VPORT record, so write and read it there. DIST's top-level angle and deltas are world values again, as ID's are, with the UCS values its message shows under ucs, computed once. --- crates/engine/src/cmd/inquiry.rs | 47 ++++++++++++++++--------------- crates/engine/tests/ucs.rs | 13 +++++---- crates/io/src/dxf_read/tables.rs | 3 ++ crates/io/src/dxf_write/header.rs | 2 -- crates/io/src/dxf_write/layout.rs | 5 ++++ crates/io/tests/ucs_roundtrip.rs | 27 +++++++++++++++--- 6 files changed, 63 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index 1278c7656..6bc6a431a 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { CommandSpec::new("dist", "Distance", run_dist) .menu(&["Tools", "Inquiry", "Distance"]) .alias(&["di"]) - .params("{p1, p2} -> {distance, angle, angleFromXY, dx, dy, dz (in the current UCS, as the message), world: {angle, angleFromXY, dx, dy, dz}, message}") + .params("{p1, p2} -> {distance, angle, angleFromXY, dx, dy, dz (world), ucs: {angle, angleFromXY, dx, dy, dz} (in the current UCS, as the message), message}") .noundo() .transparent() .interactive(|_| Ok(Box::new(DistM::default()))), @@ -192,13 +192,18 @@ fn angle_from_xy(d: Vec3) -> f64 { d.z.atan2(d.xy().len()) } -/// DIST's report: the distance, the angles and the deltas, measured in the current UCS. -fn dist_text(s: &Session, a: Vec3, b: Vec3) -> String { +/// The delta from `a` to `b` along the axes of the current UCS (the World UCS while that is +/// tilted): what DIST's report shows. +fn dist_delta(s: &Session, a: Vec3, b: Vec3) -> Vec3 { let u = s.input_ucs(); - let d = u.to_ucs3(b) - u.to_ucs3(a); + u.to_ucs3(b) - u.to_ucs3(a) +} + +/// DIST's report: the distance, the angles and the deltas `d`, measured in the current UCS. +fn dist_text(s: &Session, dist: f64, d: Vec3) -> String { format!( "Distance = {}, Angle in XY Plane = {}, Angle from XY Plane = {}\nDelta X = {}, Delta Y = {}, Delta Z = {}", - fmt_d(s, (b - a).len()), + fmt_d(s, dist), fmt_a(s, d.xy().angle()), fmt_a(s, angle_from_xy(d)), fmt_d(s, d.x), @@ -224,25 +229,23 @@ fn run_dist(s: &mut Session, p: &Value) -> Result { } s.distance = d.len(); s.last_point = a.xy(); - // `angle`, `angleFromXY` and the deltas are measured in the current UCS, as the message says - // them; `world` has the same numbers along the world axes. - let u = s.input_ucs(); - let du = u.to_ucs3(b) - u.to_ucs3(a); + // Top level: the world values, as ID's x, y, z are; `ucs` has what the message shows. + let du = dist_delta(s, a, b); Ok(json!({ "distance": d.len(), - "angle": du.xy().angle().to_degrees(), - "angleFromXY": angle_from_xy(du).to_degrees(), - "dx": du.x, - "dy": du.y, - "dz": du.z, - "world": { - "angle": d.xy().angle().to_degrees(), - "angleFromXY": angle_from_xy(d).to_degrees(), - "dx": d.x, - "dy": d.y, - "dz": d.z, + "angle": d.xy().angle().to_degrees(), + "angleFromXY": angle_from_xy(d).to_degrees(), + "dx": d.x, + "dy": d.y, + "dz": d.z, + "ucs": { + "angle": du.xy().angle().to_degrees(), + "angleFromXY": angle_from_xy(du).to_degrees(), + "dx": du.x, + "dy": du.y, + "dz": du.z, }, - "message": dist_text(s, a, b), + "message": dist_text(s, d.len(), du), })) } @@ -916,7 +919,7 @@ impl Interactive for DistM { s.last_point = first; return Err(bad("dist", "the distance is too large")); } - let t = dist_text(s, a, b); + let t = dist_text(s, (b - a).len(), dist_delta(s, a, b)); for l in t.lines() { s.echo(l.to_string()); } diff --git a/crates/engine/tests/ucs.rs b/crates/engine/tests/ucs.rs index 42143a30a..4a2067027 100644 --- a/crates/engine/tests/ucs.rs +++ b/crates/engine/tests/ucs.rs @@ -626,19 +626,20 @@ fn pressing_enter_at_the_origin_prompt_keeps_the_origin() { assert!(near3(s.ucs().origin, before.origin)); } -/// DIST's JSON says what its message says: angle and deltas in the current UCS, the world ones -/// under `world`. +/// DIST's JSON keeps world values at the top level, as ID does, and has the numbers its message +/// shows (angle and deltas in the current UCS) under `ucs`. #[test] -fn dist_json_matches_its_message_in_a_ucs() { +fn dist_json_keeps_world_values_and_adds_ucs() { let mut s = session(); turned(&mut s); // Points are given in the world: UCS (0,0) and (10,0). let r = s.execute("dist", &json!({"p1": [100, 50], "p2": [100, 60]})).unwrap(); let f = |v: &Value, k: &str| v[k].as_f64().unwrap(); - assert!((f(&r, "dx") - 10.0).abs() < 1e-9 && f(&r, "dy").abs() < 1e-9 && f(&r, "angle").abs() < 1e-9, "{r}"); + assert!(f(&r, "dx").abs() < 1e-9 && (f(&r, "dy") - 10.0).abs() < 1e-9 && (f(&r, "angle") - 90.0).abs() < 1e-9, "{r}"); + let u = &r["ucs"]; + assert!((f(u, "dx") - 10.0).abs() < 1e-9 && f(u, "dy").abs() < 1e-9 && f(u, "angle").abs() < 1e-9, "{r}"); assert!(r["message"].as_str().unwrap().contains("Delta X = 10"), "{r}"); - let w = &r["world"]; - assert!(f(w, "dx").abs() < 1e-9 && (f(w, "dy") - 10.0).abs() < 1e-9 && (f(w, "angle") - 90.0).abs() < 1e-9, "{r}"); + assert!(r.get("world").is_none(), "{r}"); } /// Deleting the current named UCS leaves no trace of its name: UCS Previous goes back to the axes diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index e98778b19..eb88d657d 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -207,6 +207,9 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { { d.header.set("SNAPBASE", HVal::Point(Vec3::new(x, y, 0.0))); } + if let Some(v) = t.i(74) { + d.header.set_i64("UCSICON", v.clamp(0, 3)); + } if let Some(a) = t.f(50).filter(|a| a.is_finite()) { d.header.set_f64("SNAPANG", a); } diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 86eba574c..bb8fb296e 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -42,8 +42,6 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("UCSORG", -3), ("UCSXDIR", -3), ("UCSYDIR", -3), - // Whether the UCS icon is shown (bit 1) and at the UCS origin (bit 2). - ("UCSICON", 70), ("PDMODE", 70), ("PDSIZE", 40), ("PLINEWID", 40), diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index b8da0209f..701aa5917 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -105,6 +105,11 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { w.f(41, if t.aspect.is_finite() && t.aspect > 0.0 { t.aspect } else { 1.0 }); w.f(42, 50.0); w.f(50, d.header.f64("SNAPANG", 0.0)); + // UCSICON: bit 1 shows the icon, bit 2 puts it at the UCS origin. A setting of the shown + // configuration (there is no header variable for it). + if name == VportConfig::ACTIVE { + w.i(74, d.header.i64("UCSICON", 3).clamp(0, 3)); + } // The shown configuration's tiles keep model space's current UCS (UCSVP 1). if name == VportConfig::ACTIVE { let ucs = model_ucs(d); diff --git a/crates/io/tests/ucs_roundtrip.rs b/crates/io/tests/ucs_roundtrip.rs index 5707e7e3f..bfbfa5b86 100644 --- a/crates/io/tests/ucs_roundtrip.rs +++ b/crates/io/tests/ucs_roundtrip.rs @@ -414,17 +414,36 @@ fn a_stale_ucs_name_copy_is_not_brought_back() { assert_eq!(cadcraft_io::read_dxf(same.as_bytes()).unwrap().header.str("UCSNAME", ""), "SITE"); } -/// UCSICON is a setting of the drawing: icon off (bit 1 clear) comes back off after a DXF save. +/// The `*ACTIVE` VPORT record's group 74 (UCSICON setting) in DXF text. +fn active_ucsicon(text: &str) -> Option { + let active = records(text, "VPORT").into_iter().find(|r| group(r, "2").is_some_and(|n| n.eq_ignore_ascii_case("*ACTIVE")))?; + group(&active, "74").map(str::to_string) +} + +/// UCSICON is a setting of the drawing, kept in the active VPORT's group 74 (bit 1 the icon, +/// bit 2 at the origin): icon off comes back off after a DXF save, and it is no header variable. #[test] fn ucsicon_survives_a_dxf_round_trip() { let mut d = Drawing::default(); d.header.set_i64("UCSICON", 0); let text = cadcraft_io::write_dxf(&d); - assert_eq!(group(&header_var(&text, "UCSICON"), "70"), Some("0"), "written to the header"); + assert_eq!(active_ucsicon(&text).as_deref(), Some("0"), "written to the active VPORT"); + assert!(header_var(&text, "UCSICON").is_empty(), "not a header variable"); let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); assert_eq!(back.header.i64("UCSICON", 3), 0); // And a value with the origin bit only. d.header.set_i64("UCSICON", 2); - let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); - assert_eq!(back.header.i64("UCSICON", 3), 2); + let text = cadcraft_io::write_dxf(&d); + assert_eq!(active_ucsicon(&text).as_deref(), Some("2")); + assert_eq!(cadcraft_io::read_dxf(text.as_bytes()).unwrap().header.i64("UCSICON", 3), 2); +} + +/// A file whose `*ACTIVE` VPORT says 74 = 0 opens with the icon off. +#[test] +fn ucsicon_reads_from_the_active_vport_group_74() { + let dxf = "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n70\n1\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n12\n6.0\n22\n4.5\n40\n9.0\n41\n1.6\n74\n0\n0\nENDTAB\n0\nENDSEC\n0\nEOF\n"; + let d = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + assert_eq!(d.header.i64("UCSICON", 3), 0); + let on = dxf.replace("74\n0\n", "74\n3\n"); + assert_eq!(cadcraft_io::read_dxf(on.as_bytes()).unwrap().header.i64("UCSICON", 3), 3); } From 30e3ae07677723fc3337d0a379f0c374c9ef5a95 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 14:39:20 +1100 Subject: [PATCH 263/531] UCS: grid snap reads the frame without the name (review) grid_frame_in went through ucs::current, which copies the UCS name on every grid snap; current_frame returns the same frame without it. --- crates/engine/src/snap.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 41649d5dd..30583d1ae 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -1107,7 +1107,7 @@ pub fn grid_frame(d: &Drawing) -> (Vec2, f64) { /// UCS (in the World UCS while it is tilted out of the XY plane). pub fn grid_frame_in(d: &Drawing, space: &Space) -> (Vec2, f64) { let (base, angle) = grid_frame(d); - let (ucs, _) = crate::ucs::current(d, space); + let ucs = crate::ucs::current_frame(d, space); if !ucs.is_planar() { return (base, angle); } From 67124500c6a26af45065b6488edc22ec7c0d1299 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 15:02:36 +1100 Subject: [PATCH 264/531] UCS: read the VPORT UCSICON setting in its own function (clippy complexity) --- crates/io/src/dxf_read/tables.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index eb88d657d..59a27ca16 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -207,9 +207,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { { d.header.set("SNAPBASE", HVal::Point(Vec3::new(x, y, 0.0))); } - if let Some(v) = t.i(74) { - d.header.set_i64("UCSICON", v.clamp(0, 3)); - } + ucsicon(d, &t); if let Some(a) = t.f(50).filter(|a| a.is_finite()) { d.header.set_f64("SNAPANG", a); } @@ -316,6 +314,13 @@ fn index_table_handles(recs: &[(String, Vec)], rx: &mut Rx) { } } +/// The `*ACTIVE` VPORT's UCSICON setting (group 74: bit 1 the icon shown, bit 2 at the UCS origin). +fn ucsicon(d: &mut Drawing, t: &T) { + if let Some(v) = t.i(74) { + d.header.set_i64("UCSICON", v.clamp(0, 3)); + } +} + /// Most tiles a viewport configuration keeps. const MAX_VPORT_TILES: usize = 64; From 95396c032d761369fb3275496ac131446a422200 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 15:34:08 +1100 Subject: [PATCH 265/531] OLE2FRAME: only picking sees the frame edges (review on #2587) Putting the frame in prims() also made it a TRIM/EXTEND edge, an object snap target and dimension geometry. prims() is back to nothing for it, the extents arm is restored, and select::hit_polylines adds the frame's outline for picking (none for a frame with no width or height or a bad corner). Tests: clicking_an_ole_frame_edge_selects_it (now also a frame with no width), ole_frame_is_not_a_trim_edge_or_snap_target. --- crates/doc/src/entity.rs | 4 ---- crates/doc/src/extents.rs | 2 ++ crates/engine/src/select.rs | 9 +++++++++ crates/engine/tests/ole_frame_transform.rs | 18 ++++++++++++++++++ 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index d24f7f49b..1237463f1 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -264,10 +264,6 @@ impl EntityKind { EntityKind::Image(i) => vec![Prim::Point(i.insert.xy())], EntityKind::Table(t) => vec![Prim::Point(t.insert.xy())], EntityKind::Tolerance(t) => vec![Prim::Point(t.insert.xy())], - // An OLE object's content is not drawn, but its frame is: the edges between its corners. - EntityKind::Unknown(u) if u.is_ole_frame() => crate::ole_frame(&u.tags) - .map(|q| q.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect()) - .unwrap_or_default(), EntityKind::Unknown(_) => Vec::new(), } } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 2e3f16a48..3630f8e66 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -458,6 +458,8 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< Bounds2::from_points([o, o + u, o + v, o + u + v]) } EntityKind::LwPolyline(p) => lwpolyline_bounds(p), + // An OLE object's content is not drawn, but its frame is, so the frame counts (#2422). + EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points), kind => { let mut b = Bounds2::EMPTY; for p in kind.prims() { diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index a3d361e84..c8a689194 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -36,6 +36,13 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { } v } + // An OLE object's frame is drawn, so it is picked on its outline (the corners the extents and + // the renderer use); a frame with no area has nothing to hit. It stays out of prims(), which + // TRIM, object snap and the dimension commands read. + EntityKind::Unknown(u) if u.is_ole_frame() => match cadcraft_doc::ole_frame(&u.tags) { + Some(q) if q.first().zip(q.get(2)).is_some_and(|(a, c)| a.x != c.x && a.y != c.y) => vec![q.to_vec()], + _ => Vec::new(), + }, kind => { let mut out = Vec::new(); for p in kind.prims() { @@ -516,10 +523,12 @@ mod tests { let mut d = Drawing::new_metric(); let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap(); d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap(); + d.add(&Space::Model, Common::default(), frame(vec![tag(10, "60"), tag(20, "-19"), tag(11, "60"), tag(21, "-22")])).unwrap(); assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -19.0), 0.2), Some(h), "top edge"); assert_eq!(pick(&d, &Space::Model, Vec2::new(35.0, -20.5), 0.2), Some(h), "right edge"); assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -20.5), 0.2), None, "inside the frame"); assert_eq!(pick(&d, &Space::Model, Vec2::new(80.0, 80.0), 0.2), None, "a frame without a second corner"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(60.0, -20.0), 0.2), None, "a frame with no width"); } /// A block holding a diagonal dashed line, inserted at `scale`. diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs index afe138ff9..171af556c 100644 --- a/crates/engine/tests/ole_frame_transform.rs +++ b/crates/engine/tests/ole_frame_transform.rs @@ -265,3 +265,21 @@ fn classic_polar_array_refuses_a_turned_frame_but_not_an_upright_one() { s.execute("-array", &upright).unwrap(); assert_eq!(s.doc().unwrap().model.len(), 4); } + +/// The frame is picked by its outline but is not geometry for other commands: a line across it is +/// not cut at its edges by TRIM, and object snap near its corner offers no frame point (review on +/// #2587). +#[test] +fn ole_frame_is_not_a_trim_edge_or_snap_target() { + use cadcraft_engine::snap::{mode, osnap}; + let (mut s, _frame) = session(); + let ln = s.execute("line", &json!({ "points": [[28, -20.5], [37, -20.5]] })).unwrap(); + let ln = ln["handle"].as_str().or_else(|| ln["handles"][0].as_str()).unwrap().to_string(); + // No cutting edge is named, so every object but the line itself is one. + let _ = s.execute("trim", &json!({ "handle": ln.clone(), "pick": [32, -20.5] })); + assert_eq!(line_ends(&s, &ln), ((28.0, -20.5), (37.0, -20.5)), "the line is not cut at the frame"); + assert_eq!(s.doc().unwrap().model.len(), 2); + let all = mode::END | mode::MID | mode::INT | mode::PER | mode::CEN | mode::QUA | mode::NOD; + let hit = osnap(s.doc().unwrap(), &Space::Model, cadcraft_engine::geom::Vec2::new(30.0, -19.0), 0.5, all, None, false); + assert!(hit.is_none(), "no snap point on the frame: {hit:?}"); +} From 63f53f6ed603abaefd9e80260cb88ed31fa80863 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 15:34:23 +1100 Subject: [PATCH 266/531] ARRAY, ARRAYPATH: one OLE frame check, after the matrices (review on #2587) A matrix every frame accepts (a rectangular array, plain translations) now needs no look at the objects, and an empty matrix list never touches the drawing. ARRAYPATH scans the selection once instead of once per item. Covered by the existing refusal tests; copy_all is not reachable without a drawing through any command, so there is no no-drawing test. --- crates/engine/src/cmd/array.rs | 4 ++-- crates/engine/src/cmd/modify2/patharray.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index c4948c9e0..89c6013d2 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -250,8 +250,8 @@ fn copy_all(s: &mut Session, hs: &[Handle], mats: impl Iterator) -> // Every copy is checked before the first is made: a refusal part way would leave the copies // already added in the drawing (a failed command is not rolled back). let mats: Vec = mats.collect(); - // The objects are looked at once; then a matrix only needs its own check. - if super::modify::holds_ole_frame(s, hs, true)? && mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) { + // A matrix every frame accepts needs no look at the objects; otherwise they are looked at once. + if mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) && super::modify::holds_ole_frame(s, hs, true)? { return Err(super::modify::ole_refusal()); } let mut n = 0; diff --git a/crates/engine/src/cmd/modify2/patharray.rs b/crates/engine/src/cmd/modify2/patharray.rs index aff058ab5..dd9597177 100644 --- a/crates/engine/src/cmd/modify2/patharray.rs +++ b/crates/engine/src/cmd/modify2/patharray.rs @@ -46,8 +46,8 @@ pub(crate) fn arraypath( } // Every copy is checked before the first is made: a refusal part way would leave the copies // already added in the drawing (a failed command is not rolled back). - for m in &mats { - crate::cmd::modify::refuse_ole_frames(s, &objs, m, true)?; + if mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) && crate::cmd::modify::holds_ole_frame(s, &objs, true)? { + return Err(crate::cmd::modify::ole_refusal()); } let mut out = Vec::new(); for m in &mats { From 35e85f8694f408643bcff47c265a2807244ba0ed Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 15:34:23 +1100 Subject: [PATCH 267/531] OLE2FRAME: comments match the tolerance; case lookup in one pass (review on #2587) The ulp term takes over from CORNER_EPS from about 1.1e9, and the doc now says so. The case of the nearest letter for each hex digit is found in two linear passes instead of a search per digit; same result, covered by moving_an_ole_frame_keeps_each_hex_digits_case. --- crates/doc/src/extents.rs | 57 ++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 3630f8e66..4cffb359f 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -96,8 +96,8 @@ fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4 // other header is not ours to rewrite. let [x1, y1, x2, y2] = frame; let want = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]; - // The floor is the fixed-ceiling match; above about 8.6e9 one ulp exceeds it, so a few ulps of the - // larger value also match. + // Two corners match within a fixed tolerance for ordinary coordinates (CORNER_EPS at most), or + // within a few ulps of the coordinate where that is larger, which is from about 1.1e9 up. let near = |a: f64, b: f64| { let m = a.abs().max(b.abs()); (a - b).abs() <= (1e-9 * m.max(1.0)).min(CORNER_EPS).max(4.0 * f64::EPSILON * m) @@ -135,30 +135,55 @@ fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4 /// is none, so bytes that did not change keep their exact text. fn recase(chunk: &[u8], old: &str) -> String { let old = old.as_bytes(); - let lower_at = |i: usize| -> bool { - if let Some(c) = old.get(i).filter(|c| c.is_ascii_alphabetic()) { - return c.is_ascii_lowercase(); + // For each place, whether the letter nearest to it (the one at it, else the closest before or + // after; the one before on a tie) is lower case: one pass for the next letter at or after each + // place, one for the previous, then the nearer of the two. + let mut next: Vec> = vec![None; old.len()]; + let mut seen: Option<(usize, bool)> = None; + for (i, c) in old.iter().enumerate().rev() { + if c.is_ascii_alphabetic() { + seen = Some((i, c.is_ascii_lowercase())); } - let nearest = (1..=old.len()).find_map(|d| { - let before = i.checked_sub(d).and_then(|j| old.get(j)).filter(|c| c.is_ascii_alphabetic()); - before.or_else(|| old.get(i + d).filter(|c| c.is_ascii_alphabetic())) - }); - nearest.is_some_and(|c| c.is_ascii_lowercase()) - }; + if let Some(slot) = next.get_mut(i) { + *slot = seen; + } + } + let mut lower_at = vec![false; old.len()]; + let mut prev: Option<(usize, bool)> = None; + for (i, c) in old.iter().enumerate() { + if c.is_ascii_alphabetic() { + prev = Some((i, c.is_ascii_lowercase())); + } + let after = next.get(i).copied().flatten(); + let lower = match (prev, after) { + (Some((p, lp)), Some((q, lq))) => { + if i - p <= q - i { + lp + } else { + lq + } + } + (Some((_, l)), None) | (None, Some((_, l))) => l, + (None, None) => false, + }; + if let Some(slot) = lower_at.get_mut(i) { + *slot = lower; + } + } let mut out = String::with_capacity(chunk.len() * 2); for (k, b) in chunk.iter().enumerate() { for (j, d) in [b >> 4, b & 15].into_iter().enumerate() { let digit = char::from_digit(d.into(), 16).unwrap_or('0'); - out.push(if lower_at(2 * k + j) { digit } else { digit.to_ascii_uppercase() }); + out.push(if lower_at.get(2 * k + j).copied().unwrap_or(false) { digit } else { digit.to_ascii_uppercase() }); } } out } -/// Ceiling for the tolerance when matching the corners in the OLE data to the frame's. The header -/// holds the same f64 the frame groups print, so they agree to a few ulps; a fixed ceiling keeps -/// distinct geometry from matching at large coordinates, where a relative tolerance would grow to -/// whole units. +/// The fixed part of the tolerance when matching the corners in the OLE data to the frame's. The +/// header holds the same f64 the frame groups print, so they agree to a few ulps. Up to about 1e9 a +/// fixed tolerance of at most this decides, so that distinct geometry does not match; from about +/// 1.1e9 on, where one ulp is no longer below it, a few ulps of the coordinate decide instead. const CORNER_EPS: f64 = 1e-6; /// Transform an OLE2FRAME by `m`: its two corners are mapped through `m` (a DWG save writes the From 50644fb0c48fcd477fb6525baa4e2d51d1e1bc9f Mon Sep 17 00:00:00 2001 From: mo <131036780+mbolling@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:46:54 -0500 Subject: [PATCH 268/531] SVG import: shapes whose coordinates overflow to infinity or NaN are left out and noted Finite numbers still overflow through transforms and relative path steps (`M1e308 0 l1e308 0`, `scale(1e308)`), and the reader added the entities with infinite or NaN coordinates, which break extents and rendering and change on a DXF save. Such a shape is now skipped and counted in the read note. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/svg_read.rs | 19 +++++++++++++++++++ crates/io/src/tests.rs | 14 ++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/crates/io/src/svg_read.rs b/crates/io/src/svg_read.rs index 54ef9d846..e40b1281a 100644 --- a/crates/io/src/svg_read.rs +++ b/crates/io/src/svg_read.rs @@ -147,6 +147,7 @@ enum LeftOut { Use, Style, RoundedCorners, + TooLarge, } impl LeftOut { @@ -166,6 +167,7 @@ impl LeftOut { Self::Use => ("`` copy", "`` copies"), Self::Style => ("`