From 7003c5b9309f5e92c2f5b5fcb2e8b34be2840e22 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Tue, 13 Oct 2026 10:50:32 -0600 Subject: [PATCH 001/900] 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/900] 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/900] 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/900] 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/900] 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/900] 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/900] 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/900] 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 212f6cc988169062c9575459f38eeefec1272a9b Mon Sep 17 00:00:00 2001 From: mattlafy Date: Wed, 14 Oct 2026 10:20:19 -0400 Subject: [PATCH 009/900] View twist: DVIEW, VIEWTWIST, per-tile, named-view and layout-viewport twist A model space view carries a twist (radians CCW, View.twist, serde default 0). VIEWTWIST reports it read-only. Each VPORTS tile keeps its own twist (VportTile.twist, DXF VPORT group 51 read and written; a single untiled Model view's twist is kept as a lone *Active VPORT tile). VIEW Save stores and Restore applies NamedView::twist. ZOOM fits in the twisted screen frame; zooms, pans, the 3D mouse and view.set keep it; ZOOM Previous turns it back. DVIEW starts with "Select objects or :" (the picked objects, or the DVIEWBLOCK sample, are the only things drawn while it runs) and repeats the "Enter option [CAmera/TArget/Distance/POints/PAn/Zoom/ TWist/CLip/Hide/Off/Undo]:" prompt. TWist, PAn, Zoom, Off and Undo work on 2D views; the 3D options say they are not available yet (docs/gaps.md F1). DVIEW works inside an active layout viewport: the doc Viewport gains a view twist (DXF VIEWPORT group 51), drawn turned on screen and in plots, mapped through MSPACE views, snaps and CHSPACE; a twist made there is one undo step. A layout with no active viewport refuses it, as does view.set's twist. Canvas: the model view and every VPORTS tile draw turned by their twist. `Xf` gains `twist`: `to_screen` turns (p - centre) by it before scaling, `to_world` is its exact inverse, `world_bounds` is the box of the four turned rect corners. The GPU needs no shader change: `Xf::gpu_xform` builds the callback xform for the drawing, drag, highlight, viewport and mask layers. Pans map screen deltas back through the twist; clicks, hover, snaps, grips and wheel zoom go through `to_world`/`to_screen`. Grid lines and axes stay world-aligned; the selection window is drawn as the world box it selects. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/entity.rs | 34 ++ crates/doc/src/tables.rs | 5 +- crates/engine/src/cmd/blocks/xref.rs | 6 +- crates/engine/src/cmd/file/template.rs | 2 +- crates/engine/src/cmd/layout.rs | 3 +- crates/engine/src/cmd/layout/viewports.rs | 2 +- crates/engine/src/cmd/layout/vplayer.rs | 2 +- crates/engine/src/cmd/modify2.rs | 3 +- crates/engine/src/cmd/modify2_tests.rs | 1 + crates/engine/src/cmd/view.rs | 68 ++- crates/engine/src/cmd/view/dview.rs | 436 ++++++++++++++++++ crates/engine/src/cmd/view/named_views.rs | 9 +- crates/engine/src/cmd/view/vports.rs | 10 +- crates/engine/src/guard.rs | 9 + crates/engine/src/lib.rs | 97 +++- crates/engine/src/prompt.rs | 44 +- crates/engine/src/snap/viewport.rs | 7 +- crates/engine/src/sysvars.rs | 19 +- crates/engine/src/tests.rs | 2 +- crates/engine/tests/dview.rs | 280 +++++++++++ crates/engine/tests/followups_626.rs | 6 +- .../engine/tests/measure_distance_snapping.rs | 1 + crates/engine/tests/named_views.rs | 10 +- crates/engine/tests/view_twist.rs | 193 ++++++++ crates/engine/tests/vports.rs | 10 +- crates/io/src/dxf_read.rs | 11 +- crates/io/src/dxf_write.rs | 7 + crates/io/src/tests.rs | 4 + crates/io/tests/dwg_roundtrip_losses.rs | 1 + crates/io/tests/paperview_marker.rs | 1 + crates/io/tests/pdf_layers.rs | 1 + crates/io/tests/pdf_text.rs | 1 + crates/io/tests/view_tables_roundtrip.rs | 2 +- crates/render/src/lib.rs | 11 +- crates/render/src/tests.rs | 1 + crates/render/tests/plot_line_styles.rs | 1 + crates/render/tests/psltscale.rs | 1 + crates/render/tests/render_props.rs | 1 + crates/render/tests/viewport_frozen_layer.rs | 1 + crates/render/tests/viewport_twist.rs | 66 +++ crates/ui-egui/src/bedit.rs | 2 +- crates/ui-egui/src/canvas.rs | 266 ++++++++--- crates/ui-egui/src/cmdline.rs | 4 +- crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/spacemouse.rs | 2 +- .../tests/measure_distance_snapping.rs | 1 + crates/ui-egui/tests/mspace_viewport_view.rs | 3 +- docs/file-format-parity.md | 5 +- docs/gaps.md | 5 +- 49 files changed, 1505 insertions(+), 153 deletions(-) create mode 100644 crates/engine/src/cmd/view/dview.rs create mode 100644 crates/engine/tests/dview.rs create mode 100644 crates/engine/tests/view_twist.rs create mode 100644 crates/render/tests/viewport_twist.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 4d22c1753..493f228ae 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -822,6 +822,39 @@ pub struct Viewport { /// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space. #[serde(default = "yes")] pub on: bool, + /// The view twist (DVIEW TWist inside the viewport; DXF group 51): radians counterclockwise, + /// the model view seen through the viewport is turned on the sheet by it. 0 is untwisted. + #[serde(default, skip_serializing_if = "is_zero_twist")] + pub twist: f64, +} +fn is_zero_twist(v: &f64) -> bool { + *v == 0.0 +} +impl Viewport { + /// The view twist, usable: 0 when it isn't finite. + pub fn view_twist(&self) -> f64 { + if self.twist.is_finite() { self.twist } else { 0.0 } + } + /// Paper units per model unit. + pub fn scale(&self) -> f64 { + self.height / self.view_height + } + /// Where model point `m` is on the sheet: `center + scale · R(twist)(m − view_center)`. + pub fn model_to_paper(&self, m: Vec2) -> Vec2 { + self.center.xy() + (m - self.view_center).rotate(self.view_twist()) * self.scale() + } + /// The model point at sheet point `p` (the inverse of [`Viewport::model_to_paper`]). + pub fn paper_to_model(&self, p: Vec2) -> Vec2 { + self.view_center + ((p - self.center.xy()) / self.scale()).rotate(-self.view_twist()) + } + /// [`Viewport::model_to_paper`] as a matrix. + pub fn model_to_paper_matrix(&self) -> Mat3 { + let s = self.scale(); + Mat3::translate(self.center.xy()) + .then_before(Mat3::scale(s, s)) + .then_before(Mat3::rotate(self.view_twist())) + .then_before(Mat3::translate(-self.view_center)) + } } impl Default for Viewport { fn default() -> Self { @@ -837,6 +870,7 @@ impl Default for Viewport { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, } } } diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index f9824ec6d..3efcb9bba 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -803,7 +803,7 @@ pub struct NamedView { /// The layer state restored with the view (its layer snapshot). #[serde(default)] pub layer_state: Option, - /// View twist (radians, counterclockwise); kept for files, not applied to the 2D display. + /// View twist (radians, counterclockwise); VIEW Restore applies it to the model space view. #[serde(default)] pub twist: f64, /// The layout a paper space view belongs to (`None`: a model space view; an empty name: a @@ -824,6 +824,9 @@ pub struct VportTile { /// Width / height of the tile on screen when it was saved (0: unknown). #[serde(default)] pub aspect: f64, + /// The tile's view twist (radians, counterclockwise; DXF VPORT group 51 in degrees). + #[serde(default)] + pub twist: f64, } /// A model space viewport configuration (VPORTS): `*Active` is the one shown, other names are diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index a3b19fa4d..aaf8bba2e 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -62,7 +62,11 @@ pub(crate) fn after_open(s: &mut Session, i: usize) { st.saved = st.doc.clone(); let ext = st.doc.extents(&cadcraft_doc::Space::Model); if !ext.is_empty() { - st.set_view_quiet(crate::View { center: ext.center(), height: (ext.height().max(ext.width() * px.1 / px.0.max(1.0)) * 1.1).max(1e-6) }); + st.set_view_quiet(crate::View { + center: ext.center(), + height: (ext.height().max(ext.width() * px.1 / px.0.max(1.0)) * 1.1).max(1e-6), + twist: 0.0, + }); } echo_all(s, &out); } diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index f5b29e450..32a534c4c 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -59,7 +59,7 @@ pub(super) fn run_new(s: &mut Session, p: &Value) -> Result> { && hi.y > lo.y { let center = cadcraft_geom::Vec2::new((lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0); - st.set_view_quiet(crate::View { center, height: (hi.y - lo.y).max(1e-6) }); + st.set_view_quiet(crate::View { center, height: (hi.y - lo.y).max(1e-6), twist: 0.0 }); } Ok(Some(json!({ "index": i, "title": title, "template": path }))) } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index cac585209..9434c7a2a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -512,6 +512,7 @@ fn viewport_json(h: Handle, v: &Viewport) -> Value { "height": v.height, "viewCenter": [v.view_center.x, v.view_center.y], "viewHeight": v.view_height, + "twist": v.view_twist().to_degrees(), "scale": if v.view_height > 0.0 { v.height / v.view_height } else { 0.0 }, "locked": v.locked, "on": v.on, @@ -1157,7 +1158,7 @@ mod tests { s.cmdline("circle 10,10 3").unwrap(); assert_eq!(s.doc().unwrap().model.len(), before + 1); // Zooming changes the viewport's model view, not the sheet. - s.state_mut().unwrap().set_view(crate::View { center: v.center, height: v.height / 2.0 }); + s.state_mut().unwrap().set_view(crate::View { center: v.center, height: v.height / 2.0, twist: v.twist }); let vp2 = viewports(&s, "L").into_iter().find(|(x, _)| *x == h).unwrap().1; assert!((vp2.view_height - vp.view_height / 2.0).abs() < 1e-9); assert_eq!(s.state().unwrap().paper_view(), pv); diff --git a/crates/engine/src/cmd/layout/viewports.rs b/crates/engine/src/cmd/layout/viewports.rs index 7f47c4e31..d81273ff6 100644 --- a/crates/engine/src/cmd/layout/viewports.rs +++ b/crates/engine/src/cmd/layout/viewports.rs @@ -329,7 +329,7 @@ pub(super) fn run_vpclip(s: &mut Session, p: &Value) -> Result { let k = cur.view_height / cur.height.max(1e-12); let mut v = cur; let c = b.center(); - let view_center = v.view_center + (c - v.center.xy()) * k; + let view_center = v.paper_to_model(c); let view_height = b.height() * k; if view_center.is_finite() && view_height.is_finite() && view_height > 0.0 { v.view_center = view_center; diff --git a/crates/engine/src/cmd/layout/vplayer.rs b/crates/engine/src/cmd/layout/vplayer.rs index 0d2e7d9eb..eab260ce9 100644 --- a/crates/engine/src/cmd/layout/vplayer.rs +++ b/crates/engine/src/cmd/layout/vplayer.rs @@ -109,7 +109,7 @@ fn parse_color(t: &str) -> Result { fn viewport_at(s: &Session, p: Vec2) -> Option { let st = s.state().ok()?; let at = match st.active_viewport() { - Some((_, vp)) => vp.center.xy() + (p - vp.view_center) * (vp.height / vp.view_height), + Some((_, vp)) => vp.model_to_paper(p), None => p, }; super::viewports::viewport_at(s, at) diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index 5562f969c..416847dbd 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -1424,8 +1424,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option) }; let m = match viewport_of(s, &layout, vp) { Some(v) => { - let k = v.view_height / v.height; - let to_paper = Mat3::translate(v.center.xy()).then_before(Mat3::scale(1.0 / k, 1.0 / k)).then_before(Mat3::translate(-v.view_center)); + let to_paper = v.model_to_paper_matrix(); if target == Space::Model { to_paper.inverse().unwrap_or(Mat3::IDENTITY) } else { to_paper } } None => Mat3::IDENTITY, diff --git a/crates/engine/src/cmd/modify2_tests.rs b/crates/engine/src/cmd/modify2_tests.rs index 9b76c84fc..5596d6fab 100644 --- a/crates/engine/src/cmd/modify2_tests.rs +++ b/crates/engine/src/cmd/modify2_tests.rs @@ -371,6 +371,7 @@ fn chspace_json_and_command_line() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Default::default(), EntityKind::Viewport(vp)).unwrap(); let r = s.execute("chspace", &json!({"handles": [l]})).unwrap(); diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index e6051a6e9..6d8440d74 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -1,5 +1,5 @@ -//! View menu: ZOOM (with Realtime and Dynamic), PAN, REGEN, REDRAW, named views (VIEW), layout -//! switching. +//! View menu: ZOOM (with Realtime and Dynamic), PAN, REGEN, REDRAW, named views (VIEW), the view +//! twist (DVIEW TWist), layout switching. use cadcraft_doc::{Space, entity_bounds}; use cadcraft_geom::{Bounds2, Vec2}; @@ -9,6 +9,7 @@ use super::machines::{SelectRun, number}; use super::*; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, View}; +mod dview; mod named_views; mod vports; @@ -94,10 +95,13 @@ pub fn specs() -> Vec { .alias(&["r"]) .noundo() .transparent(), - CommandSpec::new("view.set", "Set View", run_view_set).params("{center: [x,y], height}").noundo(), + dview::spec(), + CommandSpec::new("view.set", "Set View", run_view_set) + .params("{center: [x,y], height, twist?: degrees (default: keep the current twist; in a layout viewport it is the viewport's twist, an undoable edit; not in Paper space)}") + .noundo(), CommandSpec::new("view.get", "Get View", |s, _| { let v = s.state()?.view(); - Ok(json!({"center": [v.center.x, v.center.y], "height": v.height, "viewportPx": [s.viewport_px.0, s.viewport_px.1]})) + Ok(json!({"center": [v.center.x, v.center.y], "height": v.height, "twist": v.twist.to_degrees(), "viewportPx": [s.viewport_px.0, s.viewport_px.1]})) }) .noundo(), CommandSpec::new("layout.set", "Switch Layout", run_layout_set).params("{name: \"Model\" | layout name}").noundo(), @@ -119,8 +123,11 @@ fn fit(s: &mut Session, b: Bounds2) -> Result<()> { let (w, h) = s.viewport_px; let st = s.state_mut()?; let aspect = st.zoom_aspect(w / h.max(1.0)); - let height = b.height().max(b.width() / aspect.max(1e-6)).max(1e-9); - st.set_zoom_frame(View { center: b.center(), height }); + // A twisted view fits the box the bounds make on screen. + let twist = st.zoom_frame().twist; + let (center, bw, bh) = View::twisted_box(b, twist); + let height = bh.max(bw / aspect.max(1e-6)).max(1e-9); + st.set_zoom_frame(View { center, height, twist }); Ok(()) } @@ -149,18 +156,18 @@ pub(crate) fn zoom(s: &mut Session, p: &Value) -> Result { let f = if mode == "in" { 2.0 } else { 0.5 }; let st = s.state_mut()?; let v = st.zoom_frame(); - st.set_zoom_frame(View { center: v.center, height: v.height / f }); + st.set_zoom_frame(View { height: v.height / f, ..v }); } "center" | "c" | "dynamic" | "d" => { let c = point_req("zoom", p, "center")?; - let cur = s.state()?.zoom_frame().height; - let h = if p.get("factor").is_some() { factor_height(s, p, cur)? } else { f64_or(p, "height", cur) }; - s.state_mut()?.set_zoom_frame(View { center: c, height: h.max(1e-9) }); + let cur = s.state()?.zoom_frame(); + let h = if p.get("factor").is_some() { factor_height(s, p, cur.height)? } else { f64_or(p, "height", cur.height) }; + s.state_mut()?.set_zoom_frame(View { center: c, height: h.max(1e-9), ..cur }); } "scale" | "s" => { let v = s.state()?.zoom_frame(); let height = factor_height(s, p, v.height)?; - s.state_mut()?.set_zoom_frame(View { center: v.center, height }); + s.state_mut()?.set_zoom_frame(View { height, ..v }); } "realtime" => { let v = s.state()?.zoom_frame(); @@ -168,7 +175,7 @@ pub(crate) fn zoom(s: &mut Session, p: &Value) -> Result { if f <= 0.0 { return Err(bad("zoom", "factor must be positive")); } - s.state_mut()?.set_zoom_frame(View { center: v.center, height: (v.height / f).clamp(1e-9, 1e12) }); + s.state_mut()?.set_zoom_frame(View { height: (v.height / f).clamp(1e-9, 1e12), ..v }); } "object" | "o" => { let hs = targets(s, p)?; @@ -241,7 +248,8 @@ fn pan_frac(s: &mut Session, f: Vec2) -> Result { let st = s.state_mut()?; let v = st.view(); let ww = v.height * w / h.max(1.0); - st.set_view(View { center: v.center + Vec2::new(f.x * ww, f.y * v.height), height: v.height }); + // Screen directions: in a twisted view the drawing is turned by the twist. + st.set_view(View { center: v.center + Vec2::new(f.x * ww, f.y * v.height).rotate(-v.twist), ..v }); ok() } @@ -257,7 +265,7 @@ fn run_pan(s: &mut Session, p: &Value) -> Result { let b = point_req("pan", p, "to")?; v.center - (b - a) }; - st.set_view(View { center: c, height: v.height }); + st.set_view(View { center: c, ..v }); ok() } @@ -267,9 +275,33 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result { if h <= 0.0 { return Err(bad("view.set", "height must be positive")); } - if !s.state_mut()?.set_view(View { center: c, height: h }) { + let twist = match p.get("twist") { + Some(t) => t.as_f64().filter(|t| t.is_finite()).ok_or_else(|| bad("view.set", "twist must be a number of degrees"))?.to_radians(), + None => s.state()?.view().twist, + }; + // As DVIEW TWist: the Model tab's view or the active layout viewport turns; a layout sheet + // (paper space) is never twisted. + let target = match dview::target(s) { + Ok(t) => Some(t), + Err(_) if twist == 0.0 => None, + Err(e) => return Err(e), + }; + let before = (s.state()?.doc.clone(), s.state()?.selection.clone()); + let twist = match target { + Some(t @ dview::Target::Viewport(_)) => { + dview::set_twist(s, t, twist)?; + s.state()?.view().twist + } + Some(dview::Target::Model) => twist.rem_euclid(std::f64::consts::TAU), + None => 0.0, + }; + if !s.state_mut()?.set_view(View { center: c, height: h, twist }) { + s.state_mut()?.doc = before.0; return Err(bad("view.set", "the view is too large to show. Nothing was changed")); } + if let Some(dview::Target::Viewport(h)) = target { + dview::record_viewport_edit(s, before, h)?; + } ok() } @@ -293,7 +325,7 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result { let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default(); let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; - st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15 }); + st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 }); } s.touch(); ok() @@ -440,7 +472,7 @@ impl Interactive for ZoomM { if st.view_history.last() == Some(&b.screen) { st.view_history.pop(); } - st.set_zoom_frame(View { center: b.center, height: b.height }); + st.set_zoom_frame(View { center: b.center, height: b.height, twist: b.frame.twist }); return Ok(Step::Done); } (ZoomStage::Dynamic(mut b), Input::Point(p)) => { @@ -564,7 +596,7 @@ impl Session { let f = 2f64.powf((-dy / half).clamp(-16.0, 16.0)); let st = self.state_mut()?; let v = st.view(); - st.set_view_quiet(View { center: v.center, height: (v.height / f).clamp(1e-9, 1e12) }); + st.set_view_quiet(View { height: (v.height / f).clamp(1e-9, 1e12), ..v }); self.touch(); Ok(()) } diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs new file mode 100644 index 000000000..bfbef0047 --- /dev/null +++ b/crates/engine/src/cmd/view/dview.rs @@ -0,0 +1,436 @@ +//! DVIEW: the dynamic view, on CADCraft's 2D plan views. +//! +//! It starts with "Select objects or :": the objects +//! picked are the preview set, and Enter with nothing picked previews the DVIEWBLOCK block (the +//! drawing's own block of that name, else a built-in sample house). While DVIEW runs only the +//! preview set is drawn ([`Interactive::display_only`]); the whole drawing is regenerated when it +//! ends. Then it repeats "Enter option [CAmera/TArget/Distance/POints/PAn/Zoom/TWist/CLip/Hide/ +//! Off/Undo]:" until Enter. TWist, PAn, Zoom, Off and Undo work; the options that need a 3D +//! camera say they are not available yet and stay at the option prompt. +//! +//! DVIEW works on the Model tab's view, or on the active (double-clicked) layout viewport; on a +//! layout with no active viewport it is not available. A Model tab twist is a view change like +//! ZOOM (view history, not undo). A layout viewport's twist belongs to the viewport entity, so a +//! DVIEW that changed it is one undo step. + +use std::f64::consts::TAU; +use std::sync::Arc; + +use cadcraft_doc::{Entity, EntityKind, Handle, Insert, Line, Space}; +use cadcraft_geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +use super::super::machines::{SelOutcome, SelectPhase, number}; +use super::super::*; +use crate::{Accept, DisplayOnly, EngineError, Input, Interactive, Prompt, Result, Session, Snapshot, Step, View}; + +/// What DVIEW (and a view twist asked for anywhere) says on a layout with no active viewport. +pub(super) const PAPER_SPACE: &str = "This command is not available in Paper space."; + +/// The option prompt's keywords, in prompt order. +const OPTIONS: &[&str] = &["CAmera", "TArget", "Distance", "POints", "PAn", "Zoom", "TWist", "CLip", "Hide", "Off", "Undo"]; + +/// The block DVIEW previews when nothing is selected. +const DVIEWBLOCK: &str = "DVIEWBLOCK"; + +pub(super) fn spec() -> CommandSpec { + CommandSpec::new("dview", "DView", run_dview) + .alias(&["dv"]) + .params("{twist: degrees counterclockwise} (DVIEW TWist: the Model tab's view twist, or the active layout viewport's, an undoable edit; not in Paper space)") + .noundo() + .interactive(|s| { + // Refused as it starts on a layout with no active viewport. + target(s)?; + Ok(Box::new(DviewM::default())) + }) +} + +/// The view DVIEW changes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Target { + /// The Model tab's view. + Model, + /// The active (MSPACE) layout viewport: its own view twist. + Viewport(Handle), +} + +/// The view DVIEW changes: the active layout viewport, else the Model tab's view. A layout with +/// no active viewport has none. +pub(super) fn target(s: &Session) -> Result { + let st = s.state()?; + if let Some((h, _)) = st.active_viewport() { + return Ok(Target::Viewport(h)); + } + if st.space == Space::Model { + return Ok(Target::Model); + } + Err(EngineError::Other(PAPER_SPACE.into())) +} + +/// A twist kept as files hold it: [0, 2π). +fn normal(twist: f64) -> f64 { + twist.rem_euclid(TAU) +} + +/// The active viewport's twist, if it is `h`. +fn viewport_twist(s: &Session, h: Handle) -> Option { + s.state().ok()?.active_viewport().filter(|(vh, _)| *vh == h).map(|(_, vp)| vp.view_twist()) +} + +/// Turn `target`'s view to `twist` radians. The Model tab's twist is a view change (view +/// history, like ZOOM); a viewport's is a change to the viewport entity, which the caller +/// records as an undo step ([`record_viewport_edit`]). +pub(super) fn set_twist(s: &mut Session, target: Target, twist: f64) -> Result<()> { + if !twist.is_finite() { + return Err(bad("dview", "the twist must be a finite angle")); + } + let twist = normal(twist); + match target { + Target::Model => { + let st = s.state_mut()?; + let v = st.view(); + st.set_view(View { twist, ..v }); + } + Target::Viewport(h) => { + if viewport_twist(s, h) == Some(twist) { + return Ok(()); + } + let space = s.state()?.space.clone(); + let d = s.doc_mut()?; + if let Some(store) = d.space_mut(&space) { + store.modify(h, |e| { + if let EntityKind::Viewport(vp) = &mut e.kind { + vp.twist = twist; + } + }); + } + } + } + Ok(()) +} + +/// Record a layout viewport's twist change as one undo step, `before` being the drawing (and +/// selection) before it. Nothing when the twist did not change, and nothing inside a LISP routine +/// (its own single step holds it). +pub(super) fn record_viewport_edit(s: &mut Session, before: (Arc, Vec), h: Handle) -> Result<()> { + let old = before.0.entity(h).and_then(|e| match &e.kind { + EntityKind::Viewport(vp) => Some(vp.view_twist()), + _ => None, + }); + if old == viewport_twist(s, h) || s.lisp_groups_undo() { + return Ok(()); + } + let st = s.state_mut()?; + if !Arc::ptr_eq(&before.0, &st.doc) { + st.push_undo(Snapshot { label: "DView".into(), doc: before.0, selection: before.1 }); + st.revision += 1; + } + Ok(()) +} + +/// The drawing and selection now, for [`record_viewport_edit`]. +fn snapshot(s: &Session) -> Result<(Arc, Vec)> { + let st = s.state()?; + Ok((st.doc.clone(), st.selection.clone())) +} + +fn run_dview(s: &mut Session, p: &Value) -> Result { + let t = target(s)?; + let deg = f64_req("dview", p, "twist")?; + let before = snapshot(s)?; + set_twist(s, t, deg.to_radians())?; + if let Target::Viewport(h) = t { + record_viewport_edit(s, before, h)?; + } + let v = s.state()?.view(); + Ok(json!({ "twist": v.twist.to_degrees() })) +} + +/// The built-in DVIEWBLOCK: a house front in the unit square, origin at the lower-left corner +/// (the size and origin a DVIEWBLOCK of one's own is expected to have). CADCraft's own drawing. +fn sample_house() -> Vec<(Vec2, Vec2)> { + let p = Vec2::new; + let mut lines = Vec::new(); + let mut poly = |pts: &[Vec2], closed: bool| { + for w in pts.windows(2) { + lines.push((w[0], w[1])); + } + if closed && let (Some(a), Some(b)) = (pts.last(), pts.first()) { + lines.push((*a, *b)); + } + }; + // Walls. + poly(&[p(0.1, 0.0), p(0.9, 0.0), p(0.9, 0.6), p(0.1, 0.6)], true); + // Roof with eaves, and a chimney on its right slope. + poly(&[p(0.0, 0.55), p(0.5, 1.0), p(1.0, 0.55)], false); + poly(&[p(0.7, 0.82), p(0.7, 0.95), p(0.8, 0.95), p(0.8, 0.73)], false); + // Door. + poly(&[p(0.42, 0.0), p(0.42, 0.35), p(0.58, 0.35), p(0.58, 0.0)], false); + // Two windows with their bars. + for x in [0.17, 0.67] { + poly(&[p(x, 0.25), p(x + 0.16, 0.25), p(x + 0.16, 0.45), p(x, 0.45)], true); + poly(&[p(x + 0.08, 0.25), p(x + 0.08, 0.45)], false); + poly(&[p(x, 0.35), p(x + 0.16, 0.35)], false); + } + lines +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Stage { + #[default] + Select, + Option, + Twist, + PanBase, + PanSecond(Vec2), + Zoom, +} + +/// DVIEW, interactive. +#[derive(Default)] +struct DviewM { + stage: Stage, + sel: SelectPhase, + /// The preview set; empty with `sample` set: the DVIEWBLOCK. + preview: Vec, + /// Where the DVIEWBLOCK preview stands: its lower-left corner and size (drawing units), fixed + /// as the options start so that PAn and Zoom move the view, not the house. + sample: Option<(Vec2, f64)>, + /// The views before each DVIEW action, for Undo. + undo: Vec, + /// What DVIEW works on, and the drawing as it started (a viewport's twist change is one + /// undo step). + target: Option, + before: Option<(Arc, Vec)>, +} + +impl DviewM { + fn target(&self, s: &Session) -> Result { + match self.target { + Some(t) => Ok(t), + None => target(s), + } + } + /// Start the options with this preview set (empty: the DVIEWBLOCK). + fn options(&mut self, s: &mut Session, picked: Vec) -> Result { + // Objects picked at the prompt don't stay selected. + s.set_selection(Vec::new()); + if picked.is_empty() { + let v = s.state()?.view(); + let size = v.height * 0.5; + self.sample = Some((v.center - Vec2::new(size, size) * 0.5, size)); + } + self.preview = picked; + self.stage = Stage::Option; + Ok(Step::Continue) + } + /// Show view `v` (centre, height and twist) on the target. + fn show(&self, s: &mut Session, v: View) -> Result<()> { + let t = self.target(s)?; + let before = s.state()?.doc.clone(); + let twist = normal(v.twist); + if let Target::Viewport(_) = t { + // The twist is the viewport's; the view inside it then moves as asked. + set_twist(s, t, twist)?; + } + if !s.state_mut()?.set_view(View { twist, ..v }) { + s.state_mut()?.doc = before; + return Err(EngineError::Other("The view is too large to show.".into())); + } + Ok(()) + } + /// Apply a view as one DVIEW action (Undo takes it back). + fn change(&mut self, s: &mut Session, f: impl FnOnce(View) -> View) -> Result<()> { + let v = s.state()?.view(); + self.show(s, f(v))?; + self.undo.push(v); + Ok(()) + } + /// The command ends: a viewport twist change becomes one undo step, and the whole drawing is + /// regenerated. + fn end(&mut self, s: &mut Session) -> Result<()> { + if let (Some(Target::Viewport(h)), Some(before)) = (self.target, self.before.take()) { + record_viewport_edit(s, before, h)?; + } + s.touch(); + Ok(()) + } +} + +impl Interactive for DviewM { + fn name(&self) -> &'static str { + "DVIEW" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.target = Some(target(s)?); + self.before = Some(snapshot(s)?); + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + match self.stage { + Stage::Select if self.sel.removing => self.sel.prompt(), + Stage::Select => Prompt::new("Select objects or", Accept::SELECT).default("use DVIEWBLOCK"), + Stage::Option => Prompt::new("Enter option", Accept::TEXT).kw(OPTIONS).options_only(), + Stage::Twist => { + let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0)); + let cur = s.state().map(|st| st.view().twist).unwrap_or(0.0); + // Offered as it would be typed: clockwise is positive when ANGDIR is 1. + let cur = if s.angle_settings().clockwise { -cur } else { cur }; + let center = s.state().map(|st| st.view().center).ok(); + Prompt::new("Specify view twist angle", Accept::POINT_OR_NUMBER).default(crate::units::format_angle(cur, au, ap)).base_opt(center) + } + Stage::PanBase => Prompt::new("Specify displacement base point", Accept::POINT), + Stage::PanSecond(b) => Prompt::new("Specify second point", Accept::POINT).base(b), + Stage::Zoom => Prompt::new("Specify zoom scale factor", Accept::NUMBER).default("1"), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + self.end(s)?; + return Ok(Step::Cancel); + } + match self.stage { + Stage::Select => match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => self.options(s, Vec::new()), + SelOutcome::Done(hs) => self.options(s, hs), + }, + Stage::Option => { + let word = match &i { + Input::Enter => { + self.end(s)?; + return Ok(Step::Done); + } + Input::Keyword(t) | Input::Text(t) => self.prompt(s).match_keyword(t), + _ => None, + }; + match word.as_deref() { + Some("TWist") => self.stage = Stage::Twist, + Some("PAn") => self.stage = Stage::PanBase, + Some("Zoom") => self.stage = Stage::Zoom, + // Perspective is never on in a 2D view: there is nothing to turn off. + Some("Off") => {} + Some("Undo") => { + if let Some(v) = self.undo.pop() { + self.show(s, v)?; + } + } + // CAmera, TArget, Distance, POints, CLip and Hide need a 3D view. + Some(other) => s.echo(format!("DVIEW {other} is not available yet.")), + None => return Err(EngineError::Other("Invalid option keyword.".into())), + } + Ok(Step::Continue) + } + Stage::Twist => { + let twist = match &i { + Input::Enter => None, + Input::Point(p) => { + let c = s.state()?.view().center; + let d = *p - c; + if d.len() < 1e-12 { + return Err(EngineError::Other("Requires a valid angle.".into())); + } + Some(d.y.atan2(d.x)) + } + Input::Text(t) | Input::Keyword(t) if t.trim().is_empty() => None, + Input::Text(t) | Input::Keyword(t) => { + Some(s.angle_settings().rotation(t).ok_or_else(|| EngineError::Other("Requires a valid angle.".into()))?) + } + _ => return Ok(Step::Continue), + }; + if let Some(a) = twist { + self.change(s, |v| View { twist: normal(a), ..v })?; + } + self.stage = Stage::Option; + Ok(Step::Continue) + } + Stage::PanBase => match i { + Input::Point(p) => { + self.stage = Stage::PanSecond(p); + Ok(Step::Continue) + } + Input::Enter => { + self.stage = Stage::Option; + Ok(Step::Continue) + } + _ => Err(EngineError::Other("Invalid point.".into())), + }, + Stage::PanSecond(b) => match i { + Input::Point(p) => { + self.change(s, |v| View { center: v.center - (p - b), ..v })?; + self.stage = Stage::Option; + Ok(Step::Continue) + } + Input::Enter => { + self.stage = Stage::Option; + Ok(Step::Continue) + } + _ => Err(EngineError::Other("Invalid point.".into())), + }, + Stage::Zoom => { + let f = match &i { + Input::Enter => None, + Input::Text(t) | Input::Keyword(t) if t.trim().is_empty() => None, + Input::Text(t) | Input::Keyword(t) => match number(t) { + Some(f) if f.is_finite() && f > 0.0 => Some(f), + _ => return Err(EngineError::Other("Requires a positive number.".into())), + }, + _ => return Ok(Step::Continue), + }; + if let Some(f) = f.filter(|f| *f != 1.0) { + self.change(s, |v| View { height: v.height / f, ..v })?; + } + self.stage = Stage::Option; + Ok(Step::Continue) + } + } + } + fn display_only(&self, s: &Session) -> Option { + if self.stage == Stage::Select { + return None; + } + let mut extra = Vec::new(); + if let Some((corner, size)) = self.sample { + let common = s.current_common(); + let d = s.doc().ok()?; + if d.block(DVIEWBLOCK).is_some() { + // The drawing's own DVIEWBLOCK, defined in a 1 by 1 unit area. + let ins = Insert { + block: DVIEWBLOCK.into(), + insert: corner.to3(0.0), + scale: Vec3::new(size, size, size), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }; + extra.push(Entity { handle: Handle(0), common, kind: EntityKind::Insert(ins) }); + } else { + extra.extend(sample_house().into_iter().map(|(a, b)| Entity { + handle: Handle(0), + common: common.clone(), + kind: EntityKind::Line(Line { a: (corner + a * size).to3(0.0), b: (corner + b * size).to3(0.0) }), + })); + } + } + Some(DisplayOnly { handles: self.preview.clone(), extra }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_sample_house_fits_the_unit_square() { + let lines = sample_house(); + assert!(lines.len() > 10); + for (a, b) in lines { + for q in [a, b] { + assert!((0.0..=1.0).contains(&q.x) && (0.0..=1.0).contains(&q.y), "{q:?}"); + } + } + } +} diff --git a/crates/engine/src/cmd/view/named_views.rs b/crates/engine/src/cmd/view/named_views.rs index 40c25632b..66e5941e2 100644 --- a/crates/engine/src/cmd/view/named_views.rs +++ b/crates/engine/src/cmd/view/named_views.rs @@ -109,6 +109,8 @@ fn save(s: &mut Session, name: &str, window: Option, snapshot: bool) -> (Space::Paper(l), false) => Some(l.clone()), _ => None, }; + // The view twist goes with the view (layout viewports and paper space have none). + let twist = if in_viewport { 0.0 } else { st.view().twist }; let (center, height, width) = match window { Some(b) => { if !(b.width() > 1e-12 && b.height() > 1e-12 && b.min.is_finite() && b.max.is_finite()) { @@ -138,7 +140,7 @@ fn save(s: &mut Session, name: &str, window: Option, snapshot: bool) -> } d.views.retain(|v| !v.name.eq_ignore_ascii_case(old)); } - d.views.push(NamedView { name: name.to_string(), center, height, width, layer_state, twist: 0.0, layout }); + d.views.push(NamedView { name: name.to_string(), center, height, width, layer_state, twist, layout }); let msg = if replaced.is_some() { format!("View \"{name}\" replaced.") } else { format!("View \"{name}\" saved.") }; Ok(json!({ "name": name, "center": [center.x, center.y], "height": height, "width": width, "message": msg })) } @@ -167,7 +169,7 @@ fn restore(s: &mut Session, name: &str) -> Result { let st = s.state_mut()?; st.mspace = None; let height = v.height.max(v.width / (w / h.max(1.0)).max(1e-9)); - st.set_view(View { center: v.center, height }); + st.set_view(View { center: v.center, height, twist: 0.0 }); } None => { // A model space view: into the active MSPACE viewport, else on the Model tab. @@ -177,7 +179,8 @@ fn restore(s: &mut Session, name: &str) -> Result { let (w, h) = s.viewport_px; let st = s.state_mut()?; let aspect = st.zoom_aspect(w / h.max(1.0)).max(1e-9); - st.set_zoom_frame(View { center: v.center, height: v.height.max(v.width / aspect) }); + let twist = if v.twist.is_finite() { v.twist } else { 0.0 }; + st.set_zoom_frame(View { center: v.center, height: v.height.max(v.width / aspect), twist }); } } let mut msg = format!("View \"{}\" restored.", v.name); diff --git a/crates/engine/src/cmd/view/vports.rs b/crates/engine/src/cmd/view/vports.rs index 88ee0a6ed..9ada269f3 100644 --- a/crates/engine/src/cmd/view/vports.rs +++ b/crates/engine/src/cmd/view/vports.rs @@ -96,7 +96,7 @@ fn rect(t: &VportTile) -> Rect { } fn view_of(t: &VportTile) -> View { - View { center: t.center, height: t.height } + View { center: t.center, height: t.height, twist: if t.twist.is_finite() { t.twist } else { 0.0 } } } fn active_config(d: &Drawing) -> Option<&VportConfig> { @@ -109,7 +109,7 @@ fn live(st: &DocState, px: (f64, f64)) -> (Vec, usize) { let now = st.views.iter().find(|(sp, _)| *sp == Space::Model).map(|(_, v)| *v).unwrap_or_default(); let Some(cfg) = active_config(&st.doc) else { let aspect = px.0 / px.1.max(1.0); - return (vec![VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center: now.center, height: now.height, aspect }], 0); + return (vec![VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center: now.center, height: now.height, aspect, twist: now.twist }], 0); }; let mut tiles = cfg.tiles.clone(); let synced = @@ -117,11 +117,11 @@ fn live(st: &DocState, px: (f64, f64)) -> (Vec, usize) { let active = if synced { st.tiles.active.min(tiles.len() - 1) } else { 0 }; if synced { for (t, v) in tiles.iter_mut().zip(&st.tiles.views) { - (t.center, t.height) = (v.center, v.height); + (t.center, t.height, t.twist) = (v.center, v.height, v.twist); } } if let Some(t) = tiles.get_mut(active) { - (t.center, t.height) = (now.center, now.height); + (t.center, t.height, t.twist) = (now.center, now.height, now.twist); } // Screen aspects from the current tile's size in pixels. if let Some(cur) = tiles.get(active).copied() { @@ -163,7 +163,7 @@ fn summary(s: &Session) -> Result { let rows: Vec = tiles .iter() .enumerate() - .map(|(i, t)| json!({ "index": i + 1, "min": [t.min.x, t.min.y], "max": [t.max.x, t.max.y], "center": [t.center.x, t.center.y], "height": t.height, "current": i == active })) + .map(|(i, t)| json!({ "index": i + 1, "min": [t.min.x, t.min.y], "max": [t.max.x, t.max.y], "center": [t.center.x, t.center.y], "height": t.height, "twist": t.twist.to_degrees(), "current": i == active })) .collect(); Ok(json!({ "tiles": rows })) } diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 34401e314..7c6cfbcf6 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -93,6 +93,15 @@ impl Interactive for Guarded { None }) } + fn display_only(&self, s: &Session) -> Option { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.display_only(s))).unwrap_or_else(|_| { + self.broken.set(Some("panic in preview")); + None + }) + } } #[cfg(test)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 97f4b969b..9367a2469 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -42,7 +42,7 @@ pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; -pub use prompt::{Accept, Drag, Input, Interactive, Picker, Prompt, Step}; +pub use prompt::{Accept, DisplayOnly, Drag, Input, Interactive, Picker, Prompt, Step}; #[derive(Debug, thiserror::Error)] pub enum EngineError { @@ -69,21 +69,37 @@ impl From for EngineError { pub type Result = std::result::Result; -/// A 2D view of a space: world centre and visible height in drawing units. +/// A 2D view of a space: world centre and visible height in drawing units, and the view twist +/// (VIEWTWIST, DVIEW TWist): how far the view is turned on screen, in radians counterclockwise +/// (the drawing appears turned by `twist`; 0 is the plain plan view). #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct View { pub center: Vec2, pub height: f64, + #[serde(default)] + pub twist: f64, } impl Default for View { fn default() -> Self { - View { center: Vec2::new(6.0, 4.5), height: 10.0 } + View { center: Vec2::new(6.0, 4.5), height: 10.0, twist: 0.0 } + } +} + +impl View { + /// Box `b` (world) as a view turned by `twist` shows it: the world centre of the box it + /// makes on screen, and that box's width and height (`b`'s own when there is no twist). + pub fn twisted_box(b: Bounds2, twist: f64) -> (Vec2, f64, f64) { + if twist == 0.0 || !twist.is_finite() { + return (b.center(), b.width(), b.height()); + } + let r = Bounds2::from_points(b.corners().map(|p| p.rotate(twist))); + (r.center().rotate(-twist), r.width(), r.height()) } } fn usable_view(v: &View) -> bool { - v.center.is_finite() && v.height.is_finite() && v.height > 1e-12 + v.center.is_finite() && v.height.is_finite() && v.height > 1e-12 && v.twist.is_finite() } /// Tiled model viewports (VPORTS): the session side of the drawing's `*Active` configuration. @@ -227,7 +243,8 @@ impl DocState { match self.active_viewport() { Some((_, vp)) => { let k = vp.view_height / vp.height; - View { center: vp.view_center + (pv.center - vp.center.xy()) * k, height: pv.height * k } + // The viewport's twist turns the model view inside it. + View { center: vp.paper_to_model(pv.center), height: pv.height * k, twist: vp.view_twist() } } None => pv, } @@ -242,16 +259,17 @@ impl DocState { if vp.locked { // A locked viewport keeps its scale: pan/zoom the sheet instead. let k0 = vp.view_height / vp.height; - let pc = vp.center.xy() + (v.center - vp.view_center) / k0; - let paper = View { center: pc, height: v.height / k0 }; + let pc = vp.model_to_paper(v.center); + let paper = View { center: pc, height: v.height / k0, twist: pv.twist }; if !usable_view(&paper) { return false; } self.put_paper_view(paper); } else { - let center = v.center - (pv.center - vp.center.xy()) * k; + // The viewport keeps its own twist: `v`'s is the one it shows. + let center = v.center - ((pv.center - vp.center.xy()) * k).rotate(-vp.view_twist()); let height = vp.height * k; - if !usable_view(&View { center, height }) { + if !usable_view(&View { center, height, twist: 0.0 }) { return false; } let doc = Arc::make_mut(&mut self.doc); @@ -274,6 +292,29 @@ impl DocState { Some((_, slot)) => *slot = v, None => self.views.push((self.space.clone(), v)), } + if self.space == Space::Model { + self.keep_untiled_twist(v); + } + } + /// An untiled Model tab keeps its view twist in the drawing as a lone `*Active` VPORT tile + /// (written as that record's group 51 and read back), so it survives save and reopen. Only a + /// change of twist touches the drawing; an untwisted view keeps no record. + fn keep_untiled_twist(&mut self, v: View) { + use cadcraft_doc::{VportConfig, VportTile}; + let twist = if v.twist.is_finite() { v.twist.rem_euclid(std::f64::consts::TAU) } else { 0.0 }; + let active = self.doc.vports.iter().find(|c| c.is_active()); + if active.is_some_and(|c| c.tiles.len() > 1) { + return; + } + if active.and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist) == twist { + return; + } + let d = Arc::make_mut(&mut self.doc); + d.vports.retain(|c| !c.is_active()); + if twist != 0.0 { + let tile = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center: v.center, height: v.height, aspect: 1.0, twist }; + d.vports.insert(0, VportConfig { name: VportConfig::ACTIVE.into(), tiles: vec![tile] }); + } } /// Set the view, recording view history. Returns false, changing nothing, when the view (or, /// in MSPACE, the viewport view it maps to) isn't finite with a positive height. @@ -302,7 +343,7 @@ impl DocState { /// The view ZOOM starts from: the model view of the active unlocked viewport, else [`Self::view`]. pub fn zoom_frame(&self) -> View { match self.zoom_viewport() { - Some(v) => View { center: v.view_center, height: v.view_height }, + Some(v) => View { center: v.view_center, height: v.view_height, twist: v.view_twist() }, None => self.view(), } } @@ -317,7 +358,8 @@ impl DocState { Some(vp) => { let pv = self.paper_view(); let k = f.height / vp.height; - View { center: f.center + (pv.center - vp.center.xy()) * k, height: pv.height * k } + let twist = vp.view_twist(); + View { center: f.center + ((pv.center - vp.center.xy()) * k).rotate(-twist), height: pv.height * k, twist } } None => f, }; @@ -325,7 +367,7 @@ impl DocState { } /// Set without recording view history (realtime pan/zoom frames). pub fn set_view_quiet(&mut self, v: View) { - if !(v.center.is_finite() && v.height.is_finite() && v.height > 1e-12) { + if !usable_view(&v) { return; } self.store_view(v); @@ -725,7 +767,7 @@ impl Session { self.untitled_counter += 1; let d = if metric { Drawing::new_metric() } else { Drawing::new_imperial() }; let mut st = DocState::new(d, &format!("Drawing{}", self.untitled_counter), None); - st.set_view_quiet(if metric { View { center: Vec2::new(210.0, 148.5), height: 297.0 } } else { View::default() }); + st.set_view_quiet(if metric { View { center: Vec2::new(210.0, 148.5), height: 297.0, twist: 0.0 } } else { View::default() }); self.end_running(); self.docs.push(st); self.active = self.docs.len() - 1; @@ -734,11 +776,15 @@ impl Session { pub fn open_drawing(&mut self, d: Drawing, title: &str, path: Option) -> usize { let mut st = DocState::new(d, title, path); let ext = st.doc.extents(&Space::Model); - 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), - }); + // The current tile (the first), or the lone untiled view, keeps its saved twist. + let twist = + st.doc.vports.iter().find(|c| c.is_active()).and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist).rem_euclid(std::f64::consts::TAU); + let twist = if twist.is_finite() { twist } else { 0.0 }; + if ext.is_empty() { + st.set_view_quiet(View { twist, ..st.view() }); + } else { + let (center, w, h) = View::twisted_box(ext, twist); + st.set_view_quiet(View { center, height: (h.max(w * self.viewport_px.1 / self.viewport_px.0.max(1.0)) * 1.1).max(1e-6), twist }); } self.end_running(); self.docs.push(st); @@ -1407,6 +1453,13 @@ impl Session { kinds.into_iter().map(|k| Entity { handle: Handle(0), common: common.clone(), kind: k }).collect() } + /// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview + /// set, see [`Interactive::display_only`]), also while a transparent command interrupts it. + /// `None`: the drawing. + pub fn display_only(&self) -> Option { + [&self.running, &self.suspended].into_iter().flatten().find_map(|r| r.machine.display_only(self)) + } + /// The active command's preview as a transform of existing objects (see /// [`Interactive::drag`]), with its extra rubber-band geometry as entities. pub fn drag(&self, cursor: Vec2) -> Option<(Drag, Vec)> { @@ -1700,8 +1753,10 @@ impl Session { let ext = if ext.is_empty() { self.zoom_limits()? } else { ext }; let st = self.state_mut()?; let aspect = st.zoom_aspect(w / h.max(1.0)); - let height = ext.height().max(ext.width() / aspect.max(1e-6)).max(1e-6) * 1.05; - st.set_zoom_frame(View { center: ext.center(), height }); + let twist = st.zoom_frame().twist; + let (center, bw, bh) = View::twisted_box(ext, twist); + let height = bh.max(bw / aspect.max(1e-6)).max(1e-6) * 1.05; + st.set_zoom_frame(View { center, height, twist }); Ok(()) } @@ -1715,7 +1770,7 @@ impl Session { let h = (v.height / factor).clamp(1e-9, 1e12); let k = h / v.height; let c = about + (v.center - about) * k; - st.set_view_quiet(View { center: c, height: h }); + st.set_view_quiet(View { center: c, height: h, twist: v.twist }); Ok(()) } diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index 05eb77344..b6dbef7f5 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -57,6 +57,10 @@ pub struct Prompt { /// prompt (the routine writes all of it). #[serde(skip_serializing_if = "std::ops::Not::not")] pub raw: bool, + /// The message asks for one of the keywords, so they follow it without "or" (DVIEW's + /// "Enter option [CAmera/TArget/…]:"). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub options_only: bool, } /// Parse `@distance Self { + self.options_only = true; + self + } + /// The separator written between the message and the keywords: " or [", or " [" for a + /// question ("Fix any errors detected? [Yes/No]") or an option prompt ([`Prompt::options_only`]). + pub fn keyword_opening(&self) -> &'static str { + if self.message.is_empty() { + "[" + } else if self.message.ends_with('?') || self.options_only { + " [" + } else { + " or [" + } + } pub fn default(mut self, d: impl Into) -> Self { self.default = Some(d.into()); self @@ -133,13 +153,7 @@ impl Prompt { if !self.keywords.is_empty() { // A question offers its answers ("Fix any errors detected? [Yes/No]"); anything else // offers options besides what it asks for ("Specify next point or [Undo]"). - s.push_str(if self.message.is_empty() { - "[" - } else if self.message.ends_with('?') { - " [" - } else { - " or [" - }); + s.push_str(self.keyword_opening()); s.push_str(&self.keywords.join("/")); s.push(']'); } @@ -220,6 +234,22 @@ pub trait Interactive: Send { fn editing_mtext(&self) -> Option { None } + /// What the drawing area shows in place of the drawing while the command runs (DVIEW draws + /// only its preview set); `None` shows the drawing. + fn display_only(&self, _s: &Session) -> Option { + None + } +} + +/// See [`Interactive::display_only`]: the only things drawn in the current view while a command +/// runs. The whole drawing is drawn again when it ends. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DisplayOnly { + /// Objects of the drawing, drawn as they are. + pub handles: Vec, + /// Geometry that is not in the drawing (DVIEW's sample house, or an insert of the drawing's + /// DVIEWBLOCK block), with its own properties. + pub extra: Vec, } /// See [`Interactive::drag`]. diff --git a/crates/engine/src/snap/viewport.rs b/crates/engine/src/snap/viewport.rs index 91a456801..d016d3056 100644 --- a/crates/engine/src/snap/viewport.rs +++ b/crates/engine/src/snap/viewport.rs @@ -40,7 +40,8 @@ impl<'a> Projection<'a> { } let half = Vec2::new(viewport.width / 2.0, viewport.height / 2.0); let paper_clip = Bounds2::new(center - half, center + half); - let model_clip = Bounds2::new(viewport.view_center - half / scale, viewport.view_center + half / scale); + // The model box the viewport shows (turned, with a view twist). + let model_clip = Bounds2::from_points(paper_clip.corners().map(|p| viewport.paper_to_model(p))); if ![paper_clip.min, paper_clip.max, model_clip.min, model_clip.max].into_iter().all(Vec2::is_finite) { return None; } @@ -48,11 +49,11 @@ impl<'a> Projection<'a> { } pub fn to_model(&self, point: Vec2) -> Vec2 { - self.viewport.view_center + (point - self.viewport.center.xy()) / self.scale + self.viewport.paper_to_model(point) } fn to_paper(&self, point: Vec2) -> Vec2 { - self.viewport.center.xy() + (point - self.viewport.view_center) * self.scale + self.viewport.model_to_paper(point) } pub fn hit(&self, mut hit: SnapHit) -> Option { diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 31451b6bc..1aa73fa35 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -152,6 +152,8 @@ 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 view twist (DVIEW TWist), in degrees counterclockwise. + "VIEWTWIST" => json!(s.state().ok()?.view().twist.to_degrees()), "EXTMIN" | "EXTMAX" => { let d = s.doc().ok()?; let e = d.extents(&s.space()); @@ -196,8 +198,21 @@ 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", + "VIEWTWIST", + "EXTMIN", + "EXTMAX", + "UNDOCTL", + "UNDOMARKS", +]; 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/tests.rs b/crates/engine/src/tests.rs index 93eba7701..4c0694912 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -185,7 +185,7 @@ fn move_with_pickfirst_and_window_selection() { s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap(); s.execute("line", &json!({"points": [[5, 5], [6, 5]]})).unwrap(); s.viewport_px = (1000.0, 1000.0); - s.state_mut().unwrap().set_view(View { center: Vec2::new(3.0, 3.0), height: 10.0 }); + s.state_mut().unwrap().set_view(View { center: Vec2::new(3.0, 3.0), height: 10.0, twist: 0.0 }); // Window selection from left to right picks only the first line. s.cmdline("move").unwrap(); s.input(Input::Point(Vec2::new(-1.0, -1.0))).unwrap(); diff --git a/crates/engine/tests/dview.rs b/crates/engine/tests/dview.rs new file mode 100644 index 000000000..2a81b743a --- /dev/null +++ b/crates/engine/tests/dview.rs @@ -0,0 +1,280 @@ +//! DVIEW starts with "Select objects or :", then the option prompt; +//! TWist, PAn, Zoom, Off and Undo on a 2D view; the 3D options not available yet. It works on the +//! Model tab and inside an active layout viewport (whose twist is an undoable edit of the +//! viewport), and not on a layout sheet. + +use cadcraft_doc::{EntityKind, Handle, Viewport}; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session, View}; +use serde_json::json; + +const SELECT: &str = "Select objects or :"; +const OPTION: &str = "Enter option [CAmera/TArget/Distance/POints/PAn/Zoom/TWist/CLip/Hide/Off/Undo]:"; +const PAPER: &str = "This command is not available in Paper space."; + +fn session() -> Session { + let mut s = Session::new(); + s.viewport_px = (1200.0, 800.0); + s.execute("line", &json!({ "points": [[0, 0], [100, 50]] })).unwrap(); + s.execute("view.set", &json!({ "center": [10, 10], "height": 20 })).unwrap(); + s +} + +fn prompt(s: &Session) -> String { + s.current_prompt().map(|p| p.display()).unwrap_or_default() +} + +fn view(s: &Session) -> View { + s.state().unwrap().view() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +fn twist_deg(s: &Session) -> f64 { + view(s).twist.to_degrees() +} + +fn logged(s: &Session, m: &str) -> bool { + s.log.iter().any(|l| l == m) +} + +#[test] +fn every_prompt_step_on_the_model_tab() { + let mut s = session(); + let undo = s.state().unwrap().undo.len(); + s.cmdline("dview").unwrap(); + assert_eq!(prompt(&s), SELECT); + // The whole drawing shows while objects are picked. + assert!(s.display_only().is_none()); + // Enter with nothing selected: the DVIEWBLOCK sample (a house of lines) is the preview set. + s.cmdline("").unwrap(); + assert_eq!(prompt(&s), OPTION); + let only = s.display_only().unwrap(); + assert!(only.handles.is_empty()); + assert!(only.extra.len() > 10 && only.extra.iter().all(|e| matches!(e.kind, EntityKind::Line(_)))); + + // TWist: the current twist is the default; a typed angle turns the view. + s.cmdline("tw").unwrap(); + assert_eq!(prompt(&s), "Specify view twist angle <0>:"); + s.cmdline("30").unwrap(); + assert!(near(twist_deg(&s), 30.0)); + assert_eq!(prompt(&s), OPTION); + s.cmdline("TWist").unwrap(); + assert_eq!(prompt(&s), "Specify view twist angle <30>:"); + // Enter keeps it. + s.cmdline("").unwrap(); + assert!(near(twist_deg(&s), 30.0)); + + // PAn: base point, second point. + s.cmdline("pa").unwrap(); + assert_eq!(prompt(&s), "Specify displacement base point:"); + s.cmdline("0,0").unwrap(); + assert_eq!(prompt(&s), "Specify second point:"); + s.cmdline("4,0").unwrap(); + assert_eq!(view(&s).center, Vec2::new(6.0, 10.0)); + assert_eq!(prompt(&s), OPTION); + + // Zoom: a scale factor of the current view. + s.cmdline("z").unwrap(); + assert_eq!(prompt(&s), "Specify zoom scale factor <1>:"); + s.cmdline("2").unwrap(); + assert!(near(view(&s).height, 10.0)); + // The sample house stays where it was put: the view moves over it. + assert_eq!(s.display_only().unwrap(), only); + + // Off: perspective is never on in a 2D view, so nothing changes. + let before = view(&s); + s.cmdline("o").unwrap(); + assert_eq!(prompt(&s), OPTION); + assert_eq!(view(&s), before); + + // The options that need a 3D camera are not available yet and stay at the option prompt. + for (typed, name) in [("ca", "CAmera"), ("ta", "TArget"), ("d", "Distance"), ("po", "POints"), ("cl", "CLip"), ("h", "Hide")] { + s.cmdline(typed).unwrap(); + assert!(logged(&s, &format!("DVIEW {name} is not available yet.")), "{name}: {:?}", s.log); + assert_eq!(prompt(&s), OPTION); + } + assert!(!s.log.iter().any(|l| l.contains("Only the view twist"))); + + // Undo takes back one DVIEW action at a time: zoom, pan, twist. + s.cmdline("u").unwrap(); + assert!(near(view(&s).height, 20.0)); + s.cmdline("u").unwrap(); + assert_eq!(view(&s).center, Vec2::new(10.0, 10.0)); + assert!(near(twist_deg(&s), 30.0)); + s.cmdline("u").unwrap(); + assert_eq!(view(&s).twist, 0.0); + // Nothing left to undo: still at the option prompt. + s.cmdline("u").unwrap(); + assert_eq!(prompt(&s), OPTION); + + // An unknown option is refused and asked again. + assert!(s.cmdline("bogus").is_ok()); + assert_eq!(prompt(&s), OPTION); + + // Enter ends DVIEW; the whole drawing shows again, and a Model tab twist is no undo step. + s.cmdline("tw").unwrap(); + s.cmdline("45").unwrap(); + s.cmdline("").unwrap(); + assert!(s.current_prompt().is_none()); + assert!(s.display_only().is_none()); + assert!(near(twist_deg(&s), 45.0)); + assert_eq!(s.state().unwrap().undo.len(), undo); +} + +#[test] +fn selected_objects_are_the_preview_set() { + let mut s = session(); + let line = s.doc().unwrap().model.iter().next().map(|e| e.handle).unwrap(); + s.execute("line", &json!({ "points": [[0, 10], [10, 10]] })).unwrap(); + s.cmdline("dview").unwrap(); + s.input(Input::Pick(vec![line])).unwrap(); + assert_eq!(prompt(&s), SELECT); + s.cmdline("").unwrap(); + assert_eq!(prompt(&s), OPTION); + let only = s.display_only().unwrap(); + assert_eq!(only.handles, vec![line]); + assert!(only.extra.is_empty(), "no sample house with a selection"); + // Picked at the prompt, the objects don't stay selected. + assert!(s.selection().is_empty()); + // Escape ends it too, and the drawing shows again. + s.input(Input::Cancel).unwrap(); + assert!(s.current_prompt().is_none()); + assert!(s.display_only().is_none()); +} + +#[test] +fn a_dviewblock_of_the_drawings_own_is_previewed() { + let mut s = session(); + s.execute("circle", &json!({ "center": [0.5, 0.5], "radius": 0.5 })).unwrap(); + let c = s.doc().unwrap().model.iter().last().map(|e| e.handle).unwrap(); + s.execute("block", &json!({ "name": "DVIEWBLOCK", "base": [0, 0], "handles": [c.hex()], "keep": "delete" })).unwrap(); + s.cmdline("dview").unwrap(); + s.cmdline("").unwrap(); + let only = s.display_only().unwrap(); + assert_eq!(only.extra.len(), 1); + match &only.extra[0].kind { + EntityKind::Insert(i) => { + assert_eq!(i.block, "DVIEWBLOCK"); + // Scaled from its 1 by 1 unit area to half the view's height. + assert!(near(i.scale.x, 10.0) && near(i.scale.y, 10.0)); + } + k => panic!("{k:?}"), + } + s.cmdline("").unwrap(); +} + +/// A layout with one viewport, `(session, viewport handle)`. +fn layout_session() -> (Session, Handle) { + let mut s = session(); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + let r = s.execute("mview", &json!({ "p1": [20, 20], "p2": [220, 120] })).unwrap(); + let h = Handle::parse_hex(r["viewports"][0].as_str().unwrap()).unwrap(); + (s, h) +} + +fn vp(s: &Session, h: Handle) -> Viewport { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Viewport(v) => v.clone(), + _ => panic!("not a viewport"), + } +} + +#[test] +fn on_a_layout_sheet_it_is_not_available() { + let (mut s, _) = layout_session(); + assert_eq!(s.execute("dview", &json!({ "twist": 10 })).unwrap_err().to_string(), PAPER); + assert_eq!(s.cmdline("dview").unwrap_err().to_string(), PAPER); + assert!(s.current_prompt().is_none()); + // view.set can't turn the sheet either; an untwisted view is fine. + assert_eq!(s.execute("view.set", &json!({ "center": [0, 0], "height": 5, "twist": 15 })).unwrap_err().to_string(), PAPER); + s.execute("view.set", &json!({ "center": [0, 0], "height": 5 })).unwrap(); +} + +#[test] +fn inside_an_active_viewport_it_twists_that_viewport_as_one_undo_step() { + let (mut s, h) = layout_session(); + s.execute("mspace", &json!({ "handle": h.hex() })).unwrap(); + let undo = s.state().unwrap().undo.len(); + let pv = s.state().unwrap().paper_view(); + s.cmdline("dview").unwrap(); + assert_eq!(prompt(&s), SELECT); + s.cmdline("").unwrap(); + s.cmdline("tw").unwrap(); + s.cmdline("30").unwrap(); + // The viewport entity carries the twist, and the model view inside it is turned by it. + assert!(near(vp(&s, h).twist.to_degrees(), 30.0)); + assert!(near(twist_deg(&s), 30.0)); + // The sheet itself is not turned. + assert_eq!(s.state().unwrap().paper_view(), pv); + s.cmdline("tw").unwrap(); + s.cmdline("50").unwrap(); + s.cmdline("").unwrap(); + assert!(s.current_prompt().is_none()); + assert!(near(vp(&s, h).twist.to_degrees(), 50.0)); + // One undo step for the whole DVIEW, which turns the viewport back. + assert_eq!(s.state().unwrap().undo.len(), undo + 1); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(vp(&s, h).twist, 0.0); + + // The JSON form and view.set twist the viewport the same way, each one undo step. + s.execute("dview", &json!({ "twist": -90 })).unwrap(); + assert!(near(vp(&s, h).twist.to_degrees(), 270.0)); + assert_eq!(s.state().unwrap().undo.len(), undo + 1); + let v = view(&s); + s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height, "twist": 15 })).unwrap(); + assert!(near(vp(&s, h).twist.to_degrees(), 15.0)); + assert_eq!(s.state().unwrap().undo.len(), undo + 2); + // Setting a view without a twist keeps the viewport's. + s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height })).unwrap(); + assert!(near(vp(&s, h).twist.to_degrees(), 15.0)); + assert_eq!(s.state().unwrap().undo.len(), undo + 2); + + // Back on the sheet, DVIEW is not available again. + s.execute("pspace", &json!({})).unwrap(); + assert_eq!(s.cmdline("dview").unwrap_err().to_string(), PAPER); +} + +#[test] +fn the_view_inside_a_twisted_viewport_maps_the_screen_like_the_sheet() { + let (mut s, h) = layout_session(); + s.execute("mspace", &json!({ "handle": h.hex() })).unwrap(); + s.execute("dview", &json!({ "twist": 30 })).unwrap(); + let st = s.state().unwrap(); + let (vpe, pv, v) = (vp(&s, h), st.paper_view(), st.view()); + // The model view's centre is the model point at the sheet's view centre. + assert!((vpe.model_to_paper(v.center) - pv.center).len() < 1e-9); + assert!(near(v.twist, vpe.twist)); + // Panning the view inside the viewport moves its model view, keeping the twist. + let moved = View { center: v.center + Vec2::new(5.0, -2.0), ..v }; + s.state_mut().unwrap().set_view(moved); + let after = view(&s); + assert!((after.center - moved.center).len() < 1e-9, "{after:?}"); + assert!(near(after.twist, vpe.twist)); + assert_eq!(s.state().unwrap().paper_view(), pv); + // ZOOM Extents fits the turned box of the drawing in the viewport. + s.execute("zoom", &json!({ "mode": "extents" })).unwrap(); + assert!(near(view(&s).twist, vpe.twist)); +} + +#[test] +fn a_viewport_twist_survives_a_dxf_round_trip() { + let (mut s, h) = layout_session(); + s.execute("mspace", &json!({ "handle": h.hex() })).unwrap(); + s.execute("dview", &json!({ "twist": 30 })).unwrap(); + let dxf = cadcraft_io::write_dxf(s.doc().unwrap()); + let back = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + let twists: Vec = back + .layouts + .iter() + .flat_map(|l| l.entities.iter()) + .filter_map(|e| match &e.kind { + EntityKind::Viewport(v) if v.id != 1 => Some(v.twist.to_degrees()), + _ => None, + }) + .collect(); + assert_eq!(twists.len(), 1); + assert!((twists[0] - 30.0).abs() < 1e-9, "{twists:?}"); +} diff --git a/crates/engine/tests/followups_626.rs b/crates/engine/tests/followups_626.rs index 7032a4c31..f19ad61bb 100644 --- a/crates/engine/tests/followups_626.rs +++ b/crates/engine/tests/followups_626.rs @@ -135,9 +135,9 @@ fn mview_restore_puts_a_saved_configuration_on_a_layout() { fn mview_restore_ignores_unusable_tiles_from_files() { let (mut s, _) = two_tiles(); let bad = [ - VportTile { min: v(f64::NAN, 0.0), max: v(1.0, 1.0), center: v(0.0, 0.0), height: 1.0, aspect: 1.0 }, - VportTile { min: v(0.5, 0.5), max: v(0.5, 0.9), center: v(0.0, 0.0), height: 1.0, aspect: 1.0 }, - VportTile { min: v(-3.0, -3.0), max: v(9.0, 9.0), center: v(f64::INFINITY, 0.0), height: -1.0, aspect: f64::NAN }, + VportTile { min: v(f64::NAN, 0.0), max: v(1.0, 1.0), center: v(0.0, 0.0), height: 1.0, aspect: 1.0, twist: 0.0 }, + VportTile { min: v(0.5, 0.5), max: v(0.5, 0.9), center: v(0.0, 0.0), height: 1.0, aspect: 1.0, twist: 0.0 }, + VportTile { min: v(-3.0, -3.0), max: v(9.0, 9.0), center: v(f64::INFINITY, 0.0), height: -1.0, aspect: f64::NAN, twist: 0.0 }, ]; if let Some(c) = s.doc_mut().unwrap().vports.iter_mut().find(|c| c.name == "Two") { c.tiles = bad.to_vec(); diff --git a/crates/engine/tests/measure_distance_snapping.rs b/crates/engine/tests/measure_distance_snapping.rs index adb365774..52c1a7c99 100644 --- a/crates/engine/tests/measure_distance_snapping.rs +++ b/crates/engine/tests/measure_distance_snapping.rs @@ -27,6 +27,7 @@ fn drawing() -> (Drawing, Space) { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }), ) .unwrap(); diff --git a/crates/engine/tests/named_views.rs b/crates/engine/tests/named_views.rs index f33a02cd2..606e531bd 100644 --- a/crates/engine/tests/named_views.rs +++ b/crates/engine/tests/named_views.rs @@ -46,7 +46,7 @@ fn typed_save_restore_list_delete() { // Saving is an undo step; a view change is not. set_view(&mut s, 0.0, 0.0, 500.0); typed(&mut s, &["view", "r", "front"]); - assert_eq!(view(&s), View { center: Vec2::new(10.0, 20.0), height: 30.0 }); + assert_eq!(view(&s), View { center: Vec2::new(10.0, 20.0), height: 30.0, twist: 0.0 }); // Zoom Previous goes back to the view before the restore. s.execute("zoom.previous", &json!({})).unwrap(); assert_eq!(view(&s).height, 500.0); @@ -112,7 +112,7 @@ fn paper_space_view_switches_to_its_layout() { s.execute("layout.set", &json!({ "name": "Model" })).unwrap(); s.execute("view", &json!({ "option": "restore", "name": "Sheet" })).unwrap(); assert_eq!(s.layout_space(), Space::Paper(layout)); - assert_eq!(view(&s), View { center: Vec2::new(5.0, 4.0), height: 6.0 }); + assert_eq!(view(&s), View { center: Vec2::new(5.0, 4.0), height: 6.0, twist: 0.0 }); } #[test] @@ -138,7 +138,7 @@ fn zoom_realtime_drags_and_enter_ends() { assert_eq!(view(&s).height, 100.0); // The JSON form zooms by a factor about the centre. s.execute("zoom.realtime", &json!({ "factor": 4 })).unwrap(); - assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0 }); + assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0, twist: 0.0 }); } #[test] @@ -158,10 +158,10 @@ fn zoom_dynamic_places_and_sizes_the_view_box() { assert!(close(v.height, 40.0), "{v:?}"); // Zoom Previous skips the overview. s.execute("zoom.previous", &json!({})).unwrap(); - assert_eq!(view(&s), View { center: Vec2::new(10.0, 10.0), height: 20.0 }); + assert_eq!(view(&s), View { center: Vec2::new(10.0, 10.0), height: 20.0, twist: 0.0 }); // JSON: like Center. s.execute("zoom.dynamic", &json!({ "center": [1, 2], "height": 3 })).unwrap(); - assert_eq!(view(&s), View { center: Vec2::new(1.0, 2.0), height: 3.0 }); + assert_eq!(view(&s), View { center: Vec2::new(1.0, 2.0), height: 3.0, twist: 0.0 }); } #[test] diff --git a/crates/engine/tests/view_twist.rs b/crates/engine/tests/view_twist.rs new file mode 100644 index 000000000..02eb8d7fe --- /dev/null +++ b/crates/engine/tests/view_twist.rs @@ -0,0 +1,193 @@ +//! The view twist (VIEWTWIST): DVIEW TWist turns the Model tab's view, ZOOM Previous turns it +//! back, each VPORTS tile keeps its own (DXF VPORT group 51), and VIEW Save/Restore keep it. + +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Session, View, sysvars}; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.viewport_px = (1200.0, 800.0); + s.execute("line", &json!({ "points": [[0, 0], [100, 50]] })).unwrap(); + s.execute("view.set", &json!({ "center": [10, 10], "height": 20 })).unwrap(); + s +} + +fn typed(s: &mut Session, lines: &[&str]) { + for l in lines { + s.cmdline(l).unwrap(); + } +} + +fn view(s: &Session) -> View { + s.state().unwrap().view() +} + +fn twist_deg(s: &Session) -> f64 { + view(s).twist.to_degrees() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn dview_twist_sets_viewtwist_and_zoom_previous_turns_it_back() { + let mut s = session(); + assert_eq!(view(&s).twist, 0.0); + typed(&mut s, &["dview", "", "tw", "30", ""]); + assert!(near(twist_deg(&s), 30.0), "twist {}", twist_deg(&s)); + let vt = sysvars::get(&s, "VIEWTWIST").and_then(|v| v.as_f64()).unwrap(); + assert!(near(vt, 30.0), "VIEWTWIST {vt}"); + // Only the twist changed; the view is not an undo step. + assert_eq!((view(&s).center, view(&s).height), (Vec2::new(10.0, 10.0), 20.0)); + assert_eq!(s.state().unwrap().undo.len(), 1, "just the line"); + // Zooming keeps the twist; ZOOM Previous steps back through it. + s.execute("zoom", &json!({ "mode": "in" })).unwrap(); + assert!(near(twist_deg(&s), 30.0)); + s.execute("zoom", &json!({ "mode": "previous" })).unwrap(); + s.execute("zoom", &json!({ "mode": "previous" })).unwrap(); + assert_eq!(view(&s).twist, 0.0); + assert!(sysvars::is_read_only("VIEWTWIST")); + // JSON form; negative angles wrap into 0..360. + s.execute("dview", &json!({ "twist": -90 })).unwrap(); + assert!(near(twist_deg(&s), 270.0)); + // The 3D options are not available yet; the command carries on. + typed(&mut s, &["dview", "", "ca", ""]); + assert!(s.current_prompt().is_none()); + // Not in a layout. + let layout = s.doc().unwrap().layouts.first().map(|l| l.name.clone()).unwrap(); + s.execute("layout.set", &json!({ "name": layout })).unwrap(); + assert!(s.execute("dview", &json!({ "twist": 10 })).is_err()); +} + +const PAPER: &str = "This command is not available in Paper space."; + +#[test] +fn dview_in_paper_space_says_it_is_not_available() { + let mut s = session(); + let layout = s.doc().unwrap().layouts.first().map(|l| l.name.clone()).unwrap(); + s.execute("layout.set", &json!({ "name": layout })).unwrap(); + let e = s.execute("dview", &json!({ "twist": 10 })).unwrap_err(); + assert_eq!(e.to_string(), PAPER); + // Typed, it is refused as it starts: no prompt is left open. + let e = s.cmdline("dview").unwrap_err(); + assert_eq!(e.to_string(), PAPER); + assert!(s.current_prompt().is_none()); + // view.set can't turn a layout's view either (an untwisted one is fine). + let e = s.execute("view.set", &json!({ "center": [0, 0], "height": 5, "twist": 15 })).unwrap_err(); + assert_eq!(e.to_string(), PAPER); + s.execute("view.set", &json!({ "center": [0, 0], "height": 5 })).unwrap(); + assert_eq!(view(&s).twist, 0.0); +} + +#[test] +fn a_single_untiled_view_keeps_its_twist_through_a_dxf_round_trip() { + let mut s = session(); + s.execute("dview", &json!({ "twist": 30 })).unwrap(); + assert!(s.model_tiles().len() <= 1, "untiled"); + let dxf = cadcraft_io::write_dxf(s.doc().unwrap()); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let written = lines.windows(2).any(|w| w[0] == "51" && w[1].parse::().is_ok_and(|a| near(a, 30.0))); + assert!(written, "the lone *ACTIVE VPORT carries group 51"); + let back = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + let mut o = Session::new(); + o.viewport_px = (1200.0, 800.0); + o.open_drawing(back.clone(), "single", None); + assert!(near(twist_deg(&o), 30.0), "twist {}", twist_deg(&o)); + assert!(o.model_tiles().len() <= 1, "still untiled"); + // And again: saved from the reopened session, it is still turned. + let again = cadcraft_io::read_dxf(cadcraft_io::write_dxf(o.doc().unwrap()).as_bytes()).unwrap(); + let mut o2 = Session::new(); + o2.viewport_px = (1200.0, 800.0); + o2.open_drawing(again, "again", None); + assert!(near(twist_deg(&o2), 30.0)); + // Turned back (ZOOM Previous here), the drawing keeps no twist. + s.execute("zoom", &json!({ "mode": "previous" })).unwrap(); + assert_eq!(view(&s).twist, 0.0); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let mut o3 = Session::new(); + o3.viewport_px = (1200.0, 800.0); + o3.open_drawing(back, "plain", None); + assert_eq!(view(&o3).twist, 0.0); +} + +#[test] +fn zoom_extents_fits_in_the_twisted_frame() { + let mut s = session(); + s.execute("dview", &json!({ "twist": 90 })).unwrap(); + s.execute("zoom", &json!({ "mode": "extents" })).unwrap(); + let v = view(&s); + // Turned a quarter, the 100 x 50 line's box stands 100 high on screen. + assert!(near(v.twist.to_degrees(), 90.0)); + assert!((v.center - Vec2::new(50.0, 25.0)).len() < 1e-6, "{:?}", v.center); + assert!(near(v.height, 105.0), "height {}", v.height); +} + +#[test] +fn each_tile_keeps_its_twist_through_a_dxf_round_trip() { + let mut s = session(); + s.execute("-vports", &json!({ "option": "2", "arrangement": "vertical" })).unwrap(); + s.execute("dview", &json!({ "twist": 30 })).unwrap(); + let first = s.model_tiles().iter().position(|t| t.active).unwrap(); + s.activate_tile(1 - first).unwrap(); + assert_eq!(view(&s).twist, 0.0, "the other tile has its own twist"); + s.execute("dview", &json!({ "twist": 60 })).unwrap(); + let mut tw: Vec = s.model_tiles().iter().map(|t| t.view.twist.to_degrees()).collect(); + tw.sort_by(f64::total_cmp); + assert!(near(tw[0], 30.0) && near(tw[1], 60.0), "{tw:?}"); + // Switching back shows the first tile's twist again. + s.activate_tile(first).unwrap(); + assert!(near(twist_deg(&s), 30.0)); + // A saved configuration keeps both twists through DXF (VPORT group 51). + s.execute("-vports", &json!({ "option": "save", "name": "Pair" })).unwrap(); + let dxf = cadcraft_io::write_dxf(s.doc().unwrap()); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let written = lines.windows(2).any(|w| w[0] == "51" && w[1].parse::().is_ok_and(|a| near(a, 30.0))); + assert!(written, "group 51 written"); + let back = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + let pair = back.vports.iter().find(|c| c.name == "Pair").unwrap(); + let mut tw: Vec = pair.tiles.iter().map(|t| t.twist.to_degrees()).collect(); + tw.sort_by(f64::total_cmp); + assert!(near(tw[0], 30.0) && near(tw[1], 60.0), "{tw:?}"); + // Opened, restoring the configuration shows each tile turned as saved. + let mut o = Session::new(); + o.viewport_px = (1200.0, 800.0); + o.open_drawing(back, "pair", None); + o.execute("-vports", &json!({ "option": "restore", "name": "Pair" })).unwrap(); + let mut tw: Vec = o.model_tiles().iter().map(|t| t.view.twist.to_degrees()).collect(); + tw.sort_by(f64::total_cmp); + assert!(near(tw[0], 30.0) && near(tw[1], 60.0), "{tw:?}"); +} + +#[test] +fn opening_a_tiled_drawing_shows_the_current_tile_twisted() { + let mut s = session(); + s.execute("dview", &json!({ "twist": 45 })).unwrap(); + s.execute("-vports", &json!({ "option": "2" })).unwrap(); + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let mut o = Session::new(); + o.viewport_px = (1200.0, 800.0); + o.open_drawing(back, "tiled", None); + assert!(near(twist_deg(&o), 45.0), "twist {}", twist_deg(&o)); +} + +#[test] +fn view_save_and_restore_keep_the_twist() { + let mut s = session(); + s.execute("dview", &json!({ "twist": 30 })).unwrap(); + s.execute("view", &json!({ "option": "save", "name": "Turned" })).unwrap(); + let saved = s.doc().unwrap().views.iter().find(|v| v.name == "Turned").map(|v| v.twist.to_degrees()).unwrap(); + assert!(near(saved, 30.0)); + s.execute("dview", &json!({ "twist": 0 })).unwrap(); + s.execute("view.set", &json!({ "center": [80, 40], "height": 3 })).unwrap(); + assert_eq!(view(&s).twist, 0.0); + s.execute("view", &json!({ "option": "restore", "name": "Turned" })).unwrap(); + assert!(near(twist_deg(&s), 30.0)); + assert!((view(&s).center - Vec2::new(10.0, 10.0)).len() < 1e-9); + // view.set keeps the twist unless given one. + s.execute("view.set", &json!({ "center": [0, 0], "height": 5 })).unwrap(); + assert!(near(twist_deg(&s), 30.0)); + s.execute("view.set", &json!({ "center": [0, 0], "height": 5, "twist": 15 })).unwrap(); + assert!(near(twist_deg(&s), 15.0)); +} diff --git a/crates/engine/tests/vports.rs b/crates/engine/tests/vports.rs index 543840220..abc69d4b1 100644 --- a/crates/engine/tests/vports.rs +++ b/crates/engine/tests/vports.rs @@ -46,15 +46,15 @@ fn split_activate_and_each_tile_keeps_its_view() { s.execute("-vports", &json!({ "option": "2", "arrangement": "vertical" })).unwrap(); assert_eq!(rects(&s), vec![[0.0, 0.0, 0.5, 1.0], [0.5, 0.0, 1.0, 1.0]]); // Every new tile starts with the view that was split. - assert!(tiles(&s).iter().all(|t| t.view == View { center: Vec2::new(10.0, 10.0), height: 20.0 })); + assert!(tiles(&s).iter().all(|t| t.view == View { center: Vec2::new(10.0, 10.0), height: 20.0, twist: 0.0 })); let first = current(&s); let other = 1 - first; s.activate_tile(other).unwrap(); assert_eq!(current(&s), other); s.execute("view.set", &json!({ "center": [50, 25], "height": 5 })).unwrap(); s.execute("vports.activate", &json!({ "index": first + 1 })).unwrap(); - assert_eq!(view(&s), View { center: Vec2::new(10.0, 10.0), height: 20.0 }); - assert_eq!(tiles(&s)[other].view, View { center: Vec2::new(50.0, 25.0), height: 5.0 }); + assert_eq!(view(&s), View { center: Vec2::new(10.0, 10.0), height: 20.0, twist: 0.0 }); + assert_eq!(tiles(&s)[other].view, View { center: Vec2::new(50.0, 25.0), height: 5.0, twist: 0.0 }); // Switching tiles changes no drawing data; arranging them is an undo step. assert_eq!(s.state().unwrap().undo.len(), 2, "line + VPORTS"); s.undo().unwrap(); @@ -82,7 +82,7 @@ fn typed_three_right_then_join_and_single() { s.click_tile(bottom).unwrap(); assert!(s.running.is_none(), "{}", s.prompt_text()); assert_eq!(rects(&s), vec![[0.0, 0.0, 0.5, 1.0], [0.5, 0.0, 1.0, 1.0]]); - assert_eq!(view(&s), View { center: Vec2::new(1.0, 2.0), height: 3.0 }); + assert_eq!(view(&s), View { center: Vec2::new(1.0, 2.0), height: 3.0, twist: 0.0 }); // Tiles that don't make a rectangle can't be joined. s.execute("-vports", &json!({ "option": "3", "arrangement": "above" })).unwrap(); let t = tiles(&s); @@ -93,7 +93,7 @@ fn typed_three_right_then_join_and_single() { s.execute("view.set", &json!({ "center": [7, 7], "height": 7 })).unwrap(); typed(&mut s, &["-vports", "si"]); assert!(tiles(&s).is_empty()); - assert_eq!(view(&s), View { center: Vec2::new(7.0, 7.0), height: 7.0 }); + assert_eq!(view(&s), View { center: Vec2::new(7.0, 7.0), height: 7.0, twist: 0.0 }); } #[test] diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 7615bc569..c82179cfa 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -494,6 +494,8 @@ fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> { // Status flags: 65536 = non-rectangular clipping (by the 340 entity), 131072 = off. clip: t.s(340).and_then(|h| Handle::parse_hex(&h)).filter(|h| h.0 != 0 && t.i(90).unwrap_or(0) & 65536 != 0), on: t.i(90).unwrap_or(0) & 131072 == 0, + // View twist (group 51, degrees). + twist: t.f(51).filter(|a| a.is_finite()).map_or(0.0, |a| a.rem_euclid(360.0).to_radians()), }), "WIPEOUT" => { let o = t.p(10); @@ -1573,8 +1575,9 @@ 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). - d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active())); + // One *Active viewport is no tiling: the view is the editor's (it zooms to the extents), + // kept only for its view twist (see `cadcraft_engine::DocState`). + d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active()) || c.tiles.first().is_some_and(|t| t.twist != 0.0)); } /// Most tiles a viewport configuration keeps. @@ -1598,7 +1601,9 @@ fn vport_record(d: &mut Drawing, t: &T) { } 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 }; + // View twist (group 51, degrees). + let twist = t.f(51).filter(|a| a.is_finite()).map_or(0.0, |a| a.rem_euclid(360.0).to_radians()); + let tile = VportTile { min: clamp(min), max: clamp(max), center, height, aspect, twist }; let name = if name.eq_ignore_ascii_case(VportConfig::ACTIVE) { VportConfig::ACTIVE.to_string() } else { name }; let room = d.vports.len() < MAX_OBJECTS; match d.vports.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&name)) { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index cd4d2c17c..2df357dab 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -1059,6 +1059,10 @@ fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx w.i(69, i64::from(v.id)); w.p2(12, v.view_center); w.f(45, v.view_height); + // View twist (degrees), when the viewport has one. + if v.view_twist() != 0.0 { + w.f(51, v.view_twist().to_degrees()); + } // Status flags: 16384 = display locked, 32768 = always set, 65536 = clipped by the // 340 entity, 131072 = off. let clip = v.clip.filter(|h| *h != e.handle && d.entity(*h).is_some()); @@ -1492,6 +1496,8 @@ fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { 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, + // An untiled view's twist: the lone `*Active` tile the editor keeps for it. + twist: d.vports.iter().find(|c| c.is_active() && c.tiles.len() == 1).and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist), }; let tiled = d.vports.iter().find(|c| c.is_active() && c.tiles.len() > 1); let mut records: Vec<(&str, &VportTile)> = match tiled { @@ -1518,6 +1524,7 @@ 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)); + w.f(51, if t.twist.is_finite() { t.twist.to_degrees() } else { 0.0 }); } w.s(0, "ENDTAB"); } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 0fb8407a5..405db9a0c 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -505,6 +505,7 @@ fn pdf_layout_one_to_one_with_viewport() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }), ) .unwrap(); @@ -609,6 +610,7 @@ fn viewport_frozen_layers_roundtrip() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }) }; d.add(&paper, Common::default(), vp(2, vec!["Walls".into(), "A B".into()])).unwrap(); @@ -645,6 +647,7 @@ fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }); d.add(&paper, Common::default(), vp).unwrap(); let text = write_dxf(&d); @@ -768,6 +771,7 @@ fn viewport_layer_colors_roundtrip() { layer_colors: colors, clip: None, on: true, + twist: 0.0, }) }; let colors = vec![("Walls".to_string(), Color::Index(5)), ("A B".to_string(), Color::True(cadcraft_color::Rgb(255, 128, 0)))]; diff --git a/crates/io/tests/dwg_roundtrip_losses.rs b/crates/io/tests/dwg_roundtrip_losses.rs index 813ae6593..7b0b24c05 100644 --- a/crates/io/tests/dwg_roundtrip_losses.rs +++ b/crates/io/tests/dwg_roundtrip_losses.rs @@ -28,6 +28,7 @@ fn viewport(id: u32) -> EntityKind { layer_colors: vec![], clip: None, on: true, + twist: 0.0, }) } diff --git a/crates/io/tests/paperview_marker.rs b/crates/io/tests/paperview_marker.rs index 4159e14c3..283cfc8ac 100644 --- a/crates/io/tests/paperview_marker.rs +++ b/crates/io/tests/paperview_marker.rs @@ -18,6 +18,7 @@ fn viewport(id: u32, frozen_layers: Vec, layer_colors: Vec<(String, Colo layer_colors, clip: None, on: true, + twist: 0.0, }) } diff --git a/crates/io/tests/pdf_layers.rs b/crates/io/tests/pdf_layers.rs index ae8d916c1..2cdbe4329 100644 --- a/crates/io/tests/pdf_layers.rs +++ b/crates/io/tests/pdf_layers.rs @@ -166,6 +166,7 @@ fn viewport_contents_keep_their_layers() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&paper, Common { layer: "Viewports".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); add_line(&mut d, &paper, "Title", (10.0, 10.0), (50.0, 10.0)); diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index 4863ee628..fd4293465 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -333,6 +333,7 @@ fn text_seen_through_a_viewport_and_on_layers() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); text(&mut d, &paper, "Real", (20.0, 20.0), "B", 0.0, 1.0, 0.0); diff --git a/crates/io/tests/view_tables_roundtrip.rs b/crates/io/tests/view_tables_roundtrip.rs index b7ec71ac3..34c7fa76e 100644 --- a/crates/io/tests/view_tables_roundtrip.rs +++ b/crates/io/tests/view_tables_roundtrip.rs @@ -75,7 +75,7 @@ fn foreign_paper_view_and_hostile_twist() { } fn tile(min: (f64, f64), max: (f64, f64), center: (f64, f64), height: f64) -> VportTile { - VportTile { min: Vec2::new(min.0, min.1), max: Vec2::new(max.0, max.1), center: Vec2::new(center.0, center.1), height, aspect: 0.75 } + VportTile { min: Vec2::new(min.0, min.1), max: Vec2::new(max.0, max.1), center: Vec2::new(center.0, center.1), height, aspect: 0.75, twist: 0.0 } } #[test] diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8dadabe88..abdc6590b 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -703,11 +703,12 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou if !ok(s) { return; } - let xf = Mat3::translate(center).then_before(Mat3::scale(s, s)).then_before(Mat3::translate(-vp.view_center)); - let mhalf = Vec2::new(area.width(), area.height()) / (2.0 * s); - let mcenter = vp.view_center + (area.center() - center) / s; - // Model window with slack: entity bounds are approximate (text, dimensions). - let win = Bounds2::new(mcenter - mhalf, mcenter + mhalf).expand(mhalf.x.max(mhalf.y) * 0.1); + // Model space scaled onto the sheet and turned by the viewport's view twist. + let xf = vp.model_to_paper_matrix(); + // The model box the area covers (turned, with a twist), with slack: entity bounds are + // approximate (text, dimensions). + let mbox = Bounds2::from_points(area.corners().map(|p| vp.paper_to_model(p))); + let win = mbox.expand(mbox.width().max(mbox.height()) * 0.05); // PSLTSCALE on: model-space dashes are scaled so they measure the same on paper as in // paper space, whatever the viewport scale. let lt_factor = if d.header.i64("PSLTSCALE", 1) != 0 { 1.0 / s } else { 1.0 }; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ee22abb3c..81d7a0937 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -137,6 +137,7 @@ fn vp(center: Vec2, w: f64, h: f64, view_center: Vec2, view_height: f64, id: u32 layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, } } diff --git a/crates/render/tests/plot_line_styles.rs b/crates/render/tests/plot_line_styles.rs index 8cad7e3e5..b0abc6702 100644 --- a/crates/render/tests/plot_line_styles.rs +++ b/crates/render/tests/plot_line_styles.rs @@ -167,6 +167,7 @@ fn viewport_contents_get_their_pens() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; let space = Space::Paper("Layout1".into()); d.add(&space, Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/tests/psltscale.rs b/crates/render/tests/psltscale.rs index dab134ec5..e0b47647c 100644 --- a/crates/render/tests/psltscale.rs +++ b/crates/render/tests/psltscale.rs @@ -25,6 +25,7 @@ fn drawing(psltscale: i64) -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); d diff --git a/crates/render/tests/render_props.rs b/crates/render/tests/render_props.rs index f210dc4e1..e0e1efe2c 100644 --- a/crates/render/tests/render_props.rs +++ b/crates/render/tests/render_props.rs @@ -62,6 +62,7 @@ fn dimensions_take_the_viewport_layer_colour() { layer_colors: vec![("a".into(), Color::Index(3))], clip: None, on: true, + twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); let l = build(&d, &Space::Paper("Layout1".into()), &Options::default()); diff --git a/crates/render/tests/viewport_frozen_layer.rs b/crates/render/tests/viewport_frozen_layer.rs index bce291635..876b33574 100644 --- a/crates/render/tests/viewport_frozen_layer.rs +++ b/crates/render/tests/viewport_frozen_layer.rs @@ -21,6 +21,7 @@ fn drawing() -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common { layer: "VPORTS".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); d diff --git a/crates/render/tests/viewport_twist.rs b/crates/render/tests/viewport_twist.rs new file mode 100644 index 000000000..555852ccd --- /dev/null +++ b/crates/render/tests/viewport_twist.rs @@ -0,0 +1,66 @@ +//! A layout viewport with a view twist (DVIEW TWist inside it; DXF VIEWPORT group 51) shows model +//! space turned on the sheet, on screen, when plotting and in the canvas's active-viewport list. + +use cadcraft_doc::{Common, Drawing, EntityKind, Line, Space, Viewport}; +use cadcraft_geom::{Bounds2, Vec2, Vec3}; +use cadcraft_render::{DisplayList, Options, VIEWPORT_CONTENT, build, build_plot, viewport_content}; + +fn drawing(twist_deg: f64) -> (Drawing, cadcraft_doc::Handle) { + let mut d = Drawing::new_imperial(); + // A model line along +X, 2 long, from the view centre. + d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(2.0, 0.0, 0.0) })).unwrap(); + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: 8.0, + height: 6.0, + view_center: Vec2::ZERO, + view_height: 12.0, + id: 2, + twist: twist_deg.to_radians(), + ..Viewport::default() + }; + let h = d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); + (d, h) +} + +/// The bounds of the viewport's contents in a list. +fn contents(l: &DisplayList) -> Bounds2 { + Bounds2::from_points(l.prims.iter().filter(|p| p.handle == VIEWPORT_CONTENT).flat_map(|p| l.points(p).to_vec())) +} + +fn near(a: Vec2, b: Vec2) -> bool { + (a - b).len() < 1e-6 +} + +#[test] +fn a_twisted_viewport_turns_its_contents_on_screen_and_in_plots() { + let space = Space::Paper("Layout1".into()); + // Untwisted: the line runs right from the viewport centre (scale 1/2). + let (d, _) = drawing(0.0); + let b = contents(&build(&d, &space, &Options::default())); + assert!(near(b.min, Vec2::new(5.0, 4.0)) && near(b.max, Vec2::new(6.0, 4.0)), "{b:?}"); + // Turned 90° counterclockwise: it runs up. + let (d, h) = drawing(90.0); + for l in [build(&d, &space, &Options::default()), build_plot(&d, &space, &Options::default())] { + let b = contents(&l); + assert!(near(b.min, Vec2::new(5.0, 4.0)) && near(b.max, Vec2::new(5.0, 5.0)), "{b:?}"); + } + // The active viewport's own list, built for an area around it, agrees. + let area = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(10.0, 8.0)); + let l = viewport_content(&d, &space, h, area, &Options::default()); + let b = Bounds2::from_points(l.prims.iter().flat_map(|p| l.points(p).to_vec())); + assert!(near(b.min, Vec2::new(5.0, 4.0)) && near(b.max, Vec2::new(5.0, 5.0)), "{b:?}"); +} + +#[test] +fn model_and_paper_points_map_both_ways_through_a_twist() { + let (d, h) = drawing(30.0); + let Some(EntityKind::Viewport(vp)) = d.entity(h).map(|e| e.kind.clone()) else { panic!() }; + let m = Vec2::new(3.0, -1.5); + let p = vp.model_to_paper(m); + assert!(near(vp.paper_to_model(p), m)); + assert!(near(vp.model_to_paper_matrix().apply(m), p)); + // +X in model space points 30° above the sheet's +X. + let dir = vp.model_to_paper(Vec2::new(1.0, 0.0)) - vp.model_to_paper(Vec2::ZERO); + assert!((dir.y.atan2(dir.x).to_degrees() - 30.0).abs() < 1e-9); +} diff --git a/crates/ui-egui/src/bedit.rs b/crates/ui-egui/src/bedit.rs index 0166e72ae..298f17069 100644 --- a/crates/ui-egui/src/bedit.rs +++ b/crates/ui-egui/src/bedit.rs @@ -142,7 +142,7 @@ fn draw_preview(ui: &mut egui::Ui, list: Option<&DisplayList>, note: &str) { let inner = rect.shrink(12.0); let (w, h) = (b.width().max(1e-9), b.height().max(1e-9)); let scale = (f64::from(inner.width()) / w).min(f64::from(inner.height()) / h); - let xf = Xf { rect, center: Vec2::new((b.min.x + b.max.x) / 2.0, (b.min.y + b.max.y) / 2.0), scale }; + let xf = Xf { rect, center: Vec2::new((b.min.x + b.max.x) / 2.0, (b.min.y + b.max.y) / 2.0), scale, twist: 0.0 }; crate::canvas::draw_list(&p, &xf, l, Rgb(t.canvas.r(), t.canvas.g(), t.canvas.b()), false); } None => { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e5725e353..d2a80d29f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,7 +5,7 @@ use cadcraft_color::Rgb; use cadcraft_doc::Handle; use cadcraft_engine::Input; use cadcraft_engine::snap::{self, SnapHit}; -use cadcraft_geom::{Bounds2, Vec2}; +use cadcraft_geom::{Bounds2, Mat3, Vec2}; use cadcraft_render::{DisplayList, Kind}; use egui::{Color32, Pos2, Rect, Sense, Shape, Stroke, pos2, vec2}; @@ -19,19 +19,45 @@ pub struct Xf { pub center: Vec2, /// Pixels (points) per drawing unit. pub scale: f64, + /// The view twist (radians counterclockwise, `cadcraft_engine::View::twist`): the drawing + /// appears turned by it about `center`. 0 for paper space. + pub twist: f64, } impl Xf { + /// A world offset from `center` in the screen's frame (y up): turned by the twist. + fn turn(&self, v: Vec2) -> Vec2 { + if self.twist == 0.0 { v } else { v.rotate(self.twist) } + } pub fn to_screen(&self, p: Vec2) -> Pos2 { let c = self.rect.center(); - pos2(c.x + ((p.x - self.center.x) * self.scale) as f32, c.y - ((p.y - self.center.y) * self.scale) as f32) + let q = self.turn(p - self.center); + pos2(c.x + (q.x * self.scale) as f32, c.y - (q.y * self.scale) as f32) } pub fn to_world(&self, p: Pos2) -> Vec2 { let c = self.rect.center(); - Vec2::new(self.center.x + f64::from(p.x - c.x) / self.scale, self.center.y - f64::from(p.y - c.y) / self.scale) + self.center + self.screen_delta_to_world(p - c) } + /// The world offset a screen offset `d` (points, y down) covers: a pan moves the view by it. + pub fn screen_delta_to_world(&self, d: egui::Vec2) -> Vec2 { + let q = Vec2::new(f64::from(d.x) / self.scale, -f64::from(d.y) / self.scale); + if self.twist == 0.0 { q } else { q.rotate(-self.twist) } + } + /// The world box holding everything on screen (in a twisted view, the box of the rect's + /// four corners). pub fn world_bounds(&self) -> Bounds2 { - Bounds2::new(self.to_world(self.rect.left_bottom()), self.to_world(self.rect.right_top())) + let r = self.rect; + Bounds2::from_points([r.left_bottom(), r.right_top(), r.left_top(), r.right_bottom()].map(|p| self.to_world(p))) + } + /// The GPU transform ([`crate::gpu::CanvasCallback::xform`]) that draws vertex data built at + /// `origin`, moved by `m` (a drag; [`Mat3::IDENTITY`] for the drawing), in this view: the + /// shader takes `L·p + e + (origin − center)` to the screen frame, which must be + /// `R(m(origin + p) − center)` with `R` the twist, so `L = R·m` and + /// `e = R(m(origin) − center) − (origin − center)`. + pub(crate) fn gpu_xform(&self, origin: Vec2, m: Mat3) -> [f32; 6] { + let (a, b) = (self.turn(Vec2::new(m.a, m.b)), self.turn(Vec2::new(m.c, m.d))); + let e = self.turn(m.apply(origin) - self.center) - (origin - self.center); + [a.x as f32, a.y as f32, b.x as f32, b.y as f32, e.x as f32, e.y as f32] } } @@ -81,6 +107,8 @@ pub struct CanvasState { vp_hover: VpHighlight, /// Model space seen through the active MSPACE viewport (see [`VpContent`]). vp: VpContent, + /// What a running command shows in place of the drawing (see [`OnlyList`]). + only: OnlyList, /// Indices of infinite-line primitives in `list` (drawn on the CPU in GPU mode). infinite: Vec, /// Milliseconds spent converting the display list to vertex data (last rebuild). @@ -401,12 +429,12 @@ impl VpContent { } /// How a list built for view `built` (centre, height) of viewport `vp` maps to its current -/// view, as `p = k·p0 + b` on paper. A model point m is at p0 = c + s0 (m − c0) in the list and -/// belongs at p = c + s (m − vc), with c the viewport's centre and s, s0 paper units per model -/// unit, so k = s / s0 and b = c (1 − k) + s (c0 − vc). +/// view, as `p = k·p0 + b` on paper. A model point m is at p0 = c + s0 R(m − c0) in the list and +/// belongs at p = c + s R(m − vc), with c the viewport's centre, R its view twist and s, s0 paper +/// units per model unit, so k = s / s0 and b = c (1 − k) + s R(c0 − vc). fn vp_motion(vp: &cadcraft_doc::Viewport, built: (Vec2, f64)) -> Option<(f64, Vec2)> { let (s, k) = (vp.height / vp.view_height, built.1 / vp.view_height); - let b = vp.center.xy() * (1.0 - k) + (built.0 - vp.view_center) * s; + let b = vp.center.xy() * (1.0 - k) + (built.0 - vp.view_center).rotate(vp.view_twist()) * s; (k.is_finite() && k > 0.0 && b.is_finite()).then_some((k, b)) } @@ -488,7 +516,7 @@ fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Context) -> Op let (k, b) = vp_motion(&vp, c.view)?; c.motion = Some((k, b)); // Paper p = k·p0 + b, so the list is drawn by the paper transform scaled by k about b. - let xf = Xf { rect: xf_paper.rect, center: (xf_paper.center - b) / k, scale: xf_paper.scale * k }; + let xf = Xf { rect: xf_paper.rect, center: (xf_paper.center - b) / k, scale: xf_paper.scale * k, twist: xf_paper.twist }; let on_screen = Rect::from_two_pos(xf_paper.to_screen(Vec2::new(rect.min.x, rect.max.y)), xf_paper.to_screen(Vec2::new(rect.max.x, rect.min.y))); Some(VpFrame { xf, on_screen, outline: clip.map(|p| p.polygon().to_vec()) }) } @@ -532,7 +560,7 @@ fn draw_vp_content(c: &mut VpContent, gpu: bool, p: &egui::Painter, f: &VpFrame, scale: xf.scale as f32, center: [center.x, center.y], layer: crate::gpu::LAYER_VIEWPORT, - xform: crate::gpu::IDENTITY_XFORM, + xform: xf.gpu_xform(c.mesh_origin, Mat3::IDENTITY), dash: 0.0, stencil, }, @@ -587,7 +615,7 @@ fn draw_vp_mask(c: &mut VpContent, p: &egui::Painter, outline: &[Vec2], xf_paper scale: xf_paper.scale as f32, center: [center.x, center.y], layer: crate::gpu::LAYER_MASK, - xform: crate::gpu::IDENTITY_XFORM, + xform: xf_paper.gpu_xform(c.mask_origin, Mat3::IDENTITY), dash: 0.0, stencil: crate::gpu::Stencil::Mask, }, @@ -631,6 +659,32 @@ impl VpHighlight { } } +/// The display list of what a running command shows in place of the drawing +/// ([`cadcraft_engine::Session::display_only`]: DVIEW's preview set), rebuilt when the drawing, +/// the set or the 2x zoom band changes. +#[derive(Default)] +struct OnlyList { + key: Option, + list: DisplayList, +} + +impl OnlyList { + fn update(&mut self, st: &cadcraft_engine::DocState, only: &cadcraft_engine::DisplayOnly, scale: f64) { + let band = (1.0 / scale.max(1e-300)).log2().floor() as i32; + 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); + h.finish() + }; + if self.key != Some(key) { + let ents = only.handles.iter().filter_map(|h| st.doc.entity(*h)).map(|e| e.as_ref()).chain(only.extra.iter()); + self.list = rebuilt_preview(&st.doc, ents, 2f64.powi(-band)); + self.key = Some(key); + } + } +} + /// The area a display list is built for: each view with half its larger side of margin all /// round (panning by up to that much doesn't rebuild), joined. `None` (everything) when a view /// isn't usable. @@ -674,21 +728,20 @@ fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) { 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 { + // World-aligned lines across the visible box (the painter clips them to the rect). for i in x0..=x1 { 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())], + [xf.to_screen(Vec2::new(x, wb.min.y)), xf.to_screen(Vec2::new(x, wb.max.y))], Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }), )); } for j in y0..=y1 { 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)], + [xf.to_screen(Vec2::new(wb.min.x, y)), xf.to_screen(Vec2::new(wb.max.x, y))], Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }), )); } @@ -696,12 +749,11 @@ fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) { 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 (wb.min.y..=wb.max.y).contains(&0.0) { + p.line_segment([xf.to_screen(Vec2::new(wb.min.x, 0.0)), xf.to_screen(Vec2::new(wb.max.x, 0.0))], 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)); + if (wb.min.x..=wb.max.x).contains(&0.0) { + p.line_segment([xf.to_screen(Vec2::new(0.0, wb.min.y)), xf.to_screen(Vec2::new(0.0, wb.max.y))], Stroke::new(1.0, t.axis_y)); } } @@ -846,7 +898,7 @@ fn draw_highlight_gpu( scale: xf.scale as f32, center: [center.x, center.y], layer: crate::gpu::LAYER_HIGHLIGHT, - xform: crate::gpu::IDENTITY_XFORM, + xform: xf.gpu_xform(*hl_origin, Mat3::IDENTITY), dash: if look.dashed { 10.0 } else { 0.0 }, stencil, }, @@ -898,10 +950,8 @@ fn draw_drag_gpu( c.drag_key = Some(key); c.drag_origin = origin; } - // Positions are relative to the origin o: M(o + p) = L·p + (M(o) − o). - let m = drag.matrix; + // Positions are relative to the origin o: M(o + p) = L·p + (M(o) − o), turned with the view. let o = c.drag_origin; - let t = m.apply(o) - o; let center = xf.rect.center(); p.add(egui_wgpu::Callback::new_paint_callback( xf.rect, @@ -912,7 +962,7 @@ fn draw_drag_gpu( scale: xf.scale as f32, center: [center.x, center.y], layer: crate::gpu::LAYER_DRAG, - xform: [m.a as f32, m.b as f32, m.c as f32, m.d as f32, t.x as f32, t.y as f32], + xform: xf.gpu_xform(o, drag.matrix), dash: 0.0, stencil: crate::gpu::Stencil::Off, }, @@ -954,7 +1004,7 @@ fn draw_list_gpu(c: &mut CanvasState, p: &egui::Painter, xf: &Xf, bg: Rgb, lwdis scale: xf.scale as f32, center: [center.x, center.y], layer: crate::gpu::LAYER_DRAWING, - xform: crate::gpu::IDENTITY_XFORM, + xform: xf.gpu_xform(c.mesh_origin, Mat3::IDENTITY), dash: 0.0, stencil: crate::gpu::Stencil::Off, }, @@ -1241,7 +1291,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let Ok(st) = app.session.state() else { return }; let view = st.view(); let scale = f64::from(rect.height()) / view.height.max(1e-12); - let xf = Xf { rect, center: view.center, scale }; + let xf = Xf { rect, center: view.center, scale, twist: view.twist }; app.canvas.xf = Some(xf); // ---------- input ---------- @@ -1274,10 +1324,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { // Pinch (and Cmd+scroll) still zoom via `zoom_delta` below. if let Ok(st) = app.session.state_mut() { let v = st.view(); - st.set_view_quiet(cadcraft_engine::View { - center: v.center - Vec2::new(f64::from(scroll.x) / scale, -f64::from(scroll.y) / scale), - height: v.height, - }); + st.set_view_quiet(cadcraft_engine::View { center: v.center - xf.screen_delta_to_world(scroll), height: v.height, twist: v.twist }); } } let opts = ui.ctx().options(|o| o.input_options); @@ -1311,10 +1358,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let d = hp - last; if let Ok(st) = app.session.state_mut() { let v = st.view(); - st.set_view_quiet(cadcraft_engine::View { - center: v.center - Vec2::new(f64::from(d.x) / scale, -f64::from(d.y) / scale), - height: v.height, - }); + st.set_view_quiet(cadcraft_engine::View { center: v.center - xf.screen_delta_to_world(d), height: v.height, twist: v.twist }); } } app.canvas.pan_last = Some(hp); @@ -1343,13 +1387,14 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { // Re-read the view after navigation. let view = app.session.state().map(|s| s.view()).unwrap_or(view); let scale = f64::from(rect.height()) / view.height.max(1e-12); - let xf = Xf { rect, center: view.center, scale }; + let xf = Xf { rect, center: view.center, scale, twist: view.twist }; app.canvas.xf = Some(xf); // The paper (display) transform; equal to `xf` except inside an MSPACE viewport. let (xf_paper, active_vp) = match app.session.state() { Ok(st) => { let pv = st.paper_view(); - let xp = Xf { rect, center: pv.center, scale: f64::from(rect.height()) / pv.height.max(1e-12) }; + // Paper space is never twisted. + let xp = Xf { rect, center: pv.center, scale: f64::from(rect.height()) / pv.height.max(1e-12), twist: 0.0 }; (if st.mspace.is_some() { xp } else { xf }, st.active_viewport().map(|(_, v)| v)) } Err(_) => (xf, None), @@ -1631,16 +1676,32 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { // The active viewport's contents, drawn apart from the layout's list, under its own objects. // `masked`: its outline is in the stencil buffer this frame. let mut masked = false; - if let Some(f) = ensure_vp_content(app, &xf_paper, ui.ctx()) { - let gpu = app.canvas.gpu.is_some(); - let clipped = painter.with_clip_rect(f.on_screen.intersect(rect)); - draw_vp_content(&mut app.canvas.vp, gpu, &clipped, &f, &xf_paper, bg, app.session.settings.lwdisplay); - masked = gpu && f.outline.is_some(); - } - if app.canvas.gpu.is_some() { - draw_list_gpu(&mut app.canvas, &painter, &xf_paper, bg, app.session.settings.lwdisplay); - } else if let Some(list) = &app.canvas.list { - draw_list(&painter, &xf_paper, list, bg, app.session.settings.lwdisplay); + if let Some(only) = app.session.display_only() { + // A command that shows only some objects while it runs (DVIEW's preview set): those, + // in the view being changed (inside the active viewport, clipped to it). + let clip = active_vp.as_ref().map_or(rect, |vp| { + Rect::from_two_pos( + xf_paper.to_screen(Vec2::new(vp.center.x - vp.width / 2.0, vp.center.y + vp.height / 2.0)), + xf_paper.to_screen(Vec2::new(vp.center.x + vp.width / 2.0, vp.center.y - vp.height / 2.0)), + ) + .intersect(rect) + }); + if let Ok(st) = app.session.state() { + app.canvas.only.update(st, &only, scale); + } + draw_list(&painter.with_clip_rect(clip), &xf, &app.canvas.only.list, bg, app.session.settings.lwdisplay); + } else { + if let Some(f) = ensure_vp_content(app, &xf_paper, ui.ctx()) { + let gpu = app.canvas.gpu.is_some(); + let clipped = painter.with_clip_rect(f.on_screen.intersect(rect)); + draw_vp_content(&mut app.canvas.vp, gpu, &clipped, &f, &xf_paper, bg, app.session.settings.lwdisplay); + masked = gpu && f.outline.is_some(); + } + if app.canvas.gpu.is_some() { + draw_list_gpu(&mut app.canvas, &painter, &xf_paper, bg, app.session.settings.lwdisplay); + } else if let Some(list) = &app.canvas.list { + draw_list(&painter, &xf_paper, list, bg, app.session.settings.lwdisplay); + } } if let Some(vp) = &active_vp { // The active viewport: a heavy border, highlights in model units clipped to it. @@ -1802,19 +1863,19 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } // Pending selection window. if let (Some(pw), Some(c)) = (app.session.pending_window, raw_world) { - let a = xf.to_screen(pw.corner); - let b = xf.to_screen(c); - let r = Rect::from_two_pos(a, b); + // The world box it selects (turned in a twisted view). + let corners = [pw.corner, Vec2::new(c.x, pw.corner.y), c, Vec2::new(pw.corner.x, c.y)].map(|q| xf.to_screen(q)); let crossing = c.x < pw.corner.x; if let Some(fill) = selection_area_fill(&app.session.settings, crossing) { - painter.rect_filled(r, 0.0, fill); + painter.add(Shape::convex_polygon(corners.to_vec(), fill, Stroke::NONE)); } let st = Stroke::new(1.0, if crossing { t.crossing_stroke } else { t.window_stroke }); + let mut pts = corners.to_vec(); + pts.push(corners[0]); if crossing { - let pts = vec![r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()]; painter.extend(Shape::dashed_line(&pts, st, 5.0, 3.0)); } else { - painter.rect_stroke(r, 0.0, st, egui::StrokeKind::Middle); + painter.add(Shape::line(pts, st)); } } // Acquired tracking points and the polar / tracking paths under the cursor. @@ -1891,7 +1952,7 @@ fn tile_rects(app: &CadApp, full: Rect) -> Vec<(Rect, cadcraft_engine::ModelTile /// The world ↔ screen transform of a model tile drawn in `r`. fn tile_xf(r: Rect, tile: &cadcraft_engine::ModelTile) -> Xf { - Xf { rect: r, center: tile.view.center, scale: f64::from(r.height()) / tile.view.height.max(1e-12) } + Xf { rect: r, center: tile.view.center, scale: f64::from(r.height()) / tile.view.height.max(1e-12), twist: tile.view.twist } } /// The tiles other than the current one (each with its own view, clipped to it), then the @@ -2389,7 +2450,7 @@ pub(crate) mod tests { let h = d.add(&cadcraft_doc::Space::Model, common, cadcraft_doc::EntityKind::Line(line)).unwrap(); let drag = cadcraft_engine::Drag { handles: vec![h], matrix: cadcraft_geom::Mat3::IDENTITY, extra: Vec::new(), clipboard: false }; let rect = Rect::from_min_size(Pos2::ZERO, vec2(200.0, 100.0)); - let xf = Xf { rect, center: Vec2::new(5.0, 0.0), scale: 10.0 }; + let xf = Xf { rect, center: Vec2::new(5.0, 0.0), scale: 10.0, twist: 0.0 }; let painter = egui::Painter::new(egui::Context::default(), egui::LayerId::background(), rect); // One canvas across the toggle: the cached drag mesh must be rebuilt. let mut c = CanvasState::default(); @@ -2439,6 +2500,101 @@ pub(crate) mod tests { assert!(!list.prims.is_empty() && list.prims.iter().all(|p| p.transparency == 0)); } + fn twisted() -> Xf { + let rect = Rect::from_min_size(pos2(10.0, 20.0), vec2(300.0, 200.0)); + Xf { rect, center: Vec2::new(5.0, -3.0), scale: 4.0, twist: 30f64.to_radians() } + } + + /// A twisted view turns the drawing counterclockwise on screen, and `to_world` undoes + /// `to_screen` exactly. + #[test] + fn a_twisted_view_turns_the_drawing_and_round_trips() { + let xf = twisted(); + let p = Vec2::new(17.0, 4.0); + let back = xf.to_world(xf.to_screen(p)); + assert!((back - p).len() < 1e-4, "{back:?}"); + // World +X points 30° above the horizontal (screen y grows down). + let (a, b) = (xf.to_screen(xf.center), xf.to_screen(xf.center + Vec2::new(10.0, 0.0))); + let ang = f64::from(-(b.y - a.y)).atan2(f64::from(b.x - a.x)).to_degrees(); + assert!((ang - 30.0).abs() < 1e-3, "{ang}"); + // A screen drag maps back to the world move that pans by it. + let d = xf.screen_delta_to_world(b - a); + assert!((d - Vec2::new(10.0, 0.0)).len() < 1e-4, "{d:?}"); + // The visible box holds every corner of the rect. + let wb = xf.world_bounds(); + for c in [xf.rect.left_top(), xf.rect.right_top(), xf.rect.left_bottom(), xf.rect.right_bottom()] { + assert!(wb.expand(1e-6).contains(xf.to_world(c))); + } + // Untwisted it is the plain transform. + let plain = Xf { twist: 0.0, ..xf }; + let s = plain.to_screen(p); + assert_eq!(s, pos2(160.0 + 12.0 * 4.0, 120.0 - 7.0 * 4.0)); + } + + /// What the shader does with a callback's xform (see `to_px` in `gpu.rs`), in points. + fn shader(xf: &Xf, origin: Vec2, x: [f32; 6], p: Vec2) -> Pos2 { + let q = p - origin; + let [a, b, c, d, tx, ty] = x.map(f64::from); + let r = Vec2::new(a * q.x + c * q.y + tx, b * q.x + d * q.y + ty) + (origin - xf.center); + let k = xf.rect.center(); + pos2(k.x + (r.x * xf.scale) as f32, k.y - (r.y * xf.scale) as f32) + } + + /// The GPU transform draws each point where `to_screen` puts it, for the drawing and for a + /// dragged copy. + #[test] + fn gpu_xform_agrees_with_to_screen() { + let xf = twisted(); + let origin = Vec2::new(40.0, -12.0); + let x = xf.gpu_xform(origin, Mat3::IDENTITY); + for p in [Vec2::new(0.0, 0.0), Vec2::new(17.0, 4.0), Vec2::new(-30.0, 55.0)] { + let (g, c) = (shader(&xf, origin, x, p), xf.to_screen(p)); + assert!((g - c).length() < 1e-2, "{p:?}: {g:?} vs {c:?}"); + } + let m = Mat3::rotate_about(Vec2::new(3.0, 1.0), 0.7); + let x = xf.gpu_xform(origin, m); + for p in [Vec2::new(1.0, 2.0), Vec2::new(-8.0, 9.0), Vec2::new(25.0, -4.0)] { + let (g, c) = (shader(&xf, origin, x, p), xf.to_screen(m.apply(p))); + assert!((g - c).length() < 1e-2, "{p:?}: {g:?} vs {c:?}"); + } + // No twist: the identity for the drawing, as before. + assert_eq!(Xf { twist: 0.0, ..xf }.gpu_xform(origin, Mat3::IDENTITY), crate::gpu::IDENTITY_XFORM); + } + + /// A model tile is drawn with its own twist. + #[test] + fn tile_xf_carries_the_tiles_twist() { + let tile = cadcraft_engine::ModelTile { + min: Vec2::ZERO, + max: Vec2::new(0.5, 1.0), + view: cadcraft_engine::View { center: Vec2::new(1.0, 2.0), height: 50.0, twist: 0.5 }, + active: false, + }; + let xf = tile_xf(Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), &tile); + assert_eq!((xf.twist, xf.center, xf.scale), (0.5, Vec2::new(1.0, 2.0), 2.0)); + } + + /// The active viewport's list, built at one view of a twisted viewport, lands where the + /// viewport now shows each model point after a pan and a zoom. + #[test] + fn vp_motion_follows_a_twisted_viewport() { + let built = cadcraft_doc::Viewport { + center: cadcraft_geom::Vec3::new(5.0, 4.0, 0.0), + width: 8.0, + height: 6.0, + view_center: Vec2::new(1.0, 2.0), + view_height: 12.0, + twist: 0.7, + ..Default::default() + }; + let now = cadcraft_doc::Viewport { view_center: Vec2::new(-3.0, 0.5), view_height: 7.0, ..built.clone() }; + let (k, b) = vp_motion(&now, (built.view_center, built.view_height)).unwrap(); + for m in [Vec2::new(0.0, 0.0), Vec2::new(4.0, -2.5), Vec2::new(-7.0, 3.0)] { + let moved = built.model_to_paper(m) * k + b; + assert!((moved - now.model_to_paper(m)).len() < 1e-9, "{m:?}"); + } + } + #[test] fn viewport_highlight_tolerance_is_constant_within_a_zoom_band() { assert_eq!(viewport_highlight_tolerance(4.0), viewport_highlight_tolerance(3.0)); diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index c136b7032..7b0ec6465 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -435,7 +435,9 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; if !pr.raw && !pr.keywords.is_empty() { - let g = p.layout_no_wrap(if pr.message.is_empty() { " [".into() } else { crate::tl!(" or [").into() }, font.clone(), t.text); + // An option prompt ("Enter option [CAmera/…]") has no "or". + let opening: String = if pr.message.is_empty() || pr.options_only { " [".into() } else { crate::tl!(" or [").into() }; + let g = p.layout_no_wrap(opening, font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index adce43ae7..f56b27be1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -194,6 +194,7 @@ DWG DWG DWG Reference... Посилання на DWG... DXF DXF + DView Динамічний вид Dark Темна Data Extraction... Вилучення даних... Default Типово diff --git a/crates/ui-egui/src/spacemouse.rs b/crates/ui-egui/src/spacemouse.rs index 8f2c90e12..808c9fd88 100644 --- a/crates/ui-egui/src/spacemouse.rs +++ b/crates/ui-egui/src/spacemouse.rs @@ -128,7 +128,7 @@ fn navigate(app: &mut CadApp, params: &Value) -> Result { if !center.is_finite() || !height.is_finite() { return Err("3D mouse navigation would produce an invalid view".into()); } - state.set_view_quiet(View { center, height }); + state.set_view_quiet(View { center, height, twist: view.twist }); Ok(json!({"center": [center.x, center.y], "height": height})) } diff --git a/crates/ui-egui/tests/measure_distance_snapping.rs b/crates/ui-egui/tests/measure_distance_snapping.rs index 9f520b4ab..0deedcea4 100644 --- a/crates/ui-egui/tests/measure_distance_snapping.rs +++ b/crates/ui-egui/tests/measure_distance_snapping.rs @@ -30,6 +30,7 @@ fn harness(paper: bool, render: bool) -> Harness<'static, CadApp> { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }), ) .unwrap(); diff --git a/crates/ui-egui/tests/mspace_viewport_view.rs b/crates/ui-egui/tests/mspace_viewport_view.rs index 569665021..55c639728 100644 --- a/crates/ui-egui/tests/mspace_viewport_view.rs +++ b/crates/ui-egui/tests/mspace_viewport_view.rs @@ -37,6 +37,7 @@ fn harness(clipped: bool) -> Harness<'static, CadApp> { layer_colors: Vec::new(), clip, on: true, + twist: 0.0, }), ) .unwrap(); @@ -88,7 +89,7 @@ fn revision(h: &Harness<'_, CadApp>) -> u64 { fn pan(h: &mut Harness<'_, CadApp>, dx: f64) { let st = h.state_mut().session.state_mut().unwrap(); let v = st.view(); - st.set_view_quiet(cadcraft_engine::View { center: v.center - Vec2::new(dx, 0.0), height: v.height }); + st.set_view_quiet(cadcraft_engine::View { center: v.center - Vec2::new(dx, 0.0), height: v.height, twist: v.twist }); } /// A wheel step zooming in by `f` about the viewport's view centre. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5b3a94ce8..2cb196e0c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -80,7 +80,7 @@ early (#175), but the throughput problem remains. **DWG ≈ 30% read, ≈ 15% wr | HATCH gradient | yes | yes (#162, fixes #80) | | | SOLID, TRACE, 3DFACE | yes | yes | | | ACAD_TABLE | yes | 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) | +| VIEWPORT | yes | yes; frozen-layer lists kept (#150), also as standard group 341 layer handles that other programs read; view twist (51) | 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 | | @@ -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) with each tile's view twist (51), named views, UCSs | UCS elevation lost | | 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-13 | minor | View twist (group 51) read and written for each tiled viewport (VPORT) and each layout viewport (VIEWPORT); named views' twist (VIEW group 50) now applied on Restore | | 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..04c2233be 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -24,7 +24,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 | +| 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, DVIEW CAmera, TArget, Distance, POints, CLip and Hide (they need a 3D camera; TWist, PAn, Zoom, Off and Undo work). 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/view/dview.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 | | 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 | @@ -58,7 +58,7 @@ 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 | MVIEW Restore (a saved viewport configuration into a layout); VIEW Orthographic, UCS and background settings (view twist: DVIEW on the Model tab, each VPORTS tile and each layout viewport, VIEWTWIST, landed; 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 | @@ -145,6 +145,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | View twist: DVIEW starts with "Select objects or :" then its option prompt (TWist, PAn, Zoom, Off and Undo on 2D views, the 3D options added to F1), on the Model tab and inside an active layout viewport, which keeps its own twist (DXF VIEWPORT group 51) and is drawn turned on screen and in plots; VIEWTWIST, each VPORTS tile (VPORT group 51) and named views keep it: U11 narrowed | | 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 | 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 010/900] 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 011/900] 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 fc67a5c28a648230962905d1385bd095214f5553 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Wed, 14 Oct 2026 21:48:16 -0400 Subject: [PATCH 012/900] PAN pans in realtime by dragging; -PAN asks for two points PAN (alias P, View > Pan > Realtime) is realtime: a left-button drag moves the drawing with the cursor until Esc or Enter, and the session is one Zoom Previous entry. -PAN takes a base point and a second point, or a point then Enter as a displacement. The JSON form of pan is unchanged. Fixes #1245. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/view.rs | 72 +++++++++++++++++++++++++++--- crates/engine/tests/named_views.rs | 37 ++++++++++++++- crates/engine/tests/transparent.rs | 2 +- crates/ui-egui/src/canvas.rs | 8 +++- 4 files changed, 110 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index e6051a6e9..3babdcea0 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -65,7 +65,12 @@ pub fn specs() -> Vec { .params("{delta: [dx,dy]} | {from, to} | {center}") .noundo() .transparent() - .interactive(|_| Ok(Box::new(PanM::default()))), + .interactive(|_| Ok(Box::new(PanM))), + CommandSpec::new("-pan", "Pan", run_pan) + .params("{delta: [dx,dy]} | {from, to} | {center}") + .noundo() + .transparent() + .interactive(|_| Ok(Box::new(PanPointsM::default()))), CommandSpec::new("pan.left", "Pan Left", |s, _| pan_frac(s, Vec2::new(-0.25, 0.0))).menu(&["View", "Pan", "Left"]).noundo().transparent(), CommandSpec::new("pan.right", "Pan Right", |s, _| pan_frac(s, Vec2::new(0.25, 0.0))).menu(&["View", "Pan", "Right"]).noundo().transparent(), CommandSpec::new("pan.up", "Pan Up", |s, _| pan_frac(s, Vec2::new(0.0, 0.25))).menu(&["View", "Pan", "Up"]).noundo().transparent(), @@ -568,6 +573,24 @@ impl Session { self.touch(); Ok(()) } + /// PAN is in its realtime mode: the UI turns left-button drags into [`Session::realtime_pan`]. + pub fn realtime_pan_active(&self) -> bool { + self.running.as_ref().is_some_and(|r| r.id == "pan") && self.current_prompt().is_some_and(|p| p.message == REALTIME_PAN_PROMPT) + } + /// One step of a realtime pan drag of `dx`, `dy` screen pixels (y down): the drawing follows + /// the cursor. Does nothing outside realtime PAN. + pub fn realtime_pan(&mut self, dx: f64, dy: f64) -> Result<()> { + if !self.realtime_pan_active() || !dx.is_finite() || !dy.is_finite() { + return Ok(()); + } + let px = self.viewport_px.1.max(1.0); + let st = self.state_mut()?; + let v = st.view(); + let scale = px / v.height; + st.set_view_quiet(View { center: v.center - Vec2::new(dx / scale, -dy / scale), height: v.height }); + self.touch(); + Ok(()) + } /// The zoom of a mouse wheel scroll by `delta` points (up zooms in): ZOOMFACTOR scales it /// (60, the default, zooms about 18% per wheel step). pub fn wheel_zoom_factor(&self, delta: f64) -> f64 { @@ -579,15 +602,47 @@ impl Session { } } -#[derive(Default)] -struct PanM { - first: Option, -} +/// The prompt of realtime PAN; [`Session::realtime_pan_active`] recognises the mode by it. +const REALTIME_PAN_PROMPT: &str = "Drag to pan; press Esc or Enter to exit"; + +/// PAN: realtime. Dragging with the left button moves the drawing with the cursor until Esc or +/// Enter; the whole session is one Zoom Previous entry. +struct PanM; impl Interactive for PanM { fn name(&self) -> &'static str { "PAN" } + fn begin(&mut self, s: &mut Session) -> Result { + let st = s.state_mut()?; + let v = st.view(); + st.view_history.push(v); + if st.view_history.len() > 50 { + st.view_history.remove(0); + } + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + Prompt::new(REALTIME_PAN_PROMPT, Accept { enter: true, ..Accept::default() }) + } + fn input(&mut self, _s: &mut Session, i: Input) -> Result { + match i { + Input::Enter => Ok(Step::Done), + _ => Ok(Step::Continue), + } + } +} + +/// -PAN: a base point and a second point, or a displacement (a point, then Enter). +#[derive(Default)] +struct PanPointsM { + first: Option, +} + +impl Interactive for PanPointsM { + fn name(&self) -> &'static str { + "-PAN" + } fn prompt(&self, _s: &Session) -> Prompt { match self.first { None => Prompt::new("Specify base point or displacement (drag with the middle mouse button for realtime pan)", Accept::POINT), @@ -604,7 +659,12 @@ impl Interactive for PanM { run_pan(s, &json!({ "from": [a.x, a.y], "to": [b.x, b.y] }))?; Ok(Step::Done) } - (_, Input::Enter) => Ok(Step::Done), + // Enter at the second point: the first point is the displacement. + (Some(d), Input::Enter) => { + run_pan(s, &json!({ "delta": [d.x, d.y] }))?; + Ok(Step::Done) + } + (None, Input::Enter) => Ok(Step::Done), _ => Ok(Step::Continue), } } diff --git a/crates/engine/tests/named_views.rs b/crates/engine/tests/named_views.rs index f33a02cd2..74568dde0 100644 --- a/crates/engine/tests/named_views.rs +++ b/crates/engine/tests/named_views.rs @@ -1,5 +1,5 @@ //! Named views (#463): VIEW / -VIEW Save, Window, Restore, Delete, ? and the layer snapshot -//! setting; Zoom Realtime and Dynamic; ZOOMFACTOR. (The DXF round trip of views is tested in +//! setting; Zoom Realtime and Dynamic; realtime PAN and -PAN; ZOOMFACTOR. (The DXF round trip of views is tested in //! `cadcraft-io`'s `view_tables_roundtrip`.) use cadcraft_engine::doc::Space; @@ -141,6 +141,41 @@ fn zoom_realtime_drags_and_enter_ends() { assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0 }); } +#[test] +fn pan_realtime_drags_and_enter_ends() { + for start in ["pan", "p"] { + let mut s = session(); + set_view(&mut s, 0.0, 0.0, 100.0); + s.state_mut().unwrap().view_history.clear(); + typed(&mut s, &[start]); + assert!(s.realtime_pan_active(), "{}", s.prompt_text()); + // 800 px show 100 units: right 80 px and up 40 px move the drawing with the cursor. + s.realtime_pan(80.0, -40.0).unwrap(); + assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s)); + s.realtime_pan(f64::NAN, 3.0).unwrap(); + assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0), "{:?}", view(&s)); + typed(&mut s, &[""]); + assert!(s.running.is_none() && !s.realtime_pan_active()); + // Outside realtime PAN a drag does nothing; Zoom Previous returns to the view before it. + s.realtime_pan(80.0, -40.0).unwrap(); + assert!(close(view(&s).center.x, -10.0) && close(view(&s).center.y, -5.0)); + s.execute("zoom.previous", &json!({})).unwrap(); + assert_eq!(view(&s), View { center: Vec2::ZERO, height: 100.0 }); + } +} + +#[test] +fn dash_pan_takes_two_points_or_a_displacement() { + let mut s = session(); + set_view(&mut s, 0.0, 0.0, 100.0); + typed(&mut s, &["-pan", "0,0", "10,5"]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(view(&s).center, Vec2::new(-10.0, -5.0)); + typed(&mut s, &["-pan", "3,4", ""]); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(view(&s).center, Vec2::new(-13.0, -9.0)); +} + #[test] fn zoom_dynamic_places_and_sizes_the_view_box() { let mut s = session(); diff --git a/crates/engine/tests/transparent.rs b/crates/engine/tests/transparent.rs index 02a2d5358..4929826cb 100644 --- a/crates/engine/tests/transparent.rs +++ b/crates/engine/tests/transparent.rs @@ -30,7 +30,7 @@ fn transparent_zoom_resumes_the_running_command() { s.cmdline("").unwrap(); s.cancel(); // Scripts nest the same way. - s.script("LINE 0,0 'PAN 0,0 1,1 5,0\n\n").unwrap(); + s.script("LINE 0,0 '-PAN 0,0 1,1 5,0\n\n").unwrap(); assert!(s.running.is_none(), "{}", s.prompt_text()); assert_eq!(lines(&s), 2); // Enter ends the nested command; Esc and a new command cancel both levels. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e5725e353..068a4db28 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1328,6 +1328,11 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { if resp.dragged_by(egui::PointerButton::Primary) && app.session.realtime_zoom_active() { let _ = app.session.realtime_zoom(f64::from(resp.drag_delta().y)); } + // PAN (realtime): the drawing follows a left-button drag. + if resp.dragged_by(egui::PointerButton::Primary) && app.session.realtime_pan_active() { + let d = resp.drag_delta(); + let _ = app.session.realtime_pan(f64::from(d.x), f64::from(d.y)); + } // A click in another tile makes it current (or answers -VPORTS Join's prompts). if pressed_primary && let Some(hp) = hover_pos @@ -1408,7 +1413,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { // 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(); + && !app.session.realtime_zoom_active() + && !app.session.realtime_pan_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| { From ad072e6cb027411c99470b272189b42238912974 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Thu, 15 Oct 2026 10:54:43 -0600 Subject: [PATCH 013/900] 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 7f84dab94861e3f08a1cb7701c0daf7e0e368d82 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Fri, 16 Oct 2026 18:48:18 -0400 Subject: [PATCH 014/900] Fade objects on locked layers on screen by LAYLOCKFADECTL Objects on a locked layer draw faded by LAYLOCKFADECTL percent (default 50; 0 or negative: no fade), whether or not transparency display is on. An object keeps its own transparency when that is greater. Plots never fade. Layer 0 inside a block takes the reference's layer. LAYLOCKFADECTL is a header variable (-90 to 90) available to GETVAR and SETVAR. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/sysvars/table.rs | 2 + crates/engine/tests/setvar_coverage.rs | 6 +++ crates/render/src/lib.rs | 29 +++++++++----- crates/render/src/mline.rs | 2 +- crates/render/src/tests.rs | 52 ++++++++++++++++++++++++++ 5 files changed, 81 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index b1a91b8e1..0aca13baa 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -60,6 +60,8 @@ const HEADER: &[(&str, Kind, Def)] = &[ ("HPNAME", Kind::Pattern, Def::Str("ANSI31")), ("HPSCALE", Kind::Real { min: 0.0, strict: true }, Def::Real(1.0)), ("INSNAME", Kind::Name, Def::Str("")), + // Percent that objects on locked layers fade on screen; 0 or negative: no fade. + ("LAYLOCKFADECTL", Kind::Int(-90, 90), Def::Int(50)), ("LWDEFAULT", Kind::Choice(&LINEWEIGHTS), Def::Int(25)), // Negative: Through (OFFSET picks a point). ("OFFSETDIST", Kind::AnyReal, Def::Real(-1.0)), diff --git a/crates/engine/tests/setvar_coverage.rs b/crates/engine/tests/setvar_coverage.rs index 639f6ddb7..e5d9a7a26 100644 --- a/crates/engine/tests/setvar_coverage.rs +++ b/crates/engine/tests/setvar_coverage.rs @@ -29,6 +29,7 @@ fn defaults_are_the_ones_the_commands_use() { ("DONUTOD", json!(1.0)), ("WIPEOUTFRAME", json!(1)), ("LWDEFAULT", json!(25)), + ("LAYLOCKFADECTL", json!(50)), ("DIMASSOC", json!(2)), ("CPLOTSTYLE", json!("ByLayer")), ("TRANSPARENCYDISPLAY", json!(1)), @@ -61,6 +62,9 @@ fn values_reach_the_commands() { assert!(!s.settings.transparency_display); s.cmdline("setvar plottransparencyoverride 2").unwrap(); assert_eq!(s.settings.plot_transparency_override, 2); + for v in [-90, 0, 90] { + assert!(setvar(&mut s, "LAYLOCKFADECTL", json!(v)), "LAYLOCKFADECTL {v}"); + } assert!(setvar(&mut s, "INSNAME", json!("Valve"))); assert!(setvar(&mut s, "INSNAME", json!("."))); assert_eq!(getvar(&mut s, "INSNAME"), json!("")); @@ -74,6 +78,8 @@ fn bad_values_and_unknown_names_are_refused() { ("POLYSIDES", json!(5000)), ("TRIMMODE", json!(3)), ("LWDEFAULT", json!(26)), + ("LAYLOCKFADECTL", json!(91)), + ("LAYLOCKFADECTL", json!(-91)), ("HPSCALE", json!(0)), ("HPNAME", json!("NO-SUCH-PATTERN")), ("DONUTOD", json!(0)), diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8dadabe88..5208b99ed 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -218,6 +218,7 @@ pub struct Options { pub view: Option, /// Draw objects with their transparency ([`DPrim::transparency`]). Off by default: the screen /// follows TRANSPARENCYDISPLAY, plots the page setup's "Plot transparency". + /// On-screen builds fade objects on locked layers by LAYLOCKFADECTL either way. pub transparency: bool, /// A layout viewport whose model-space contents are left out (its border is still drawn): /// the canvas draws the active viewport's contents itself, see [`viewport_content`]. @@ -943,9 +944,9 @@ fn take_viewport_layers(list: &mut DisplayList) { } } -/// An object's colour, lineweight (mm), linetype, linetype scale, visibility and the transparency -/// of the layer it is drawn on (for ByLayer, see [`transparency`]). -type Resolved = (Ink, f32, Option, f64, bool, u8); +/// An object's colour, lineweight (mm), linetype, linetype scale, visibility, the transparency +/// of the layer it is drawn on (for ByLayer, see [`transparency`]) and its locked-layer fade. +type Resolved = (Ink, f32, Option, f64, bool, u8, u8); fn resolve(ctx: &Ctx, e: &Entity, plotting: bool) -> Resolved { resolve_common(ctx, &e.common, plotting) @@ -977,7 +978,16 @@ fn resolve_common(ctx: &Ctx, c: &cadcraft_doc::Common, plotting: bool) -> Resolv }; let lt = d.linetype(<_name).filter(|l| !l.pattern.is_empty()).cloned(); let scale = d.header.f64("LTSCALE", 1.0) * c.ltscale * ctx.lt_factor; - (rgb, lw_mm, lt, scale, visible, layer.map_or(0, |l| l.transparency)) + (rgb, lw_mm, lt, scale, visible, layer.map_or(0, |l| l.transparency), lock_fade(d, layer, plotting)) +} + +/// The fade (percent, 0..=90) of an object on `layer`: LAYLOCKFADECTL on screen when the layer is +/// locked (0 or negative: no fade); plots never fade. +fn lock_fade(d: &Drawing, layer: Option<&cadcraft_doc::Layer>, plotting: bool) -> u8 { + if plotting || !layer.is_some_and(|l| l.locked) { + return 0; + } + d.header.i64("LAYLOCKFADECTL", 50).clamp(0, i64::from(MAX_TRANSPARENCY)) as u8 } /// The transparency (percent, 0..=90) of an object whose own setting is `t`: the percentage, its @@ -1049,13 +1059,13 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { cadcraft_doc::AnnoDraw::Plain => {} } } - let (rgb, lw, lt, ltscale, visible, layer_transparency) = resolve(ctx, e, b.plotting); + let (rgb, lw, lt, ltscale, visible, layer_transparency, fade) = resolve(ctx, e, b.plotting); if !visible { return; } - if b.opts.transparency { - b.transparency = transparency(e.common.transparency, layer_transparency, ctx.block_transparency); - } + // A locked layer's fade shows even when transparency display is off. + let own = if b.opts.transparency { transparency(e.common.transparency, layer_transparency, ctx.block_transparency) } else { 0 }; + b.transparency = own.max(fade); // A plot style's linetype replaces the object's. let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { Some(over) => over, @@ -1547,8 +1557,9 @@ fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rg (None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference), (def, _) => { let c = a.props.over(&def.map(|d| d.common.clone()).unwrap_or_else(by_block)); - let (ink, lw, _, _, shown, layer_t) = resolve_common(&sub_ctx(ctx, e, Mat3::IDENTITY), &c, b.plotting); + let (ink, lw, _, _, shown, layer_t, fade) = resolve_common(&sub_ctx(ctx, e, Mat3::IDENTITY), &c, b.plotting); let t = if b.opts.transparency { transparency(c.transparency, layer_t, reference) } else { 0 }; + let t = t.max(fade); (ink, lw, shown, t) } }; diff --git a/crates/render/src/mline.rs b/crates/render/src/mline.rs index bbaacb5cc..e63f17489 100644 --- a/crates/render/src/mline.rs +++ b/crates/render/src/mline.rs @@ -33,7 +33,7 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &MLine, rgb: Ink, if !lt.is_empty() && !lt.eq_ignore_ascii_case("bylayer") && !lt.eq_ignore_ascii_case("byblock") { c.linetype = lt.to_string(); } - let (rgb, w, lt, scale, _, _) = resolve_common(ctx, &c, b.plotting); + let (rgb, w, lt, scale, _, _, _) = resolve_common(ctx, &c, b.plotting); let lt = match b.styles.and_then(|s| s.linetype(rgb, b.named)) { Some(over) => over, None => lt, diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ee22abb3c..e09bdde20 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -924,3 +924,55 @@ fn cancelled_build_stops_early() { assert!(!crate::hatch::pattern_lines_until(&drawing, &h, &loops, 0.0, None, None).is_empty()); assert!(crate::hatch::pattern_lines_until(&drawing, &h, &loops, 0.0, None, set.as_deref()).is_empty()); } + +// ---------- locked-layer fade ---------- + +/// A line on locked layer "Locked" (own transparency `own`) and a line on layer 0. +fn locked_lines(own: cadcraft_doc::Transparency) -> Drawing { + let mut d = Drawing::new_imperial(); + d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() }); + let (c, k) = line_common(Common { layer: "Locked".into(), transparency: own, ..Default::default() }); + d.add(&Space::Model, c, k).unwrap(); + let (c, k) = line_common(Common::default()); + d.add(&Space::Model, c, k).unwrap(); + d +} + +fn faded(l: &DisplayList) -> Vec { + l.prims.iter().map(|p| p.transparency).collect() +} + +#[test] +fn objects_on_locked_layers_fade_on_screen() { + use cadcraft_doc::Transparency::{ByLayer, Percent}; + let mut d = locked_lines(ByLayer); + // Default 50, whether transparency display is on or off; the unlocked line is unchanged. + for opts in [Options::default(), with_transparency()] { + let l = build(&d, &Space::Model, &opts); + assert_eq!(faded(&l), vec![50, 0]); + assert!(l.prims[0].alpha() < 255); + assert_eq!(l.prims[1].alpha(), 255); + } + // Plots never fade. + assert_eq!(faded(&build_plot(&d, &Space::Model, &Options::default())), vec![0, 0]); + for (v, want) in [(0, 0), (-30, 0), (70, 70)] { + d.header.set_i64("LAYLOCKFADECTL", v); + assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![want, 0], "LAYLOCKFADECTL {v}"); + } + // An object more transparent than the fade keeps its own transparency. + let d = locked_lines(Percent(80)); + assert_eq!(faded(&build(&d, &Space::Model, &with_transparency())), vec![80, 0]); + assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![50, 0]); +} + +#[test] +fn layer_zero_in_a_block_on_a_locked_layer_fades() { + let mut d = Drawing::new_imperial(); + d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() }); + let mut blk = cadcraft_doc::Block::new("B"); + let (c, k) = line_common(Common::default()); + blk.entities.push(block_entity(1, c, k)); + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + d.add(&Space::Model, Common { layer: "Locked".into(), ..Default::default() }, insert_of("B")).unwrap(); + assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![50]); +} From bc7357ffb86cdcc727c439f166daa78138824492 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 17 Oct 2026 20:06:36 +1100 Subject: [PATCH 015/900] 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 016/900] 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 017/900] 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 018/900] 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 019/900] 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 020/900] 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 021/900] 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 022/900] 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 023/900] 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 17408bdb65203aede5c0700429fc91f6a4647ee0 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Mon, 19 Oct 2026 09:15:02 -0400 Subject: [PATCH 024/900] Fade locked layers only in on-screen builds The render `Options::on_screen` flag (off by default) applies the LAYLOCKFADECTL fade; only the interactive canvas sets it, so plots and SVG, PNG, PDF and CLI exports never fade objects on locked layers. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/pdf.rs | 1 + crates/io/src/tests.rs | 20 ++++++++++++++++++++ crates/render/src/lib.rs | 14 +++++++++----- crates/render/src/tests.rs | 21 +++++++++++++++------ crates/ui-egui/src/canvas.rs | 2 ++ 5 files changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 1423e7a1d..35967655c 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -408,6 +408,7 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String view_height: 0.0, plot_style_table, view: None, + on_screen: false, skip_viewport: None, cancel: None, }; diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 0fb8407a5..f81492cc5 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -358,6 +358,26 @@ fn svg_and_png_export() { assert_eq!(&png[1..4], b"PNG"); } +#[test] +fn exports_do_not_fade_locked_layers() { + let drawing = |locked: bool, t: Transparency| { + let mut d = Drawing::new_imperial(); + d.header.set_i64("LAYLOCKFADECTL", 50); + d.layers.push(Layer { name: "Locked".into(), locked, ..Default::default() }); + let line = EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) }); + d.add(&Space::Model, Common { layer: "Locked".into(), transparency: t, ..Common::default() }, line).unwrap(); + d + }; + let locked = drawing(true, Transparency::ByLayer); + let svg = String::from_utf8(write(&locked, "a.svg").unwrap()).unwrap(); + assert!(!svg.contains("opacity="), "{svg}"); + // An object's own transparency still exports. + let own = String::from_utf8(write(&drawing(true, Transparency::Percent(50)), "a.svg").unwrap()).unwrap(); + assert!(own.contains("opacity="), "{own}"); + // The PNG of a locked layer's object matches the unlocked one. + assert_eq!(write(&locked, "a.png").unwrap(), write(&drawing(false, Transparency::ByLayer), "a.png").unwrap()); +} + fn view_box(svg: &str) -> String { let i = svg.find("viewBox=\"").map(|i| i + 9).unwrap_or(0); svg[i..].split('"').next().unwrap_or("").to_string() diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5208b99ed..7ae6809e6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -218,8 +218,10 @@ pub struct Options { pub view: Option, /// Draw objects with their transparency ([`DPrim::transparency`]). Off by default: the screen /// follows TRANSPARENCYDISPLAY, plots the page setup's "Plot transparency". - /// On-screen builds fade objects on locked layers by LAYLOCKFADECTL either way. pub transparency: bool, + /// A build for the interactive canvas: objects on locked layers fade by LAYLOCKFADECTL, + /// whatever [`Options::transparency`] says. Off by default, so plots and exports never fade. + pub on_screen: bool, /// A layout viewport whose model-space contents are left out (its border is still drawn): /// the canvas draws the active viewport's contents itself, see [`viewport_content`]. pub skip_viewport: Option, @@ -249,6 +251,7 @@ impl Default for Options { view: None, skip_viewport: None, transparency: false, + on_screen: false, cancel: None, } } @@ -981,8 +984,8 @@ fn resolve_common(ctx: &Ctx, c: &cadcraft_doc::Common, plotting: bool) -> Resolv (rgb, lw_mm, lt, scale, visible, layer.map_or(0, |l| l.transparency), lock_fade(d, layer, plotting)) } -/// The fade (percent, 0..=90) of an object on `layer`: LAYLOCKFADECTL on screen when the layer is -/// locked (0 or negative: no fade); plots never fade. +/// The fade (percent, 0..=90) of an object on `layer`: LAYLOCKFADECTL when the layer is locked +/// (0 or negative: no fade); plots never fade. Only [`Options::on_screen`] builds apply it. fn lock_fade(d: &Drawing, layer: Option<&cadcraft_doc::Layer>, plotting: bool) -> u8 { if plotting || !layer.is_some_and(|l| l.locked) { return 0; @@ -1063,7 +1066,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if !visible { return; } - // A locked layer's fade shows even when transparency display is off. + // A locked layer's fade shows on screen even when transparency display is off. + let fade = if b.opts.on_screen { fade } else { 0 }; let own = if b.opts.transparency { transparency(e.common.transparency, layer_transparency, ctx.block_transparency) } else { 0 }; b.transparency = own.max(fade); // A plot style's linetype replaces the object's. @@ -1559,7 +1563,7 @@ fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rg let c = a.props.over(&def.map(|d| d.common.clone()).unwrap_or_else(by_block)); let (ink, lw, _, _, shown, layer_t, fade) = resolve_common(&sub_ctx(ctx, e, Mat3::IDENTITY), &c, b.plotting); let t = if b.opts.transparency { transparency(c.transparency, layer_t, reference) } else { 0 }; - let t = t.max(fade); + let t = if b.opts.on_screen { t.max(fade) } else { t }; (ink, lw, shown, t) } }; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index e09bdde20..6fcfafce5 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -942,27 +942,35 @@ fn faded(l: &DisplayList) -> Vec { l.prims.iter().map(|p| p.transparency).collect() } +fn on_screen(o: Options) -> Options { + Options { on_screen: true, ..o } +} + #[test] fn objects_on_locked_layers_fade_on_screen() { use cadcraft_doc::Transparency::{ByLayer, Percent}; let mut d = locked_lines(ByLayer); // Default 50, whether transparency display is on or off; the unlocked line is unchanged. - for opts in [Options::default(), with_transparency()] { + for opts in [on_screen(Options::default()), on_screen(with_transparency())] { let l = build(&d, &Space::Model, &opts); assert_eq!(faded(&l), vec![50, 0]); assert!(l.prims[0].alpha() < 255); assert_eq!(l.prims[1].alpha(), 255); } - // Plots never fade. - assert_eq!(faded(&build_plot(&d, &Space::Model, &Options::default())), vec![0, 0]); + // Builds without the on-screen flag (exports) and plots never fade. + for opts in [Options::default(), with_transparency()] { + assert_eq!(faded(&build(&d, &Space::Model, &opts)), vec![0, 0]); + } + assert_eq!(faded(&build_plot(&d, &Space::Model, &on_screen(Options::default()))), vec![0, 0]); for (v, want) in [(0, 0), (-30, 0), (70, 70)] { d.header.set_i64("LAYLOCKFADECTL", v); - assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![want, 0], "LAYLOCKFADECTL {v}"); + assert_eq!(faded(&build(&d, &Space::Model, &on_screen(Options::default()))), vec![want, 0], "LAYLOCKFADECTL {v}"); } // An object more transparent than the fade keeps its own transparency. let d = locked_lines(Percent(80)); + assert_eq!(faded(&build(&d, &Space::Model, &on_screen(with_transparency()))), vec![80, 0]); + assert_eq!(faded(&build(&d, &Space::Model, &on_screen(Options::default()))), vec![50, 0]); assert_eq!(faded(&build(&d, &Space::Model, &with_transparency())), vec![80, 0]); - assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![50, 0]); } #[test] @@ -974,5 +982,6 @@ fn layer_zero_in_a_block_on_a_locked_layer_fades() { blk.entities.push(block_entity(1, c, k)); d.blocks.insert("B".into(), std::sync::Arc::new(blk)); d.add(&Space::Model, Common { layer: "Locked".into(), ..Default::default() }, insert_of("B")).unwrap(); - assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![50]); + assert_eq!(faded(&build(&d, &Space::Model, &on_screen(Options::default()))), vec![50]); + assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![0]); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e5725e353..20df85156 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -313,6 +313,7 @@ fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], ctx: &egui:: plot_style_table: None, view: build_window(views), transparency: app.session.settings.transparency_display, + on_screen: true, skip_viewport: split, cancel: None, }; @@ -475,6 +476,7 @@ fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Context) -> Op view: Some(area), skip_viewport: None, transparency, + on_screen: true, cancel: None, }; c.list = cadcraft_render::viewport_content(&st.doc, &st.space, h, area, &opts); From 99b7dc808f87660f388dd1af009df320d0d353f1 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 20 Oct 2026 01:06:04 +1100 Subject: [PATCH 025/900] 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 28fe95fff00fef5d9f8232272219746d0556a4cb Mon Sep 17 00:00:00 2001 From: Rodrigo Gressler Date: Mon, 19 Oct 2026 16:36:13 -0300 Subject: [PATCH 026/900] DXF: save pre-2007 text in the file's code page instead of all \U+ escapes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before 2007, DXF text is in the code page `$DWGCODEPAGE` names. Since #169 every non-ASCII character was written as a `\U+XXXX` escape, so a Portuguese drawing saved at 2000/2004 had layers, blocks and text such as `A\U+00E7\U+00E3o` in the file. Characters the declared code page has are now written as its bytes (`Ação` in ANSI_1252); the others are still escaped, and an unknown code page still gives pure ASCII. The DWG bridge is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dxf/src/codepage.rs | 24 +++++++++ crates/dxf/src/lib.rs | 79 ++++++++++++++++++++--------- crates/dxf/tests/code_page_write.rs | 57 +++++++++++++++++++++ crates/io/src/dxf_write.rs | 8 +-- crates/io/src/lib.rs | 11 ++-- crates/io/tests/codepages.rs | 30 +++++++++++ crates/io/tests/dxf_versions.rs | 16 ++++-- crates/io/tests/followups_626.rs | 7 ++- docs/file-format-parity.md | 5 +- docs/localization-parity.md | 4 +- 10 files changed, 197 insertions(+), 44 deletions(-) create mode 100644 crates/dxf/tests/code_page_write.rs diff --git a/crates/dxf/src/codepage.rs b/crates/dxf/src/codepage.rs index 6f27b5be4..53f24c3b6 100644 --- a/crates/dxf/src/codepage.rs +++ b/crates/dxf/src/codepage.rs @@ -69,6 +69,30 @@ pub fn decode_code_page(bytes: &[u8], code_page: &str) -> Option { decoder(code_page).map(|d| decode(bytes, d).into_owned()) } +/// Append the bytes of the non-ASCII character `c` in the code page `d`, and return true, when +/// the code page has it; otherwise append nothing and return false (the caller escapes it). +pub(crate) fn encode_char(c: char, d: Decoder, out: &mut Vec) -> bool { + let mut buf = [0; 4]; + match d { + Decoder::Utf8 => out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()), + Decoder::Encoding(e) => { + let (bytes, _, unmappable) = e.encode(c.encode_utf8(&mut buf)); + // A code page byte that is ASCII would read back as another character, and a NUL, + // CR or LF would break the group, so only all-high-bit sequences or proper double-byte + // characters are kept (their trail byte may be ASCII, as in Shift-JIS). + if unmappable || bytes.is_empty() || !bytes.first().is_some_and(|b| *b >= 0x80) || bytes.iter().any(|b| matches!(b, 0 | b'\r' | b'\n')) { + return false; + } + out.extend_from_slice(&bytes); + } + Decoder::Table(t) => { + let Some(i) = t.iter().position(|&x| x == c).and_then(|i| u8::try_from(i).ok()) else { return false }; + out.push(0x80 | i); + } + } + true +} + /// Decode bytes with a decoder. UTF-8 that isn't valid falls back to Windows-1252. pub(crate) fn decode(bytes: &[u8], d: Decoder) -> Cow<'_, str> { match d { diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 82ecf55e8..e37e3e13e 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -8,6 +8,7 @@ #![forbid(unsafe_code)] use std::fmt::Write as _; +use std::io::Write as _; mod version; pub use version::Version; @@ -409,18 +410,41 @@ pub fn write_ascii(tags: &[Tag]) -> String { /// characters as they are) or escaped as `\U+XXXX` (older versions, see [`write_ascii`]). Line /// breaks inside strings become spaces either way. pub fn write_ascii_as(tags: &[Tag], utf8: bool) -> String { - let mut out = String::with_capacity(tags.len() * 16); + let bytes = ascii(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }); + // Both forms are UTF-8 (the escaped one is ASCII). + String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()) +} + +/// Write tags as pre-R2007 ASCII DXF with text in the code page `code_page` names (a +/// `$DWGCODEPAGE` value such as `ANSI_1252`), as the DXF Reference describes for those versions: +/// a character the code page has is written as its bytes, any other as a `\U+XXXX` escape. A +/// code page CADCraft doesn't know gives [`write_ascii`]'s pure ASCII output. +pub fn write_ascii_in(tags: &[Tag], code_page: &str) -> Vec { + ascii(tags, Strings::Escaped(codepage::decoder(code_page))) +} + +/// How a writer stores string values. +#[derive(Clone, Copy)] +enum Strings { + /// As they are (R2007+). + Utf8, + /// ASCII as it is, other characters in this code page when it has them, otherwise as + /// `\U+XXXX` escapes (before R2007). + Escaped(Option), +} + +fn ascii(tags: &[Tag], strings: Strings) -> Vec { + let mut out = Vec::with_capacity(tags.len() * 16); for t in tags { let _ = write!(out, "{:>3}\r\n", t.code); match &t.value { - Value::Str(s) if utf8 => out.extend(s.chars().map(|c| if matches!(c, '\r' | '\n') { ' ' } else { c })), - Value::Str(s) => escape_unicode(s, &mut out), - 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::Str(s) => push_string(s, strings, &mut out), + Value::Real(r) => out.extend_from_slice(format_real(*r).as_bytes()), + Value::Int(i) => out.extend_from_slice(i.to_string().as_bytes()), + Value::Bool(b) => out.extend_from_slice(i64::from(*b).to_string().as_bytes()), + Value::Hex(h) => out.extend_from_slice(h.as_bytes()), } - out.push_str("\r\n"); + out.extend_from_slice(b"\r\n"); } out } @@ -433,6 +457,16 @@ pub fn write_ascii_as(tags: &[Tag], utf8: bool) -> String { /// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text /// is stored as a number; a code outside the 16-bit range is skipped. pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { + binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }) +} + +/// Write tags as pre-R2007 binary DXF with text in the code page `code_page` names, as +/// [`write_ascii_in`] does. +pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Vec { + binary(tags, Strings::Escaped(codepage::decoder(code_page))) +} + +fn binary(tags: &[Tag], strings: Strings) -> Vec { let mut out = Vec::with_capacity(BINARY_SENTINEL.len() + tags.len() * 12); out.extend_from_slice(BINARY_SENTINEL); for t in tags { @@ -445,13 +479,9 @@ pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { Value::Str(s) => s.clone(), v => v.as_str(), }; - let mut text = String::with_capacity(s.len()); - if utf8 { - text.extend(s.chars().map(|c| if matches!(c, '\r' | '\n') { ' ' } else { c })); - } else { - escape_unicode(&s, &mut text); - } - out.extend(text.bytes().filter(|&b| b != 0)); + let mut text = Vec::with_capacity(s.len()); + push_string(&s, strings, &mut text); + out.extend(text.into_iter().filter(|&b| b != 0)); out.push(0); } Kind::Real => { @@ -505,15 +535,18 @@ pub fn is_binary(bytes: &[u8]) -> bool { bytes.starts_with(BINARY_SENTINEL) } -/// Escape a string for a pre-R2007 DXF, whose text is in the `$DWGCODEPAGE` code page: ASCII -/// stays as it is and every other character becomes `\U+XXXX` (a surrogate pair of escapes -/// above U+FFFF), so the bytes are valid in any code page. Line breaks become spaces. -fn escape_unicode(s: &str, out: &mut String) { +/// A string value as `strings` stores it. Line breaks become spaces. Before R2007 the text is +/// in the `$DWGCODEPAGE` code page: ASCII stays as it is, a character the code page has becomes +/// its bytes, and every other one `\U+XXXX` (a surrogate pair of escapes above U+FFFF). Without +/// a code page the result is ASCII, so it is valid in any code page. +fn push_string(s: &str, strings: Strings, out: &mut Vec) { for c in s.chars() { - match c { - '\r' | '\n' => out.push(' '), - c if c.is_ascii() => out.push(c), - c => { + match (c, strings) { + ('\r' | '\n', _) => out.push(b' '), + (c, Strings::Utf8) => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()), + (c, _) if c.is_ascii() => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()), + (c, Strings::Escaped(Some(d))) if codepage::encode_char(c, d, out) => {} + (c, Strings::Escaped(_)) => { let mut units = [0u16; 2]; for u in c.encode_utf16(&mut units) { let _ = write!(out, "\\U+{u:04X}"); diff --git a/crates/dxf/tests/code_page_write.rs b/crates/dxf/tests/code_page_write.rs new file mode 100644 index 000000000..316f2edd5 --- /dev/null +++ b/crates/dxf/tests/code_page_write.rs @@ -0,0 +1,57 @@ +//! Pre-R2007 DXF text is written in the `$DWGCODEPAGE` code page: characters it has as their +//! bytes, the others as `\U+XXXX` escapes; every form reads back to the same text. + +use cadcraft_dxf::{Tag, parse, write_ascii, write_ascii_in, write_binary_in}; + +fn file(code_page: &str, text: &str) -> Vec { + vec![ + Tag::s(0, "SECTION"), + Tag::s(2, "HEADER"), + Tag::s(9, "$ACADVER"), + Tag::s(1, "AC1015"), + Tag::s(9, "$DWGCODEPAGE"), + Tag::s(3, code_page), + Tag::s(0, "ENDSEC"), + Tag::s(0, "SECTION"), + Tag::s(2, "ENTITIES"), + Tag::s(0, "TEXT"), + Tag::s(1, text), + Tag::s(0, "ENDSEC"), + Tag::s(0, "EOF"), + ] +} + +fn contains(bytes: &[u8], part: &[u8]) -> bool { + bytes.windows(part.len()).any(|w| w == part) +} + +#[test] +fn text_is_written_in_the_code_page() { + // (code page, text, the bytes written for it) + let cases: [(&str, &str, &[u8]); 6] = [ + ("ANSI_1252", "Ação € 图", b"A\xE7\xE3o \x80 \\U+56FE"), + ("ANSI_1251", "Слой é", b"\xD1\xEB\xEE\xE9 \\U+00E9"), + ("ANSI_932", "表図面 é", b"\x95\x5C\x90\x7D\x96\xCA \\U+00E9"), + ("DOS850", "Größe €", b"Gr\x94\xE1e \\U+20AC"), + ("ANSI_1252", "😀", b"\\U+D83D\\U+DE00"), + // A code page CADCraft doesn't know: everything non-ASCII is escaped. + ("ANSI_1361", "Ação", b"A\\U+00E7\\U+00E3o"), + ]; + for (cp, text, raw) in cases { + let tags = file(cp, text); + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + assert!(contains(&bytes, raw), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); + assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); + } + } +} + +/// Without a known code page the output is what `write_ascii` writes, line breaks included. +#[test] +fn unknown_code_page_is_pure_ascii() { + let tags = file("EBCDIC", "Ação\r\nfim"); + let bytes = write_ascii_in(&tags, "EBCDIC"); + assert!(bytes.is_ascii()); + assert_eq!(bytes, write_ascii(&tags).into_bytes()); + assert!(contains(&bytes, b"A\\U+00E7\\U+00E3o fim")); +} diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 521654e3d..ec4b8595f 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -1234,10 +1234,10 @@ fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx } } -/// `$DWGCODEPAGE`: before 2007 the code page read from the file when CADCraft knows it (the text -/// is ASCII with `\U+XXXX` escapes, right in any code page, but the file keeps its declared one); -/// otherwise, and from 2007 (UTF-8 text), `ANSI_1252`. -fn code_page(d: &Drawing, version: Version) -> String { +/// `$DWGCODEPAGE`: before 2007 the code page read from the file when CADCraft knows it, in which +/// a saved file's text is written (characters outside it as `\U+XXXX` escapes); otherwise, and +/// from 2007 (UTF-8 text), `ANSI_1252`. +pub(crate) fn code_page(d: &Drawing, version: Version) -> String { let read = d.header.get("DWGCODEPAGE").and_then(HVal::as_str).map(str::trim).unwrap_or_default(); let known = read.is_ascii() && read.len() <= 32 && cadcraft_dxf::decode_code_page(b"", read).is_some(); if version < Version::R2007 && known { read.to_string() } else { "ANSI_1252".into() } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ef56e6602..605298db9 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -88,10 +88,13 @@ pub fn write_with(d: &Drawing, name: &str, opts: &SaveOptions) -> Result match ext(name).as_str() { "dxf" | "" => { let tags = dxf_write::tags(d, version); - Ok(if opts.binary { - cadcraft_dxf::write_binary(&tags, version.utf8()) - } else { - cadcraft_dxf::write_ascii_as(&tags, version.utf8()).into_bytes() + // Before 2007 the text is in the code page the header declares. + let code_page = dxf_write::code_page(d, version); + Ok(match (opts.binary, version.utf8()) { + (true, true) => cadcraft_dxf::write_binary(&tags, true), + (true, false) => cadcraft_dxf::write_binary_in(&tags, &code_page), + (false, true) => cadcraft_dxf::write_ascii_as(&tags, true).into_bytes(), + (false, false) => cadcraft_dxf::write_ascii_in(&tags, &code_page), }) } // The DWG bridge reads our R2000 DXF and writes the DWG at the version asked for. Without diff --git a/crates/io/tests/codepages.rs b/crates/io/tests/codepages.rs index 40d85b3f4..53c22e908 100644 --- a/crates/io/tests/codepages.rs +++ b/crates/io/tests/codepages.rs @@ -116,6 +116,36 @@ fn code_page_text_survives_a_round_trip() { assert_eq!(names(&back), ("Слой".into(), "Блок".into(), "Привет".into())); } +/// Saving a pre-2007 DXF writes the text in the file's code page, as the DXF Reference +/// describes: a Portuguese drawing keeps `Elétrica`, `Ação` and `Função` as ANSI_1252 bytes +/// instead of `\U+00E9` escapes, a Cyrillic one its ANSI_1251 bytes, and characters the code +/// page lacks are still escaped. ASCII and binary, R2000 and R2004, read back the same. +#[test] +fn saving_writes_text_in_the_code_page() { + use cadcraft_io::{SaveOptions, Version}; + let pt = ascii_dxf("AC1015", "ANSI_1252", b"El\xE9trica", b"A\xE7\xE3o", b"Fun\xE7\xE3o \\U+56FE"); + let ru = ascii_dxf("AC1015", "ANSI_1251", b"\xD1\xEB\xEE\xE9", b"\xC1\xEB\xEE\xEA", b"\xCF\xF0\xE8\xE2\xE5\xF2 \\U+00E9"); + let cases: [(&[u8], (&str, &str, &str), &[&[u8]]); 2] = [ + (&pt, ("Elétrica", "Ação", "Função 图"), &[b"El\xE9trica", b"A\xE7\xE3o", b"Fun\xE7\xE3o \\U+56FE"]), + (&ru, ("Слой", "Блок", "Привет é"), &[b"\xD1\xEB\xEE\xE9", b"\xC1\xEB\xEE\xEA", b"\xCF\xF0\xE8\xE2\xE5\xF2 \\U+00E9"]), + ]; + for (file, want, raw) in cases { + let d = cadcraft_io::read_dxf(file).unwrap(); + assert_eq!(names(&d), (want.0.into(), want.1.into(), want.2.into())); + for version in [Version::R2000, Version::R2004] { + for binary in [false, true] { + let out = cadcraft_io::write_with(&d, "x.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + for r in raw { + assert!(out.windows(r.len()).any(|w| w == *r), "{version} binary={binary}: {}", String::from_utf8_lossy(r)); + } + assert!(!out.windows(7).any(|w| w == b"\\U+00E7"), "{version} binary={binary}: ç is written as its byte"); + let back = cadcraft_io::read_dxf(&out).unwrap(); + assert_eq!(names(&back), (want.0.into(), want.1.into(), want.2.into()), "{version} binary={binary}"); + } + } + } +} + /// A binary DXF: R2000 strings are in the code page, R2007+ strings UTF-8. #[test] fn binary_dxf_honours_the_code_page() { diff --git a/crates/io/tests/dxf_versions.rs b/crates/io/tests/dxf_versions.rs index 3fc2f1c73..eafd989e9 100644 --- a/crates/io/tests/dxf_versions.rs +++ b/crates/io/tests/dxf_versions.rs @@ -87,9 +87,11 @@ fn dxf_at_every_version_reads_back_the_same() { assert_eq!(acadver(&bytes), v.code(), "{what}"); assert_eq!(cadcraft_dxf::is_binary(&bytes), binary, "{what}"); let raw = bytes.windows("图号".len()).any(|w| w == "图号".as_bytes()); - assert_eq!(raw, v.utf8(), "{what}: UTF-8 text from 2007, \\U+ escapes before"); - if !v.utf8() && !binary { - assert!(bytes.is_ascii(), "{what}"); + assert_eq!(raw, v.utf8(), "{what}: UTF-8 text from 2007, the code page before"); + if !v.utf8() { + // ANSI_1252 has the Latin characters; the others are escaped. + let has = |b: &[u8]| bytes.windows(b.len()).any(|w| w == b); + assert!(has(b"\\U+56FE\\U+53F7 Caf\xe9 \xd8 \\U+D83D\\U+DE00"), "{what}"); } let back = read(&bytes, "x.dxf").unwrap(); assert_eq!(first_text(&back).as_deref(), Some(INTL), "{what}"); @@ -99,11 +101,15 @@ fn dxf_at_every_version_reads_back_the_same() { } } -/// R2000 ASCII is exactly the R2000 DXF CADCraft always wrote. +/// R2000 ASCII is the R2000 DXF CADCraft always wrote, tag for tag; only the text is in the +/// code page instead of all `\U+` escapes. #[test] fn r2000_ascii_is_unchanged() { let d = sample(); - assert_eq!(write_with(&d, "x.dxf", &opts(Version::R2000, false)).unwrap(), write_dxf(&d).into_bytes()); + let saved = write_with(&d, "x.dxf", &opts(Version::R2000, false)).unwrap(); + let escaped = write_dxf(&d); + assert_ne!(saved, escaped.as_bytes(), "Café is written in ANSI_1252"); + assert_eq!(cadcraft_dxf::parse(&saved).unwrap(), cadcraft_dxf::parse(escaped.as_bytes()).unwrap()); } /// Without a version asked for: 2018 for a new drawing, otherwise the file's own version (the diff --git a/crates/io/tests/followups_626.rs b/crates/io/tests/followups_626.rs index a44a27eb4..10e355cd3 100644 --- a/crates/io/tests/followups_626.rs +++ b/crates/io/tests/followups_626.rs @@ -177,10 +177,9 @@ fn code_page_is_kept_before_2007() { .unwrap(); for v in [Version::R2000, Version::R2004] { let bytes = save(&d, "x.dxf", v); - assert!(bytes.is_ascii(), "{v:?}: ASCII with escapes"); - let text = String::from_utf8(bytes).unwrap(); - assert_eq!(code_page(&text), "ANSI_1251", "{v:?}"); - let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + assert!(bytes.windows(6).any(|w| w == b"\xCF\xF0\xE8\xE2\xE5\xF2"), "{v:?}: the text in ANSI_1251"); + assert_eq!(code_page(&String::from_utf8_lossy(&bytes)), "ANSI_1251", "{v:?}"); + let back = cadcraft_io::read_dxf(&bytes).unwrap(); assert_eq!(back.header.str("DWGCODEPAGE", ""), "ANSI_1251"); assert!(back.model.iter().any(|e| matches!(&e.kind, EntityKind::Text(t) if t.value == "Привет"))); } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c598193d7..122b654a8 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-19 · **Change:** minor (pre-2007 DXF text saved in its code page) · **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 @@ -66,7 +66,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | R12 binary | read, write | **no** (binary parser expects R13+ 2-byte group codes) | no | | R13–R2018, ASCII | read, write each of 2000/2004/2007/2010/2013/2018 | yes, one reader for all versions | yes, each of 2000–2018 (#421): R2000 structure (later versions add only optional groups) with that `$ACADVER`; UTF-8 text from 2007; no CLASS instance counts (91) | | R13–R2018, binary | read, write | yes | yes, each of 2000–2018 (SAVEAS `binary`; a binary file stays binary on QSAVE) | -| Code pages (`$DWGCODEPAGE`, ANSI_932/936/949/950/125x) | yes | yes (#505): ASCII and binary DXF before 2007 decode from their code page (ANSI_874/932/936/949/950/1250–1258, DOS437/850/852/866, ISO 8859, Macintosh); a file that is valid UTF-8 reads as UTF-8; Johab and other DOS code pages read as ANSI_1252 (`dxf/src/codepage.rs`) | writes `\U+` escapes (#169), which is correct; declares `ANSI_1252` | +| Code pages (`$DWGCODEPAGE`, ANSI_932/936/949/950/125x) | yes | yes (#505): ASCII and binary DXF before 2007 decode from their code page (ANSI_874/932/936/949/950/1250–1258, DOS437/850/852/866, ISO 8859, Macintosh); a file that is valid UTF-8 reads as UTF-8; Johab and other DOS code pages read as ANSI_1252 (`dxf/src/codepage.rs`) | before 2007 writes text in the declared code page (the one read from the file, else `ANSI_1252`), characters outside it as `\U+` escapes; an unknown code page gives pure ASCII with escapes (#169) | | `\U+`/`\M+` escapes | yes | yes (`\M+` since #505; Johab `\M+4` stays literal) | `\U+` yes | ### DXF content: read and write by object type @@ -138,6 +138,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-19 | minor | Pre-2007 DXF saves write text in the file's code page (`Ação` as ANSI_1252 bytes, not `A\U+00E7\U+00E3o`); characters outside it stay `\U+` escapes | | 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 | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 3dbd01e22..5c0574616 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -31,8 +31,8 @@ shaping and right-to-left text through TrueType, vertical SHX text styles. English. For scale: about 1,160 unique capitalised string literals exist in `crates/engine` and `crates/ui-egui` (grep, 2026-10-10). - **Drawing text:** TrueType/OpenType/`.ttc` through `skrifa` with per-character font fallback - and FONTALT, so CJK characters render (#173). DXF text is written with `\U+` escapes so - non-ASCII survives in R2000 files (#169). Lines with right-to-left text get the Unicode + and FONTALT, so CJK characters render (#173). Pre-2007 DXF text is written in the file's code page, + with `\U+` escapes for characters outside it, so non-ASCII survives in R2000 files (#169). Lines with right-to-left text get the Unicode 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 From a0e023d75806cdad65da8f8b555a57ff0a30c594 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 20 Oct 2026 12:09:54 +1100 Subject: [PATCH 027/900] 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 936f08db1feba5515f5ea7d51a9d3a37dda3aecd Mon Sep 17 00:00:00 2001 From: Rodrigo Gressler Date: Mon, 19 Oct 2026 22:25:35 -0300 Subject: [PATCH 028/900] DXF: keep files that declare ASCII or UTF8 pure ASCII when saving A pre-2007 file whose header says $DWGCODEPAGE ASCII (or UTF8/UNICODE, which no pre-2007 reader expects) is still written with \U+ escapes only, instead of Windows-1252 (or UTF-8) bytes the header doesn't declare. Review of #1693. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/dxf/src/codepage.rs | 14 +++++++++++++- crates/dxf/src/lib.rs | 7 ++++--- crates/dxf/tests/code_page_write.rs | 18 +++++++++++------- crates/io/tests/codepages.rs | 19 +++++++++++++++++++ 4 files changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/dxf/src/codepage.rs b/crates/dxf/src/codepage.rs index 53f24c3b6..9377404d9 100644 --- a/crates/dxf/src/codepage.rs +++ b/crates/dxf/src/codepage.rs @@ -69,12 +69,24 @@ pub fn decode_code_page(bytes: &[u8], code_page: &str) -> Option { decoder(code_page).map(|d| decode(bytes, d).into_owned()) } +/// The code page a pre-2007 file's text is written in, or `None` for pure ASCII with escapes: +/// when CADCraft doesn't know `code_page`, and for `ASCII` (the reader takes such files as +/// Windows-1252, but a writer must keep them ASCII) and `UTF8`/`UNICODE`, which no pre-2007 +/// reader expects. +pub(crate) fn encoder(code_page: &str) -> Option { + if code_page.trim().eq_ignore_ascii_case("ASCII") { + return None; + } + decoder(code_page).filter(|d| !matches!(d, Decoder::Utf8)) +} + /// Append the bytes of the non-ASCII character `c` in the code page `d`, and return true, when /// the code page has it; otherwise append nothing and return false (the caller escapes it). pub(crate) fn encode_char(c: char, d: Decoder, out: &mut Vec) -> bool { let mut buf = [0; 4]; match d { - Decoder::Utf8 => out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()), + // Not a pre-2007 code page ([`encoder`] never gives it): escaped. + Decoder::Utf8 => return false, Decoder::Encoding(e) => { let (bytes, _, unmappable) = e.encode(c.encode_utf8(&mut buf)); // A code page byte that is ASCII would read back as another character, and a NUL, diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index e37e3e13e..0bbb4ee68 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -418,9 +418,10 @@ pub fn write_ascii_as(tags: &[Tag], utf8: bool) -> String { /// Write tags as pre-R2007 ASCII DXF with text in the code page `code_page` names (a /// `$DWGCODEPAGE` value such as `ANSI_1252`), as the DXF Reference describes for those versions: /// a character the code page has is written as its bytes, any other as a `\U+XXXX` escape. A -/// code page CADCraft doesn't know gives [`write_ascii`]'s pure ASCII output. +/// code page CADCraft doesn't know, `ASCII`, and `UTF8`/`UNICODE` (not a pre-2007 code page) +/// give [`write_ascii`]'s pure ASCII output. pub fn write_ascii_in(tags: &[Tag], code_page: &str) -> Vec { - ascii(tags, Strings::Escaped(codepage::decoder(code_page))) + ascii(tags, Strings::Escaped(codepage::encoder(code_page))) } /// How a writer stores string values. @@ -463,7 +464,7 @@ pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { /// Write tags as pre-R2007 binary DXF with text in the code page `code_page` names, as /// [`write_ascii_in`] does. pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Vec { - binary(tags, Strings::Escaped(codepage::decoder(code_page))) + binary(tags, Strings::Escaped(codepage::encoder(code_page))) } fn binary(tags: &[Tag], strings: Strings) -> Vec { diff --git a/crates/dxf/tests/code_page_write.rs b/crates/dxf/tests/code_page_write.rs index 316f2edd5..67e7e7e57 100644 --- a/crates/dxf/tests/code_page_write.rs +++ b/crates/dxf/tests/code_page_write.rs @@ -46,12 +46,16 @@ fn text_is_written_in_the_code_page() { } } -/// Without a known code page the output is what `write_ascii` writes, line breaks included. +/// Without a known code page, and for `ASCII`, `UTF8` and `UNICODE` headers, the output is what +/// `write_ascii` writes (pure ASCII with escapes), line breaks included. #[test] -fn unknown_code_page_is_pure_ascii() { - let tags = file("EBCDIC", "Ação\r\nfim"); - let bytes = write_ascii_in(&tags, "EBCDIC"); - assert!(bytes.is_ascii()); - assert_eq!(bytes, write_ascii(&tags).into_bytes()); - assert!(contains(&bytes, b"A\\U+00E7\\U+00E3o fim")); +fn unknown_ascii_and_utf8_code_pages_are_pure_ascii() { + for cp in ["EBCDIC", "ASCII", "ascii ", "UTF8", "UNICODE"] { + let tags = file(cp, "Ação\r\nfim"); + let bytes = write_ascii_in(&tags, cp); + assert!(bytes.is_ascii(), "{cp}"); + assert_eq!(bytes, write_ascii(&tags).into_bytes(), "{cp}"); + assert!(contains(&bytes, b"A\\U+00E7\\U+00E3o fim"), "{cp}"); + assert!(write_binary_in(&tags, cp).iter().all(u8::is_ascii), "{cp} binary"); + } } diff --git a/crates/io/tests/codepages.rs b/crates/io/tests/codepages.rs index 53c22e908..56f9af80f 100644 --- a/crates/io/tests/codepages.rs +++ b/crates/io/tests/codepages.rs @@ -146,6 +146,25 @@ fn saving_writes_text_in_the_code_page() { } } +/// A file whose header declares `ASCII` keeps that code page and stays ASCII when saved: its +/// non-ASCII text is written as `\U+` escapes, not as Windows-1252 bytes. +#[test] +fn saving_an_ascii_file_keeps_it_ascii() { + use cadcraft_io::{SaveOptions, Version}; + let d = cadcraft_io::read_dxf(&ascii_dxf("AC1015", "ASCII", b"El\\U+00E9trica", b"B", b"Eletrica \\U+00E9")).unwrap(); + assert_eq!(names(&d), ("Elétrica".into(), "B".into(), "Eletrica é".into())); + for version in [Version::R2000, Version::R2004] { + let ascii = cadcraft_io::write_with(&d, "x.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap(); + assert!(ascii.is_ascii(), "{version}"); + let binary = cadcraft_io::write_with(&d, "x.dxf", &SaveOptions { version: Some(version), binary: true }).unwrap(); + for out in [&ascii, &binary] { + assert!(out.windows(14).any(|w| w == b"El\\U+00E9trica"), "{version}"); + assert!(out.windows(5).any(|w| w == b"ASCII"), "{version}: the header keeps its code page"); + assert_eq!(names(&cadcraft_io::read_dxf(out).unwrap()), ("Elétrica".into(), "B".into(), "Eletrica é".into()), "{version}"); + } + } +} + /// A binary DXF: R2000 strings are in the code page, R2007+ strings UTF-8. #[test] fn binary_dxf_honours_the_code_page() { From 4c75916c75e4409b2d56af9bfbddd055407875f3 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Mon, 19 Oct 2026 22:40:23 -0400 Subject: [PATCH 029/900] Keep the saved view twist when a template opens or xrefs load after open --- crates/engine/src/cmd/blocks/xref.rs | 9 ++++----- crates/engine/src/cmd/file/template.rs | 3 ++- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index 060dca22c..32e674670 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -62,11 +62,10 @@ pub(crate) fn after_open(s: &mut Session, i: usize) { st.saved = st.doc.clone(); let ext = st.doc.extents(&cadcraft_doc::Space::Model); if !ext.is_empty() { - st.set_view_quiet(crate::View { - center: ext.center(), - height: (ext.height().max(ext.width() * px.1 / px.0.max(1.0)) * 1.1).max(1e-6), - twist: 0.0, - }); + // Fit in the frame of the saved twist, which open_drawing has restored. + let twist = st.view().twist; + let (center, w, h) = crate::View::twisted_box(ext, twist); + st.set_view_quiet(crate::View { center, height: (h.max(w * px.1 / px.0.max(1.0)) * 1.1).max(1e-6), twist }); } echo_all(s, &out); } diff --git a/crates/engine/src/cmd/file/template.rs b/crates/engine/src/cmd/file/template.rs index 32a534c4c..2671a2cce 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -59,7 +59,8 @@ pub(super) fn run_new(s: &mut Session, p: &Value) -> Result> { && hi.y > lo.y { let center = cadcraft_geom::Vec2::new((lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0); - st.set_view_quiet(crate::View { center, height: (hi.y - lo.y).max(1e-6), twist: 0.0 }); + let twist = st.view().twist; + st.set_view_quiet(crate::View { center, height: (hi.y - lo.y).max(1e-6), twist }); } Ok(Some(json!({ "index": i, "title": title, "template": path }))) } From 15dcfcfba97d469d19b047275aaed8f3ff2a631a Mon Sep 17 00:00:00 2001 From: mattlafy Date: Mon, 19 Oct 2026 22:42:36 -0400 Subject: [PATCH 030/900] ByBlock children of a reference on a locked layer take its own transparency, not its fade --- crates/render/src/lib.rs | 12 +++++++----- crates/render/src/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d1d61e330..958a2dd86 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1130,12 +1130,12 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { } mtext(b, ctx, t, rgb, lw); } - EntityKind::Insert(ins) => insert(b, ctx, e, ins, rgb), + EntityKind::Insert(ins) => insert(b, ctx, e, ins, rgb, own), EntityKind::Dimension(dm) => { if let Some(blk) = dm.block.as_ref().and_then(|n| ctx.d.block(n)) && ctx.depth < cadcraft_doc::MAX_BLOCK_DEPTH { - let sub = Ctx { block_pstyle: b.named, block_transparency: b.transparency, ..sub_ctx(ctx, e, Mat3::IDENTITY) }; + let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::IDENTITY) }; for be in blk.entities.iter() { if !b.expand() { break; @@ -1280,7 +1280,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { let dir = if ins.insert.x >= land.x { 1.0 } else { -1.0 }; b.polyline(ctx, rgb, lw, &[land, land + Vec2::new(m.dogleg * dir, 0.0)]); } - insert(b, ctx, e, ins, rgb); + insert(b, ctx, e, ins, rgb, own); } } EntityKind::Point(p) => { @@ -1549,7 +1549,9 @@ fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> { } } -fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink) { +/// `own` is the reference's resolved transparency without its locked-layer fade: what ByBlock +/// children inherit (a child fades only for its own layer). +fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink, own: u8) { if ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH { return; } @@ -1563,7 +1565,7 @@ fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rg } 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) }; + let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, m) }; for be in blk.entities.iter() { // Constant/visible attribute definitions inside blocks are not drawn; attribs are. if matches!(be.kind, EntityKind::AttDef(_)) { diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 2edf53e92..c16712a63 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -985,6 +985,26 @@ fn layer_zero_in_a_block_on_a_locked_layer_fades() { assert_eq!(faded(&build(&d, &Space::Model, &on_screen(Options::default()))), vec![50]); assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![0]); } +#[test] +fn byblock_child_on_an_unlocked_layer_does_not_inherit_the_fade() { + use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent}; + // A ByBlock line on unlocked layer "Open" in a block inserted on locked layer "Locked". + let drawing = |insert_transparency| { + let mut d = Drawing::new_imperial(); + d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() }); + d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() }); + let mut blk = cadcraft_doc::Block::new("B"); + let (c, k) = line_common(Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() }); + blk.entities.push(block_entity(1, c, k)); + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let common = Common { layer: "Locked".into(), transparency: insert_transparency, ..Default::default() }; + d.add(&Space::Model, common, insert_of("B")).unwrap(); + d + }; + // The child takes the reference's own transparency, not its display fade. + assert_eq!(faded(&build(&drawing(ByLayer), &Space::Model, &on_screen(with_transparency()))), vec![0]); + assert_eq!(faded(&build(&drawing(Percent(20)), &Space::Model, &on_screen(with_transparency()))), vec![20]); +} /// #1434: a closed polyline with a global width narrower than a pixel loses whole sides at /// some zooms, while the same polyline with width 0 always shows every side. From 94b6c485b40090666b3b3e637ff2e8bc5220e57c Mon Sep 17 00:00:00 2001 From: mattlafy Date: Tue, 20 Oct 2026 00:00:47 -0400 Subject: [PATCH 031/900] DVIEW records a viewport twist as one undo step when cancelled --- crates/engine/src/cmd/view/dview.rs | 9 +++++---- crates/engine/src/guard.rs | 8 ++++++++ crates/engine/src/lib.rs | 8 ++++++-- crates/engine/src/prompt.rs | 3 +++ crates/engine/tests/dview.rs | 16 ++++++++++++++++ 5 files changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs index bfbef0047..7fbe2b832 100644 --- a/crates/engine/src/cmd/view/dview.rs +++ b/crates/engine/src/cmd/view/dview.rs @@ -284,11 +284,12 @@ impl Interactive for DviewM { Stage::Zoom => Prompt::new("Specify zoom scale factor", Accept::NUMBER).default("1"), } } - fn input(&mut self, s: &mut Session, i: Input) -> Result { - if matches!(i, Input::Cancel) { - self.end(s)?; - return Ok(Step::Cancel); + fn cancelled(&mut self, s: &mut Session) { + if let Err(e) = self.end(s) { + s.echo(e.to_string()); } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { match self.stage { Stage::Select => match self.sel.feed(s, &i)? { SelOutcome::More => Ok(Step::Continue), diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index b224994ed..8e3d25001 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -66,6 +66,14 @@ impl Interactive for Guarded { fn begin(&mut self, s: &mut Session) -> Result { catch_unwind(AssertUnwindSafe(|| self.inner.begin(s))).unwrap_or_else(|p| Err(self.internal(&*p))) } + fn cancelled(&mut self, s: &mut Session) { + if self.broken.get().is_none() + && let Err(p) = catch_unwind(AssertUnwindSafe(|| self.inner.cancelled(s))) + { + let e = self.internal(&*p); + s.echo(e.to_string()); + } + } fn preview(&self, s: &Session, cursor: Vec2) -> Vec { if self.broken.get().is_some() { return Vec::new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a3e4cd1e3..d72938de4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1264,7 +1264,10 @@ impl Session { let base = if matches!(input, Some(Input::Point(_))) { self.current_prompt().and_then(|p| p.base) } else { None }; let Some(mut run) = self.running.take() else { return Ok(()) }; let step = match input { - Some(Input::Cancel) => Ok(Step::Cancel), + Some(Input::Cancel) => { + run.machine.cancelled(self); + Ok(Step::Cancel) + } Some(i) => { if let Input::Point(p) = &i { self.last_point = *p; @@ -1403,7 +1406,8 @@ impl Session { } if self.running.is_some() { if self.suspended.is_some() { - if let Some(nested) = self.running.take() { + if let Some(mut nested) = self.running.take() { + nested.machine.cancelled(self); self.finish(nested, true); } self.running = self.suspended.take(); diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index 1d3fa06ff..eaa7480a9 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -229,6 +229,9 @@ pub trait Interactive: Send { fn begin(&mut self, _s: &mut Session) -> Result { Ok(Step::Continue) } + /// Called when the command is cancelled from outside (Esc, or another command starting), + /// before it finishes: what it records on every exit path. + fn cancelled(&mut self, _s: &mut Session) {} /// Rubber-band geometry for the cursor position. fn preview(&self, _s: &Session, _cursor: Vec2) -> Vec { Vec::new() diff --git a/crates/engine/tests/dview.rs b/crates/engine/tests/dview.rs index 2a81b743a..154b9b4e1 100644 --- a/crates/engine/tests/dview.rs +++ b/crates/engine/tests/dview.rs @@ -237,6 +237,22 @@ fn inside_an_active_viewport_it_twists_that_viewport_as_one_undo_step() { assert_eq!(s.cmdline("dview").unwrap_err().to_string(), PAPER); } +#[test] +fn escape_inside_an_active_viewport_keeps_the_twist_as_one_undo_step() { + let (mut s, h) = layout_session(); + s.execute("mspace", &json!({ "handle": h.hex() })).unwrap(); + let undo = s.state().unwrap().undo.len(); + for l in ["dview", "", "tw", "30"] { + s.cmdline(l).unwrap(); + } + s.input(Input::Cancel).unwrap(); + assert!(s.current_prompt().is_none()); + assert!(near(vp(&s, h).twist.to_degrees(), 30.0)); + assert_eq!(s.state().unwrap().undo.len(), undo + 1); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(vp(&s, h).twist, 0.0); +} + #[test] fn the_view_inside_a_twisted_viewport_maps_the_screen_like_the_sheet() { let (mut s, h) = layout_session(); From afcb6aa74345ec188caf8967f3d5dcd06d9ffcaf Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 20 Oct 2026 21:01:57 +1100 Subject: [PATCH 032/900] 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 033/900] 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 6f5bf85dc0ac329b1b75274821a3fc30a1bdbbb7 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:42:53 +0200 Subject: [PATCH 034/900] REVCLOUD: the Object option accepts an entity name (#1713) --- crates/engine/src/cmd/draw2.rs | 8 ++++++-- crates/engine/src/cmd/draw2_tests.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 1d3b10c6c..df4d90901 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -1109,8 +1109,12 @@ impl Interactive for RevcloudM { return Ok(Step::Continue); } if self.object { - let Input::Point(p) = i else { return if i == Input::Enter { Ok(Step::Cancel) } else { Ok(Step::Continue) } }; - let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; + let h = match i { + Input::Point(p) => curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?, + Input::Pick(hs) => hs.first().copied().ok_or_else(|| other("*Invalid selection*"))?, + Input::Enter => return Ok(Step::Cancel), + _ => return Ok(Step::Continue), + }; let pts = object_outline(s, h)?; let vs = cloud_vertices(&pts, self.arc_len, false, false).ok_or_else(|| other("The object has no area."))?; let nh = s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?; diff --git a/crates/engine/src/cmd/draw2_tests.rs b/crates/engine/src/cmd/draw2_tests.rs index 56be94cc4..9a1461cfe 100644 --- a/crates/engine/src/cmd/draw2_tests.rs +++ b/crates/engine/src/cmd/draw2_tests.rs @@ -372,6 +372,18 @@ fn revcloud_command_line() { assert_eq!(kinds(&s).len(), 4); } +#[test] +fn revcloud_object_accepts_entity_name() { + let mut s = Session::new(); + s.execute("rectang", &json!({"p1": [0, 0], "p2": [4, 4]})).unwrap(); + let h = s.doc().unwrap().model.last().unwrap().handle; + s.cmdline("revcloud o").unwrap(); + s.input(Input::Pick(vec![h])).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(kinds(&s).len(), 1); + assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() > 4)); +} + // ---------------- BREAKLINE ---------------- fn breakline_points(s: &Session) -> Vec<(f64, f64)> { From b44cb36865c2d3a8849490c20d608ed591f2ca0d Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:43:37 +0200 Subject: [PATCH 035/900] REVCLOUD: ask maximum arc length and Reverse direction for Object (#1714) --- crates/engine/src/cmd/draw2.rs | 72 +++++++++++++++++++++++----- crates/engine/src/cmd/draw2_tests.rs | 21 +++++++- 2 files changed, 80 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 1d3b10c6c..3bcbee605 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -918,6 +918,11 @@ fn default_arc_len(s: &Session) -> f64 { d.map(|d| d.header.f64("REVCLOUDARCLEN", if metric { 15.0 } else { 0.5 })).unwrap_or(0.5).max(1e-6) } +/// Maximum arc length remembered between REVCLOUD runs (CADCraft-only state, not an AutoCAD variable); never below `min`. +fn default_max_arc_len(s: &Session, min: f64) -> f64 { + s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min) +} + /// Bulged closed polyline vertices for a revision cloud around `boundary`. pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option> { let mut pts: Vec = Vec::new(); @@ -1024,15 +1029,31 @@ struct RevcloudM { kind: CloudKind, pts: Vec, arc_len: f64, + max_arc_len: f64, asking_arc: bool, + asking_max: bool, object: bool, + /// Outline of the picked object while "Reverse direction" is being asked. + picked: Option<(Handle, Vec)>, calligraphy: bool, asking_style: bool, } impl RevcloudM { fn new(s: &Session, kind: CloudKind) -> Self { - RevcloudM { kind, pts: Vec::new(), arc_len: default_arc_len(s), asking_arc: false, object: false, calligraphy: false, asking_style: false } + let arc_len = default_arc_len(s); + RevcloudM { + kind, + pts: Vec::new(), + arc_len, + max_arc_len: default_max_arc_len(s, arc_len), + asking_arc: false, + asking_max: false, + object: false, + picked: None, + calligraphy: false, + asking_style: false, + } } fn boundary(&self, extra: Option) -> Vec { let mut pts = self.pts.clone(); @@ -1067,13 +1088,19 @@ impl Interactive for RevcloudM { CloudKind::Poly => "Polygonal", CloudKind::Free => "Freehand", }; - s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {0:.4} Style: Normal Type: {t}", self.arc_len)); + s.echo(format!("Minimum arc length: {0:.4} Maximum arc length: {1:.4} Style: Normal Type: {t}", self.arc_len, self.max_arc_len)); Ok(Step::Continue) } fn prompt(&self, _s: &Session) -> Prompt { + if self.picked.is_some() { + return Prompt::new("Reverse direction", curves::KW).kw(&["Yes", "No"]).default("No"); + } if self.asking_arc { return Prompt::new("Specify minimum length of arc", Accept::NUMBER).default(format!("{:.4}", self.arc_len)); } + if self.asking_max { + return Prompt::new("Specify maximum length of arc", Accept::NUMBER).default(format!("{:.4}", self.max_arc_len)); + } if self.asking_style { return Prompt::new("Select arc style", curves::KW).kw(&["Normal", "Calligraphy"]).default("Normal"); } @@ -1092,13 +1119,38 @@ impl Interactive for RevcloudM { } } fn input(&mut self, s: &mut Session, i: Input) -> Result { + if let Some((h, pts)) = self.picked.take() { + let reverse = matches!(&i, Input::Keyword(k) | Input::Text(k) if k.to_ascii_lowercase().starts_with('y')); + let vs = cloud_vertices(&pts, self.arc_len, false, reverse).ok_or_else(|| other("The object has no area."))?; + let nh = s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?; + let common = curves::entity(s, h)?.common; + let d = s.doc_mut()?; + d.modify_entity(nh, |e| e.common = common)?; + d.remove_entity(h); + s.echo("Revision cloud finished."); + return Ok(Step::Done); + } if self.asking_arc { if let Input::Text(t) = &i { let v = number(t).filter(|v| *v > 0.0).ok_or_else(|| other("Requires a positive value."))?; self.arc_len = v; - s.doc_mut()?.header.set_f64("REVCLOUDARCLEN", v); + self.max_arc_len = self.max_arc_len.max(v); + let max = self.max_arc_len; + let d = s.doc_mut()?; + d.header.set_f64("REVCLOUDARCLEN", v); + d.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", max); } self.asking_arc = false; + self.asking_max = true; + return Ok(Step::Continue); + } + if self.asking_max { + if let Input::Text(t) = &i { + let v = number(t).filter(|v| *v >= self.arc_len).ok_or_else(|| other("Requires a value not less than the minimum arc length."))?; + self.max_arc_len = v; + s.doc_mut()?.header.set_f64("CADCRAFT_REVCLOUDMAXARCLEN", v); + } + self.asking_max = false; return Ok(Step::Continue); } if self.asking_style { @@ -1112,14 +1164,12 @@ impl Interactive for RevcloudM { let Input::Point(p) = i else { return if i == Input::Enter { Ok(Step::Cancel) } else { Ok(Step::Continue) } }; let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; let pts = object_outline(s, h)?; - let vs = cloud_vertices(&pts, self.arc_len, false, false).ok_or_else(|| other("The object has no area."))?; - let nh = s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?; - let common = curves::entity(s, h)?.common; - let d = s.doc_mut()?; - d.modify_entity(nh, |e| e.common = common)?; - d.remove_entity(h); - s.echo("Revision cloud finished."); - return Ok(Step::Done); + if cloud_vertices(&pts, self.arc_len, false, false).is_none() { + return Err(other("The object has no area.")); + } + self.object = false; + self.picked = Some((h, pts)); + return Ok(Step::Continue); } match i { Input::Keyword(k) => { diff --git a/crates/engine/src/cmd/draw2_tests.rs b/crates/engine/src/cmd/draw2_tests.rs index 56be94cc4..8ddc7bc3b 100644 --- a/crates/engine/src/cmd/draw2_tests.rs +++ b/crates/engine/src/cmd/draw2_tests.rs @@ -354,7 +354,7 @@ fn revcloud_json() { #[test] fn revcloud_command_line() { let mut s = Session::new(); - s.cmdline("revcloud a 1").unwrap(); + s.cmdline("revcloud a 1 1").unwrap(); s.cmdline("0,0 4,2").unwrap(); assert!(s.running.is_none(), "{}", s.prompt_text()); assert!(matches!(last(&s), EntityKind::LwPolyline(p) if p.vertices.len() == 12)); @@ -367,11 +367,28 @@ fn revcloud_command_line() { assert_eq!(kinds(&s).len(), 3); // Object option converts a closed polyline. s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap(); - s.cmdline("revcloud o 10,11").unwrap(); + s.cmdline("revcloud o 10,11 n").unwrap(); assert!(s.running.is_none()); assert_eq!(kinds(&s).len(), 4); } +#[test] +fn revcloud_arc_length_asks_max_and_object_asks_reverse() { + let mut s = Session::new(); + s.execute("rectang", &json!({"p1": [10, 10], "p2": [12, 12]})).unwrap(); + s.cmdline("revcloud a 200 800").unwrap(); + assert!(s.prompt_text().contains("first corner"), "{}", s.prompt_text()); + s.cmdline("0,0 2000,1000").unwrap(); + assert!(s.running.is_none()); + s.cmdline("revcloud").unwrap(); + assert!(s.log.iter().any(|l| l.contains("Minimum arc length: 200.0000 Maximum arc length: 800.0000")), "{:?}", s.log); + s.cmdline("o").unwrap(); + s.cmdline("10,11").unwrap(); + assert!(s.running.is_some() && s.prompt_text().contains("Reverse direction"), "{}", s.prompt_text()); + s.cmdline("n").unwrap(); + assert!(s.running.is_none()); +} + // ---------------- BREAKLINE ---------------- fn breakline_points(s: &Session) -> Vec<(f64, f64)> { 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 036/900] 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 037/900] 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 038/900] 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 039/900] 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 040/900] 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 bbd4eddd45e96c766985c0097ac7f8cf34f11e8a Mon Sep 17 00:00:00 2001 From: mo <131036780+mbolling@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:05:48 -0400 Subject: [PATCH 041/900] Find installed fonts where fontconfig looks: XDG dirs, fontconfig entries, Flatpak host fonts On Linux and the BSDs the font scan only walked /usr/share/fonts, /usr/local/share/fonts, ~/.fonts and ~/.local/share/fonts. NixOS and Guix keep every font package in its own store path and tell fontconfig about them through entries (/etc/fonts/conf.d/00-nixos-cache.conf, home-manager's ~/.config/fontconfig/conf.d) and $XDG_DATA_DIRS; a Flatpak sandbox sees the host's fonts only under /run/host. On such systems the scan found nothing, so CJK and Arabic characters in drawing text drew the missing-glyph box although fonts with them were installed (#674). A resolver in ttf/dirs.rs returns the directories fontconfig would use, in priority order: $XDG_DATA_HOME/fonts and ~/.fonts, every $XDG_DATA_DIRS entry + /fonts (plus /usr/share/fonts and /usr/local/share/fonts whether listed or not), Flatpak's /run/host/{fonts,local-fonts,user-fonts}, then the elements of $FONTCONFIG_FILE or /etc/fonts/fonts.conf, following files and conf.d directories with fontconfig's documented prefix rules (~, xdg, relative). It is a pure function of injected env and file lookups, so its tests run the same everywhere, and bounded in files, nesting, bytes, elements and directories; a hand-written scanner reads the two element names rather than adding an XML dependency to the fonts crate. The scan canonicalizes the directories so a symlinked profile is not walked twice, and keeps its entry cap. macOS and Windows are unchanged. installed_font_path() exposes the scan's stem map, for the interface to find its fonts by file stem. Co-Authored-By: Claude Fable 5.1 --- crates/fonts/src/ttf.rs | 31 ++- crates/fonts/src/ttf/dirs.rs | 433 +++++++++++++++++++++++++++++++++++ 2 files changed, 460 insertions(+), 4 deletions(-) create mode 100644 crates/fonts/src/ttf/dirs.rs diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 62759c1b0..f393d399a 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -27,6 +27,9 @@ use skrifa::{FontRef, GlyphId, MetadataProvider}; use crate::{Run, Shaped}; +#[cfg(not(target_arch = "wasm32"))] +mod dirs; + /// One face of a font file (a TrueType collection holds several). #[derive(Clone)] pub struct Face { @@ -218,6 +221,8 @@ fn lock() -> MutexGuard<'static, Db> { g } +/// Installed font files by lower-case stem, from the platform's font directories (on Linux and +/// the BSDs, wherever fontconfig looks: [`dirs`]). #[cfg(not(target_arch = "wasm32"))] fn scan() -> HashMap { let mut out = HashMap::new(); @@ -233,11 +238,19 @@ fn scan() -> HashMap { dirs.push(PathBuf::from(l).join("Microsoft\\Windows\\Fonts")); } } else { - dirs.extend(["/usr/share/fonts", "/usr/local/share/fonts"].map(Into::into)); - if let Some(h) = std::env::var_os("HOME") { - dirs.push(PathBuf::from(&h).join(".fonts")); - dirs.push(PathBuf::from(h).join(".local/share/fonts")); + // Where fontconfig looks: NixOS, Guix and Flatpak keep fonts outside /usr/share/fonts + // (#674). Later directories take precedence (the stack pops them first), so the + // resolver's priority order is reversed; symlinked directories resolve so none is + // walked twice. + let mut found: Vec = Vec::new(); + for d in dirs::font_dirs(|k| std::env::var_os(k), dirs::read_config) { + if let Ok(c) = std::fs::canonicalize(&d) + && !found.contains(&c) + { + found.push(c); + } } + dirs.extend(found.into_iter().rev()); } let mut stack = dirs; let mut seen = 0usize; @@ -515,6 +528,16 @@ pub fn find(name: &str) -> Option { r } +/// The installed font file with this stem (`DejaVuSans`, `NotoSansCJK-Regular`; case and an +/// extension don't matter), wherever the system keeps its fonts. A font compiled in from +/// craft-fonts is no file and gives `None`. +pub fn installed_font_path(stem: &str) -> Option { + match lock().paths.get(&key(stem))? { + Source::File(p) => Some(p.clone()), + Source::Static(_) => None, + } +} + struct Prefs { alt: String, fallback: Vec, diff --git a/crates/fonts/src/ttf/dirs.rs b/crates/fonts/src/ttf/dirs.rs new file mode 100644 index 000000000..7d362b0bd --- /dev/null +++ b/crates/fonts/src/ttf/dirs.rs @@ -0,0 +1,433 @@ +//! Where installed fonts live on Linux and the BSDs, the way fontconfig finds them: the XDG base +//! directories, the `` entries of fontconfig's configuration (NixOS and Guix keep each font +//! package in its own store path, nowhere near `/usr/share/fonts`) and the host fonts a Flatpak +//! sandbox mounts. Directories only: fontconfig's aliases and matching rules are not read. +//! +//! The resolver is a pure function of the environment and a configuration reader, so its tests +//! run the same on every machine. + +use std::collections::HashSet; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +/// Bounds on a configuration a package or a user may have made hostile: files read, `` +/// nesting, bytes per file, elements per file, entries per path list, directories returned. +const MAX_CONFIG_FILES: usize = 256; +const MAX_INCLUDE_DEPTH: usize = 4; +const MAX_CONFIG_BYTES: u64 = 1 << 20; +const MAX_ELEMENTS: usize = 4096; +const MAX_PATH_LIST: usize = 64; +const MAX_DIRS: usize = 1024; + +/// Where Flatpak mounts the host's system, local and user font directories in a sandbox (it also +/// lists them in `/run/host/font-dirs.xml`, which the runtime's `fonts.conf` includes). +const FLATPAK_FONT_DIRS: &[&str] = &["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"]; + +/// What an `` names: a configuration file's text, or the `[0-9]*.conf` files of a +/// directory, sorted, as fontconfig reads them. +pub(super) enum Include { + File(String), + Dir(Vec), +} + +/// Font directories in priority order, without duplicates: the user's XDG font directories, +/// `$XDG_DATA_DIRS/fonts` (`/usr/local/share/fonts` and `/usr/share/fonts` whether listed or +/// not), Flatpak's host font mounts, then the `` entries of fontconfig's configuration +/// (`$FONTCONFIG_FILE`, else `/etc/fonts/fonts.conf`, following its ``s). `env` reads an +/// environment variable, `read` a configuration file or directory (`None` when missing). +pub(super) fn font_dirs(env: impl Fn(&str) -> Option, read: impl Fn(&Path) -> Option) -> Vec { + let var = |k: &str| env(k).filter(|v| !v.is_empty()); + let home = var("HOME").map(PathBuf::from); + let data_home = var("XDG_DATA_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".local/share"))); + let config_home = var("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| home.as_ref().map(|h| h.join(".config"))); + let list = |k: &str, default: &str| -> Vec { + std::env::split_paths(&var(k).unwrap_or_else(|| default.into())).filter(|p| p.is_absolute()).take(MAX_PATH_LIST).collect() + }; + let mut user: Vec = data_home.iter().map(|d| d.join("fonts")).chain(home.iter().map(|h| h.join(".fonts"))).collect(); + user.extend(list("XDG_DATA_DIRS", "/usr/local/share:/usr/share").into_iter().map(|d| d.join("fonts"))); + user.extend(["/usr/local/share/fonts", "/usr/share/fonts"].iter().chain(FLATPAK_FONT_DIRS).map(PathBuf::from)); + let mut r = Resolver { + home, + data_home, + config_home, + config_path: list("FONTCONFIG_PATH", "/etc/fonts"), + read: &read, + out: Vec::new(), + visited: HashSet::new(), + }; + for d in user { + r.add(d); + } + r.include(&var("FONTCONFIG_FILE").map(|f| f.to_string_lossy().into_owned()).unwrap_or_else(|| "/etc/fonts/fonts.conf".into()), None, 0); + r.out +} + +struct Resolver<'a> { + home: Option, + data_home: Option, + config_home: Option, + /// Where a relative `` name is looked up: `$FONTCONFIG_PATH`, else `/etc/fonts`. + config_path: Vec, + read: &'a dyn Fn(&Path) -> Option, + out: Vec, + /// Configuration files and directories read: cycles and the file bound. + visited: HashSet, +} + +impl Resolver<'_> { + fn add(&mut self, p: PathBuf) { + if p.is_absolute() && self.out.len() < MAX_DIRS && !self.out.contains(&p) { + self.out.push(p); + } + } + + /// A path with a leading `~` meaning `$HOME`. + fn expand_home(&self, s: &str) -> Option { + match s.strip_prefix('~') { + Some(rest) => self.home.as_ref().map(|h| h.join(rest.trim_start_matches('/'))), + None => Some(PathBuf::from(s)), + } + } + + /// Follow an `` (or the top-level file): an absolute name, or a relative one looked + /// up in the configuration path. `here` is the including file's directory. + fn include(&mut self, name: &str, here: Option<&Path>, depth: usize) { + match self.expand_home(name) { + Some(p) if p.is_absolute() => { + self.config(&p, depth); + } + Some(p) => { + let bases: Vec = if here.is_some() { here.map(Path::to_path_buf).into_iter().collect() } else { self.config_path.clone() }; + for base in bases { + if self.config(&base.join(&p), depth) { + break; + } + } + } + None => {} + } + } + + /// Read a configuration file (or every file of a directory) and its includes, nested at most + /// `MAX_INCLUDE_DEPTH` deep. True when something was read. + fn config(&mut self, file: &Path, depth: usize) -> bool { + if depth > MAX_INCLUDE_DEPTH || self.visited.len() >= MAX_CONFIG_FILES || !self.visited.insert(file.to_path_buf()) { + return false; + } + let xml = match (self.read)(file) { + Some(Include::File(xml)) => xml, + Some(Include::Dir(files)) => { + for f in files.iter().take(MAX_CONFIG_FILES) { + self.config(f, depth); + } + return true; + } + None => return false, + }; + let here = file.parent().map(Path::to_path_buf); + for e in elements(&xml) { + match (e.name, e.prefix) { + ("dir", Some("xdg")) => { + if let Some(d) = self.data_home.as_ref().map(|d| d.join(&e.text)) { + self.add(d); + } + } + ("dir", Some("relative")) => { + if let Some(d) = here.as_ref().map(|h| h.join(&e.text)) { + self.add(d); + } + } + // "default", "cwd" or none: as written; a relative directory is skipped. + ("dir", _) => { + if let Some(d) = self.expand_home(&e.text) { + self.add(d); + } + } + ("include", Some("xdg")) => { + if let Some(f) = self.config_home.as_ref().map(|c| c.join(&e.text)) { + self.config(&f, depth + 1); + } + } + ("include", Some("relative")) => self.include(&e.text, here.as_deref(), depth + 1), + ("include", _) => self.include(&e.text, None, depth + 1), + _ => {} + } + } + true + } +} + +struct Element<'a> { + name: &'a str, + prefix: Option<&'a str>, + text: String, +} + +/// The `` and `` elements of a configuration file with text, in order; comments +/// are skipped. A bounded scan over the text: fontconfig files are small and regular. +fn elements(xml: &str) -> Vec> { + let mut out = Vec::new(); + let mut rest = xml; + while let Some(i) = rest.find('<') { + let Some(tag) = rest.get(i + 1..) else { break }; + if let Some(c) = tag.strip_prefix("!--") { + rest = c.find("-->").and_then(|j| c.get(j + 3..)).unwrap_or(""); + continue; + } + let Some(end) = tag.find('>') else { break }; + let (head, after) = (tag.get(..end).unwrap_or(""), tag.get(end + 1..).unwrap_or("")); + rest = after; + let mut words = head.split_whitespace(); + let name = words.next().unwrap_or(""); + if !matches!(name, "dir" | "include") { + continue; + } + let prefix = words.find_map(|w| w.strip_prefix("prefix=")).map(|v| v.trim_matches(['"', '\''])); + let text = unescape(after.split('<').next().unwrap_or("").trim()); + if !text.is_empty() { + out.push(Element { name, prefix, text }); + } + if out.len() >= MAX_ELEMENTS { + break; + } + } + out +} + +fn unescape(s: &str) -> String { + if !s.contains('&') { + return s.to_string(); + } + s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&") +} + +/// Read a configuration file (skipped beyond `MAX_CONFIG_BYTES`) or list a directory's +/// `[0-9]*.conf` files, sorted. +pub(super) fn read_config(path: &Path) -> Option { + use std::io::Read as _; + if path.is_dir() { + let conf = + |p: &Path| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.ends_with(".conf")); + let mut files: Vec = std::fs::read_dir(path).ok()?.flatten().map(|e| e.path()).filter(|p| conf(p)).take(MAX_CONFIG_FILES).collect(); + files.sort(); + return Some(Include::Dir(files)); + } + let mut xml = String::new(); + std::fs::File::open(path).ok()?.take(MAX_CONFIG_BYTES.saturating_add(1)).read_to_string(&mut xml).ok()?; + (xml.len() as u64 <= MAX_CONFIG_BYTES).then_some(Include::File(xml)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env_of<'a>(vars: &'a [(&str, &str)]) -> impl Fn(&str) -> Option + 'a { + move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v)) + } + + fn reader<'a>(files: &'a [(&str, &str)], dirs: &'a [(&str, &[&str])]) -> impl Fn(&Path) -> Option + 'a { + move |p| { + if let Some((_, xml)) = files.iter().find(|(n, _)| Path::new(n) == p) { + return Some(Include::File((*xml).to_string())); + } + dirs.iter().find(|(n, _)| Path::new(n) == p).map(|(_, fs)| Include::Dir(fs.iter().map(PathBuf::from).collect())) + } + } + + fn paths(v: &[&str]) -> Vec { + v.iter().map(PathBuf::from).collect() + } + + const XDG: &[&str] = &["/usr/local/share/fonts", "/usr/share/fonts", "/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"]; + + #[test] + fn xdg_defaults_without_variables() { + let d = font_dirs(env_of(&[("HOME", "/home/u")]), |_| None); + assert_eq!(d, paths(&[&["/home/u/.local/share/fonts", "/home/u/.fonts"], XDG].concat())); + assert_eq!(font_dirs(|_| None, |_| None), paths(XDG), "no HOME: system directories only"); + } + + #[test] + fn xdg_variables_name_the_font_dirs() { + let env = env_of(&[ + ("HOME", "/home/u"), + ("XDG_DATA_HOME", "/data"), + ("XDG_DATA_DIRS", "/nix/profile/share:/run/current-system/sw/share:relative:/usr/share/:"), + ]); + let d = font_dirs(env, |_| None); + assert_eq!( + d.get(..6), + Some( + paths(&[ + "/data/fonts", + "/home/u/.fonts", + "/nix/profile/share/fonts", + "/run/current-system/sw/share/fonts", + "/usr/share/fonts", + "/usr/local/share/fonts" + ]) + .as_slice() + ) + ); + assert_eq!(d.len(), 9, "{d:?}"); + } + + #[test] + fn fontconfig_dirs_nixos_style() { + let files = [ + ( + "/etc/fonts/fonts.conf", + "\n\n\n\ + \nfontconfig\n\ + /etc/fonts/conf.d\nfonts\n\ + /nix/store/aaa-dejavu-fonts-minimal-2.37\n\n", + ), + ( + "/etc/fonts/conf.d/00-nixos-cache.conf", + "\n \n /nix/store/bbb-dejavu-fonts-2.37\n/nix/store/ccc-unifont-16.0.03\n\ + \n /nix/store/ddd-fc-cache\n\n", + ), + ( + "/etc/fonts/conf.d/50-user.conf", + "\nfontconfig/conf.d\n\n", + ), + ( + "/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf", + "\n/nix/store/eee-home-manager-path/etc/fonts/conf.d\n\ + /nix/store/eee-home-manager-path/share/fonts\n/etc/profiles/per-user/u/share/fonts\n\n", + ), + ]; + let dirs: [(&str, &[&str]); 2] = [ + ("/etc/fonts/conf.d", &["/etc/fonts/conf.d/00-nixos-cache.conf", "/etc/fonts/conf.d/50-user.conf"]), + ("/home/u/.config/fontconfig/conf.d", &["/home/u/.config/fontconfig/conf.d/10-hm-fonts.conf"]), + ]; + let d = font_dirs(env_of(&[("HOME", "/home/u"), ("XDG_DATA_DIRS", "/etc/profiles/per-user/u/share")]), reader(&files, &dirs)); + let expect = [ + "/home/u/.local/share/fonts", + "/home/u/.fonts", + "/etc/profiles/per-user/u/share/fonts", + "/usr/local/share/fonts", + "/usr/share/fonts", + "/run/host/fonts", + "/run/host/local-fonts", + "/run/host/user-fonts", + "/nix/store/bbb-dejavu-fonts-2.37", + "/nix/store/ccc-unifont-16.0.03", + "/nix/store/eee-home-manager-path/share/fonts", + "/nix/store/aaa-dejavu-fonts-minimal-2.37", + ]; + assert_eq!(d, paths(&expect)); + } + + #[test] + fn fontconfig_dirs_debian_style() { + let files = [ + ( + "/etc/fonts/fonts.conf", + "\n/usr/share/fonts\n/usr/local/share/fonts\nfonts\n\ + ~/.fonts\n/opt/fonts & more\nrelative/skipped\nalso/skipped\n\ + conf.d\n\n", + ), + ("/etc/fonts/conf.d/51-local.conf", "local.conf"), + ("/etc/fonts/conf.d/52-site.conf", "../site/fonts.conf"), + ("/etc/fonts/local.conf", "/srv/fontsmore"), + ("/etc/fonts/conf.d/../site/fonts.conf", "/site/fonts"), + ]; + let dirs: [(&str, &[&str]); 1] = [("/etc/fonts/conf.d", &["/etc/fonts/conf.d/51-local.conf", "/etc/fonts/conf.d/52-site.conf"])]; + let d = font_dirs(env_of(&[("HOME", "/home/u")]), reader(&files, &dirs)); + let tail: Vec = d.iter().skip(7).cloned().collect(); + assert_eq!(tail, paths(&["/opt/fonts & more", "/srv/fonts", "/etc/fonts/more", "/site/fonts"])); + assert_eq!(d.len(), 11, "the directories already listed are not repeated: {d:?}"); + } + + #[test] + fn fontconfig_file_and_path_variables() { + let files = [("/cfg/custom.conf", "/custom/fonts")]; + let env = env_of(&[("FONTCONFIG_FILE", "custom.conf"), ("FONTCONFIG_PATH", "/nowhere:/cfg")]); + let d = font_dirs(env, reader(&files, &[])); + assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts"))); + let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/custom.conf")]), reader(&files, &[])); + assert_eq!(d.last(), Some(&PathBuf::from("/custom/fonts"))); + assert_eq!(font_dirs(env_of(&[("FONTCONFIG_FILE", "/cfg/missing.conf")]), reader(&files, &[])), paths(XDG)); + } + + #[test] + fn include_cycles_and_depth_are_bounded() { + let files = [ + ("/etc/fonts/fonts.conf", "/d0/etc/fonts/b.conf"), + ( + "/etc/fonts/b.conf", + "/d1/etc/fonts/fonts.conf/etc/fonts/b.conf", + ), + ]; + let d = font_dirs(|_| None, reader(&files, &[])); + assert_eq!(d.iter().skip(XDG.len()).cloned().collect::>(), paths(&["/d0", "/d1"])); + + let chain: Vec<(String, String)> = (0..10) + .map(|i| { + (format!("/etc/fonts/{i}.conf"), format!("/depth{i}/etc/fonts/{}.conf", i + 1)) + }) + .collect(); + let read = |p: &Path| chain.iter().find(|(n, _)| Path::new(n) == p).map(|(_, xml)| Include::File(xml.clone())); + let d = font_dirs(env_of(&[("FONTCONFIG_FILE", "/etc/fonts/0.conf")]), read); + let depths: Vec<&PathBuf> = d.iter().skip(XDG.len()).collect(); + assert_eq!(depths.len(), MAX_INCLUDE_DEPTH + 1, "{depths:?}"); + assert_eq!(depths.last().map(|p| p.as_path()), Some(Path::new("/depth4"))); + } + + #[test] + fn many_files_are_bounded() { + let names: Vec = (0..1000).map(|i| format!("/etc/fonts/conf.d/{i:04}.conf")).collect(); + let read = |p: &Path| { + if p == Path::new("/etc/fonts/fonts.conf") { + return Some(Include::File("/etc/fonts/conf.d".into())); + } + if p == Path::new("/etc/fonts/conf.d") { + return Some(Include::Dir(names.iter().map(PathBuf::from).collect())); + } + p.starts_with("/etc/fonts/conf.d").then(|| Include::File(format!("{}", p.display()))) + }; + let d = font_dirs(|_| None, read); + assert!(d.len() <= XDG.len() + MAX_CONFIG_FILES, "{}", d.len()); + assert!(d.len() > XDG.len() + 200); + } + + #[test] + fn elements_survive_odd_markup() { + let xml = "/unterminated/xr - - + + + - + @@ -39,7 +18,9 @@ - + + + @@ -50,44 +31,42 @@ - - - + + - + - + - + + + - + - + - - - - - + + + + + + @@ -97,12 +76,9 @@ - - - + + + @@ -137,18 +113,14 @@ - - + + - - + + diff --git a/packaging/windows/check-install-policy.ps1 b/packaging/windows/check-install-policy.ps1 new file mode 100644 index 000000000..dd2895643 --- /dev/null +++ b/packaging/windows/check-install-policy.ps1 @@ -0,0 +1,195 @@ +<# +.SYNOPSIS + Check the compiled installation policy without installing any product. +.DESCRIPTION + Uses Windows Installer's safe session (OpenPackage option 1). Only property-setting custom + actions are exercised. No AppSearch, install, repair, removal or file-writing action runs. +#> +param([Parameter(Mandatory = $true)] [string] $MsiPath) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$policy = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'install-policy.json') | ConvertFrom-Json +function Read-Rows($Database, [string] $Sql, [int] $Columns) { + $view = $Database.OpenView($Sql) + try { + [void]$view.Execute() + while ($null -ne ($record = $view.Fetch())) { + try { + $values = @(for ($i = 1; $i -le $Columns; $i++) { + $record.GetType().InvokeMember('StringData', 'GetProperty', $null, $record, @($i)) + }) + ,$values + } finally { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($record) } + } + } finally { + [void]$view.Close() + [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($view) + } +} +function Set-SessionProperty($Session, [string] $Name, [string] $Value) { + [void]$Session.GetType().InvokeMember('Property', 'SetProperty', $null, $Session, @($Name, $Value)) +} +function Get-SessionProperty($Session, [string] $Name) { + $Session.GetType().InvokeMember('Property', 'GetProperty', $null, $Session, @($Name)) +} +$installer = $null; $database = $null; $session = $null +try { + $installer = New-Object -ComObject WindowsInstaller.Installer + $file = (Resolve-Path -LiteralPath $MsiPath).Path + $database = $installer.OpenDatabase($file, 0) + $session = $installer.OpenPackage($file, 1) + $properties = @{} + foreach ($row in (Read-Rows $database 'SELECT `Property`, `Value` FROM `Property`' 2)) { $properties[$row[0]] = $row[1] } + $secureProperties = @($properties['SecureCustomProperties'] -split ';') + if ('INSTALLFOLDER' -notin $secureProperties) { + throw 'The selected installation folder must survive elevation (secure INSTALLFOLDER).' + } + if ($policy.mode -eq 'perUser') { + if ($properties.ContainsKey('ALLUSERS')) { throw 'Launcher must remain per-user; machine self-update is not part of this change.' } + if ($properties['UpgradeCode'].Trim('{}') -ne $policy.upgradeCode) { throw 'Launcher upgrade identity changed.' } + $dirs = @{} + foreach ($row in (Read-Rows $database 'SELECT `Directory`, `Directory_Parent`, `DefaultDir` FROM `Directory`' 3)) { $dirs[$row[0]] = @($row[1],$row[2]) } + if ($dirs['INSTALLFOLDER'][0] -ne 'CraftSuiteFolder' -or $dirs['CraftSuiteFolder'][1] -ne 'ArtCraft' -or + $dirs['CraftSuiteFolder'][0] -ne 'LocalProgramsFolder' -or $dirs['LocalProgramsFolder'][0] -ne 'LocalAppDataFolder') { + throw 'Launcher new-install folder must be under the per-user ArtCraft suite root.' + } + foreach ($explicit in @('', 'F:\Chosen exact launcher')) { + Set-SessionProperty $session 'PREVIOUSINSTALLFOLDER' 'E:\Existing exact launcher' + Set-SessionProperty $session 'INSTALLFOLDER' $explicit + $row = @(Read-Rows $database 'SELECT `Condition` FROM `InstallUISequence` WHERE `Action` = ''CraftRestoreLauncherFolder''' 1)[0] + if ($session.EvaluateCondition($row[0]) -eq 1) { + if ($session.DoAction('CraftRestoreLauncherFolder') -ne 1) { throw 'Launcher restore action failed.' } + } + $expected = if ($explicit) { $explicit } else { 'E:\Existing exact launcher' } + if ((Get-SessionProperty $session 'INSTALLFOLDER') -ne $expected) { throw 'Launcher custom or existing path was lost.' } + } + $rows = @(Read-Rows $database 'SELECT `Root`, `Key`, `Name`, `Value` FROM `Registry`' 4) + if (@($rows | Where-Object { $_[0] -ne '1' }).Count) { throw 'Launcher registration must stay under the current account.' } + foreach ($entry in $policy.registry) { + if (@($rows | Where-Object { $_[0] -eq $entry[0] -and $_[1] -eq $entry[1] -and $_[2] -eq $entry[2] -and $_[3] -eq $entry[3] }).Count -ne 1) { + throw 'Launcher registration or shortcut preference changed unexpectedly.' + } + } + Write-Output 'PASS ArtCraft Launcher: per-user scope, suite folder, remembered/custom paths and existing registration. No installation performed.' + return + } + if ($properties['ALLUSERS'] -ne '2' -or $properties['MSIINSTALLPERUSER'] -ne '1') { + throw 'Policy regression: new packages must default to the per-user dual-scope context.' + } + if ($properties['UpgradeCode'].Trim('{}') -ne $policy.upgradeCode) { throw 'The existing upgrade identity must not change.' } + $directories = @{} + foreach ($row in (Read-Rows $database 'SELECT `Directory`, `Directory_Parent`, `DefaultDir` FROM `Directory`' 3)) { + $directories[$row[0]] = @($row[1], $row[2]) + } + if ($directories['INSTALLFOLDER'][0] -ne 'CraftSuiteFolder' -or + $directories['CraftSuiteFolder'][1] -ne 'ArtCraft') { throw 'Expected the app under the ArtCraft suite folder.' } + $programs = $directories['CraftSuiteFolder'][0] + if ($programs -eq 'ProgramFiles6432Folder') { $programs = $directories[$programs][0] } + if ($programs -notin 'ProgramFilesFolder', 'ProgramFiles64Folder') { + throw 'Use Windows Installer native folder redirection, not a hard-coded profile path.' + } + $guards = @(Read-Rows $database 'SELECT `Condition`, `Description` FROM `LaunchCondition`' 2 | + Where-Object { $_[0] -match 'CRAFT_(USER|MACHINE)_DIR' }) + if ($guards.Count -ne 2) { throw 'Expected both duplicate-installation guards.' } + $cases = 0 + foreach ($scope in @('', '2', '1')) { + foreach ($user in @('', 'D:\Existing user app')) { + foreach ($machine in @('', 'E:\Existing machine app')) { + foreach ($installed in @('', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'Installed' $installed + Set-SessionProperty $session 'CRAFT_USER_DIR' $user + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' $machine + $allowed = $true + foreach ($guard in $guards) { + $value = $session.EvaluateCondition($guard[0]) + if ($value -notin 0, 1) { throw 'Invalid duplicate guard.' } + if ($value -eq 0) { $allowed = $false } + } + $opposite = if ($scope -eq '1') { $user } else { $machine } + $expected = [bool]$installed -or -not [bool]$opposite + if ($allowed -ne $expected) { throw "Scope regression: ALLUSERS='$scope', user=$([bool]$user), machine=$([bool]$machine), maintenance=$([bool]$installed)." } + $cases++ + } + } + } + } + # Execute the actual authored type-51 actions in a safe session, not copied resolver logic. + foreach ($scope in @('', '2', '1')) { + foreach ($explicit in @('', 'F:\Chosen exact app')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'INSTALLFOLDER' $explicit + Set-SessionProperty $session 'CRAFT_USER_DIR' 'D:\Existing user app' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' 'E:\Existing machine app' + $action = if ($scope -eq '1') { 'CraftRestoreMachineFolder' } else { 'CraftRestoreUserFolder' } + if (-not $explicit) { + if ($session.DoAction($action) -ne 1) { throw 'Remembered-folder property action failed.' } + } + $expected = if ($explicit) { $explicit } elseif ($scope -eq '1') { 'E:\Existing machine app' } else { 'D:\Existing user app' } + if ((Get-SessionProperty $session 'INSTALLFOLDER') -ne $expected) { throw 'Custom or remembered folder was not preserved.' } + } + } + $ui = @{} + foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallUISequence`' 2)) { $ui[$row[0]] = [int]$row[1] } + if (-not ($ui['AppSearch'] -lt $ui['CraftScopeDlg'] -and $ui['CraftScopeDlg'] -lt $ui['LaunchConditions'] -and + $ui['CraftScopeDlg'] -lt $ui['CraftRestoreUserFolder'] -and $ui['CraftRestoreUserFolder'] -lt $ui['CostInitialize'])) { + throw 'Scope must be chosen after discovery and before duplicate checks, folder restoration and costing.' + } + $execute = @{} + foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallExecuteSequence`' 2)) { $execute[$row[0]] = [int]$row[1] } + foreach ($action in @('CraftRestoreUserFolder','CraftRestoreMachineFolder')) { + if (-not ($execute['AppSearch'] -lt $execute[$action] -and $execute[$action] -lt $execute['CostInitialize'])) { + throw 'Silent updates must restore the folder before directory costing.' + } + } + # Switching the first-page choice must reset BOTH properties, including a back-and-forth change. + $events = @(Read-Rows $database 'SELECT `Event`, `Argument`, `Condition`, `Ordering` FROM `ControlEvent` WHERE `Dialog_` = ''CraftScopeDlg'' AND `Control_` = ''Next'' ORDER BY `Ordering`' 4) + foreach ($choice in @('user','machine','user')) { + Set-SessionProperty $session 'CRAFT_SCOPE' $choice + foreach ($event in $events) { + if ($event[0] -notmatch '^\[([^\]]+)\]$') { continue } + $property = $Matches[1] + if ($session.EvaluateCondition($event[2]) -eq 1) { + Set-SessionProperty $session $property $(if ($event[1] -eq '{}') { '' } else { $event[1] }) + } + } + $allUsers = Get-SessionProperty $session 'ALLUSERS' + $perUser = Get-SessionProperty $session 'MSIINSTALLPERUSER' + if (($choice -eq 'machine' -and ($allUsers -ne '1' -or $perUser)) -or + ($choice -eq 'user' -and ($allUsers -ne '2' -or $perUser -ne '1'))) { + throw 'Scope selector does not reset the requested installation context.' + } + } + $actions = @(Read-Rows $database 'SELECT `Action`, `Source`, `Target`, `Type` FROM `CustomAction`' 4) + $savedOptions = @($actions | Where-Object { $_[0] -match '^CraftLoadOption[0-9]+M$' }) + foreach ($option in $savedOptions) { + if ([int]$option[3] -ne 51) { throw 'Saved-option test may run only property-setting actions.' } + $number = [regex]::Match($option[0], '[0-9]+').Value + foreach ($scope in @('2','1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session "CRAFT_OPTION_${number}_M" 'saved-machine-choice' + Set-SessionProperty $session "CRAFT_OPTION_${number}_U" 'saved-user-choice' + Set-SessionProperty $session $option[1] '' + $action = "CraftLoadOption$number" + $(if ($scope -eq '1') { 'M' } else { 'U' }) + if ($session.DoAction($action) -ne 1) { throw 'Saved-option property action failed.' } + $expected = if ($scope -eq '1') { 'saved-machine-choice' } else { 'saved-user-choice' } + if ((Get-SessionProperty $session $option[1]) -ne $expected) { throw 'Saved installer choices leaked across contexts.' } + } + } + $registry = @(Read-Rows $database 'SELECT `Root`, `Key`, `Name`, `Value` FROM `Registry`' 4) + if (@($registry | Where-Object { $_[0] -in '1', '2' }).Count) { throw 'Registration must follow the selected context, not force HKCU or HKLM.' } + if (@($registry | Where-Object { $_[0] -eq '0' -and $_[1] -match '^Software\\Classes(\\|$)' }).Count) { + throw 'HKCR keys must be relative to Classes.' + } + foreach ($entry in $policy.registry) { + $found = @($registry | Where-Object { $_[0] -eq $entry[0] -and $_[1] -eq $entry[1] -and $_[2] -eq $entry[2] -and $_[3] -eq $entry[3] }) + if ($found.Count -ne 1) { throw "Lost or changed registration: $($entry[1]) / $($entry[2])" } + } + $installDir = @($registry | Where-Object { $_[0] -eq '-1' -and $_[1] -eq "Software\$($policy.name)" -and $_[2] -eq 'InstallDir' -and $_[3] -eq '[INSTALLFOLDER]' }) + if ($installDir.Count -ne 1) { throw 'A context-sensitive installation-folder record is required.' } + Write-Output "PASS $($policy.name): $cases scope cases, folder preservation, action sequencing and registry contract. No installation performed." +} finally { + foreach ($com in @($session, $database, $installer)) { + if ($null -ne $com) { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($com) } + } +} diff --git a/packaging/windows/install-policy.json b/packaging/windows/install-policy.json new file mode 100644 index 000000000..e5c63e72d --- /dev/null +++ b/packaging/windows/install-policy.json @@ -0,0 +1,56 @@ +{ + "id": "cadcraft", + "name": "CADCraft", + "upgradeCode": "119D7D76-0167-4A9E-8F37-09DA0235F68E", + "sources": [ + "cadcraft.wxs" + ], + "icon": "assets/app-icon/cadcraft.ico", + "localization": [], + "extensions": [ + "UI" + ], + "payloads": [ + "cadcraft-cli.exe", + "cadcraft.exe" + ], + "registry": [ + [ + "-1", + "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\cadcraft.exe", + "", + "[#CadcraftExe]" + ], + [ + "-1", + "Software\\Classes\\Applications\\cadcraft.exe\\shell\\open\\command", + "", + "\"[#CadcraftExe]\" \"%1\"" + ], + [ + "-1", + "Software\\Classes\\.dxf\\OpenWithProgids", + "CADCraft.Drawing", + "" + ], + [ + "-1", + "Software\\Classes\\.dwg\\OpenWithProgids", + "CADCraft.Drawing", + "" + ], + [ + "-1", + "Software\\Classes\\CADCraft.Drawing\\shell\\open\\command", + "", + "\"[#CadcraftExe]\" \"%1\"" + ], + [ + "-1", + "Software\\Learning Machines LLC\\CADCraft", + "DesktopShortcut", + "1" + ] + ], + "mode": "dualScope" +} diff --git a/packaging/windows/install-policy.wxi b/packaging/windows/install-policy.wxi new file mode 100644 index 000000000..02371ed07 --- /dev/null +++ b/packaging/windows/install-policy.wxi @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 92b48e134..042b46f73 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -115,6 +115,8 @@ Invoke-Native 'wix build' { -d "DocsDir=$Docs" -d "HasCraftFontLicences=$HasCraftFontLicences" ` -o $Msi } +# Check the compiled scope, path and registration contract before signing. +& (Join-Path $PSScriptRoot 'check-install-policy.ps1') -MsiPath $Msi # wix writes its debug symbols (.wixpdb) next to the MSI; keep them out of the release assets. Remove-Item -Force -ErrorAction SilentlyContinue ([IO.Path]::ChangeExtension($Msi, '.wixpdb')) & (Join-Path $PSScriptRoot 'sign.ps1') $Msi diff --git a/packaging/windows/test-install-policy.ps1 b/packaging/windows/test-install-policy.ps1 new file mode 100644 index 000000000..21199ca7f --- /dev/null +++ b/packaging/windows/test-install-policy.ps1 @@ -0,0 +1,54 @@ +<# +.SYNOPSIS + Build non-executable installer metadata fixtures; never install them. +#> +param( + [Parameter(Mandatory = $true)] [string] $OutputDirectory, + [ValidateSet('x64','x86','arm64')] [string[]] $Architectures = @('x64','x86','arm64') +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest +$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$policy = Get-Content -Raw -LiteralPath (Join-Path $PSScriptRoot 'install-policy.json') | ConvertFrom-Json +[void](New-Item -ItemType Directory -Force -Path $OutputDirectory) +$output = (Resolve-Path -LiteralPath $OutputDirectory).Path +Add-Type -AssemblyName System.Drawing +foreach ($arch in $Architectures) { + $stage = Join-Path $output $arch + [void](New-Item -ItemType Directory -Force -Path $stage) + foreach ($name in $policy.payloads) { + $destination = Join-Path $stage $name + [void](New-Item -ItemType Directory -Force -Path ([IO.Path]::GetDirectoryName($destination))) + Set-Content -LiteralPath $destination -Encoding Ascii -Value 'NON-EXECUTABLE MSI METADATA TEST FIXTURE' + } + foreach ($folder in @('docs','models','notices')) { + $path = Join-Path $stage $folder + [void](New-Item -ItemType Directory -Force -Path $path) + Set-Content -LiteralPath (Join-Path $path "$folder-fixture.txt") -Value 'Metadata test fixture, not a user file or model.' + } + foreach ($model in @('metadata-one.rten','metadata-two.rten')) { + Set-Content -LiteralPath (Join-Path (Join-Path $stage 'models') $model) -Encoding Ascii -Value 'NON-EXECUTABLE MODEL METADATA FIXTURE' + } + foreach ($spec in @(@('banner.bmp',493,58),@('dialog.bmp',493,312))) { + $bitmap = [Drawing.Bitmap]::new($spec[1],$spec[2],[Drawing.Imaging.PixelFormat]::Format24bppRgb) + try { $bitmap.Save((Join-Path $stage $spec[0]),[Drawing.Imaging.ImageFormat]::Bmp) } + finally { $bitmap.Dispose() } + } + Set-Content -LiteralPath (Join-Path $stage 'licence.rtf') -Encoding Ascii -Value '{\rtf1 Metadata test fixture.}' + $sources = @($policy.sources | ForEach-Object { Join-Path $PSScriptRoot $_ }) + $msi = Join-Path $stage "$($policy.id)-NOT-INSTALLABLE.msi" + $extensions = @($policy.extensions | ForEach-Object { '-ext'; "WixToolset.$_.wixext" }) + & wix build @sources -arch $arch -wx @extensions ` + -culture en-US -d 'Version=0.0.1' -d 'DisplayVersion=0.0.1-metadata-test' ` + -d "BinDir=$stage" -d "IconPath=$(Join-Path $root $policy.icon)" ` + -d "DocsDir=$(Join-Path $stage 'docs')" -d "ModelsDir=$(Join-Path $stage 'models')" ` + -d "AppNoticesDir=$(Join-Path $stage 'notices')" -d 'HasCraftFontLicences=1' -d 'HasCli=1' ` + -d "BannerBmp=$(Join-Path $stage 'banner.bmp')" -d "DialogBmp=$(Join-Path $stage 'dialog.bmp')" ` + -d "UiBannerBmp=$(Join-Path $stage 'banner.bmp')" -d "UiDialogBmp=$(Join-Path $stage 'dialog.bmp')" ` + -d "LicenseRtf=$(Join-Path $stage 'licence.rtf')" -o $msi @($policy.localization | ForEach-Object { '-loc'; Join-Path $PSScriptRoot $_ }) + if ($LASTEXITCODE -ne 0) { throw "WiX validation failed for $arch (exit $LASTEXITCODE)." } + $shell = (Get-Process -Id $PID).Path + & $shell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot 'check-install-policy.ps1') -MsiPath $msi + if ($LASTEXITCODE -ne 0) { throw "Compiled installer policy failed for $arch (exit $LASTEXITCODE)." } + Write-Output "PASS $arch metadata-only package. This is not an executable installer." +} From 6795f0bd03c0434af177bb5cfcb624ee07d442c3 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Tue, 27 Oct 2026 10:51:15 +0000 Subject: [PATCH 107/900] fix(installer): address scope and ARM64 review feedback --- .github/workflows/windows-arm64.yml | 6 +- packaging/windows/check-install-policy.ps1 | 66 +++++++++++++++++++++- packaging/windows/install-policy.wxi | 6 +- 3 files changed, 72 insertions(+), 6 deletions(-) diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index f7bb0996e..865f069d4 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -25,8 +25,10 @@ permissions: jobs: windows-arm64: - # 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/windows-arm64.yml@main + # Immutable supporting workflow revision until the new install contract lands upstream. + uses: Jeremy8776/craft-common-actions/.github/workflows/windows-arm64.yml@f4666d5cbf35f9bdeda24f1f88c7fb5c6adf5276 with: app-name: cadcraft app-dir: CADCraft + install-relative-path: Programs/ArtCraft/CADCraft + install-scope: perUser diff --git a/packaging/windows/check-install-policy.ps1 b/packaging/windows/check-install-policy.ps1 index dd2895643..00b683d70 100644 --- a/packaging/windows/check-install-policy.ps1 +++ b/packaging/windows/check-install-policy.ps1 @@ -131,9 +131,12 @@ try { } $ui = @{} foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallUISequence`' 2)) { $ui[$row[0]] = [int]$row[1] } - if (-not ($ui['AppSearch'] -lt $ui['CraftScopeDlg'] -and $ui['CraftScopeDlg'] -lt $ui['LaunchConditions'] -and + if (-not ($ui['AppSearch'] -lt $ui['CraftPreferMachineScope'] -and + $ui['CraftPreferMachineScope'] -lt $ui['CraftScopeDlg'] -and + $ui['CraftScopeDlg'] -lt $ui['FindRelatedProducts'] -and + $ui['FindRelatedProducts'] -lt $ui['LaunchConditions'] -and $ui['CraftScopeDlg'] -lt $ui['CraftRestoreUserFolder'] -and $ui['CraftRestoreUserFolder'] -lt $ui['CostInitialize'])) { - throw 'Scope must be chosen after discovery and before duplicate checks, folder restoration and costing.' + throw 'Scope must be chosen after AppSearch and before FindRelatedProducts, launch checks and costing.' } $execute = @{} foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallExecuteSequence`' 2)) { $execute[$row[0]] = [int]$row[1] } @@ -144,7 +147,18 @@ try { } # Switching the first-page choice must reset BOTH properties, including a back-and-forth change. $events = @(Read-Rows $database 'SELECT `Event`, `Argument`, `Condition`, `Ordering` FROM `ControlEvent` WHERE `Dialog_` = ''CraftScopeDlg'' AND `Control_` = ''Next'' ORDER BY `Ordering`' 4) - foreach ($choice in @('user','machine','user')) { + # Model the full-UI upgrade entry with an existing machine-wide copy. Run + # the actual preference action, then the compiled Next events before discovery. + Set-SessionProperty $session 'ALLUSERS' '2' + Set-SessionProperty $session 'CRAFT_SCOPE' 'user' + Set-SessionProperty $session 'CRAFT_USER_DIR' '' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' 'E:\Existing machine app' + $preference = @(Read-Rows $database 'SELECT `Condition` FROM `InstallUISequence` WHERE `Action` = ''CraftPreferMachineScope''' 1)[0] + if ($session.EvaluateCondition($preference[0]) -ne 1 -or $session.DoAction('CraftPreferMachineScope') -ne 1 -or + (Get-SessionProperty $session 'CRAFT_SCOPE') -ne 'machine') { + throw 'Full-UI machine upgrades must initially select the existing machine context.' + } + foreach ($choice in @('machine','user','machine','user')) { Set-SessionProperty $session 'CRAFT_SCOPE' $choice foreach ($event in $events) { if ($event[0] -notmatch '^\[([^\]]+)\]$') { continue } @@ -176,6 +190,52 @@ try { if ((Get-SessionProperty $session $option[1]) -ne $expected) { throw 'Saved installer choices leaked across contexts.' } } } + # Follow the compiled control conditions, not the source's intended appearance. + $controls = @(Read-Rows $database 'SELECT `Dialog_`, `Control`, `Type`, `Attributes`, `Text` FROM `Control`' 5) + $conditions = @() + if (@(Read-Rows $database 'SELECT `Name` FROM `_Tables` WHERE `Name` = ''ControlCondition''' 1).Count) { + $conditions = @(Read-Rows $database 'SELECT `Dialog_`, `Control_`, `Action`, `Condition` FROM `ControlCondition`' 4) + } + function Test-ControlVisible($Control) { + $visible = ([int]$Control[3] -band 1) -ne 0 + foreach ($condition in $conditions) { + if ($condition[0] -eq $Control[0] -and $condition[1] -eq $Control[1] -and $session.EvaluateCondition($condition[3]) -eq 1) { + if ($condition[2] -eq 'Show') { $visible = $true } + if ($condition[2] -eq 'Hide') { $visible = $false } + } + } + return $visible + } + foreach ($button in @($controls | Where-Object { $_[0] -in 'InstallWelcome','InstallMaintenance','DesktopShortcutDlg' -and ([int]$_[3] -band 8388608) -ne 0 })) { + $plain = @($controls | Where-Object { $_[0] -eq $button[0] -and $_[1] -eq ($button[1] + 'User') }) + if ($plain.Count -ne 1 -or ([int]$plain[0][3] -band 8388608)) { throw 'Scope-aware buttons need an unshielded per-user counterpart.' } + foreach ($scope in @('', '2', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + if ((Test-ControlVisible $button) -ne ($scope -eq '1') -or (Test-ControlVisible $plain[0]) -ne ($scope -ne '1')) { + throw 'The elevation shield must follow the selected scope.' + } + } + $dialog = $button[0]; $shieldId = $button[1]; $plainId = $plain[0][1] + $shieldEvents = @(Read-Rows $database "SELECT ``Event``, ``Argument``, ``Condition``, ``Ordering`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$shieldId' ORDER BY ``Ordering``" 4 | ForEach-Object { $_ -join '|' }) + $plainEvents = @(Read-Rows $database "SELECT ``Event``, ``Argument``, ``Condition``, ``Ordering`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$plainId' ORDER BY ``Ordering``" 4 | ForEach-Object { $_ -join '|' }) + if (($shieldEvents -join "`n") -ne ($plainEvents -join "`n")) { throw 'Per-user and machine buttons must perform the same operation.' } + } + foreach ($scope in @('', '2', '1')) { + Set-SessionProperty $session 'ALLUSERS' $scope + foreach ($text in @($controls | Where-Object { $_[4] -like '*for all users*' })) { + if ((Test-ControlVisible $text) -ne ($scope -eq '1')) { throw 'The welcome-page scope text must follow the selected scope.' } + } + } + if ($policy.id -in 'deckcraft','filmcraft','soundcraft') { + foreach ($route in @(@('WelcomeDlg','Next','InstallDirDlg'),@('InstallDirDlg','Back','WelcomeDlg'))) { + $dialog = $route[0]; $control = $route[1] + $routes = @(Read-Rows $database "SELECT ``Argument``, ``Condition`` FROM ``ControlEvent`` WHERE ``Dialog_`` = '$dialog' AND ``Control_`` = '$control' AND ``Event`` = 'NewDialog' ORDER BY ``Ordering``" 2) + Set-SessionProperty $session 'Installed' '' + $destination = '' + foreach ($event in $routes) { if ($session.EvaluateCondition($event[1]) -eq 1) { $destination = $event[0] } } + if ($destination -ne $route[2]) { throw 'Skipping the licence page must work in both navigation directions.' } + } + } $registry = @(Read-Rows $database 'SELECT `Root`, `Key`, `Name`, `Value` FROM `Registry`' 4) if (@($registry | Where-Object { $_[0] -in '1', '2' }).Count) { throw 'Registration must follow the selected context, not force HKCU or HKLM.' } if (@($registry | Where-Object { $_[0] -eq '0' -and $_[1] -match '^Software\\Classes(\\|$)' }).Count) { diff --git a/packaging/windows/install-policy.wxi b/packaging/windows/install-policy.wxi index 02371ed07..8a02f2328 100644 --- a/packaging/windows/install-policy.wxi +++ b/packaging/windows/install-policy.wxi @@ -50,5 +50,9 @@ - + + + + + From 29e2a139db09687fe916d9018c2cb86f5438005f Mon Sep 17 00:00:00 2001 From: Jeremy Date: Tue, 27 Oct 2026 11:45:42 +0000 Subject: [PATCH 108/900] fix(installer): harden install-policy checks and packaging-lint workflow --- .github/workflows/packaging-lint.yml | 9 +++++++-- packaging/windows/check-install-policy.ps1 | 13 ++++++++++--- packaging/windows/test-install-policy.ps1 | 2 +- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 7e847137f..ea61d8430 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -28,6 +28,8 @@ jobs: runs-on: windows-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install the pinned packaging toolchain shell: pwsh run: | @@ -35,8 +37,11 @@ jobs: dotnet tool install --tool-path $tools wix --version 5.0.2 if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' } $tools >> $env:GITHUB_PATH - & (Join-Path $tools 'wix.exe') extension add -g WixToolset.UI.wixext/5.0.2 WixToolset.Util.wixext/5.0.2 - if ($LASTEXITCODE -ne 0) { throw 'WiX extension installation failed.' } + $policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json + foreach ($extension in @($policy.extensions)) { + & (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2" + if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." } + } - name: Build and check non-executable installer fixtures shell: pwsh run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') diff --git a/packaging/windows/check-install-policy.ps1 b/packaging/windows/check-install-policy.ps1 index 00b683d70..451295a2e 100644 --- a/packaging/windows/check-install-policy.ps1 +++ b/packaging/windows/check-install-policy.ps1 @@ -122,9 +122,11 @@ try { Set-SessionProperty $session 'CRAFT_USER_DIR' 'D:\Existing user app' Set-SessionProperty $session 'CRAFT_MACHINE_DIR' 'E:\Existing machine app' $action = if ($scope -eq '1') { 'CraftRestoreMachineFolder' } else { 'CraftRestoreUserFolder' } - if (-not $explicit) { - if ($session.DoAction($action) -ne 1) { throw 'Remembered-folder property action failed.' } - } + # Evaluate the compiled condition, so the test exercises it instead of calling the action directly. + $restore = @(Read-Rows $database ('SELECT `Condition` FROM `InstallExecuteSequence` WHERE `Action` = ''{0}''' -f $action) 1)[0] + $selected = $session.EvaluateCondition($restore[0]) -eq 1 + if ($selected -eq [bool]$explicit) { throw "$action must run only when no folder was supplied (condition: $($restore[0]))." } + if ($selected -and $session.DoAction($action) -ne 1) { throw 'Remembered-folder property action failed.' } $expected = if ($explicit) { $explicit } elseif ($scope -eq '1') { 'E:\Existing machine app' } else { 'D:\Existing user app' } if ((Get-SessionProperty $session 'INSTALLFOLDER') -ne $expected) { throw 'Custom or remembered folder was not preserved.' } } @@ -145,6 +147,11 @@ try { throw 'Silent updates must restore the folder before directory costing.' } } + foreach ($resolver in @('CraftUFromLegacyExe','CraftMFromLegacyExe')) { + if (-not ($execute['AppSearch'] -lt $execute[$resolver] -and $execute[$resolver] -lt $execute['LaunchConditions'])) { + throw 'Both legacy folder resolvers must run after AppSearch and before the launch checks.' + } + } # Switching the first-page choice must reset BOTH properties, including a back-and-forth change. $events = @(Read-Rows $database 'SELECT `Event`, `Argument`, `Condition`, `Ordering` FROM `ControlEvent` WHERE `Dialog_` = ''CraftScopeDlg'' AND `Control_` = ''Next'' ORDER BY `Ordering`' 4) # Model the full-UI upgrade entry with an existing machine-wide copy. Run diff --git a/packaging/windows/test-install-policy.ps1 b/packaging/windows/test-install-policy.ps1 index 21199ca7f..d455d19d1 100644 --- a/packaging/windows/test-install-policy.ps1 +++ b/packaging/windows/test-install-policy.ps1 @@ -38,7 +38,7 @@ foreach ($arch in $Architectures) { $sources = @($policy.sources | ForEach-Object { Join-Path $PSScriptRoot $_ }) $msi = Join-Path $stage "$($policy.id)-NOT-INSTALLABLE.msi" $extensions = @($policy.extensions | ForEach-Object { '-ext'; "WixToolset.$_.wixext" }) - & wix build @sources -arch $arch -wx @extensions ` + & wix build @sources -arch $arch @extensions ` -culture en-US -d 'Version=0.0.1' -d 'DisplayVersion=0.0.1-metadata-test' ` -d "BinDir=$stage" -d "IconPath=$(Join-Path $root $policy.icon)" ` -d "DocsDir=$(Join-Path $stage 'docs')" -d "ModelsDir=$(Join-Path $stage 'models')" ` From b98c55c7fa21025e580211823a251dadd56902c3 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 27 Oct 2026 16:09:18 +0400 Subject: [PATCH 109/900] 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 7b947c3383a8dcd2f800c3884408c7588d8c1751 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Tue, 27 Oct 2026 12:26:55 +0000 Subject: [PATCH 110/900] docs(installer): say that silent installs are per-user and when the scope page appears --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index dd0abd25d..142ebb1af 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,7 @@ See [ROADMAP.md](ROADMAP.md) for the stage, measured parity and the estimate of Installers and executables are code-signed. The installer adds CADCraft to the Start menu and asks whether to add a desktop shortcut too (unticked by default). For a silent install with the desktop shortcut: `msiexec /i cadcraft--windows-x64.msi /qn DESKTOPSHORTCUT=1`. +A silent install is per-user by default; add `ALLUSERS=1`, from an elevated terminal or deployment tool, for an all-users install. **If the app doesn't open on Windows:** the desktop app initializes only DirectX 12 by default. Letting wgpu also create an OpenGL instance can crash some graphics drivers (AMD's From d1847cf9a04258cf4952456e40b832aa2887edf0 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Tue, 27 Oct 2026 15:32:13 +0000 Subject: [PATCH 111/900] fix(installer): resolve the wizard scope and folder correctly Real msiexec runs (per-user and all-users, silent and wizard) found two defects that the metadata fixtures cannot see: - "Only for me" published ALLUSERS=2, so FindRelatedProducts treated the run as per-machine and skipped the existing per-user copy. An interactive upgrade left two registered products and uninstall left files behind. The page now leaves ALLUSERS unset for a per-user choice. - Windows Installer resolves Program Files once, for the context it started in, so choosing "Everyone" in the wizard installed into the user profile with a machine-wide registration. The wizard now sets the new-install folder itself after the choice (Program Files, Program Files (x86) for 32-bit, or the per-user Programs folder). Silent installs are unchanged. check-install-policy.ps1 now fails if either regresses. --- packaging/windows/check-install-policy.ps1 | 24 +++++++++++++++++++++- packaging/windows/install-policy.wxi | 15 +++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packaging/windows/check-install-policy.ps1 b/packaging/windows/check-install-policy.ps1 index 451295a2e..a4a14bc64 100644 --- a/packaging/windows/check-install-policy.ps1 +++ b/packaging/windows/check-install-policy.ps1 @@ -140,6 +140,28 @@ try { $ui['CraftScopeDlg'] -lt $ui['CraftRestoreUserFolder'] -and $ui['CraftRestoreUserFolder'] -lt $ui['CostInitialize'])) { throw 'Scope must be chosen after AppSearch and before FindRelatedProducts, launch checks and costing.' } + # Windows Installer resolves Program Files for the context it started in, before the wizard's scope choice. + # The wizard therefore sets the new-install folder itself, and only in the wizard. + $defaults = @(Read-Rows $database 'SELECT `Action`, `Sequence`, `Condition` FROM `InstallUISequence`' 3 | Where-Object { $_[0] -like 'CraftDefault*' }) + if ($defaults.Count -lt 2) { throw 'The wizard must set the new-install folder after the scope page; Program Files is resolved before the choice.' } + foreach ($row in $defaults) { + if (-not ($ui['CraftScopeDlg'] -lt [int]$row[1] -and [int]$row[1] -lt $ui['CostInitialize'])) { throw "$($row[0]) must run after the scope page and before costing." } + } + if (@(Read-Rows $database 'SELECT `Action` FROM `InstallExecuteSequence`' 1 | Where-Object { $_[0] -like 'CraftDefault*' }).Count) { + throw 'Silent installs must not use the wizard-only default folder actions.' + } + foreach ($scope in @('1', '')) { + Set-SessionProperty $session 'ALLUSERS' $scope + Set-SessionProperty $session 'INSTALLFOLDER' '' + Set-SessionProperty $session 'CRAFT_MACHINE_DIR' '' + Set-SessionProperty $session 'CRAFT_USER_DIR' '' + foreach ($row in @($defaults | Sort-Object { [int]$_[1] })) { + if ($session.EvaluateCondition($row[2]) -eq 1 -and $session.DoAction($row[0]) -ne 1) { throw "$($row[0]) failed." } + } + $folder = Get-SessionProperty $session 'INSTALLFOLDER' + $wanted = if ($scope -eq '1') { '^[A-Za-z]:\\Program Files( \(x86\))?\\ArtCraft\\[^\\]+\\$' } else { '^' + [regex]::Escape($env:LOCALAPPDATA) + '\\Programs\\ArtCraft\\[^\\]+\\$' } + if ($folder -notmatch $wanted) { throw "Wizard default folder for ALLUSERS='$scope' is '$folder'." } + } $execute = @{} foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallExecuteSequence`' 2)) { $execute[$row[0]] = [int]$row[1] } foreach ($action in @('CraftRestoreUserFolder','CraftRestoreMachineFolder')) { @@ -177,7 +199,7 @@ try { $allUsers = Get-SessionProperty $session 'ALLUSERS' $perUser = Get-SessionProperty $session 'MSIINSTALLPERUSER' if (($choice -eq 'machine' -and ($allUsers -ne '1' -or $perUser)) -or - ($choice -eq 'user' -and ($allUsers -ne '2' -or $perUser -ne '1'))) { + ($choice -eq 'user' -and ($allUsers -or $perUser -ne '1'))) { throw 'Scope selector does not reset the requested installation context.' } } diff --git a/packaging/windows/install-policy.wxi b/packaging/windows/install-policy.wxi index 8a02f2328..407c41cf3 100644 --- a/packaging/windows/install-policy.wxi +++ b/packaging/windows/install-policy.wxi @@ -1,6 +1,9 @@ + @@ -25,6 +28,16 @@ + + + + + + + + + @@ -42,7 +55,7 @@ - + From 9107479ade5e2a2986fe70a53ac24e65ffaba702 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Thu, 22 Oct 2026 15:17:08 +0200 Subject: [PATCH 112/900] io: open -> save -> reopen round-trip harness with loss report (FF5) cadcraft_io::roundtrip compares a drawing with itself saved and reopened (entities by handle, tables, blocks, layouts, unmodelled objects, xdata, classes, header variables; numbers within a tolerance), and roundtrip::corpus runs a folder of DXF/DWG files through DXF and DWG into report.md and report.json; exposed as `cadcraft-cli roundtrip` and `cargo xtask corpus`. The corpus itself stays outside the repo. The DWG bridge now says what its writer leaves out, per DXF type (cadcraft_dwg::dxf_to_dwg_noted, cadcraft_io::write_noted): the report shows those records as lost on save and a strict corpus run fails on them. OLE2FRAME, which the writer keeps with its data, is no longer listed as not saved in a DWG. CADCRAFT_CORPUS_STRICT=1 makes cadcraft-cli roundtrip (and so cargo xtask corpus) fail on the same strict failures as the corpus test; xtask makes a relative corpus folder and --out absolute before running the CLI. Co-Authored-By: Claude Opus 5.5 (1M context) --- apps/cadcraft-cli/src/main.rs | 126 ++ crates/dwg/src/lib.rs | 87 +- crates/engine/src/cmd/file.rs | 10 + crates/engine/tests/save_reports_not_saved.rs | 13 + crates/io/src/lib.rs | 35 +- crates/io/src/roundtrip.rs | 1148 +++++++++++++++++ crates/io/src/roundtrip/census.rs | 212 +++ crates/io/src/roundtrip/corpus.rs | 651 ++++++++++ crates/io/src/roundtrip/tests.rs | 559 ++++++++ docs/gaps.md | 7 +- xtask/src/main.rs | 50 +- 11 files changed, 2872 insertions(+), 26 deletions(-) create mode 100644 crates/io/src/roundtrip.rs create mode 100644 crates/io/src/roundtrip/census.rs create mode 100644 crates/io/src/roundtrip/corpus.rs create mode 100644 crates/io/src/roundtrip/tests.rs diff --git a/apps/cadcraft-cli/src/main.rs b/apps/cadcraft-cli/src/main.rs index 99a8b4282..7b9916a55 100644 --- a/apps/cadcraft-cli/src/main.rs +++ b/apps/cadcraft-cli/src/main.rs @@ -9,6 +9,7 @@ //! cadcraft-cli perf [N] timing table on a synthetic N-entity drawing //! cadcraft-cli perf FILE canvas display-list build of a drawing, zoomed in step by step //! cadcraft-cli sample (bracket|floorplan) OUT write a built-in sample drawing +//! cadcraft-cli roundtrip [FILE|FOLDER] [--out DIR] open → save → reopen report (Markdown + JSON) //! ``` #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -63,6 +64,11 @@ const USAGE: &str = "usage: cadcraft-cli mcp [--connect HOST:PORT [--lazy] [--launch]] cadcraft-cli perf [N | FILE] cadcraft-cli sample (bracket|floorplan) OUT.(dxf|dwg|svg|png) + cadcraft-cli roundtrip [FILE | FOLDER] [--out DIR] [--keep-saved] [--same-format] [--no-census] [--tolerance T] + open each DXF/DWG, save it as DXF and DWG, reopen and compare; writes + report.md and report.json to DIR (default: the folder's `report`). + FOLDER defaults to $CADCRAFT_CORPUS_DIR. With CADCRAFT_CORPUS_STRICT=1 it + fails when a file doesn't open, save or reopen, or loses records on save. cadcraft-cli --version image framing (png 2400x1600, svg, pdf; always model space): @@ -819,6 +825,125 @@ mod mcp_args_tests { } } +/// What `roundtrip` was asked to do. +#[derive(Debug, PartialEq)] +struct RoundTripArgs { + path: Option, + out: Option, + keep_saved: bool, + opts: cadcraft_io::roundtrip::corpus::CorpusOptions, +} + +fn parse_roundtrip_args(args: &[String]) -> Result { + let mut r = RoundTripArgs { path: None, out: None, keep_saved: false, opts: Default::default() }; + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--out" => r.out = Some(it.next().filter(|v| !v.starts_with("--")).ok_or("roundtrip: --out needs a folder")?.into()), + "--keep-saved" => r.keep_saved = true, + "--same-format" => r.opts.cross_format = false, + "--no-census" => r.opts.census = false, + "--tolerance" => { + let v = it.next().ok_or("roundtrip: --tolerance needs a number")?; + match v.parse::() { + Ok(t) if t.is_finite() && t >= 0.0 => r.opts.compare.abs_tol = t, + _ => return Err(format!("roundtrip: --tolerance must be a number >= 0, got `{v}`")), + } + } + s if s.starts_with("--") => return Err(format!("roundtrip: unknown option {s}")), + _ if r.path.is_none() => r.path = Some(a.into()), + _ => return Err("roundtrip: give one FILE or FOLDER".into()), + } + } + Ok(r) +} + +/// `roundtrip`: the corpus harness of `cadcraft_io::roundtrip::corpus` over a file or folder. +fn roundtrip(args: &[String]) -> Result<(), String> { + use cadcraft_io::roundtrip::corpus; + let mut a = parse_roundtrip_args(args)?; + let path = a + .path + .take() + .or_else(|| std::env::var_os("CADCRAFT_CORPUS_DIR").map(Into::into)) + .ok_or("roundtrip: give a FILE or FOLDER, or set CADCRAFT_CORPUS_DIR")?; + let (root, files, out) = if path.is_dir() { + let out = a.out.take().unwrap_or_else(|| path.join("report")); + let files = corpus::corpus_files(&path, std::slice::from_ref(&out)); + (path, files, out) + } else if path.is_file() { + let root = path.parent().map(std::path::Path::to_path_buf).unwrap_or_default(); + let out = a.out.take().unwrap_or_else(|| root.join("report")); + (root, vec![path], out) + } else { + return Err(format!("roundtrip: no such file or folder: {}", path.display())); + }; + if files.is_empty() { + return Err(format!("roundtrip: no DXF or DWG files in {}", root.display())); + } + if a.keep_saved { + a.opts.keep_saved = Some(out.join("saved")); + } + let report = corpus::run(&root, &files, &a.opts, &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1)); + for f in &report.files { + let routes: Vec = f + .routes + .iter() + .map(|r| match (&r.save_error, &r.reopen_error) { + (Some(_), _) => format!("{}: save failed", r.route), + (None, Some(_)) => format!("{}: reopen failed", r.route), + (None, None) => { + let t = r.comparison.total(); + format!("{}: {} lost, {} added, {} changed", r.route, t.lost, t.added, t.changed) + } + }) + .collect(); + match &f.open_error { + Some(e) => outln!("{}: open failed: {e}", f.path), + None => outln!("{}: opened; {}", f.path, routes.join("; ")), + } + } + let (md, json) = report.write(&out).map_err(|e| format!("roundtrip: can't write the report to {}: {e}", out.display()))?; + outln!("report: {}", md.display()); + outln!(" {}", json.display()); + // CADCRAFT_CORPUS_STRICT=1: a file that doesn't open, save or reopen, or records a writer + // leaves out, fail the run (the report is written first). + if std::env::var("CADCRAFT_CORPUS_STRICT").is_ok_and(|v| v == "1") { + let failed = report.strict_failures(); + if !failed.is_empty() { + return Err(format!("roundtrip: {} strict failures:\n{}", failed.len(), failed.join("\n"))); + } + } + Ok(()) +} + +#[cfg(test)] +mod roundtrip_args_tests { + use super::*; + + fn args(a: &[&str]) -> Vec { + a.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn roundtrip_options_parse() { + let r = parse_roundtrip_args(&args(&["corpus", "--out", "rep", "--keep-saved", "--same-format", "--tolerance", "0.001"])).unwrap(); + assert_eq!(r.path, Some("corpus".into())); + assert_eq!(r.out, Some("rep".into())); + assert!(r.keep_saved && !r.opts.cross_format && r.opts.census); + assert_eq!(r.opts.compare.abs_tol, 0.001); + assert_eq!(parse_roundtrip_args(&args(&[])).unwrap().path, None); + for bad in [&["--out"][..], &["--tolerance", "nan"], &["--tolerance", "-1"], &["a", "b"], &["--typo"]] { + assert!(parse_roundtrip_args(&args(bad)).is_err(), "{bad:?}"); + } + } + + #[test] + fn roundtrip_reports_a_missing_folder() { + assert!(roundtrip(&args(&["no/such/folder/anywhere"])).is_err()); + } +} + fn main() -> ExitCode { let code = cli(); if STDOUT_ERROR.load(Ordering::Relaxed) { ExitCode::FAILURE } else { code } @@ -845,6 +970,7 @@ fn cli() -> ExitCode { outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()); }), Some("mcp") => mcp(&rest), + Some("roundtrip") => roundtrip(&rest), Some("--version" | "-V") => { outln!("cadcraft-cli {}", env!("CARGO_PKG_VERSION")); Ok(()) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index b81bd00d1..d6efdac70 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -360,15 +360,22 @@ mod native { /// Leave out what acadrust can't write as this DWG version: other programs' custom entities /// and objects without raw DWG data of that version. acadrust 0.6.4 refuses the whole file /// for one of them (0.6.3 left them out); CADCraft already tells the user which entity types - /// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many. - fn drop_unwritable(doc: &mut acadrust::CadDocument) -> usize { + /// a DWG doesn't keep (`not_saved`), so the rest of the drawing is written. Returns how many + /// records of each DXF type were left out, so a save can say so. + fn drop_unwritable(doc: &mut acadrust::CadDocument) -> super::Unwritten { let version = doc.version; + let mut dropped = super::Unwritten::new(); + let mut count = |name: &str| { + let n = dropped.entry(name.trim().to_ascii_uppercase()).or_insert(0); + *n = n.saturating_add(1); + }; let unwritable: Vec = doc .entities() .filter_map(|e| match e { acadrust::entities::EntityType::Unknown(u) if u.raw_dwg_data.is_none() || u.dwg_source_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => { + count(&u.dxf_name); Some(u.common.handle) } _ => None, @@ -381,9 +388,10 @@ mod native { .objects .iter() .filter_map(|(h, o)| match o { - acadrust::objects::ObjectType::Unknown { raw_dwg_data, raw_dwg_version, .. } + acadrust::objects::ObjectType::Unknown { type_name, raw_dwg_data, raw_dwg_version, .. } if raw_dwg_data.is_none() || raw_dwg_version.is_some_and(|v| v != version) || version == acadrust::DxfVersion::AC1009 => { + count(type_name); Some(*h) } _ => None, @@ -392,7 +400,7 @@ mod native { for h in &objects { doc.objects.remove(h); } - unwritable.len() + objects.len() + dropped } /// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of @@ -460,12 +468,19 @@ 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).map(|(dwg, _)| dwg) } /// 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> { + dxf_to_dwg_noted(dxf, version).map(|(dwg, _)| dwg) + } + + /// [`dxf_to_dwg_as`], also returning what the DWG writer left out: how many records of each + /// DXF type it can't write (other programs' custom entities and objects that the DWG reader + /// didn't read from a DWG of this version), empty when the DWG keeps everything. + pub fn dxf_to_dwg_noted(dxf: &[u8], version: &str) -> Result<(Vec, super::Unwritten), String> { let v = match version.trim().to_ascii_uppercase().as_str() { "AC1015" => acadrust::DxfVersion::AC1015, "AC1018" => acadrust::DxfVersion::AC1018, @@ -512,7 +527,7 @@ mod native { } } - fn convert(dxf: &[u8], version: Option) -> Result, String> { + fn convert(dxf: &[u8], version: Option) -> Result<(Vec, super::Unwritten), 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 @@ -539,13 +554,14 @@ mod native { other_layout_owners(&mut doc); table_style_rows(&mut doc, true); dimension_flags(&mut doc); - drop_unwritable(&mut doc); + let unwritten = drop_unwritable(&mut doc); current_dimstyle(&mut doc); add_variable_dictionary(&mut doc); current_text_style(&mut doc); - std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) + let dwg = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) .map_err(|_| "the DWG writer failed on this drawing".to_string())? - .map_err(|e| format!("DWG write: {e}")) + .map_err(|e| format!("DWG write: {e}"))?; + Ok((dwg, unwritten)) } /// AutoCAD's entry name for the drawing variables dictionary (the DXF Reference calls it the @@ -642,7 +658,11 @@ 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_noted}; + +/// What saving as DWG left out: how many records of each DXF type (upper case) the DWG writer +/// can't write. +pub type Unwritten = std::collections::BTreeMap; /// The error for a DWG version CADCraft can't write. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -671,6 +691,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_noted(_dxf: &[u8], _version: &str) -> Result<(Vec, Unwritten), String> { + Err("DWG files can't be written in the web build yet; save as DXF".into()) +} #[cfg(test)] mod tests { @@ -911,4 +935,47 @@ 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"]); } + + /// Saving says what the DWG writer left out, per type: entities of types acadrust's DXF + /// reader doesn't model (another program's custom entity) can't be written; a drawing the DWG + /// keeps whole reports nothing. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn saving_lists_the_types_the_dwg_writer_leaves_out() { + let line = " 0\nLINE\n 8\n0\n100\nAcDbEntity\n100\nAcDbLine\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 11\n10.0\n 21\n0.0\n 31\n0.0\n"; + let widget = " 0\nACME_WIDGET\n 8\n0\n100\nAcDbEntity\n100\nAcmeWidget\n 10\n1.0\n 20\n2.0\n 30\n0.0\n"; + let dxf = |body: &str| { + format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{body} 0\nENDSEC\n 0\nEOF\n") + }; + for version in ["AC1015", "AC1018", "AC1032"] { + let (dwg, unwritten) = dxf_to_dwg_noted(dxf(&format!("{line}{widget}{widget}")).as_bytes(), version).unwrap(); + assert!(is_dwg(&dwg), "{version}"); + assert_eq!(unwritten, [("ACME_WIDGET".to_string(), 2)].into_iter().collect::(), "{version}"); + } + let (_, unwritten) = dxf_to_dwg_noted(dxf(line).as_bytes(), "AC1032").unwrap(); + assert!(unwritten.is_empty(), "{unwritten:?}"); + } + + /// An OLE2FRAME, which CADCraft keeps as its DXF groups without modelling it, is written to + /// the DWG with its data: it isn't in the list of what the writer left out. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn ole_frames_are_written_with_their_data() { + let ole = " 0\nOLE2FRAME\n 8\n0\n100\nAcDbEntity\n100\nAcDbOle2Frame\n 70\n2\n 10\n1.0\n 20\n9.0\n 30\n0.0\n 11\n8.0\n 21\n2.0\n 31\n0.0\n 71\n2\n 72\n0\n 73\n1\n 90\n4\n310\nDEADBEEF\n 1\nOLE\n"; + let dxf = + format!(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n{ole} 0\nENDSEC\n 0\nEOF\n"); + for version in ["AC1015", "AC1018", "AC1032"] { + let (dwg, unwritten) = dxf_to_dwg_noted(dxf.as_bytes(), version).unwrap(); + assert!(unwritten.is_empty(), "{version} {unwritten:?}"); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let frames: Vec> = back + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Ole2Frame(o) => Some(o.encoded_payload()), + _ => None, + }) + .collect(); + assert_eq!(frames, [vec![0xDE, 0xAD, 0xBE, 0xEF]], "{version}"); + } + } } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 95975a4e2..cfad2e61f 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -534,6 +534,13 @@ 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"]; +/// Entity types CADCraft keeps without modelling them that the DWG bridge writes all the same: +/// its DWG library models them and writes them whole (an OLE2FRAME with its data bytes, for +/// every DWG version; `cadcraft-dwg`'s `ole_frames_are_written_with_their_data`). What the bridge +/// can't write it reports per type through `cadcraft_io::write_noted`, which the round-trip +/// harness reads; a save from here warns with [`not_saved_as`] only. +const DWG_WRITTEN_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 { @@ -545,6 +552,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 DWG_WRITTEN_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) { + 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..a52fa7097 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 (an embedded OLE object) is kept by CADCraft as its DXF groups and written to +/// DWG whole, so saving doesn't report it as not saved (it was: "… 4 OLE2FRAME"). +#[test] +fn ole_frames_are_not_reported_as_not_saved() { + 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("ACME_WIDGET")).unwrap(); + for v in [Version::R2000, Version::R2018] { + assert_eq!(not_saved_as(&d, v), [("ACME_WIDGET".to_string(), 1)].into_iter().collect(), "{v:?}"); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ef56e6602..39afd2df9 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -14,6 +14,8 @@ mod dxf_write; mod dxf_xref; pub mod pdf; pub mod plotter; +/// Open → save → reopen comparison and the real-file corpus harness (gaps FF1, FF5). +pub mod roundtrip; pub mod svg; mod svg_read; @@ -60,18 +62,25 @@ fn ext(name: &str) -> String { /// Read a drawing; the format comes from the content (DXF ASCII/binary, DWG) or the name /// (SVG and gzip-compressed SVGZ). pub fn read(bytes: &[u8], name: &str) -> Result { + read_source(bytes, name).map(|(d, _)| d) +} + +/// [`read`], also returning the DXF rendition a DWG was read through (`None` for other files), +/// which the round-trip harness counts. +pub(crate) fn read_source(bytes: &[u8], name: &str) -> Result<(Drawing, Option>)> { if cadcraft_dwg::is_dwg(bytes) { let (dxf, notes) = cadcraft_dwg::dwg_to_dxf_noted(bytes, cadcraft_dwg::Limits::DEFAULT).map_err(IoError::Format)?; let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?; d.read_notes = notes; - return Ok(d); + return Ok((d, Some(dxf))); } - match ext(name).as_str() { + let d = match ext(name).as_str() { "svg" | "svgz" => svg_read::read(bytes), "dxf" | "" => dxf_read::read(bytes), e if bytes.len() > 4 => dxf_read::read(bytes).map_err(|_| IoError::Unsupported(e.to_string())), e => Err(IoError::Unsupported(e.to_string())), - } + }?; + Ok((d, None)) } /// Write a drawing in the format chosen by the name's extension. Images (PNG, SVG, PDF) show @@ -97,15 +106,27 @@ pub fn write_with(d: &Drawing, name: &str, opts: &SaveOptions) -> Result // 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. - "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) - } + "dwg" if !opts.binary => write_dwg(d, opts.version.unwrap_or_else(|| version.max(Version::R2004))).map(|(dwg, _)| dwg), e if opts.binary => Err(IoError::Format(format!("binary output is for DXF files, not `{e}`"))), _ => write_framed(d, name, None), } } +/// [`write_with`], also returning what the file leaves out of the drawing: for a DWG, how many +/// records of each DXF type the DWG writer can't write (other programs' custom entities and +/// objects); for other formats, nothing. +pub fn write_noted(d: &Drawing, name: &str, opts: &SaveOptions) -> Result<(Vec, cadcraft_dwg::Unwritten)> { + if ext(name) == "dwg" && !opts.binary { + return write_dwg(d, opts.version.unwrap_or_else(|| save_version(d).max(Version::R2004))); + } + write_with(d, name, opts).map(|b| (b, cadcraft_dwg::Unwritten::new())) +} + +/// The DWG bridge reads our R2000 DXF and writes the DWG at `version`. +fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec, cadcraft_dwg::Unwritten)> { + cadcraft_dwg::dxf_to_dwg_noted(dxf_write::dwg_bridge(d, version).as_bytes(), version.code()).map_err(IoError::Format) +} + /// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in /// drawing units, centred and scaled to fit the image without distortion) instead of the /// extents. Formats that are not images (DXF, DWG) ignore the window. The window is checked with diff --git a/crates/io/src/roundtrip.rs b/crates/io/src/roundtrip.rs new file mode 100644 index 000000000..e801e663d --- /dev/null +++ b/crates/io/src/roundtrip.rs @@ -0,0 +1,1148 @@ +//! Round-trip checks (gaps FF1 and FF5): open a drawing, save it, open the saved file again and +//! list everything that differs between the two drawings. +//! +//! [`compare`] works on CADCraft's own model ([`Drawing`]), so it measures what saving and +//! reopening lose or change: entities per type in every space and block (matched by handle, +//! geometry and properties within a tolerance), table records, blocks, layouts, the data CADCraft +//! keeps without modelling it (other programs' objects and entities, dictionaries, CLASS records, +//! extension dictionaries, reactors, xdata) and header variables. [`census`] counts what the +//! file itself holds, so opening a file can be checked against it too. +//! +//! The corpus harness ([`corpus`], native only) runs both over a folder of real files and writes +//! a Markdown and JSON report; `cadcraft-cli roundtrip` and `cargo xtask corpus` run it. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; + +use cadcraft_doc::foreign::{Foreign, ForeignExtra}; +use cadcraft_doc::{Drawing, Entity, EntityKind, EntityStore, Handle, RawTag}; +use serde::Serialize; +use serde_json::Value; + +mod census; +#[cfg(not(target_arch = "wasm32"))] +pub mod corpus; + +pub use census::{Census, census, census_of, compare_census}; + +/// What a difference is about. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Category { + /// Opening the file: what the file holds that the drawing read from it doesn't. + Read, + /// Entities of a type in a space or block. + Count, + /// Entity, object or dictionary entry handles. + Handle, + /// An entity's geometry and type-specific data. + Geometry, + /// An entity's common properties (layer, colour, linetype, lineweight, transparency…). + Properties, + /// Entities CADCraft doesn't model, kept as their DXF groups. + Opaque, + /// Other applications' extended data. + Xdata, + /// Extension dictionaries and persistent reactors. + ExtDict, + /// Table records: layers, linetypes, text, dimension, multileader, table and multiline styles, + /// views, viewport configurations, UCSs, layer states, groups, scales, plot style tables. + Table, + /// Block definitions (their own properties; their entities are under the other categories). + Block, + /// Layouts and their page setups. + Layout, + /// Non-graphical objects CADCraft doesn't model, kept as their DXF groups; constraints. + Object, + /// Entries of the named object dictionary. + Dictionary, + /// CLASS records. + Class, + /// Header variables. + Header, +} + +impl Category { + pub const ALL: [Category; 15] = [ + Category::Read, + Category::Count, + Category::Handle, + Category::Geometry, + Category::Properties, + Category::Opaque, + Category::Xdata, + Category::ExtDict, + Category::Table, + Category::Block, + Category::Layout, + Category::Object, + Category::Dictionary, + Category::Class, + Category::Header, + ]; + + /// A short name for reports. + pub fn label(self) -> &'static str { + match self { + Category::Read => "read", + Category::Count => "entity count", + Category::Handle => "handles", + Category::Geometry => "geometry", + Category::Properties => "properties", + Category::Opaque => "unknown entities", + Category::Xdata => "xdata", + Category::ExtDict => "ext. dictionaries/reactors", + Category::Table => "table records", + Category::Block => "blocks", + Category::Layout => "layouts", + Category::Object => "objects", + Category::Dictionary => "dictionary entries", + Category::Class => "classes", + Category::Header => "header", + } + } +} + +/// Whether something went missing, appeared, or is there with other values. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Change { + Lost, + Added, + Changed, +} + +impl Change { + pub fn label(self) -> &'static str { + match self { + Change::Lost => "lost", + Change::Added => "added", + Change::Changed => "changed", + } + } +} + +/// One difference between two drawings. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Difference { + pub category: Category, + pub change: Change, + /// Where: `Model LINE 1A`, `Block DOOR`, `LAYER Walls`, `$LTSCALE`… + pub place: String, + /// What: the values before and after, or the items lost. + pub detail: String, + /// How many items this difference stands for (several entities lost of one type: one row). + pub count: usize, +} + +/// How many items were lost, added and changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +pub struct Tally { + pub lost: usize, + pub added: usize, + pub changed: usize, +} + +impl Tally { + pub fn total(&self) -> usize { + self.lost.saturating_add(self.added).saturating_add(self.changed) + } + fn add(&mut self, change: Change, n: usize) { + let slot = match change { + Change::Lost => &mut self.lost, + Change::Added => &mut self.added, + Change::Changed => &mut self.changed, + }; + *slot = slot.saturating_add(n); + } +} + +/// How two drawings are compared. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Options { + /// Absolute tolerance for numbers (drawing units, radians…). + pub abs_tol: f64, + /// Relative tolerance for numbers, of the larger magnitude. + pub rel_tol: f64, + /// Most differences listed; the rest are only counted ([`Comparison::omitted`]). + pub max_differences: usize, + /// Most changed values named for one object. + pub max_paths: usize, +} + +impl Default for Options { + fn default() -> Self { + Options { abs_tol: 1e-6, rel_tol: 1e-9, max_differences: 5000, max_paths: 6 } + } +} + +/// Every difference found between two drawings. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct Comparison { + pub differences: Vec, + /// Differences found beyond [`Options::max_differences`] (counted in `totals`, not listed). + pub omitted: usize, + /// Items lost, added and changed per category. + pub totals: BTreeMap, +} + +impl Comparison { + pub fn is_empty(&self) -> bool { + self.totals.values().all(|t| t.total() == 0) + } + /// Items lost, added and changed in all categories. + pub fn total(&self) -> Tally { + let mut all = Tally::default(); + for t in self.totals.values() { + all.add(Change::Lost, t.lost); + all.add(Change::Added, t.added); + all.add(Change::Changed, t.changed); + } + all + } + /// The tally of one category. + pub fn tally(&self, c: Category) -> Tally { + self.totals.get(&c).copied().unwrap_or_default() + } + /// Add another comparison's differences (within this one's limit). + pub fn merge(&mut self, other: Comparison, max: usize) { + for (c, t) in other.totals { + let mine = self.totals.entry(c).or_default(); + mine.add(Change::Lost, t.lost); + mine.add(Change::Added, t.added); + mine.add(Change::Changed, t.changed); + } + for d in other.differences { + if self.differences.len() < max { + self.differences.push(d); + } else { + self.omitted = self.omitted.saturating_add(1); + } + } + self.omitted = self.omitted.saturating_add(other.omitted); + } +} + +/// Collects differences within the limit. +struct Out<'o> { + opts: &'o Options, + cmp: Comparison, + /// Anonymous blocks saved under another name (`*D344` → `*D10`), upper case: references + /// to them compare equal. + renamed: HashMap, + /// Things that only got new handles, summed up in one row each: (what) → (how many, an + /// example). + renumbered: BTreeMap, + /// Anonymous blocks of the first drawing that nothing refers to and that the second one + /// doesn't have (saving drops them, as PURGE would), upper case: reported in one row. + orphans: BTreeSet, +} + +/// What values are compared with: the tolerances and the renamed anonymous blocks. +struct Norm<'a> { + o: &'a Options, + renamed: &'a HashMap, +} + +impl Norm<'_> { + /// Equal strings, or an anonymous block's name and the name it was saved under. + fn same_str(&self, a: &str, b: &str) -> bool { + a == b || (a.starts_with('*') && self.renamed.get(&a.to_ascii_uppercase()).is_some_and(|n| n.eq_ignore_ascii_case(b))) + } +} + +impl<'o> Out<'o> { + fn new(opts: &'o Options) -> Self { + Out { opts, cmp: Comparison::default(), renamed: HashMap::new(), renumbered: BTreeMap::new(), orphans: BTreeSet::new() } + } + fn norm(&self) -> Norm<'_> { + Norm { o: self.opts, renamed: &self.renamed } + } + /// Note that one of `what` only got a new handle. + fn renumber(&mut self, what: &str, example: impl FnOnce() -> String) { + match self.renumbered.get_mut(what) { + Some(slot) => slot.0 = slot.0.saturating_add(1), + None => { + self.renumbered.insert(what.to_string(), (1, example())); + } + } + } + /// The rows of [`Out::renumber`]. + fn flush_renumbered(&mut self) { + for (what, (n, example)) in std::mem::take(&mut self.renumbered) { + self.push_n(Category::Handle, Change::Changed, n, what.clone(), format!("{n} {what} got new handles (e.g. {example})")); + } + } + fn push(&mut self, category: Category, change: Change, place: impl Into, detail: impl Into) { + self.push_n(category, change, 1, place, detail); + } + fn push_n(&mut self, category: Category, change: Change, count: usize, place: impl Into, detail: impl Into) { + self.cmp.totals.entry(category).or_default().add(change, count); + if self.cmp.differences.len() < self.opts.max_differences { + self.cmp.differences.push(Difference { category, change, place: place.into(), detail: detail.into(), count }); + } else { + self.cmp.omitted = self.cmp.omitted.saturating_add(1); + } + } +} + +/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not +/// compared. +pub const VOLATILE_HEADER: &[&str] = + &["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"]; + +/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and +/// reopened). Differences are reported as what `after` lost, gained or changed. +pub fn compare(before: &Drawing, after: &Drawing, opts: &Options) -> Comparison { + let mut out = Out::new(opts); + compare_entities(before, after, &mut out); + compare_tables(before, after, &mut out); + compare_foreign(&before.foreign, &after.foreign, &mut out); + compare_header(before, after, &mut out); + out.flush_renumbered(); + out.cmp +} + +// --------------------------------------------------------------------------------------------- +// Values + +fn close(a: f64, b: f64, o: &Options) -> bool { + a == b || (a - b).abs() <= o.abs_tol + o.rel_tol * a.abs().max(b.abs()) +} + +/// The changed values of one object, as `path: before → after`. +struct Paths { + list: Vec, + cap: usize, + more: usize, +} + +impl Paths { + fn new(cap: usize) -> Self { + Paths { list: Vec::new(), cap: cap.max(1), more: 0 } + } + fn add(&mut self, s: String) { + if self.list.len() < self.cap { + self.list.push(s); + } else { + self.more = self.more.saturating_add(1); + } + } + fn is_empty(&self) -> bool { + self.list.is_empty() + } + /// Far more changes than can be listed: stop looking. + fn saturated(&self) -> bool { + self.more > 1000 + } + fn text(&self) -> String { + let mut s = self.list.join("; "); + if self.more > 0 { + s.push_str(&format!("; and {} more", if self.saturated() { "many".to_string() } else { self.more.to_string() })); + } + s + } +} + +/// A value for a report: strings quoted, at most 60 characters. +fn short(v: &Value) -> String { + let s = match v { + Value::String(s) => format!("\"{s}\""), + Value::Array(a) => format!("[{} items]", a.len()), + Value::Object(_) => "{…}".to_string(), + other => other.to_string(), + }; + clip(&s, 60) +} + +/// `s` cut to `n` characters, with an ellipsis when cut. +pub(crate) fn clip(s: &str, n: usize) -> String { + if s.chars().count() <= n { + s.to_string() + } else { + let mut t: String = s.chars().take(n.saturating_sub(1)).collect(); + t.push('…'); + t + } +} + +fn show(path: &str) -> &str { + if path.is_empty() { "value" } else { path } +} + +const MAX_DEPTH: usize = 64; + +/// Whether a value's path names an angle (in radians in the model): `rotation`, `start`, +/// `end`, `angle`, `twist`, `oblique`. +fn is_angle(path: &str) -> bool { + let last = path.rsplit('.').next().unwrap_or(path); + let last = last.split('[').next().unwrap_or(last).to_ascii_lowercase(); + ["rotation", "start", "end", "angle", "twist", "oblique"].iter().any(|k| last.ends_with(k)) +} + +/// The same angle, a whole number of turns apart (-π/4 and 7π/4). +fn same_angle(a: f64, b: f64, o: &Options) -> bool { + let d = (a - b).rem_euclid(std::f64::consts::TAU); + let tol = o.abs_tol + o.rel_tol * a.abs().max(b.abs()); + d <= tol || std::f64::consts::TAU - d <= tol +} + +fn diff_values(a: &Value, b: &Value, path: &mut String, n: &Norm, p: &mut Paths, depth: usize) { + if p.saturated() { + return; + } + if depth > MAX_DEPTH { + if a != b { + p.add(format!("{}: differs", show(path))); + } + return; + } + match (a, b) { + (Value::Number(x), Value::Number(y)) => { + let same = match (x.as_i64(), y.as_i64()) { + (Some(i), Some(j)) => i == j, + _ => match (x.as_f64(), y.as_f64()) { + (Some(f), Some(g)) => close(f, g, n.o) || (is_angle(path) && same_angle(f, g, n.o)), + _ => x == y, + }, + }; + if !same { + p.add(format!("{}: {x} → {y}", show(path))); + } + } + (Value::String(x), Value::String(y)) => { + if !n.same_str(x, y) { + p.add(format!("{}: {} → {}", show(path), short(a), short(b))); + } + } + (Value::Object(x), Value::Object(y)) => { + let keys: BTreeSet<&String> = x.keys().chain(y.keys()).collect(); + for k in keys { + let len = path.len(); + if !path.is_empty() { + path.push('.'); + } + path.push_str(k); + match (x.get(k.as_str()), y.get(k.as_str())) { + (Some(u), Some(v)) => diff_values(u, v, path, n, p, depth + 1), + (Some(Value::Null), None) | (None, Some(Value::Null)) | (None, None) => {} + (Some(u), None) => p.add(format!("{}: {} → (none)", show(path), short(u))), + (None, Some(v)) => p.add(format!("{}: (none) → {}", show(path), short(v))), + } + path.truncate(len); + } + } + (Value::Array(x), Value::Array(y)) => { + if x.len() != y.len() { + p.add(format!("{}: {} items → {}", show(path), x.len(), y.len())); + } + for (i, (u, v)) in x.iter().zip(y).enumerate() { + if p.saturated() { + return; + } + let len = path.len(); + path.push_str(&format!("[{i}]")); + diff_values(u, v, path, n, p, depth + 1); + path.truncate(len); + } + } + _ if a == b => {} + _ => p.add(format!("{}: {} → {}", show(path), short(a), short(b))), + } +} + +/// The values that differ between two serializable things. +fn diff_ser(a: &T, b: &T, n: &Norm) -> Paths { + let mut p = Paths::new(n.o.max_paths); + match (serde_json::to_value(a), serde_json::to_value(b)) { + (Ok(x), Ok(y)) => diff_values(&x, &y, &mut String::new(), n, &mut p, 0), + _ if a != b => p.add("differs (not comparable field by field)".into()), + _ => {} + } + p +} + +/// A key for matching things that may have been renumbered: the value with numbers rounded. +fn signature(v: &Value, out: &mut String, depth: usize) { + if depth > MAX_DEPTH { + return; + } + match v { + Value::Number(n) => match n.as_f64() { + Some(f) if f.is_finite() => { + let r = if f.abs() < 1e-9 { 0.0 } else { f }; + out.push_str(&format!("{r:.6e}")); + } + _ => out.push_str(&n.to_string()), + }, + Value::Array(a) => { + out.push('['); + for x in a { + signature(x, out, depth + 1); + out.push(','); + } + out.push(']'); + } + Value::Object(m) => { + out.push('{'); + for (k, x) in m { + out.push_str(k); + out.push(':'); + signature(x, out, depth + 1); + out.push(','); + } + out.push('}'); + } + other => out.push_str(&other.to_string()), + } +} + +fn sig_of(t: &T) -> String { + let mut s = String::new(); + if let Ok(v) = serde_json::to_value(t) { + signature(&v, &mut s, 0); + } + s +} + +/// Pair up the items of `a` and `b` that weren't matched by handle: equal signatures first, then +/// in order. Returns the pairs and the items left over on each side. +fn pair_up<'x, T>(a: Vec<&'x T>, b: Vec<&'x T>, sig: impl Fn(&T) -> String) -> (Vec<(&'x T, &'x T)>, Vec<&'x T>, Vec<&'x T>) { + let mut by_sig: HashMap> = HashMap::new(); + for (i, y) in b.iter().enumerate().rev() { + by_sig.entry(sig(y)).or_default().push(i); + } + let mut used = vec![false; b.len()]; + let mut pairs = Vec::new(); + let mut rest_a = Vec::new(); + for x in a { + match by_sig.get_mut(&sig(x)).and_then(Vec::pop) { + Some(i) => { + if let (Some(y), Some(u)) = (b.get(i), used.get_mut(i)) { + *u = true; + pairs.push((x, *y)); + } + } + None => rest_a.push(x), + } + } + let mut rest_b: Vec<&T> = b.iter().zip(&used).filter(|(_, u)| !**u).map(|(y, _)| *y).collect(); + let n = rest_a.len().min(rest_b.len()); + let tail_a = rest_a.split_off(n); + let tail_b = rest_b.split_off(n); + pairs.extend(rest_a.into_iter().zip(rest_b)); + (pairs, tail_a, tail_b) +} + +fn hex_list(hs: impl Iterator, n: usize) -> String { + let all: Vec = hs.map(Handle::hex).collect(); + let mut s = all.iter().take(n).cloned().collect::>().join(", "); + if all.len() > n { + s.push_str(", …"); + } + s +} + +/// Group codes that hold handles (DXF Reference: 5, 105, 320–369, 390–399, 480–481, xdata +/// 1005). A file's objects can be renumbered on save (gap FF7), so a handle compares equal to +/// any other handle; only a reference that became null (or stopped being null) counts. +fn is_handle_code(code: i32) -> bool { + matches!(code, 5 | 105 | 320..=369 | 390..=399 | 480 | 481 | 1005) +} + +fn null_handle(v: &str) -> bool { + v.trim().trim_start_matches('0').is_empty() +} + +/// Whether two groups hold the same value: the same text, numbers within the tolerance, or two +/// (non-null) handles. +fn tag_eq(a: &RawTag, b: &RawTag, o: &Options) -> bool { + if a.code != b.code { + return false; + } + if is_handle_code(a.code) { + return null_handle(&a.value) == null_handle(&b.value); + } + a.value == b.value + || a.value.trim() == b.value.trim() + || matches!((a.value.trim().parse::(), b.value.trim().parse::()), (Ok(x), Ok(y)) if close(x, y, o)) +} + +/// How two group lists differ, or `None` when they hold the same values. +fn tags_diff(a: &[RawTag], b: &[RawTag], o: &Options) -> Option { + let first = a.iter().zip(b).position(|(x, y)| !tag_eq(x, y, o)); + if first.is_none() && a.len() == b.len() { + return None; + } + let mut s = String::new(); + if a.len() != b.len() { + s.push_str(&format!("{} groups → {}; ", a.len(), b.len())); + } + let at = first.unwrap_or(a.len().min(b.len())); + let show_tag = |t: Option<&RawTag>| t.map_or("(end)".to_string(), |t| format!("{} `{}`", t.code, clip(&t.value, 40))); + s.push_str(&format!("first difference at group #{at}: {} → {}", show_tag(a.get(at)), show_tag(b.get(at)))); + Some(s) +} + +// --------------------------------------------------------------------------------------------- +// Entities + +/// An entity collection of a drawing: model space, a layout's paper space or a block. `key` is +/// upper case (`BLOCK *D12`), `name` for reports (`Block *D12`). +struct Container<'d> { + key: String, + name: String, + store: &'d EntityStore, +} + +fn containers(d: &Drawing) -> Vec> { + let mut v = vec![Container { key: "MODEL".into(), name: "Model".into(), store: &d.model }]; + for l in &d.layouts { + v.push(Container { key: format!("LAYOUT {}", l.name.to_ascii_uppercase()), name: format!("Layout {}", l.name), store: &l.entities }); + } + for (name, b) in &d.blocks { + v.push(Container { key: format!("BLOCK {}", name.to_ascii_uppercase()), name: format!("Block {name}"), store: &b.entities }); + } + v +} + +/// Which container each entity is in. +fn locate(cs: &[Container]) -> HashMap { + cs.iter().enumerate().flat_map(|(i, c)| c.store.iter().map(move |e| (e.handle, i))).collect() +} + +/// Anonymous blocks of `a` whose entities (by handle) are, at least half of them, in another +/// anonymous block of `b`: saving renamed them (`*D344` → `*D10`). Upper-case names. +fn anonymous_renames(ca: &[Container], cb: &[Container], where_b: &HashMap) -> HashMap { + let mut renamed = HashMap::new(); + let mut taken: HashSet = HashSet::new(); + for c in ca { + let Some(name) = c.key.strip_prefix("BLOCK ").filter(|n| n.starts_with('*')) else { continue }; + if c.store.is_empty() { + continue; + } + let mut votes: BTreeMap = BTreeMap::new(); + for e in c.store.iter() { + if let Some(j) = where_b.get(&e.handle) { + *votes.entry(*j).or_default() += 1; + } + } + let best = votes.into_iter().max_by(|x, y| x.1.cmp(&y.1).then(y.0.cmp(&x.0))); + let Some((j, n)) = best else { continue }; + let Some(target) = cb.get(j).and_then(|t| t.key.strip_prefix("BLOCK ")) else { continue }; + if n.saturating_mul(2) >= c.store.len() && target != name && target.starts_with('*') && taken.insert(j) { + renamed.insert(name.to_string(), target.to_string()); + } + } + renamed +} + +struct Ctx<'d> { + a: &'d Drawing, + b: &'d Drawing, + cb: &'d [Container<'d>], + where_a: &'d HashMap, + where_b: &'d HashMap, +} + +fn compare_entities(a: &Drawing, b: &Drawing, out: &mut Out) { + let ca = containers(a); + let cb = containers(b); + let where_a = locate(&ca); + let where_b = locate(&cb); + out.renamed = anonymous_renames(&ca, &cb, &where_b); + let index_b: HashMap<&str, usize> = cb.iter().enumerate().map(|(i, c)| (c.key.as_str(), i)).collect(); + let target = |c: &Container| match c.key.strip_prefix("BLOCK ").and_then(|n| out.renamed.get(n)) { + Some(n) => index_b.get(format!("BLOCK {n}").as_str()).copied(), + None => index_b.get(c.key.as_str()).copied(), + }; + let targets: Vec> = ca.iter().map(target).collect(); + // A block renamed onto the name another block had: that one has no counterpart by name. + let renamed_onto: HashSet = ca + .iter() + .zip(&targets) + .filter(|(c, _)| c.key.strip_prefix("BLOCK ").is_some_and(|n| out.renamed.contains_key(n))) + .filter_map(|(_, t)| *t) + .collect(); + let ctx = Ctx { a, b, cb: &cb, where_a: &where_a, where_b: &where_b }; + let empty = EntityStore::new(); + let mut matched: HashSet = HashSet::new(); + let mut moves: BTreeMap<(String, String), Vec> = BTreeMap::new(); + let referenced = referenced_blocks(&ca); + let mut orphan_entities = 0usize; + for (c, t) in ca.iter().zip(&targets) { + let renamed = c.key.strip_prefix("BLOCK ").is_some_and(|n| out.renamed.contains_key(n)); + let j = t.filter(|j| renamed || !renamed_onto.contains(j)).filter(|j| matched.insert(*j)); + if j.is_none() + && let Some(name) = c.key.strip_prefix("BLOCK ").filter(|n| n.starts_with('*') && !referenced.contains(*n)) + && c.store.iter().all(|e| !where_b.contains_key(&e.handle)) + { + out.orphans.insert(name.to_string()); + orphan_entities = orphan_entities.saturating_add(c.store.len()); + continue; + } + let sb = j.and_then(|j| cb.get(j)).map_or(&empty, |x| x.store); + compare_store(&c.name, c.store, sb, &ctx, &mut moves, out); + } + if let Some(first) = out.orphans.first().cloned() { + let n = out.orphans.len(); + let detail = format!("{orphan_entities} entities of {n} anonymous blocks nothing refers to (e.g. {first}) were not saved"); + out.push_n(Category::Count, Change::Lost, orphan_entities, "unreferenced anonymous blocks", detail); + } + for (j, c) in cb.iter().enumerate() { + if !matched.contains(&j) { + compare_store(&c.name, &empty, c.store, &ctx, &mut moves, out); + } + } + for ((from, to), hs) in moves { + let detail = format!("{} entities moved from {from} to {to} ({})", hs.len(), hex_list(hs.iter().copied(), 6)); + out.push_n(Category::Handle, Change::Changed, hs.len(), from, detail); + } +} + +/// The blocks a drawing's entities refer to (block references, dimensions, multileaders), upper +/// case. +fn referenced_blocks(cs: &[Container]) -> HashSet { + let mut out = HashSet::new(); + for e in cs.iter().flat_map(|c| c.store.iter()) { + match &e.kind { + EntityKind::Insert(i) => { + out.insert(i.block.to_ascii_uppercase()); + } + EntityKind::Dimension(d) => out.extend(d.block.as_ref().map(|b| b.to_ascii_uppercase())), + EntityKind::MLeader(m) => out.extend(m.block.as_ref().map(|b| b.block.to_ascii_uppercase())), + _ => {} + } + } + out +} + +fn kind_sig(e: &Entity) -> String { + sig_of(&e.kind) +} + +fn compare_store(name: &str, sa: &EntityStore, sb: &EntityStore, ctx: &Ctx, moves: &mut BTreeMap<(String, String), Vec>, out: &mut Out) { + let ib: HashMap = sb.iter().map(|e| (e.handle, e.as_ref())).collect(); + let ia: HashSet = sa.iter().map(|e| e.handle).collect(); + let mut count_a: BTreeMap = BTreeMap::new(); + let mut count_b: BTreeMap = BTreeMap::new(); + let mut un_a: BTreeMap> = BTreeMap::new(); + let mut un_b: BTreeMap> = BTreeMap::new(); + for e in sa.iter() { + let t = e.kind.dxf_name().to_string(); + *count_a.entry(t.clone()).or_default() += 1; + if let Some(f) = ib.get(&e.handle) { + compare_entity(name, e, f, ctx, out); + } else if let Some(other) = ctx.where_b.get(&e.handle).and_then(|j| ctx.cb.get(*j)) { + moves.entry((name.to_string(), other.name.clone())).or_default().push(e.handle); + if let Some(f) = other.store.get(e.handle) { + compare_entity(name, e, f, ctx, out); + } + } else { + un_a.entry(t).or_default().push(e); + } + } + for e in sb.iter() { + let t = e.kind.dxf_name().to_string(); + *count_b.entry(t.clone()).or_default() += 1; + if !ia.contains(&e.handle) && !ctx.where_a.contains_key(&e.handle) { + un_b.entry(t).or_default().push(e); + } + } + let types: BTreeSet = un_a.keys().chain(un_b.keys()).cloned().collect(); + for t in types { + let xs = un_a.remove(&t).unwrap_or_default(); + let ys = un_b.remove(&t).unwrap_or_default(); + let (pairs, lost, added) = pair_up(xs, ys, kind_sig); + for (x, y) in &pairs { + out.renumber(&format!("{t} entities"), || format!("{} → {} in {name}", x.handle.hex(), y.handle.hex())); + compare_entity(name, x, y, ctx, out); + } + let (na, nb) = (count_a.get(&t).copied().unwrap_or(0), count_b.get(&t).copied().unwrap_or(0)); + if !lost.is_empty() { + let detail = format!("{t}: {na} → {nb} ({} lost: {})", lost.len(), hex_list(lost.iter().map(|e| e.handle), 8)); + out.push_n(Category::Count, Change::Lost, lost.len(), format!("{name} {t}"), detail); + } + if !added.is_empty() { + let detail = format!("{t}: {na} → {nb} ({} added: {})", added.len(), hex_list(added.iter().map(|e| e.handle), 8)); + out.push_n(Category::Count, Change::Added, added.len(), format!("{name} {t}"), detail); + } + } +} + +fn compare_entity(container: &str, x: &Entity, y: &Entity, ctx: &Ctx, out: &mut Out) { + let handles = if x.handle == y.handle { x.handle.hex() } else { format!("{}→{}", x.handle.hex(), y.handle.hex()) }; + let place = format!("{container} {} {handles}", x.kind.dxf_name()); + if std::mem::discriminant(&x.kind) != std::mem::discriminant(&y.kind) || x.kind.dxf_name() != y.kind.dxf_name() { + out.push(Category::Geometry, Change::Changed, place, format!("type {} → {}", x.kind.dxf_name(), y.kind.dxf_name())); + return; + } + match (&x.kind, &y.kind) { + (EntityKind::Unknown(u), EntityKind::Unknown(v)) => { + if let Some(d) = tags_diff(&u.tags, &v.tags, out.opts) { + out.push(Category::Opaque, Change::Changed, place.clone(), d); + } + } + _ => { + let p = diff_ser(&x.kind, &y.kind, &out.norm()); + if !p.is_empty() { + out.push(Category::Geometry, Change::Changed, place.clone(), p.text()); + } + } + } + let common = |e: &Entity| { + let mut v = serde_json::to_value(&e.common).unwrap_or(Value::Null); + if let Value::Object(m) = &mut v { + m.remove("xdata"); + } + v + }; + let mut p = Paths::new(out.opts.max_paths); + diff_values(&common(x), &common(y), &mut String::new(), &out.norm(), &mut p, 0); + if !p.is_empty() { + out.push(Category::Properties, Change::Changed, place.clone(), p.text()); + } + compare_xdata(&place, &x.common.xdata, &y.common.xdata, out); + compare_extra(&place, ctx.a.foreign.entities.get(&x.handle), ctx.b.foreign.entities.get(&y.handle), out); +} + +/// Extended data split per application (from each 1001 group). +fn xdata_apps(tags: &[RawTag]) -> Vec<(String, &[RawTag])> { + let starts: Vec = tags.iter().enumerate().filter(|(_, t)| t.code == 1001).map(|(i, _)| i).collect(); + let mut v = Vec::new(); + for (k, &s) in starts.iter().enumerate() { + let end = starts.get(k + 1).copied().unwrap_or(tags.len()); + let name = tags.get(s).map(|t| t.value.trim().to_ascii_uppercase()).unwrap_or_default(); + v.push((name, tags.get(s..end).unwrap_or(&[]))); + } + if starts.first().is_some_and(|&s| s > 0) || (starts.is_empty() && !tags.is_empty()) { + let end = starts.first().copied().unwrap_or(tags.len()); + v.insert(0, (String::new(), tags.get(..end).unwrap_or(&[]))); + } + v +} + +fn compare_xdata(place: &str, a: &[RawTag], b: &[RawTag], out: &mut Out) { + if a.is_empty() && b.is_empty() { + return; + } + let (xa, xb) = (xdata_apps(a), xdata_apps(b)); + let mb: HashMap<&str, &[RawTag]> = xb.iter().map(|(n, t)| (n.as_str(), *t)).collect(); + let ma: HashSet<&str> = xa.iter().map(|(n, _)| n.as_str()).collect(); + for (name, ta) in &xa { + let label = if name.is_empty() { "(no application)" } else { name }; + match mb.get(name.as_str()) { + None => out.push(Category::Xdata, Change::Lost, place, format!("application {label} ({} groups)", ta.len())), + Some(tb) => { + if let Some(d) = tags_diff(ta, tb, out.opts) { + out.push(Category::Xdata, Change::Changed, place, format!("application {label}: {d}")); + } + } + } + } + for (name, tb) in &xb { + if !ma.contains(name.as_str()) { + let label = if name.is_empty() { "(no application)" } else { name }; + out.push(Category::Xdata, Change::Added, place, format!("application {label} ({} groups)", tb.len())); + } + } +} + +fn compare_extra(place: &str, a: Option<&ForeignExtra>, b: Option<&ForeignExtra>, out: &mut Out) { + let none = ForeignExtra::default(); + let (a, b) = (a.unwrap_or(&none), b.unwrap_or(&none)); + if a == b { + return; + } + match (a.xdict, b.xdict) { + (Some(h), None) => out.push(Category::ExtDict, Change::Lost, place, format!("extension dictionary {}", h.hex())), + (None, Some(h)) => out.push(Category::ExtDict, Change::Added, place, format!("extension dictionary {}", h.hex())), + (Some(h), Some(k)) if h != k => out.renumber("extension dictionaries", || format!("{} → {} of {place}", h.hex(), k.hex())), + _ => {} + } + if a.reactors.len() > b.reactors.len() { + let n = a.reactors.len() - b.reactors.len(); + out.push_n(Category::ExtDict, Change::Lost, n, place, format!("reactors: {} → {}", a.reactors.len(), b.reactors.len())); + } else if b.reactors.len() > a.reactors.len() { + let n = b.reactors.len() - a.reactors.len(); + out.push_n(Category::ExtDict, Change::Added, n, place, format!("reactors: {} → {}", a.reactors.len(), b.reactors.len())); + } + compare_xdata(place, &a.xdata, &b.xdata, out); + if a.color_book != b.color_book { + let show = |c: &Option<(String, String)>| c.as_ref().map_or("(none)".to_string(), |(book, tc)| format!("`{}` ({tc})", clip(book, 40))); + let change = match (&a.color_book, &b.color_book) { + (Some(_), None) => Change::Lost, + (None, Some(_)) => Change::Added, + _ => Change::Changed, + }; + out.push(Category::Properties, change, place, format!("colour book colour {} → {}", show(&a.color_book), show(&b.color_book))); + } + if let Some(d) = tags_diff(&a.props, &b.props, out.opts) { + out.push(Category::Properties, Change::Changed, place, format!("other property groups (material, shadows…): {d}")); + } +} + +// --------------------------------------------------------------------------------------------- +// Tables, blocks, layouts + +/// Compare two lists of named records, matched by name without case. +fn compare_named(out: &mut Out, cat: Category, kind: &str, a: &[&T], b: &[&T], name: impl Fn(&T) -> &str) { + let mut mb: HashMap = HashMap::new(); + for y in b.iter().rev() { + mb.insert(name(y).to_ascii_uppercase(), *y); + } + let mut seen: HashSet = HashSet::new(); + for x in a { + let key = name(x).to_ascii_uppercase(); + if !seen.insert(key.clone()) { + continue; + } + let place = format!("{kind} {}", name(x)); + match mb.get(&key) { + None => out.push(cat, Change::Lost, place, String::new()), + Some(y) => { + let p = diff_ser(*x, *y, &out.norm()); + if !p.is_empty() { + out.push(cat, Change::Changed, place, p.text()); + } + } + } + } + let mut seen_b: HashSet = HashSet::new(); + for y in b { + let key = name(y).to_ascii_uppercase(); + if !seen.contains(&key) && seen_b.insert(key) { + out.push(cat, Change::Added, format!("{kind} {}", name(y)), String::new()); + } + } +} + +fn refs(v: &[T]) -> Vec<&T> { + v.iter().collect() +} + +fn compare_tables(a: &Drawing, b: &Drawing, out: &mut Out) { + use Category::{Block, Layout, Table}; + compare_named(out, Table, "LAYER", &refs(&a.layers), &refs(&b.layers), |x| &x.name); + compare_named(out, Table, "LTYPE", &refs(&a.linetypes), &refs(&b.linetypes), |x| &x.name); + compare_named(out, Table, "STYLE", &refs(&a.text_styles), &refs(&b.text_styles), |x| &x.name); + compare_named(out, Table, "DIMSTYLE", &refs(&a.dim_styles), &refs(&b.dim_styles), |x| &x.name); + compare_named(out, Table, "MLEADERSTYLE", &refs(&a.mleader_styles), &refs(&b.mleader_styles), |x| &x.name); + compare_named(out, Table, "TABLESTYLE", &refs(&a.table_styles), &refs(&b.table_styles), |x| &x.name); + compare_named(out, Table, "MLINESTYLE", &refs(&a.mline_styles), &refs(&b.mline_styles), |x| &x.name); + compare_named(out, Table, "VIEW", &refs(&a.views), &refs(&b.views), |x| &x.name); + compare_named(out, Table, "VPORT", &refs(&a.vports), &refs(&b.vports), |x| &x.name); + compare_named(out, Table, "UCS", &refs(&a.ucss), &refs(&b.ucss), |x| &x.name); + compare_named(out, Table, "LAYERSTATE", &refs(&a.layer_states), &refs(&b.layer_states), |x| &x.name); + compare_named(out, Table, "GROUP", &refs(&a.groups), &refs(&b.groups), |x| &x.name); + compare_named(out, Table, "SCALE", &refs(&a.scales), &refs(&b.scales), |x| &x.name); + compare_named(out, Table, "PLOTSTYLE", &refs(&a.plot_style_tables), &refs(&b.plot_style_tables), |x| &x.name); + // Blocks: renamed anonymous blocks are compared with what they were saved as. + let renamed_to: HashSet = out.renamed.values().cloned().collect(); + let ba: Vec<&cadcraft_doc::Block> = a + .blocks + .values() + .map(|x| x.as_ref()) + .filter(|x| { + let up = x.name.to_ascii_uppercase(); + !out.renamed.contains_key(&up) && !out.orphans.contains(&up) + }) + .collect(); + if let Some(first) = out.orphans.first().cloned() { + let n = out.orphans.len(); + out.push_n( + Block, + Change::Lost, + n, + "unreferenced anonymous blocks", + format!("{n} anonymous blocks nothing refers to (e.g. {first}) were not saved"), + ); + } + let bb: Vec<&cadcraft_doc::Block> = + b.blocks.values().map(|x| x.as_ref()).filter(|x| !renamed_to.contains(&x.name.to_ascii_uppercase())).collect(); + let mut pairs: Vec<(&cadcraft_doc::Block, &cadcraft_doc::Block)> = Vec::new(); + for (from, to) in &out.renamed { + if let (Some(x), Some(y)) = (a.block(from), b.block(to)) { + pairs.push((x.as_ref(), y.as_ref())); + } + } + compare_named(out, Block, "BLOCK", &ba, &bb, |x| &x.name); + pairs.sort_by(|x, y| x.0.name.cmp(&y.0.name)); + if let Some((x, y)) = pairs.first() { + let detail = format!("{} anonymous blocks saved under new names (e.g. {} → {})", pairs.len(), x.name, y.name); + out.push_n(Block, Change::Changed, pairs.len(), "anonymous blocks", detail); + } + for (x, y) in pairs { + let p = diff_ser(x, y, &out.norm()); + if !p.is_empty() { + out.push(Block, Change::Changed, format!("BLOCK {} → {}", x.name, y.name), p.text()); + } + } + compare_named(out, Layout, "LAYOUT", &refs(&a.layouts), &refs(&b.layouts), |x| &x.name); + for (place, p) in + [("CONSTRAINTS", diff_ser(&a.constraints, &b.constraints, &out.norm())), ("PARAMETERS", diff_ser(&a.parametric, &b.parametric, &out.norm()))] + { + if !p.is_empty() { + out.push(Category::Object, Change::Changed, place, p.text()); + } + } +} + +// --------------------------------------------------------------------------------------------- +// Data kept without modelling it + +fn class_name(c: &[RawTag]) -> String { + c.iter().find(|t| t.code == 1).map(|t| t.value.trim().to_string()).unwrap_or_default() +} + +/// A CLASS record without its instance count (group 91), which follows the objects written. +fn class_groups(c: &[RawTag]) -> Vec { + c.iter().filter(|t| t.code != 91).cloned().collect() +} + +fn compare_foreign(a: &Foreign, b: &Foreign, out: &mut Out) { + let o = out.opts; + type Obj = cadcraft_doc::foreign::ForeignObject; + // Objects, by handle, then by content. + let ib: HashMap = b.objects.iter().map(|x| (x.handle, x)).collect(); + let ia: HashSet = a.objects.iter().map(|x| x.handle).collect(); + let mut un_a: BTreeMap> = BTreeMap::new(); + let mut un_b: BTreeMap> = BTreeMap::new(); + for x in &a.objects { + match ib.get(&x.handle) { + Some(y) if y.kind != x.kind => { + out.push(Category::Object, Change::Changed, format!("{} {}", x.kind, x.handle.hex()), format!("type {} → {}", x.kind, y.kind)) + } + Some(y) => { + if let Some(d) = tags_diff(&x.tags, &y.tags, o) { + out.push(Category::Object, Change::Changed, format!("{} {}", x.kind, x.handle.hex()), d); + } + } + None => un_a.entry(x.kind.clone()).or_default().push(x), + } + } + for y in &b.objects { + if !ia.contains(&y.handle) { + un_b.entry(y.kind.clone()).or_default().push(y); + } + } + // Content without handles, so renumbered objects pair up. + let content = |x: &Obj| sig_of(&x.tags.iter().filter(|t| !is_handle_code(t.code)).map(|t| (t.code, &t.value)).collect::>()); + let kinds: BTreeSet = un_a.keys().chain(un_b.keys()).cloned().collect(); + for k in kinds { + let xs = un_a.remove(&k).unwrap_or_default(); + let ys = un_b.remove(&k).unwrap_or_default(); + let (pairs, lost, added) = pair_up(xs, ys, content); + for (x, y) in &pairs { + out.renumber(&format!("{k} objects"), || format!("{} → {}", x.handle.hex(), y.handle.hex())); + if let Some(d) = tags_diff(&x.tags, &y.tags, o) { + out.push(Category::Object, Change::Changed, format!("{k} {}→{}", x.handle.hex(), y.handle.hex()), d); + } + } + if !lost.is_empty() { + out.push_n( + Category::Object, + Change::Lost, + lost.len(), + format!("objects {k}"), + format!("{} lost: {}", lost.len(), hex_list(lost.iter().map(|x| x.handle), 8)), + ); + } + if !added.is_empty() { + out.push_n( + Category::Object, + Change::Added, + added.len(), + format!("objects {k}"), + format!("{} added: {}", added.len(), hex_list(added.iter().map(|x| x.handle), 8)), + ); + } + } + // Named object dictionary entries. + let db: HashMap = b.dictionary.iter().map(|(k, h)| (k.to_ascii_uppercase(), *h)).collect(); + let da: HashSet = a.dictionary.iter().map(|(k, _)| k.to_ascii_uppercase()).collect(); + for (k, h) in &a.dictionary { + match db.get(&k.to_ascii_uppercase()) { + None => out.push(Category::Dictionary, Change::Lost, format!("NOD {k}"), format!("entry for {}", h.hex())), + Some(g) if g != h => out.renumber("dictionary entries", || format!("{k}: {} → {}", h.hex(), g.hex())), + Some(_) => {} + } + } + for (k, h) in &b.dictionary { + if !da.contains(&k.to_ascii_uppercase()) { + out.push(Category::Dictionary, Change::Added, format!("NOD {k}"), format!("entry for {}", h.hex())); + } + } + // CLASS records. + let cb: HashMap> = b.classes.iter().map(|c| (class_name(c).to_ascii_uppercase(), c)).collect(); + let ca: HashSet = a.classes.iter().map(|c| class_name(c).to_ascii_uppercase()).collect(); + for c in &a.classes { + let n = class_name(c); + match cb.get(&n.to_ascii_uppercase()) { + None => out.push(Category::Class, Change::Lost, format!("CLASS {n}"), String::new()), + Some(d) => { + if let Some(t) = tags_diff(&class_groups(c), &class_groups(d), o) { + out.push(Category::Class, Change::Changed, format!("CLASS {n}"), t); + } + } + } + } + for c in &b.classes { + let n = class_name(c); + if !ca.contains(&n.to_ascii_uppercase()) { + out.push(Category::Class, Change::Added, format!("CLASS {n}"), String::new()); + } + } + // Extras of table records, tables and blocks (renamed anonymous blocks by their new name). + let key_of = |k: &(String, String)| -> (String, String) { + match out.renamed.get(&k.1.to_ascii_uppercase()) { + Some(n) if k.0.starts_with("BLOCK") => (k.0.clone(), n.clone()), + _ => k.clone(), + } + }; + let ra: BTreeMap<(String, String), &ForeignExtra> = a.records.iter().map(|(k, v)| (key_of(k), v)).collect(); + let rb: BTreeMap<(String, String), &ForeignExtra> = b.records.iter().map(|(k, v)| ((k.0.clone(), k.1.to_ascii_uppercase()), v)).collect(); + let ra: BTreeMap<(String, String), &ForeignExtra> = ra.into_iter().map(|((k0, k1), v)| ((k0, k1.to_ascii_uppercase()), v)).collect(); + let keys: BTreeSet<&(String, String)> = ra.keys().chain(rb.keys()).collect(); + for k in keys { + compare_extra(&format!("{} {}", k.0, k.1), ra.get(k).copied(), rb.get(k).copied(), out); + } + // The data store (ACIS data of 2013+ files). + if let Some(d) = tags_diff(&a.data_store, &b.data_store, o) { + let change = match (a.data_store.is_empty(), b.data_store.is_empty()) { + (false, true) => Change::Lost, + (true, false) => Change::Added, + _ => Change::Changed, + }; + out.push(Category::Object, change, "ACDSDATA", d); + } +} + +// --------------------------------------------------------------------------------------------- +// Header + +fn compare_header(a: &Drawing, b: &Drawing, out: &mut Out) { + let skip = |k: &str| VOLATILE_HEADER.contains(&k); + for (k, va) in &a.header.vars { + if skip(k) { + continue; + } + let place = format!("${k}"); + match b.header.vars.get(k) { + None => out.push(Category::Header, Change::Lost, place, va.display()), + Some(vb) => { + let p = diff_ser(va, vb, &out.norm()); + if !p.is_empty() { + out.push(Category::Header, Change::Changed, place, format!("{} → {}", clip(&va.display(), 60), clip(&vb.display(), 60))); + } + } + } + } + for (k, vb) in &b.header.vars { + if !skip(k) && !a.header.vars.contains_key(k) { + out.push(Category::Header, Change::Added, format!("${k}"), vb.display()); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/io/src/roundtrip/census.rs b/crates/io/src/roundtrip/census.rs new file mode 100644 index 000000000..bf0d4488e --- /dev/null +++ b/crates/io/src/roundtrip/census.rs @@ -0,0 +1,212 @@ +//! What a DXF file holds, counted from its groups, and the same counts of a drawing read from it: +//! together they show what opening a file leaves out (the DXF rendition of a DWG for DWG files). + +use std::collections::{BTreeMap, HashSet}; + +use cadcraft_doc::Drawing; +use serde::Serialize; + +use super::{Category, Change, Comparison, Options, Out}; + +/// Counts of what a file (or a drawing) holds. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Census { + /// Entities of model space and every layout, per DXF type. + pub entities: BTreeMap, + /// Entities of block definitions (other than the model and paper space blocks), per type. + pub block_entities: BTreeMap, + /// Block definitions other than the model and paper space blocks and the generated ones. + pub blocks: usize, + /// Blocks CADCraft generates and so doesn't read (tables' blocks, standard arrowheads + /// nothing inserts); their entities are not counted. + pub generated_blocks: usize, + /// Table records per table type (LAYER, LTYPE, STYLE, DIMSTYLE, VIEW, UCS…). + pub tables: BTreeMap, + /// Non-graphical objects per type. For a drawing: only those kept without being modelled. + pub objects: BTreeMap, + /// CLASS records. For a drawing: only those kept for unmodelled objects. + pub classes: usize, +} + +/// Records that belong to the record before them (or delimit blocks), not entities of their own. +const SUB_RECORDS: &[&str] = &["VERTEX", "SEQEND", "ATTRIB", "BLOCK", "ENDBLK"]; + +fn bump(m: &mut BTreeMap, k: &str) { + let n = m.entry(k.to_string()).or_insert(0); + *n = n.saturating_add(1); +} + +/// A layout's own paper-space viewport (VIEWPORT with ID 1, group 69): part of the layout, not +/// an entity of its own for CADCraft. +fn is_overall_viewport(t: &str, g: &[cadcraft_dxf::Tag]) -> bool { + t == "VIEWPORT" && g.iter().any(|x| x.code == 69 && x.i64() == 1) +} + +fn is_space_block(name: &str) -> bool { + let up = name.trim().to_ascii_uppercase(); + up.starts_with("*MODEL_SPACE") || up.starts_with("*PAPER_SPACE") +} + +/// Count what a DXF file (ASCII or binary) holds; `None` when it can't be parsed. +pub fn census(dxf: &[u8]) -> Option { + let tags = cadcraft_dxf::parse(dxf).ok()?; + let mut c = Census::default(); + // Blocks CADCraft generates (tables' blocks, standard arrowheads nothing inserts) are left out + // on read and rebuilt on save: counted apart. + let mut table_blocks: HashSet = HashSet::new(); + let mut inserted: HashSet = HashSet::new(); + let mut blocks: Vec<(String, BTreeMap)> = Vec::new(); + let mut note_refs = |t: &str, g: &[cadcraft_dxf::Tag]| { + let name = || g.iter().find(|x| x.code == 2).map(|x| x.str().trim().to_ascii_uppercase()); + match t { + "ACAD_TABLE" => table_blocks.extend(name()), + "INSERT" => inserted.extend(name()), + _ => {} + } + }; + for s in cadcraft_dxf::sections(&tags) { + let records = cadcraft_dxf::records(&s.tags); + match s.name.trim().to_ascii_uppercase().as_str() { + "ENTITIES" => { + for (t, g) in &records { + note_refs(t, g); + if !SUB_RECORDS.contains(&t.as_str()) && !is_overall_viewport(t, g) { + bump(&mut c.entities, t); + } + } + } + "BLOCKS" => { + let mut space = false; + for (t, g) in &records { + note_refs(t, g); + match t.as_str() { + "BLOCK" => { + let name = g.iter().find(|x| x.code == 2).map(cadcraft_dxf::Tag::str).unwrap_or_default(); + space = is_space_block(&name); + if !space { + blocks.push((name.trim().to_ascii_uppercase(), BTreeMap::new())); + } + } + t if SUB_RECORDS.contains(&t) || is_overall_viewport(t, g) => {} + t if space => bump(&mut c.entities, t), + t => { + if let Some((_, m)) = blocks.last_mut() { + bump(m, t); + } + } + } + } + } + "TABLES" => { + for (t, _) in &records { + if t != "TABLE" && t != "ENDTAB" { + bump(&mut c.tables, t); + } + } + } + "OBJECTS" => { + for (t, _) in &records { + bump(&mut c.objects, t); + } + } + "CLASSES" => c.classes = c.classes.saturating_add(records.iter().filter(|(t, _)| t == "CLASS").count()), + _ => {} + } + } + for (name, m) in blocks { + if table_blocks.contains(&name) || (crate::dxf_ext::is_standard_arrow(&name) && !inserted.contains(&name)) { + c.generated_blocks = c.generated_blocks.saturating_add(1); + continue; + } + c.blocks = c.blocks.saturating_add(1); + for (t, n) in m { + let slot = c.block_entities.entry(t).or_insert(0); + *slot = slot.saturating_add(n); + } + } + Some(c) +} + +/// The same counts of a drawing: its entities, blocks and table records, and the objects and +/// classes it keeps without modelling them. +pub fn census_of(d: &Drawing) -> Census { + let mut c = Census::default(); + for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())) { + bump(&mut c.entities, e.kind.dxf_name()); + } + for b in d.blocks.values() { + for e in b.entities.iter() { + bump(&mut c.block_entities, e.kind.dxf_name()); + } + } + c.blocks = d.blocks.len(); + for (t, n) in [ + ("LAYER", d.layers.len()), + ("LTYPE", d.linetypes.len()), + ("STYLE", d.text_styles.len()), + ("DIMSTYLE", d.dim_styles.len()), + ("VIEW", d.views.len()), + ("UCS", d.ucss.len()), + ] { + c.tables.insert(t.to_string(), n); + } + for o in &d.foreign.objects { + bump(&mut c.objects, &o.kind); + } + c.classes = d.foreign.classes.len(); + c +} + +/// Polylines may change between the old-style POLYLINE and LWPOLYLINE when read: counted +/// together. +fn merged(m: &BTreeMap) -> BTreeMap { + let mut out = BTreeMap::new(); + for (k, n) in m { + let key = if k == "POLYLINE" || k == "LWPOLYLINE" { "POLYLINE+LWPOLYLINE" } else { k.as_str() }; + let slot = out.entry(key.to_string()).or_insert(0usize); + *slot = slot.saturating_add(*n); + } + out +} + +fn compare_counts(out: &mut Out, place: &str, file: &BTreeMap, read: &BTreeMap) { + let (file, read) = (merged(file), merged(read)); + let keys: std::collections::BTreeSet<&String> = file.keys().chain(read.keys()).collect(); + for k in keys { + let (f, r) = (file.get(k).copied().unwrap_or(0), read.get(k).copied().unwrap_or(0)); + if r < f { + out.push_n(Category::Read, Change::Lost, f - r, format!("{place} {k}"), format!("{k}: {f} in the file, {r} read")); + } else if r > f { + out.push_n(Category::Read, Change::Added, r - f, format!("{place} {k}"), format!("{k}: {f} in the file, {r} read")); + } + } +} + +/// What a drawing read from a file holds less (or more) than the file: entities per type in the +/// spaces and in blocks, blocks, and the table records CADCraft models. Blocks CADCraft generates +/// (tables' blocks, unused standard arrowheads) are left out on both sides. +pub fn compare_census(file: &Census, d: &Drawing, opts: &Options) -> Comparison { + let read = census_of(d); + let mut out = Out::new(opts); + compare_counts(&mut out, "spaces", &file.entities, &read.entities); + compare_counts(&mut out, "blocks", &file.block_entities, &read.block_entities); + if file.blocks != read.blocks { + let change = if read.blocks < file.blocks { Change::Lost } else { Change::Added }; + out.push_n( + Category::Read, + change, + file.blocks.abs_diff(read.blocks), + "BLOCK definitions", + format!("{} in the file, {} read", file.blocks, read.blocks), + ); + } + for t in ["LAYER", "LTYPE", "STYLE", "DIMSTYLE", "VIEW", "UCS"] { + let (f, r) = (file.tables.get(t).copied().unwrap_or(0), read.tables.get(t).copied().unwrap_or(0)); + if f != r { + let change = if r < f { Change::Lost } else { Change::Added }; + out.push_n(Category::Read, change, f.abs_diff(r), format!("{t} table"), format!("{f} records in the file, {r} read")); + } + } + out.cmp +} diff --git a/crates/io/src/roundtrip/corpus.rs b/crates/io/src/roundtrip/corpus.rs new file mode 100644 index 000000000..72f78ce53 --- /dev/null +++ b/crates/io/src/roundtrip/corpus.rs @@ -0,0 +1,651 @@ +//! The corpus harness: every DXF and DWG file of a folder is opened, saved as DXF and as DWG, +//! reopened and compared with the drawing first opened; the findings go to a Markdown and a JSON +//! report. A file that fails, or even makes CADCraft panic, is a reported failure: each stage runs +//! under `catch_unwind` here, as a last resort of the harness only. + +use std::collections::BTreeMap; +use std::panic::AssertUnwindSafe; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use cadcraft_doc::Drawing; +use serde::Serialize; + +use super::{Category, Census, Change, Comparison, Options, Tally, census, census_of, clip, compare, compare_census}; + +/// A drawing file format the harness checks. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Format { + Dxf, + Dwg, +} + +impl Format { + pub fn ext(self) -> &'static str { + match self { + Format::Dxf => "dxf", + Format::Dwg => "dwg", + } + } + pub fn label(self) -> &'static str { + match self { + Format::Dxf => "DXF", + Format::Dwg => "DWG", + } + } + /// The format of a file's bytes: DWG by its magic, otherwise DXF. + pub fn of(bytes: &[u8]) -> Format { + if cadcraft_dwg::is_dwg(bytes) { Format::Dwg } else { Format::Dxf } + } + fn other(self) -> Format { + match self { + Format::Dxf => Format::Dwg, + Format::Dwg => Format::Dxf, + } + } +} + +/// How the harness runs. +#[derive(Clone, Debug, PartialEq)] +pub struct CorpusOptions { + pub compare: Options, + /// Also save in the other format (DWG → DXF, DXF → DWG). + pub cross_format: bool, + /// Count what each file holds, to report what opening it leaves out. + pub census: bool, + /// Keep the saved files in this folder (and reopen them from there). + pub keep_saved: Option, +} + +impl Default for CorpusOptions { + fn default() -> Self { + CorpusOptions { compare: Options::default(), cross_format: true, census: true, keep_saved: None } + } +} + +/// Largest file the harness opens. +pub const MAX_FILE_BYTES: u64 = 1 << 30; +/// Deepest folder nesting walked. +const MAX_DEPTH: usize = 32; +/// Most files taken from one corpus. +const MAX_FILES: usize = 100_000; + +/// One save → reopen of a drawing. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RouteReport { + /// `dwg → dxf`. + pub route: String, + pub saved_bytes: usize, + /// Where the saved file was kept, when it was. + #[serde(skip_serializing_if = "Option::is_none")] + pub saved_path: Option, + pub save_error: Option, + pub reopen_error: Option, + /// What reopening reported (records the reader couldn't place or decode). + pub reopen_notes: Vec, + /// What the writer itself left out of the saved file: records per DXF type (upper case) it + /// can't write in that format (for DWG: other programs' custom entities and objects). Each + /// is lost; the reopened drawing's entity counts show the same entities missing, and a strict + /// corpus run fails on any. + pub not_written: BTreeMap, + /// The reopened drawing against the drawing first opened. + pub comparison: Comparison, + pub seconds: f64, +} + +impl RouteReport { + pub fn ok(&self) -> bool { + self.save_error.is_none() && self.reopen_error.is_none() + } + /// Saved and reopened with no difference at all. + pub fn lossless(&self) -> bool { + self.ok() && self.not_written.is_empty() && self.comparison.is_empty() + } + /// How many records the writer left out ([`Self::not_written`]). + pub fn not_written_total(&self) -> usize { + self.not_written.values().fold(0usize, |a, n| a.saturating_add(*n)) + } +} + +/// `2 ACME_WIDGET, 1 OLE2FRAME`. +fn per_type(m: &BTreeMap) -> String { + m.iter().map(|(t, n)| format!("{n} {t}")).collect::>().join(", ") +} + +/// Everything found for one file. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileReport { + /// The path relative to the corpus folder. + pub path: String, + pub format: Option, + /// `AC1032` for a DWG, the `$ACADVER` of a DXF. + pub version: String, + pub bytes: u64, + pub open_error: Option, + /// What opening reported (a DWG's records the reader skipped, damaged records). + pub open_notes: Vec, + pub open_seconds: f64, + /// What the file holds (for a DWG: its DXF rendition), when counted. + pub file_census: Option, + /// What the drawing read from it holds. + pub drawing_census: Option, + /// What the drawing holds less or more than the file. + pub read: Comparison, + pub routes: Vec, +} + +impl FileReport { + pub fn opened(&self) -> bool { + self.open_error.is_none() + } +} + +impl CorpusReport { + /// What makes a strict corpus run fail, one line each: a file that didn't open, a round trip + /// that didn't save or reopen, and records a writer left out ([`RouteReport::not_written`]). + /// Other differences are reported, not failed on. + pub fn strict_failures(&self) -> Vec { + let mut out = Vec::new(); + for f in &self.files { + if !f.opened() { + out.push(format!("{}: failed to open", f.path)); + } + for r in &f.routes { + if !r.ok() { + out.push(format!("{} ({}): failed to save or reopen", f.path, r.route)); + } + if !r.not_written.is_empty() { + out.push(format!("{} ({}): lost on save, not written: {}", f.path, r.route, per_type(&r.not_written))); + } + } + } + out + } +} + +/// The whole corpus run. +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CorpusReport { + pub corpus: String, + /// UTC, `2026-10-21 09:30`. + pub generated: String, + pub cadcraft_version: String, + pub abs_tol: f64, + pub rel_tol: f64, + pub files: Vec, +} + +/// Run `f`, turning a panic into an error message. +fn guard(f: impl FnOnce() -> T) -> Result { + std::panic::catch_unwind(AssertUnwindSafe(f)).map_err(|p| { + let msg = + p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::().cloned()).unwrap_or_else(|| "no message".into()); + format!("CRASH (panic): {msg}") + }) +} + +/// A drawing's notes on what reading it left out. +fn notes(d: &Drawing) -> Vec { + let mut v = d.read_notes.clone(); + for (section, n) in &d.skipped_records { + v.push(format!("{n} record(s) of the {section} section couldn't be placed and were skipped")); + } + v +} + +/// Save `d` as `to`, reopen it and compare. `keep` is the file to keep the saved bytes in (and +/// reopen them from). +pub fn round_trip(d: &Drawing, from: Format, to: Format, opts: &Options, keep: Option<&Path>) -> RouteReport { + let start = Instant::now(); + let mut r = RouteReport { route: format!("{} → {}", from.ext(), to.ext()), ..RouteReport::default() }; + let name = format!("roundtrip.{}", to.ext()); + let saved = match guard(|| crate::write_noted(d, &name, &crate::SaveOptions::default())) { + Ok(Ok((b, not_written))) => { + r.not_written = not_written; + b + } + Ok(Err(e)) => { + r.save_error = Some(e.to_string()); + r.seconds = start.elapsed().as_secs_f64(); + return r; + } + Err(e) => { + r.save_error = Some(e); + r.seconds = start.elapsed().as_secs_f64(); + return r; + } + }; + r.saved_bytes = saved.len(); + let mut bytes = saved; + if let Some(path) = keep { + let kept = path.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|_| std::fs::write(path, &bytes)).and_then(|_| std::fs::read(path)); + match kept { + Ok(b) => { + bytes = b; + r.saved_path = Some(path.display().to_string()); + } + Err(e) => r.reopen_notes.push(format!("couldn't keep the saved file at {}: {e}", path.display())), + } + } + let reopened = match guard(|| crate::read(&bytes, &name)) { + Ok(Ok(d2)) => d2, + Ok(Err(e)) => { + r.reopen_error = Some(e.to_string()); + r.seconds = start.elapsed().as_secs_f64(); + return r; + } + Err(e) => { + r.reopen_error = Some(e); + r.seconds = start.elapsed().as_secs_f64(); + return r; + } + }; + r.reopen_notes.extend(notes(&reopened)); + match guard(|| compare(d, &reopened, opts)) { + Ok(c) => r.comparison = c, + Err(e) => r.reopen_error = Some(format!("comparing: {e}")), + } + attribute_unwritten(&mut r, to); + r.seconds = start.elapsed().as_secs_f64(); + r +} + +/// Say on the lost entity rows of a type the writer couldn't write that this is why they are +/// lost, so a writer's gap reads as one and isn't taken for a reader's or a comparison's. +fn attribute_unwritten(r: &mut RouteReport, to: Format) { + if r.not_written.is_empty() { + return; + } + for d in r.comparison.differences.iter_mut().filter(|d| d.category == Category::Count && d.change == Change::Lost) { + if let Some(t) = r.not_written.keys().find(|t| d.detail.starts_with(&format!("{t}: "))) { + d.detail.push_str(&format!(" (not written: the {} writer can't write {t})", to.label())); + } + } +} + +/// The kept saved file of `rel` saved as `to`, in `dir`. +fn kept_path(dir: &Path, rel: &str, to: Format) -> PathBuf { + let flat: String = rel.chars().map(|c| if matches!(c, '/' | '\\' | ':') { '_' } else { c }).collect(); + dir.join(format!("{flat}.roundtrip.{}", to.ext())) +} + +/// Check one file's bytes: open, count, save in each format, reopen, compare. `rel` names it in +/// the report. +pub fn check_bytes(bytes: &[u8], rel: &str, opts: &CorpusOptions) -> FileReport { + let format = Format::of(bytes); + let mut f = FileReport { path: rel.to_string(), format: Some(format), bytes: bytes.len() as u64, ..FileReport::default() }; + if format == Format::Dwg { + f.version = cadcraft_dwg::version(bytes).unwrap_or_default(); + } + let start = Instant::now(); + let name = format!("source.{}", format.ext()); + let opened = guard(|| crate::read_source(bytes, &name)); + f.open_seconds = start.elapsed().as_secs_f64(); + let (d, dxf) = match opened { + Ok(Ok(x)) => x, + Ok(Err(e)) => { + f.open_error = Some(e.to_string()); + return f; + } + Err(e) => { + f.open_error = Some(e); + return f; + } + }; + if format == Format::Dxf { + f.version = d.header.str("ACADVER", ""); + } + f.open_notes = notes(&d); + f.drawing_census = guard(|| census_of(&d)).ok(); + if opts.census { + let source = dxf.as_deref().unwrap_or(bytes); + match guard(|| census(source)) { + Ok(Some(c)) => { + if let Ok(read) = guard(|| compare_census(&c, &d, &opts.compare)) { + f.read = read; + } + f.file_census = Some(c); + } + Ok(None) => f.open_notes.push("the file's groups couldn't be counted".into()), + Err(e) => f.open_notes.push(format!("counting the file's groups: {e}")), + } + } + let mut targets = vec![format]; + if opts.cross_format { + targets.push(format.other()); + } + for to in targets { + let keep = opts.keep_saved.as_deref().map(|dir| kept_path(dir, rel, to)); + f.routes.push(round_trip(&d, format, to, &opts.compare, keep.as_deref())); + } + f +} + +/// Check one file on disk; `rel` names it in the report. +pub fn check_file(path: &Path, rel: &str, opts: &CorpusOptions) -> FileReport { + let fail = |e: String| FileReport { path: rel.to_string(), open_error: Some(e), ..FileReport::default() }; + match std::fs::metadata(path) { + Ok(m) if m.len() > MAX_FILE_BYTES => return fail(format!("the file is {} bytes, more than the {MAX_FILE_BYTES} the harness opens", m.len())), + Ok(_) => {} + Err(e) => return fail(format!("can't read the file: {e}")), + } + match std::fs::read(path) { + Ok(bytes) => check_bytes(&bytes, rel, opts), + Err(e) => fail(format!("can't read the file: {e}")), + } +} + +/// Whether a path names a DXF or DWG file (by extension). +pub fn is_drawing_file(path: &Path) -> bool { + path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).is_some_and(|e| e == "dxf" || e == "dwg") +} + +/// Every DXF and DWG file under `dir`, sorted, leaving out hidden folders and the folders in +/// `skip` (the report folder). Symbolic links are not followed. +pub fn corpus_files(dir: &Path, skip: &[PathBuf]) -> Vec { + let skip: Vec = skip.iter().map(|p| p.canonicalize().unwrap_or_else(|_| p.clone())).collect(); + let mut out = Vec::new(); + let mut stack = vec![(dir.to_path_buf(), 0usize)]; + while let Some((d, depth)) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&d) else { continue }; + for entry in entries.flatten() { + let path = entry.path(); + let Ok(ft) = entry.file_type() else { continue }; + if ft.is_dir() { + let hidden = entry.file_name().to_string_lossy().starts_with('.'); + let canon = path.canonicalize().unwrap_or_else(|_| path.clone()); + if !hidden && depth < MAX_DEPTH && !skip.contains(&canon) { + stack.push((path, depth + 1)); + } + } else if ft.is_file() && is_drawing_file(&path) && out.len() < MAX_FILES { + out.push(path); + } + } + } + out.sort(); + out +} + +/// `path` relative to `root`, with forward slashes. +pub fn relative(path: &Path, root: &Path) -> String { + let rel = path.strip_prefix(root).unwrap_or(path); + rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect::>().join("/") +} + +/// Check `files` (paths under `root`, which names the corpus in the report), calling `progress` +/// with (index, count, relative path) before each. +pub fn run(root: &Path, files: &[PathBuf], opts: &CorpusOptions, progress: &mut dyn FnMut(usize, usize, &str)) -> CorpusReport { + let mut report = CorpusReport { + corpus: root.display().to_string(), + generated: now_utc(), + cadcraft_version: env!("CARGO_PKG_VERSION").to_string(), + abs_tol: opts.compare.abs_tol, + rel_tol: opts.compare.rel_tol, + files: Vec::new(), + }; + for (i, path) in files.iter().enumerate() { + let rel = relative(path, root); + progress(i, files.len(), &rel); + let f = match guard(|| check_file(path, &rel, opts)) { + Ok(f) => f, + Err(e) => FileReport { path: rel, open_error: Some(e), ..FileReport::default() }, + }; + report.files.push(f); + } + report +} + +/// The current time, UTC, as `2026-10-21 09:30`. +fn now_utc() -> String { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + let days = i64::try_from(secs / 86_400).unwrap_or(0); + let (h, m) = ((secs % 86_400) / 3600, (secs % 3600) / 60); + // Days to a civil date (proleptic Gregorian), after Howard Hinnant's public-domain algorithm. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02} {h:02}:{m:02} UTC") +} + +// --------------------------------------------------------------------------------------------- +// Rendering + +/// Most differences listed per round trip in the Markdown report (all are in the JSON). +const MD_ROWS: usize = 300; + +/// Text for a Markdown table cell. +fn cell(s: &str) -> String { + s.replace('|', "\\|").replace(['\r', '\n'], " ") +} + +fn size(n: u64) -> String { + if n >= 1 << 20 { + format!("{:.1} MB", n as f64 / f64::from(1u32 << 20)) + } else if n >= 1 << 10 { + format!("{:.0} KB", n as f64 / 1024.0) + } else { + format!("{n} B") + } +} + +fn status(err: &Option) -> String { + match err { + None => "ok".into(), + Some(e) if e.starts_with("CRASH") => "**CRASH**".into(), + Some(_) => "**failed**".into(), + } +} + +fn tally_cells(t: Tally) -> String { + format!("{} | {} | {}", t.lost, t.added, t.changed) +} + +impl CorpusReport { + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}")) + } + + /// Totals per category over every round trip. + pub fn totals(&self) -> std::collections::BTreeMap { + let mut all: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for r in self.files.iter().flat_map(|f| f.routes.iter()) { + for (c, t) in &r.comparison.totals { + let slot = all.entry(*c).or_default(); + slot.add(Change::Lost, t.lost); + slot.add(Change::Added, t.added); + slot.add(Change::Changed, t.changed); + } + } + all + } + + pub fn to_markdown(&self) -> String { + let mut s = String::new(); + let opened = self.files.iter().filter(|f| f.opened()).count(); + let routes: Vec<&RouteReport> = self.files.iter().flat_map(|f| f.routes.iter()).collect(); + let save_failed = routes.iter().filter(|r| r.save_error.is_some()).count(); + let reopen_failed = routes.iter().filter(|r| r.reopen_error.is_some()).count(); + let lossless = routes.iter().filter(|r| r.lossless()).count(); + let crashes = self.files.iter().filter(|f| f.open_error.as_deref().is_some_and(|e| e.starts_with("CRASH"))).count() + + routes.iter().filter(|r| [&r.save_error, &r.reopen_error].iter().any(|e| e.as_deref().is_some_and(|e| e.contains("CRASH")))).count(); + s.push_str("# CADCraft round-trip report\n\n"); + s.push_str(&format!("- Corpus: `{}`\n", self.corpus)); + s.push_str(&format!("- Generated: {} by CADCraft {}\n", self.generated, self.cadcraft_version)); + s.push_str(&format!("- Tolerance for numbers: {:e} absolute + {:e} relative\n", self.abs_tol, self.rel_tol)); + s.push_str(&format!( + "- Files: {} ({opened} opened, {} failed to open); round trips: {} ({save_failed} failed to save, {reopen_failed} failed to reopen, {lossless} without any difference); crashes: {crashes}\n", + self.files.len(), + self.files.len() - opened, + routes.len() + )); + let mut unwritten: BTreeMap = BTreeMap::new(); + for r in &routes { + for (t, n) in &r.not_written { + let slot = unwritten.entry(format!("{t} ({})", r.route)).or_insert(0); + *slot = slot.saturating_add(*n); + } + } + if unwritten.is_empty() { + s.push_str("- Lost on save (records a writer can't write): none\n\n"); + } else { + s.push_str(&format!("- **Lost on save** (records a writer can't write): {}\n\n", per_type(&unwritten))); + } + s.push_str( + "Each file is opened, saved in its own format and in the other one, and the saved file is reopened and compared with \ + the drawing first opened. *Read* counts what the file holds that the drawing read from it doesn't (for a DWG: its \ + DXF rendition). Lost/added/changed count items (entities, records, values).\n\n", + ); + s.push_str("## Summary\n\n"); + s.push_str("| File | Format | Size | Open | Read lost | Round trip | Save | Reopen | Not written | Lost | Added | Changed |\n"); + s.push_str("|---|---|---|---|---|---|---|---|---|---|---|---|\n"); + for f in &self.files { + let fmt = f.format.map_or("?".to_string(), |x| format!("{} {}", x.label(), f.version).trim().to_string()); + let open = if f.opened() { format!("ok ({:.1} s)", f.open_seconds) } else { status(&f.open_error) }; + let lead = format!("| `{}` | {} | {} | {} | {} ", cell(&f.path), cell(&fmt), size(f.bytes), open, f.read.tally(Category::Read).lost); + if f.routes.is_empty() { + s.push_str(&format!("{lead}| — | — | — | — | — | — | — |\n")); + } + for (i, r) in f.routes.iter().enumerate() { + let head = if i == 0 { lead.clone() } else { "| | | | | ".to_string() }; + let t = r.comparison.total(); + let reopen = if r.save_error.is_some() { "—".to_string() } else { status(&r.reopen_error) }; + let unwritten = if r.not_written.is_empty() { "0".to_string() } else { format!("**{}**", r.not_written_total()) }; + s.push_str(&format!("{head}| {} | {} | {} | {unwritten} | {} |\n", r.route, status(&r.save_error), reopen, tally_cells(t))); + } + } + s.push_str("\n## By category (all round trips)\n\n| Category | Lost | Added | Changed |\n|---|---|---|---|\n"); + let totals = self.totals(); + for c in Category::ALL { + if let Some(t) = totals.get(&c).filter(|t| t.total() > 0) { + s.push_str(&format!("| {} | {} |\n", c.label(), tally_cells(*t))); + } + } + if totals.values().all(|t| t.total() == 0) { + s.push_str("| (no differences) | 0 | 0 | 0 |\n"); + } + s.push_str("\n## Files\n"); + for f in &self.files { + self.file_markdown(f, &mut s); + } + s + } + + fn file_markdown(&self, f: &FileReport, s: &mut String) { + s.push_str(&format!("\n### `{}`\n\n", f.path)); + let fmt = f.format.map_or("unknown format".to_string(), |x| format!("{} {}", x.label(), f.version).trim().to_string()); + s.push_str(&format!("- {fmt}, {}\n", size(f.bytes))); + match &f.open_error { + Some(e) => { + s.push_str(&format!("- Open: {}: {}\n", status(&f.open_error), cell(e))); + return; + } + None => { + let what = f.drawing_census.as_ref().map_or(String::new(), |c| { + let n: usize = c.entities.values().sum(); + let nb: usize = c.block_entities.values().sum(); + format!( + ": {n} entities in model and paper space, {} blocks holding {nb} entities, {} layers, {} unmodelled objects kept", + c.blocks, + c.tables.get("LAYER").copied().unwrap_or(0), + c.objects.values().sum::() + ) + }); + s.push_str(&format!("- Open: ok in {:.1} s{what}\n", f.open_seconds)); + } + } + for n in &f.open_notes { + s.push_str(&format!("- Note on opening: {}\n", cell(n))); + } + if let Some(c) = &f.file_census + && !c.objects.is_empty() + { + let kept = f.drawing_census.as_ref().map(|d| &d.objects); + let list: Vec = c + .objects + .iter() + .map(|(k, n)| match kept.and_then(|m| m.get(k)) { + Some(m) => format!("{k} {n} ({m} kept as unmodelled)"), + None => format!("{k} {n}"), + }) + .collect(); + s.push_str(&format!("- Objects in the file: {}\n", cell(&list.join(", ")))); + } + if !f.read.is_empty() { + s.push_str("\n#### Read (file → drawing)\n\n"); + diff_table(&f.read, s); + } + for r in &f.routes { + s.push_str(&format!("\n#### {}\n\n", r.route)); + match (&r.save_error, &r.reopen_error) { + (Some(e), _) => s.push_str(&format!("- Save: {}: {}\n", status(&r.save_error), cell(e))), + (None, Some(e)) => { + s.push_str(&format!("- Save: ok ({})\n", size(r.saved_bytes as u64))); + s.push_str(&format!("- Reopen: {}: {}\n", status(&r.reopen_error), cell(e))); + } + (None, None) => { + let t = r.comparison.total(); + s.push_str(&format!( + "- Saved {} and reopened in {:.1} s: {} lost, {} added, {} changed\n", + size(r.saved_bytes as u64), + r.seconds, + t.lost, + t.added, + t.changed + )); + } + } + if !r.not_written.is_empty() { + s.push_str(&format!("- **Lost on save**, not written (the writer can't write these types): {}\n", per_type(&r.not_written))); + } + if let Some(p) = &r.saved_path { + s.push_str(&format!("- Saved file: `{p}`\n")); + } + for n in &r.reopen_notes { + s.push_str(&format!("- Note on reopening: {}\n", cell(n))); + } + if !r.comparison.is_empty() { + s.push('\n'); + diff_table(&r.comparison, s); + } + } + } + + /// Write `report.md` and `report.json` into `dir` (created if needed); returns their paths. + pub fn write(&self, dir: &Path) -> std::io::Result<(PathBuf, PathBuf)> { + std::fs::create_dir_all(dir)?; + let (md, json) = (dir.join("report.md"), dir.join("report.json")); + std::fs::write(&md, self.to_markdown())?; + std::fs::write(&json, self.to_json())?; + Ok((md, json)) + } +} + +/// A comparison's differences as a Markdown table (the first [`MD_ROWS`]). +fn diff_table(c: &Comparison, s: &mut String) { + let tallies: Vec = Category::ALL + .iter() + .filter_map(|cat| { + let t = c.tally(*cat); + (t.total() > 0).then(|| format!("{} {}/{}/{}", cat.label(), t.lost, t.added, t.changed)) + }) + .collect(); + s.push_str(&format!("By category (lost/added/changed): {}\n\n", tallies.join(" · "))); + s.push_str("| Category | Change | Where | Detail |\n|---|---|---|---|\n"); + for d in c.differences.iter().take(MD_ROWS) { + s.push_str(&format!("| {} | {} | {} | {} |\n", d.category.label(), d.change.label(), cell(&clip(&d.place, 80)), cell(&clip(&d.detail, 400)))); + } + let more = c.differences.len().saturating_sub(MD_ROWS).saturating_add(c.omitted); + if more > 0 { + s.push_str(&format!("\n… and {more} more differences (see report.json; differences beyond the listing limit are only counted).\n")); + } +} diff --git a/crates/io/src/roundtrip/tests.rs b/crates/io/src/roundtrip/tests.rs new file mode 100644 index 000000000..57b77a74a --- /dev/null +++ b/crates/io/src/roundtrip/tests.rs @@ -0,0 +1,559 @@ +use std::sync::Arc; + +use cadcraft_color::Color; +use cadcraft_doc::foreign::{ForeignExtra, ForeignObject}; +use cadcraft_doc::*; +use cadcraft_geom::{PolyVertex, Vec2, Vec3}; + +use super::*; + +fn tag(code: i32, value: &str) -> RawTag { + RawTag { code, value: value.into() } +} + +fn line(a: (f64, f64), b: (f64, f64)) -> EntityKind { + EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) }) +} + +/// A small drawing touching every part the comparator looks at. +fn drawing() -> Drawing { + let mut d = Drawing::new_metric(); + d.layers.push(Layer { name: "Walls".into(), color: Color::Index(1), ..Layer::default() }); + let walls = Common { layer: "Walls".into(), ..Common::default() }; + d.add(&Space::Model, walls.clone(), line((0.0, 0.0), (10.0, 0.0))).unwrap(); + d.add(&Space::Model, walls, line((0.0, 5.0), (10.0, 5.0))).unwrap(); + d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(3.0, 4.0, 0.0), radius: 2.5 })).unwrap(); + let tagged = Common { xdata: vec![tag(1001, "ACME"), tag(1000, "door"), tag(1040, "2.5")], ..Common::default() }; + d.add( + &Space::Model, + tagged, + EntityKind::LwPolyline(LwPolyline { + vertices: vec![PolyVertex::new(Vec2::ZERO), PolyVertex::with_bulge(Vec2::new(4.0, 0.0), 0.5), PolyVertex::new(Vec2::new(4.0, 3.0))], + closed: true, + const_width: 0.0, + elevation: 0.0, + plinegen: false, + }), + ) + .unwrap(); + d.add( + &Space::Model, + Common::default(), + EntityKind::Unknown(Unknown { dxf_type: "ACME_WIDGET".into(), tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")] }), + ) + .unwrap(); + d.add(&Space::Paper("Layout1".into()), Common::default(), line((1.0, 1.0), (2.0, 2.0))).unwrap(); + let mut b = Block::new("DOOR"); + let h = d.new_handle(); + b.entities.push(Entity::new(h, line((0.0, 0.0), (0.0, 1.0)))); + d.blocks.insert("DOOR".into(), Arc::new(b)); + let f = Arc::make_mut(&mut d.foreign); + f.objects.push(ForeignObject { handle: Handle(0x500), kind: "XRECORD".into(), tags: vec![tag(100, "AcDbXrecord"), tag(1, "kept")] }); + f.dictionary.push(("ACME_DATA".into(), Handle(0x500))); + f.classes.push(vec![tag(1, "ACME_WIDGET"), tag(2, "AcmeWidget"), tag(3, "Acme")]); + f.records.insert(("LAYER".into(), "WALLS".into()), ForeignExtra { xdata: vec![tag(1001, "ACME"), tag(1070, "3")], ..ForeignExtra::default() }); + d +} + +fn cmp(a: &Drawing, b: &Drawing) -> Comparison { + compare(a, b, &Options::default()) +} + +fn only(c: &Comparison, cat: Category, change: Change) -> Vec<&Difference> { + c.differences.iter().filter(|d| d.category == cat && d.change == change).collect() +} + +fn first_handle(d: &Drawing, kind: &str) -> Handle { + d.model.iter().find(|e| e.kind.dxf_name() == kind).map(|e| e.handle).unwrap() +} + +#[test] +fn identical_drawings_have_no_differences() { + let d = drawing(); + let c = cmp(&d, &d.clone()); + assert!(c.is_empty(), "{:#?}", c.differences); + assert_eq!(c.total(), Tally::default()); +} + +#[test] +fn geometry_is_compared_by_handle_within_the_tolerance() { + let a = drawing(); + let h = first_handle(&a, "LINE"); + let mut b = a.clone(); + b.modify_entity(h, |e| { + if let EntityKind::Line(l) = &mut e.kind { + l.b.x += 1e-9; + } + }) + .unwrap(); + assert!(cmp(&a, &b).is_empty(), "a change within the tolerance is no difference"); + b.modify_entity(h, |e| { + if let EntityKind::Line(l) = &mut e.kind { + l.b.x = 11.0; + } + }) + .unwrap(); + let c = cmp(&a, &b); + let g = only(&c, Category::Geometry, Change::Changed); + assert_eq!(g.len(), 1, "{:#?}", c.differences); + assert!(g[0].place.contains(&h.hex()) && g[0].place.starts_with("Model LINE"), "{:?}", g[0]); + assert!(g[0].detail.contains("b.x: 10") && g[0].detail.contains("11"), "{:?}", g[0]); + assert_eq!(c.tally(Category::Geometry).changed, 1); +} + +#[test] +fn angles_a_whole_turn_apart_are_the_same() { + let mut a = drawing(); + let h = a + .add(&Space::Model, Common::default(), EntityKind::Arc(cadcraft_doc::Arc { center: Vec3::ZERO, radius: 2.0, start: -0.5, end: 1.0 })) + .unwrap(); + let mut b = a.clone(); + b.modify_entity(h, |e| { + if let EntityKind::Arc(x) = &mut e.kind { + x.start += std::f64::consts::TAU; + x.end -= std::f64::consts::TAU; + } + }) + .unwrap(); + assert!(cmp(&a, &b).is_empty(), "{:#?}", cmp(&a, &b).differences); + // A radius is no angle. + b.modify_entity(h, |e| { + if let EntityKind::Arc(x) = &mut e.kind { + x.radius += std::f64::consts::TAU; + } + }) + .unwrap(); + assert_eq!(cmp(&a, &b).tally(Category::Geometry).changed, 1); +} + +#[test] +fn properties_and_type_changes_are_reported() { + let a = drawing(); + let h = first_handle(&a, "CIRCLE"); + let mut b = a.clone(); + b.modify_entity(h, |e| e.common.color = Color::Index(3)).unwrap(); + let c = cmp(&a, &b); + assert_eq!(only(&c, Category::Properties, Change::Changed).len(), 1, "{:#?}", c.differences); + b.modify_entity(h, |e| e.kind = line((0.0, 0.0), (1.0, 1.0))).unwrap(); + let c = cmp(&a, &b); + let g = only(&c, Category::Geometry, Change::Changed); + assert!(g.iter().any(|d| d.detail == "type CIRCLE → LINE"), "{:#?}", c.differences); +} + +#[test] +fn lost_and_added_entities_are_counted_per_type_and_space() { + let a = drawing(); + let h = first_handle(&a, "CIRCLE"); + let mut b = a.clone(); + b.remove_entity(h); + let mut paper = b.clone(); + paper.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Point(Point { p: Vec3::ZERO, angle: 0.0 })).unwrap(); + let c = cmp(&a, &paper); + let lost = only(&c, Category::Count, Change::Lost); + assert_eq!(lost.len(), 1, "{:#?}", c.differences); + assert_eq!(lost[0].place, "Model CIRCLE"); + assert!(lost[0].detail.contains("1 → 0") && lost[0].detail.contains(&h.hex()), "{:?}", lost[0]); + let added = only(&c, Category::Count, Change::Added); + assert_eq!(added.len(), 1); + assert_eq!(added[0].place, "Layout Layout1 POINT"); + assert_eq!(c.tally(Category::Count), Tally { lost: 1, added: 1, changed: 0 }); +} + +#[test] +fn renumbered_entities_are_matched_by_content() { + let a = drawing(); + let mut b = a.clone(); + // Every line gets a new handle, in reverse order, and one of them moves. + let lines: Vec> = b.model.iter().filter(|e| e.kind.dxf_name() == "LINE").cloned().collect(); + for (i, e) in lines.iter().rev().enumerate() { + b.model.remove(e.handle); + let mut e = Entity::clone(e); + e.handle = Handle(0x9000 + i as u64); + b.model.push(e); + } + let c = cmp(&a, &b); + assert_eq!(c.tally(Category::Count), Tally::default(), "{:#?}", c.differences); + assert_eq!(c.tally(Category::Geometry), Tally::default(), "pairs by content, not by order: {:#?}", c.differences); + assert_eq!(c.tally(Category::Handle).changed, 2); +} + +#[test] +fn entities_moving_between_spaces_are_reported() { + let a = drawing(); + let h = first_handle(&a, "CIRCLE"); + let mut b = a.clone(); + let e = b.remove_entity(h).unwrap(); + if let Some(l) = b.layouts.first_mut() { + l.entities.push(Entity::clone(&e)); + } + let c = cmp(&a, &b); + let moved = only(&c, Category::Handle, Change::Changed); + assert_eq!(moved.len(), 1, "{:#?}", c.differences); + assert_eq!(moved[0].detail, format!("1 entities moved from Model to Layout Layout1 ({})", h.hex())); + assert_eq!(c.tally(Category::Count), Tally::default()); +} + +#[test] +fn unreferenced_anonymous_blocks_dropped_on_save_are_one_row() { + let mut a = drawing(); + for name in ["*D5", "*D6"] { + let mut blk = Block::new(name); + for _ in 0..2 { + let h = a.new_handle(); + blk.entities.push(Entity::new(h, line((0.0, 0.0), (1.0, 0.0)))); + } + a.blocks.insert(name.into(), Arc::new(blk)); + } + let mut b = a.clone(); + b.blocks.remove("*D5"); + b.blocks.remove("*D6"); + let c = cmp(&a, &b); + let lost = only(&c, Category::Count, Change::Lost); + assert_eq!(lost.len(), 1, "{:#?}", c.differences); + assert_eq!(lost[0].detail, "4 entities of 2 anonymous blocks nothing refers to (e.g. *D5) were not saved"); + assert_eq!(c.tally(Category::Count).lost, 4); + assert_eq!(c.tally(Category::Block), Tally { lost: 2, added: 0, changed: 0 }, "{:#?}", c.differences); + assert_eq!(only(&c, Category::Block, Change::Lost).len(), 1); +} + +#[test] +fn renamed_anonymous_blocks_are_matched_by_their_entities() { + let mut a = drawing(); + let mut blk = Block::new("*D1"); + let h = a.new_handle(); + blk.entities.push(Entity::new(h, line((0.0, 0.0), (5.0, 0.0)))); + a.blocks.insert("*D1".into(), Arc::new(blk.clone())); + let key = ("BLOCK_RECORD".to_string(), "*D1".to_string()); + Arc::make_mut(&mut a.foreign).records.insert(key, ForeignExtra { xdata: vec![tag(1001, "ACME"), tag(1070, "1")], ..ForeignExtra::default() }); + let mut b = a.clone(); + b.blocks.remove("*D1"); + blk.name = "*D7".into(); + b.blocks.insert("*D7".into(), Arc::new(blk)); + let f = Arc::make_mut(&mut b.foreign); + let extra = f.records.remove(&("BLOCK_RECORD".to_string(), "*D1".to_string())).unwrap(); + f.records.insert(("BLOCK_RECORD".into(), "*D7".into()), extra); + let c = cmp(&a, &b); + assert_eq!(c.tally(Category::Count), Tally::default(), "{:#?}", c.differences); + assert_eq!(c.tally(Category::Xdata), Tally::default(), "{:#?}", c.differences); + assert_eq!(c.tally(Category::Block), Tally { lost: 0, added: 0, changed: 1 }, "{:#?}", c.differences); + assert!(c.differences.iter().any(|d| d.detail == "1 anonymous blocks saved under new names (e.g. *D1 → *D7)"), "{:#?}", c.differences); +} + +#[test] +fn xdata_extension_dictionaries_and_opaque_entities_are_compared() { + let a = drawing(); + let pl = first_handle(&a, "LWPOLYLINE"); + let unknown = first_handle(&a, "ACME_WIDGET"); + let mut b = a.clone(); + b.modify_entity(pl, |e| e.common.xdata.clear()).unwrap(); + b.modify_entity(unknown, |e| { + if let EntityKind::Unknown(u) = &mut e.kind { + u.tags.pop(); + } + }) + .unwrap(); + Arc::make_mut(&mut b.foreign).records.clear(); + let mut a2 = a.clone(); + Arc::make_mut(&mut a2.foreign) + .entities + .insert(pl, ForeignExtra { xdict: Some(Handle(0x600)), reactors: vec![Handle(0x601)], ..ForeignExtra::default() }); + let c = cmp(&a2, &b); + let x = only(&c, Category::Xdata, Change::Lost); + assert_eq!(x.len(), 2, "the entity's and the layer's: {:#?}", c.differences); + assert!(x.iter().any(|d| d.place == "LAYER WALLS" && d.detail.starts_with("application ACME")), "{x:#?}"); + assert!(x.iter().any(|d| d.place.contains("LWPOLYLINE")), "{x:#?}"); + assert_eq!(c.tally(Category::ExtDict).lost, 2, "the dictionary and a reactor: {:#?}", c.differences); + let o = only(&c, Category::Opaque, Change::Changed); + assert_eq!(o.len(), 1, "{:#?}", c.differences); + assert!(o[0].detail.contains("3 groups → 2"), "{:?}", o[0]); + // Numbers in kept groups compare within the tolerance. + let mut b2 = a.clone(); + b2.modify_entity(unknown, |e| { + if let EntityKind::Unknown(u) = &mut e.kind { + u.tags[1].value = "1.0000000000001".into(); + } + }) + .unwrap(); + assert!(cmp(&a, &b2).is_empty()); +} + +#[test] +fn tables_blocks_and_layouts_are_compared_by_name() { + let a = drawing(); + let mut b = a.clone(); + b.layers.retain(|l| l.name != "Walls"); + b.linetypes.push(Linetype { name: "Dashed".into(), description: String::new(), pattern: Vec::new() }); + if let Some(s) = b.text_styles.first_mut() { + s.height = 7.0; + } + b.blocks.remove("DOOR"); + b.layouts.retain(|l| l.name != "Layout2"); + let c = cmp(&a, &b); + let t = |cat, ch, place: &str| c.differences.iter().any(|d| d.category == cat && d.change == ch && d.place == place); + assert!(t(Category::Table, Change::Lost, "LAYER Walls"), "{:#?}", c.differences); + assert!(t(Category::Table, Change::Added, "LTYPE Dashed")); + assert!(t(Category::Table, Change::Changed, "STYLE Standard")); + assert!(t(Category::Block, Change::Lost, "BLOCK DOOR")); + assert!(t(Category::Layout, Change::Lost, "LAYOUT Layout2")); + // The block's entity is lost with it, counted where it was. + assert!(t(Category::Count, Change::Lost, "Block DOOR LINE"), "{:#?}", c.differences); + // Names match without case. + let mut upper = a.clone(); + if let Some(l) = upper.layers.iter_mut().find(|l| l.name == "Walls") { + l.name = "WALLS".into(); + } + let c = cmp(&a, &upper); + assert_eq!(c.tally(Category::Table).lost, 0, "{:#?}", c.differences); +} + +#[test] +fn unmodelled_objects_dictionary_entries_and_classes_are_compared() { + let a = drawing(); + let mut b = a.clone(); + let f = Arc::make_mut(&mut b.foreign); + f.objects.clear(); + f.dictionary.clear(); + f.classes.clear(); + let c = cmp(&a, &b); + assert_eq!(c.tally(Category::Object).lost, 1, "{:#?}", c.differences); + assert_eq!(c.tally(Category::Dictionary).lost, 1); + assert_eq!(c.tally(Category::Class).lost, 1); + // A renumbered object is matched by its groups. + let mut b = a.clone(); + Arc::make_mut(&mut b.foreign).objects[0].handle = Handle(0x700); + let c = cmp(&a, &b); + assert_eq!(c.tally(Category::Object), Tally::default(), "{:#?}", c.differences); + assert_eq!(c.tally(Category::Handle).changed, 1); +} + +#[test] +fn header_variables_are_compared_without_volatile_ones() { + let a = drawing(); + let mut b = a.clone(); + b.header.set_f64("LTSCALE", 2.0); + b.header.vars.remove("TEXTSIZE"); + b.header.set_str("HANDSEED", "FFFF"); + b.header.set_str("TDUPDATE", "2461000.5"); + // 1 and 1.0 are the same value. + b.header.set_i64("DIMSCALE", 1); + let c = cmp(&a, &b); + assert!(only(&c, Category::Header, Change::Changed).iter().any(|d| d.place == "$LTSCALE"), "{:#?}", c.differences); + assert!(only(&c, Category::Header, Change::Lost).iter().any(|d| d.place == "$TEXTSIZE")); + assert_eq!(c.tally(Category::Header).total(), 2, "{:#?}", c.differences); +} + +#[test] +fn the_listing_limit_keeps_counting() { + let a = drawing(); + let mut b = a.clone(); + for i in 0..20 { + b.header.set_i64(&format!("USERI{i}"), i); + } + let c = compare(&a, &b, &Options { max_differences: 5, ..Options::default() }); + assert_eq!(c.differences.len(), 5); + assert_eq!(c.omitted, 15); + assert_eq!(c.tally(Category::Header).added, 20); +} + +#[test] +fn census_counts_what_a_dxf_holds() { + let dxf = " 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nLAYER\n 0\nLAYER\n 2\n0\n 0\nLAYER\n 2\nA\n 0\nENDTAB\n 0\nENDSEC\n\ + 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 2\n*Model_Space\n 0\nENDBLK\n 0\nBLOCK\n 2\n*Paper_Space\n 0\nLINE\n 0\nENDBLK\n\ + 0\nBLOCK\n 2\nB1\n 0\nCIRCLE\n 0\nPOLYLINE\n 0\nVERTEX\n 0\nSEQEND\n 0\nENDBLK\n 0\nENDSEC\n\ + 0\nSECTION\n 2\nENTITIES\n 0\nLINE\n 0\nINSERT\n 0\nATTRIB\n 0\nSEQEND\n 0\nENDSEC\n\ + 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 0\nXRECORD\n 0\nXRECORD\n 0\nENDSEC\n 0\nEOF\n"; + let c = census(dxf.as_bytes()).unwrap(); + assert_eq!(c.entities.get("LINE"), Some(&2)); + assert_eq!(c.entities.get("INSERT"), Some(&1)); + assert!(!c.entities.contains_key("ATTRIB") && !c.entities.contains_key("SEQEND")); + assert_eq!(c.block_entities.get("CIRCLE"), Some(&1)); + assert_eq!(c.block_entities.get("POLYLINE"), Some(&1)); + assert_eq!(c.blocks, 1); + assert_eq!(c.tables.get("LAYER"), Some(&2)); + assert_eq!(c.objects.get("XRECORD"), Some(&2)); + let _ = census(b""); +} + +#[test] +fn read_census_reports_entities_the_reader_left_out() { + let d = drawing(); + let mut file = census_of(&d); + *file.entities.entry("LINE".into()).or_default() += 2; + *file.entities.entry("WEIRD".into()).or_default() += 1; + let c = compare_census(&file, &d, &Options::default()); + let lost = only(&c, Category::Read, Change::Lost); + assert_eq!(c.tally(Category::Read).lost, 3, "{:#?}", c.differences); + assert!(lost.iter().any(|x| x.place == "spaces LINE" && x.detail == "LINE: 5 in the file, 3 read"), "{lost:#?}"); + assert!(compare_census(&census_of(&d), &d, &Options::default()).is_empty()); +} + +/// The round trips of a synthetic drawing through CADCraft's own DXF and DWG writers: whatever +/// they lose shows in the comparison. Plain geometry, layers, xdata and unmodelled objects must +/// come back from DXF. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dxf_round_trip_of_plain_geometry_is_lossless() { + use corpus::{Format, round_trip}; + let mut d = drawing(); + // What the comparator should see in a round trip: the drawing as read from its own DXF. + d = crate::read(crate::write(&d, "a.dxf").unwrap().as_slice(), "a.dxf").unwrap(); + let r = round_trip(&d, Format::Dxf, Format::Dxf, &Options::default(), None); + assert!(r.ok(), "{r:#?}"); + let core = [Category::Count, Category::Geometry, Category::Table, Category::Xdata, Category::Object, Category::Opaque]; + for cat in core { + assert_eq!(r.comparison.tally(cat), Tally::default(), "{cat:?}: {:#?}", r.comparison.differences); + } + let dwg = round_trip(&d, Format::Dxf, Format::Dwg, &Options::default(), None); + assert!(dwg.save_error.is_none() && dwg.reopen_error.is_none(), "{dwg:#?}"); + assert!(dwg.saved_bytes > 0); + // Through DWG, only the custom-class entity is lost (gap FF1: acadrust drops other programs' + // entities without DWG data of their own) — and the comparator says so. + let lost: Vec<&str> = dwg.comparison.differences.iter().filter(|d| d.category == Category::Count).map(|d| d.place.as_str()).collect(); + assert_eq!(lost, ["Model ACME_WIDGET"], "{:#?}", dwg.comparison.differences); + assert_eq!(dwg.comparison.tally(Category::Geometry), Tally::default(), "{:#?}", dwg.comparison.differences); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn hostile_files_are_reported_not_crashed() { + use corpus::{CorpusOptions, check_bytes}; + let opts = CorpusOptions::default(); + for (bytes, name) in [ + (&b""[..], "empty.dxf"), + (b"AC1032 not really a dwg file at all", "fake.dwg"), + (b" 0\nSECTION\n 2\nENTITIES\n 0\nLINE\n 10\nnan\n 20\n1e400\n 0\nENDSEC\n 0\nEOF\n", "odd.dxf"), + (&[0xFFu8; 64][..], "noise.dxf"), + ] { + let f = check_bytes(bytes, name, &opts); + assert_eq!(f.path, name); + if f.opened() { + assert!(!f.routes.is_empty()); + } else { + assert!(f.routes.is_empty() && f.open_error.as_deref().is_some_and(|e| !e.is_empty()), "{f:#?}"); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn report_renders_as_markdown_and_json() { + use corpus::{CorpusOptions, CorpusReport, check_bytes}; + let d = drawing(); + let dxf = crate::write(&d, "a.dxf").unwrap(); + let opts = CorpusOptions::default(); + let report = CorpusReport { + corpus: "corpus".into(), + generated: "2026-10-21 09:30 UTC".into(), + cadcraft_version: "0".into(), + abs_tol: 1e-6, + rel_tol: 1e-9, + files: vec![check_bytes(&dxf, "synthetic/a.dxf", &opts), check_bytes(b"AC1032 broken", "dwg/broken.dwg", &opts)], + }; + let md = report.to_markdown(); + assert!(md.starts_with("# CADCraft round-trip report"), "{md}"); + assert!(md.contains("| `synthetic/a.dxf` | DXF AC1032 |"), "{md}"); + assert!(md.contains("dxf → dxf") && md.contains("dxf → dwg"), "{md}"); + assert!(md.contains("| `dwg/broken.dwg` | DWG AC1032 |") && md.contains("**failed**"), "{md}"); + assert!(md.contains("## By category")); + let json: serde_json::Value = serde_json::from_str(&report.to_json()).unwrap(); + assert_eq!(json["files"][0]["path"], "synthetic/a.dxf"); + assert_eq!(json["files"][0]["routes"][0]["route"], "dxf → dxf"); + assert!(json["files"][1]["openError"].as_str().is_some_and(|e| !e.is_empty()), "{json}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn corpus_files_walks_folders_and_skips_the_report() { + use corpus::corpus_files; + let dir = std::env::temp_dir().join(format!("cadcraft-corpus-walk-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for p in ["dxf/a.DXF", "dwg/b.dwg", "dwg/sub/c.dwg", "notes.txt", "report/a.roundtrip.dxf", ".git/x.dxf"] { + let path = dir.join(p); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"x").unwrap(); + } + let files = corpus_files(&dir, &[dir.join("report")]); + let rel: Vec = files.iter().map(|f| corpus::relative(f, &dir)).collect(); + assert_eq!(rel, ["dwg/b.dwg", "dwg/sub/c.dwg", "dxf/a.DXF"]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The real-file corpus: set `CADCRAFT_CORPUS_DIR` to a folder of DXF/DWG files (a checkout of +/// `storytold/cadcraft-corpus`) to open, save and reopen each one and write `report.md` and +/// `report.json` to `CADCRAFT_CORPUS_REPORT` (default: the corpus folder's `report`). Skipped +/// when the variable is unset, so CI passes without the corpus. It reports, it doesn't fail on +/// differences; set `CADCRAFT_CORPUS_STRICT=1` to fail when a file doesn't open, save or reopen, +/// or when a writer leaves records out of a saved file ([`corpus::CorpusReport::strict_failures`]). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn corpus_round_trip_report() { + let Some(dir) = std::env::var_os("CADCRAFT_CORPUS_DIR").map(std::path::PathBuf::from) else { + eprintln!("CADCRAFT_CORPUS_DIR is not set: corpus round trip skipped"); + return; + }; + let out = std::env::var_os("CADCRAFT_CORPUS_REPORT").map_or_else(|| dir.join("report"), std::path::PathBuf::from); + let files = corpus::corpus_files(&dir, std::slice::from_ref(&out)); + let report = corpus::run(&dir, &files, &corpus::CorpusOptions::default(), &mut |i, n, rel| eprintln!("[{}/{n}] {rel}", i + 1)); + let (md, json) = report.write(&out).unwrap(); + eprintln!("corpus report: {} and {}", md.display(), json.display()); + if std::env::var("CADCRAFT_CORPUS_STRICT").is_ok_and(|v| v == "1") { + let failed = report.strict_failures(); + assert!(failed.is_empty(), "corpus failures:\n{}", failed.join("\n")); + } +} + +/// A type the DWG writer can't write is reported as lost on save, per type: in the route's +/// `not_written`, on the lost entity rows, in the Markdown and as a strict failure. A type it +/// writes (OLE2FRAME, kept by CADCraft without modelling it) is none of these. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn types_the_dwg_writer_cannot_write_are_reported_lost() { + use corpus::{CorpusReport, FileReport, Format, round_trip}; + let unknown = |t: &str, tags: Vec| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags }); + let mut d = Drawing::new_metric(); + let widget = vec![tag(100, "AcDbEntity"), tag(100, "AcmeWidget"), tag(10, "1.0"), tag(20, "2.0"), tag(30, "0.0")]; + d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget.clone())).unwrap(); + d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget)).unwrap(); + // Its data has no DWG wrapper, which is where a DWG keeps the corners: the reader's defaults. + let ole = ["100", "AcDbEntity", "8", "0", "100", "AcDbOle2Frame", "70", "2", "10", "1.0", "20", "1.0", "30", "0.0", "11", "0.0", "21", "0.0"] + .chunks(2) + .map(|g| tag(g[0].parse().unwrap(), g[1])) + .chain( + ["31", "0.0", "71", "2", "72", "0", "73", "0", "90", "4", "310", "C0FFEE00", "1", "OLE"] + .chunks(2) + .map(|g| tag(g[0].parse().unwrap(), g[1])), + ) + .collect(); + d.add(&Space::Model, Common::default(), unknown("OLE2FRAME", ole)).unwrap(); + let d = crate::read(&crate::write(&d, "a.dxf").unwrap(), "a.dxf").unwrap(); + + let r = round_trip(&d, Format::Dxf, Format::Dwg, &Options::default(), None); + assert!(r.ok(), "{r:#?}"); + assert_eq!(r.not_written, [("ACME_WIDGET".to_string(), 2)].into_iter().collect()); + let lost: Vec<&Difference> = r.comparison.differences.iter().filter(|x| x.category == Category::Count && x.change == Change::Lost).collect(); + assert_eq!(lost.len(), 1, "{lost:#?}"); + assert!(lost[0].place.ends_with("ACME_WIDGET") && lost[0].detail.contains("not written: the DWG writer can't write ACME_WIDGET"), "{lost:#?}"); + // The OLE2FRAME is written (only the CLASS record AutoCAD's files have is added). + assert!( + !r.comparison.differences.iter().any(|x| x.category != Category::Class && x.place.contains("OLE2FRAME")), + "{:#?}", + r.comparison.differences + ); + assert!(!r.lossless()); + + let report = + CorpusReport { files: vec![FileReport { path: "a.dxf".into(), routes: vec![r], ..FileReport::default() }], ..CorpusReport::default() }; + assert_eq!(report.strict_failures(), ["a.dxf (dxf → dwg): lost on save, not written: 2 ACME_WIDGET"]); + let md = report.to_markdown(); + assert!(md.contains("- **Lost on save** (records a writer can't write): 2 ACME_WIDGET (dxf → dwg)"), "{md}"); + assert!(md.contains("| dxf → dwg | ok | ok | **2** |"), "{md}"); + assert!(md.contains("- **Lost on save**, not written (the writer can't write these types): 2 ACME_WIDGET"), "{md}"); + + // DXF keeps everything: nothing lost on save, nothing to fail on. + let r = round_trip(&d, Format::Dxf, Format::Dxf, &Options::default(), None); + assert!(r.not_written.is_empty()); + let report = + CorpusReport { files: vec![FileReport { path: "a.dxf".into(), routes: vec![r], ..FileReport::default() }], ..CorpusReport::default() }; + assert!(report.strict_failures().is_empty()); + assert!(report.to_markdown().contains("- Lost on save (records a writer can't write): none")); +} diff --git a/docs/gaps.md b/docs/gaps.md index a4a12cff8..7ab8202fa 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 (DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (open → save → reopen round-trip harness with loss report: FF5 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 @@ -14,7 +14,7 @@ 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) | +| 2 | **[alpha blocker]** **No real-file test corpus and no check in AutoCAD** | The open → save → reopen harness exists (FF5), but no real files run through it yet and all file tests are synthetic; nobody has verified a CADCraft DWG/DXF opens cleanly in AutoCAD | 8–12 + 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) | | 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) | @@ -77,7 +77,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame), annotative scale contexts; check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | | FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 | | FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 | -| FF5 | **[alpha blocker]** Real-file corpus (`storytold/cadcraft-corpus`), open → save → reopen tests, black-box check in AutoCAD | High | 10–15 + human | +| FF5 | **[alpha blocker]** Real-file corpus (`storytold/cadcraft-corpus`) and black-box check in AutoCAD. The open → save → reopen harness landed 2026-10-22 (`cadcraft_io::roundtrip`, `cadcraft-cli roundtrip`, `cargo xtask corpus`: entities by handle, tables, objects, xdata, classes and header compared, Markdown and JSON report, with the records the DWG writer leaves out). Left: the corpus itself (no real files run in CI yet); nobody has opened CADCraft's output in AutoCAD | High | 8–12 + 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 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Round-trip harness: `cadcraft_io::roundtrip` compares a drawing with itself saved and reopened (entities by handle, tables, blocks, layouts, unmodelled objects, xdata, classes, header variables; numbers within a tolerance), `roundtrip::corpus` runs a folder of DXF/DWG files through DXF and DWG into `report.md`/`report.json`, exposed as `cadcraft-cli roundtrip` and `cargo xtask corpus`; the harness reports per type the records the DWG writer leaves out (`cadcraft_dwg::dxf_to_dwg_noted`, `cadcraft_io::write_noted`), and OLE2FRAME, which it writes, is no longer listed as not saved: FF5 narrowed | | 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 | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | diff --git a/xtask/src/main.rs b/xtask/src/main.rs index d5ef7dcab..8d8d78631 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -23,8 +23,10 @@ commands: test cargo nextest run (cargo test without nextest) plus the doctests i18n print the strings each interface language shows in English (never fails) ci fmt --check, clippy -D warnings, test, i18n, assets, layers, wasm (stops at first failure) - corpus [--download] - show where test corpora live; --download fetches PngSuite into corpus/pngsuite + corpus [DIR] [--out DIR] [--keep-saved] [--same-format] + open -> save -> reopen every DXF/DWG of a real-file corpus (DIR, default + $CADCRAFT_CORPUS_DIR or ../cadcraft-corpus) and write report.md + report.json + (default DIR/report); runs `cadcraft-cli roundtrip` in release mode stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`) parity recompute the AutoCAD menu-breadth checklist in docs/parity-checklist.md ico ... @@ -41,7 +43,7 @@ fn main() -> ExitCode { Some("test") => cmd_test(), Some("i18n") => cmd_i18n(), Some("ci") => cmd_ci(), - Some("corpus") => cmd_corpus(rest.contains(&"--download")), + Some("corpus") => cmd_corpus(&rest), Some("stats") => stats::run(&root(), rest.contains(&"--exact")), Some("parity") => parity::run(&root()), Some("ico") => ico::run(&rest), @@ -226,7 +228,43 @@ fn cmd_ci() -> Result<(), String> { Ok(()) } -fn cmd_corpus(_download: bool) -> Result<(), String> { - println!("Test corpora live in storytold/cadcraft-corpus (planned); never commit large binaries here."); - Ok(()) +/// `corpus [DIR] [options]`: the round-trip report over a real-file corpus (gaps FF1, FF5). The +/// corpus lives outside this repo (storytold/cadcraft-corpus); its files are never committed here. +fn cmd_corpus(args: &[&str]) -> Result<(), String> { + // `cadcraft-cli` runs from the repository root: relative paths are made absolute against the + // folder `cargo xtask` was run from first, so they mean what the user typed. + let here = std::env::current_dir().map_err(|e| format!("current folder: {e}"))?; + let mut pass: Vec = Vec::new(); + let mut dir: Option = None; + let mut it = args.iter(); + while let Some(a) = it.next() { + match *a { + "--out" => { + let v = it.next().ok_or_else(|| format!("{a} needs a value"))?; + pass.extend([a.to_string(), here.join(v).display().to_string()]); + } + "--tolerance" => { + let v = it.next().ok_or_else(|| format!("{a} needs a value"))?; + pass.extend([a.to_string(), v.to_string()]); + } + s if s.starts_with("--") => pass.push(s.to_string()), + s if dir.is_none() => dir = Some(s.to_string()), + _ => return Err("corpus takes one DIR".into()), + } + } + let dir = dir + .or_else(|| std::env::var("CADCRAFT_CORPUS_DIR").ok()) + .unwrap_or_else(|| root().parent().map(|p| p.join("cadcraft-corpus").display().to_string()).unwrap_or_else(|| "../cadcraft-corpus".into())); + let dir = here.join(&dir); + if !dir.is_dir() { + return Err(format!( + "no corpus at `{}`: clone storytold/cadcraft-corpus next to this repo, set CADCRAFT_CORPUS_DIR or pass DIR \ + (never commit corpus files to this repo)", + dir.display() + )); + } + let dir = dir.display().to_string(); + let mut c = cargo(); + c.args(["run", "--release", "-q", "-p", "cadcraft-cli", "--", "roundtrip", &dir]).args(&pass); + run(c, &format!("cadcraft-cli roundtrip {dir} {}", pass.join(" "))) } From 52c1e6de98916e2a15b19c90d1495e6cd34c0a5c Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Thu, 22 Oct 2026 15:55:56 +0200 Subject: [PATCH 113/900] fonts: read SHX shape fonts, big fonts and unifonts; draw linetype shapes (FF8, FF9) SHX files referenced by text styles are found by file name through a font map, registered bytes, an app provider, the drawing's folder and a search path (CADCRAFT_SHXPATH); never in a CAD program's install folder. TEXT, MTEXT, attributes, dimension text and table cells draw with the style's font, big font and vertical flag; linetype shape elements are drawn when their file is found. The web build registers .shx files picked or dropped with a drawing. All test fonts are compiled in code from shape source. Plain MTEXT text decodes \U+XXXX escapes as the layout does, and an SHX file whose name differs in case from the one asked for is found on case-sensitive file systems too (the folder is looked through). Co-Authored-By: Claude Opus 5.5 (1M context) --- Cargo.lock | 2 + apps/cadcraft-web/Cargo.toml | 1 + apps/cadcraft-web/src/upload.rs | 45 ++- crates/engine/src/cmd/file.rs | 4 + crates/engine/tests/shx_beside_drawing.rs | 34 ++ crates/fonts/Cargo.toml | 1 + crates/fonts/src/lib.rs | 82 +++- crates/fonts/src/mtext.rs | 16 + crates/fonts/src/shx/compile.rs | 313 +++++++++++++++ crates/fonts/src/shx/mod.rs | 248 ++++++++++++ crates/fonts/src/shx/parse.rs | 224 +++++++++++ crates/fonts/src/shx/program.rs | 344 +++++++++++++++++ crates/fonts/src/shx/table.rs | 268 +++++++++++++ crates/fonts/src/shx/tests.rs | 450 ++++++++++++++++++++++ crates/fonts/src/shx/text.rs | 202 ++++++++++ crates/fonts/tests/shx_lookup.rs | 76 ++++ crates/render/src/dim_draw.rs | 2 +- crates/render/src/draw.rs | 2 +- crates/render/src/lib.rs | 2 +- crates/render/src/linetype_text.rs | 137 ++++++- crates/render/src/table.rs | 2 +- crates/render/src/text_entity.rs | 10 +- docs/gaps.md | 7 +- 23 files changed, 2427 insertions(+), 45 deletions(-) create mode 100644 crates/engine/tests/shx_beside_drawing.rs create mode 100644 crates/fonts/src/shx/compile.rs create mode 100644 crates/fonts/src/shx/mod.rs create mode 100644 crates/fonts/src/shx/parse.rs create mode 100644 crates/fonts/src/shx/program.rs create mode 100644 crates/fonts/src/shx/table.rs create mode 100644 crates/fonts/src/shx/tests.rs create mode 100644 crates/fonts/src/shx/text.rs create mode 100644 crates/fonts/tests/shx_lookup.rs diff --git a/Cargo.lock b/Cargo.lock index 0633f38f3..8b626efed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -670,6 +670,7 @@ name = "cadcraft-fonts" version = "0.13.0" dependencies = [ "cadcraft-geom", + "encoding_rs", "harfrust 0.14.0", "skrifa 0.48.0", "unicode-bidi", @@ -760,6 +761,7 @@ name = "cadcraft-web" version = "0.13.0" dependencies = [ "cadcraft-engine", + "cadcraft-fonts", "cadcraft-io", "cadcraft-ui-egui", "eframe", diff --git a/apps/cadcraft-web/Cargo.toml b/apps/cadcraft-web/Cargo.toml index e5e86a0e3..cb9ddb81b 100644 --- a/apps/cadcraft-web/Cargo.toml +++ b/apps/cadcraft-web/Cargo.toml @@ -18,6 +18,7 @@ path = "src/main.rs" cadcraft-engine = { workspace = true } cadcraft-ui-egui = { workspace = true } cadcraft-io = { workspace = true } +cadcraft-fonts = { workspace = true } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/apps/cadcraft-web/src/upload.rs b/apps/cadcraft-web/src/upload.rs index 0b567f8b7..4b4f51829 100644 --- a/apps/cadcraft-web/src/upload.rs +++ b/apps/cadcraft-web/src/upload.rs @@ -2,6 +2,11 @@ //! a path from, so the picker is a hidden ``; the chosen file (or one dropped on //! the page) is read in the background and handed to the app on its next frame, which opens it //! with OPEN `{data, name}` ([`CadApp::open_bytes`]). +//! +//! SHX fonts (text fonts, big fonts, shape files) chosen or dropped with a drawing are the web +//! build's font folder: they are registered with the font table +//! ([`cadcraft_fonts::shx::register`]) under their file name, so the styles and linetypes that +//! name them draw with them, and the drawings are regenerated. use std::cell::Cell; use std::rc::Rc; @@ -12,8 +17,11 @@ use web_sys::js_sys; /// The hidden file input (one at a time; a cancelled pick leaves it until the next one). const INPUT_ID: &str = "cadcraft_open_input"; -/// What the picker offers: the formats OPEN reads. -const ACCEPT: &str = ".dxf,.dwg"; +/// What the picker offers: the formats OPEN reads, and the SHX fonts drawings name. +const ACCEPT: &str = ".dxf,.dwg,.shx"; + +/// Most files taken from one pick. +const MAX_PICKED: u32 = 64; /// A file read in the browser (name, contents), or why it couldn't be read. type Upload = Result<(String, Vec), String>; @@ -51,13 +59,19 @@ impl Inbox { .map_err(|_| "could not create a file input".to_string())?; input.set_type("file"); input.set_accept(ACCEPT); + // A drawing and the fonts it uses can be chosen together. + input.set_multiple(true); input.set_id(INPUT_ID); input.set_attribute("style", "display:none").map_err(js_error)?; let (inbox, chosen) = (self.clone(), input.clone()); - // Called once, when a file was chosen (browsers don't fire `change` on cancel). + // Called once, when files were chosen (browsers don't fire `change` on cancel). let on_change = wasm_bindgen::closure::Closure::once_into_js(move || { - if let Some(file) = chosen.files().and_then(|f| f.get(0)) { - inbox.read(file); + if let Some(files) = chosen.files() { + for i in 0..files.length().min(MAX_PICKED) { + if let Some(file) = files.get(i) { + inbox.read(file); + } + } } chosen.remove(); }); @@ -118,9 +132,21 @@ impl Inbox { self.ctx.request_repaint(); } - /// Open what arrived since the last frame (or report why it couldn't be read). + /// Open what arrived since the last frame (or report why it couldn't be read). Fonts are + /// registered first, so drawings opened with them draw with them. pub fn drain(&self, app: &mut CadApp) { - for upload in self.files.take() { + let (fonts, files): (Vec, Vec) = self.files.take().into_iter().partition(|u| u.as_ref().is_ok_and(|(n, _)| is_shx(n))); + let mut registered = false; + for (name, bytes) in fonts.into_iter().flatten() { + match cadcraft_fonts::shx::register(&name, &bytes) { + Ok(()) => registered = true, + Err(e) => app.open_failed(format!("{name}: {e}")), + } + } + if registered { + let _ = app.run("regenall", serde_json::json!({})); + } + for upload in files { match upload { Ok((name, bytes)) => app.open_bytes(&name, &bytes), Err(e) => app.open_failed(e), @@ -129,6 +155,11 @@ impl Inbox { } } +/// Whether `name` is an SHX font or shape file. +fn is_shx(name: &str) -> bool { + name.to_ascii_lowercase().ends_with(".shx") +} + fn js_error(e: wasm_bindgen::JsValue) -> String { e.as_string().unwrap_or_else(|| format!("{e:?}")) } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 95975a4e2..44edf0629 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -307,6 +307,10 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result Vec<(char, bool, bool)> { let mut out = Vec::with_capacity(s.len()); let mut under = false; @@ -49,6 +51,14 @@ pub fn decode_controls(s: &str) -> Vec<(char, bool, bool)> { let mut i = 0; while i < chars.len() { let c = chars.get(i).copied().unwrap_or(' '); + // `\U+XXXX`: a Unicode character by its code. + if c == '\\' + && let Some(u) = unicode_escape(&chars, i) + { + out.push((u, under, over)); + i += 7; + continue; + } if c == '%' && chars.get(i + 1) == Some(&'%') { let code = chars.get(i + 2).copied().unwrap_or(' '); match code.to_ascii_lowercase() { @@ -80,6 +90,18 @@ pub fn decode_controls(s: &str) -> Vec<(char, bool, bool)> { out } +/// The character of a `\U+XXXX` escape (four hex digits) starting at `chars[i]`. +pub(crate) fn unicode_escape(chars: &[char], i: usize) -> Option { + if chars.get(i) != Some(&'\\') || !matches!(chars.get(i + 1), Some('U' | 'u')) || chars.get(i + 2) != Some(&'+') { + return None; + } + let hex: String = chars.get(i + 3..i + 7)?.iter().collect(); + if !hex.chars().all(|c| c.is_ascii_hexdigit()) { + return None; + } + char::from_u32(u32::from_str_radix(&hex, 16).ok()?) +} + /// Advance width of one character at height 1 and width factor 1. pub fn char_advance(c: char) -> f64 { match stroke::glyph(c) { @@ -268,35 +290,65 @@ pub fn space_width(font: &TextFont, height: f64, width_factor: f64) -> f64 { { return w; } + if let TextFont::Shx(t) = font { + return shx::width(t, " ", height, width_factor); + } 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, an installed TrueType / +/// OpenType face (outlines) or the user's SHX fonts (a main font and a big font). Whichever, +/// 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; - /// else the stroke font. + /// Resolve a text style font name (no big font, horizontal): see [`TextFont::resolve_style`]. pub fn resolve(name: &str) -> TextFont { - if let Some(f) = ttf::find(name) { + TextFont::resolve_style(name, "", false) + } + + /// Resolve a text style's fonts: an installed TTF/OTF/TTC when `font` names one; else the + /// SHX font and big font when found ([`shx::find`]), a missing one replaced by the FONTALT + /// font ([`ttf::font_alt`], which may name both: `simplex.shx,bigfont.shx`); else FONTALT + /// as a TrueType font; else the stroke font (which also draws the characters a missing big + /// font would have). `vertical` is the style's vertical flag, honoured by fonts made for it. + pub fn resolve_style(font: &str, big_font: &str, vertical: bool) -> TextFont { + if let Some(f) = ttf::find(font) { return TextFont::Outline(f); } - let n = name.trim(); - if n.is_empty() || n.eq_ignore_ascii_case(BUILTIN_FONT) { + let n = font.trim(); + let builtin = n.is_empty() || n.eq_ignore_ascii_case(BUILTIN_FONT); + let alt = ttf::font_alt(); + let (alt_main, alt_big) = alt.split_once(',').map_or((alt.as_str(), ""), |(a, b)| (a.trim(), b.trim())); + let main = if builtin { None } else { shx::find(n).or_else(|| shx::find(alt_main)) }; + let (big, big_name) = match big_font.trim() { + "" => (None, ""), + b => match shx::find(b) { + Some(f) => (Some(f), b), + None => (shx::find(alt_big), alt_big), + }, + }; + if main.is_some() || big.is_some() { + return TextFont::Shx(std::sync::Arc::new(shx::ShxText::new(main, big, big_name, vertical))); + } + if builtin { return TextFont::Stroke; } - ttf::find(&ttf::font_alt()).map(TextFont::Outline).unwrap_or(TextFont::Stroke) + ttf::find(alt_main).map(TextFont::Outline).unwrap_or(TextFont::Stroke) } pub fn is_outline(&self) -> bool { matches!(self, TextFont::Outline(_)) } + /// Whether the text is drawn with SHX fonts. + pub fn is_shx(&self) -> bool { + matches!(self, TextFont::Shx(_)) + } } /// Shaped text in local or world coordinates: open strokes (stroke-font glyphs, underlines, @@ -419,6 +471,9 @@ pub fn shape_line(font: &TextFont, s: &str, height: f64, width_factor: f64, obli { return sh; } + if let TextFont::Shx(t) = font { + return shx::shape(t, s, height, width_factor, oblique); + } shape_stroke(s, height, width_factor, oblique) } @@ -429,6 +484,9 @@ pub fn text_width(font: &TextFont, s: &str, height: f64, width_factor: f64) -> f { return w; } + if let TextFont::Shx(t) = font { + return shx::width(t, s, height, width_factor); + } line_width(s, height, width_factor) } diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 0c6cb074c..32d01fe99 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -55,6 +55,13 @@ pub fn plain_mtext(s: &str) -> String { i = j + 1; } 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => i += 2, + // `\U+XXXX`: a character by its Unicode code, as the layout reads it. + 'U' | 'u' if crate::unicode_escape(&chars, i).is_some() => { + if let Some(u) = crate::unicode_escape(&chars, i) { + out.push(u); + } + i += 7; + } // Codes with an argument terminated by ';' (\f, \F, \H, \W, \Q, \T, \A, \C, \c, \p). _ => { let mut j = i + 2; @@ -287,6 +294,13 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { 'O' => derive(&mut fmts, &mut cur, &|f| f.over = true), 'o' => derive(&mut fmts, &mut cur, &|f| f.over = false), 'K' | 'k' => {} + // `\U+XXXX`: a character by its Unicode code. + 'U' if i >= 2 && crate::unicode_escape(&chars, i - 2).is_some() => { + if let Some(u) = crate::unicode_escape(&chars, i - 2) { + push_char(&mut word, u, cur); + } + i += 5; + } 'S' => { let mut j = i; let (mut top, mut bottom, mut sep) = (String::new(), String::new(), None); @@ -702,6 +716,8 @@ mod tests { assert_eq!(plain_mtext("a\\~b\\\\c"), "a b\\c"); assert_eq!(plain_mtext("\\H2.5x;Big"), "Big"); assert_eq!(plain_mtext("unterminated \\H2"), "unterminated "); + assert_eq!(plain_mtext("\\U+0041B \\U+00E8"), "AB è"); + assert_eq!(plain_mtext("\\U+12"), "", "a short escape is a code with an argument"); } #[test] diff --git a/crates/fonts/src/shx/compile.rs b/crates/fonts/src/shx/compile.rs new file mode 100644 index 000000000..2e8cb3c25 --- /dev/null +++ b/crates/fonts/src/shx/compile.rs @@ -0,0 +1,313 @@ +//! Shape source (`.shp`) to a compiled SHX file, as COMPILE does. +//! +//! A source is a list of definitions: a header line `*number,defbytes,NAME` followed by its +//! specification bytes (on as many lines as needed, ending with 0). Numbers are decimal, or +//! hexadecimal after a leading `0` (`012`, `08cfb`); parentheses only group; `;` starts a +//! comment. A big font starts with `*BIGFONT nchars,nranges,first,last,…` and a Unicode font +//! with `*UNIFONT,6,name` followed by `above,below,modes,encoding,type,0`. Shape 0 is a text +//! font's record (`above,below,modes,0`). +//! +//! Operands are encoded by what they are: a subshape number takes two bytes in a Unicode font +//! (and after `7,0` in a big font), displacements and bulges are two's complement, and an arc's +//! direction byte (`-043`) keeps its sign in the high bit. `defbytes` is not checked: the +//! program's own length is written. + +use super::ShxError; +use super::parse::{BIGFONT, SHAPES_10, UNIFONT}; + +/// Largest source compiled. +const MAX_SOURCE: usize = 8 << 20; + +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Shapes, + Big, + Uni, +} + +struct Shape { + number: u16, + name: String, + program: Vec, +} + +/// A number token: value (sign included). +fn number(tok: &str, line: usize) -> Result { + let t: String = tok.chars().filter(|c| !matches!(c, '(' | ')') && !c.is_whitespace()).collect(); + let (neg, digits) = match t.strip_prefix('-') { + Some(d) => (true, d), + None => (false, t.strip_prefix('+').unwrap_or(&t)), + }; + let err = || ShxError::Source(line, format!("not a number: {tok:?}")); + let v = if digits.len() > 1 && digits.starts_with('0') { + i64::from_str_radix(digits.get(1..).unwrap_or_default(), 16).map_err(|_| err())? + } else { + digits.parse::().map_err(|_| err())? + }; + if v > 0xFFFF { + return Err(err()); + } + Ok(if neg { -v } else { v }) +} + +/// The comma-separated numbers of a line (comment removed, blank fields skipped). +fn numbers(text: &str, line: usize) -> Result, ShxError> { + text.split(',').map(str::trim).filter(|t| !t.is_empty() && *t != "(" && *t != ")").map(|t| number(t, line)).collect() +} + +/// The spec-byte encoder: walks the tokens as the reader walks the bytes. +struct Enc<'a> { + toks: &'a [i64], + i: usize, + out: Vec, + kind: Kind, + line: usize, +} + +impl Enc<'_> { + fn next(&mut self) -> Result { + let v = self.toks.get(self.i).copied().ok_or_else(|| ShxError::Source(self.line, "the shape ends inside a command".into()))?; + self.i += 1; + Ok(v) + } + fn byte(&mut self) -> Result<(), ShxError> { + let v = self.next()?; + let b = u8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a byte")))?; + self.out.push(b); + Ok(()) + } + /// Two's complement −128..127. + fn signed(&mut self) -> Result { + let v = self.next()?; + let b = i8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not −128..127")))?; + self.out.extend(b.to_le_bytes()); + Ok(v) + } + /// Sign in the high bit (an arc's direction byte). + fn sign_magnitude(&mut self) -> Result<(), ShxError> { + let v = self.next()?; + let m = u8::try_from(v.unsigned_abs()) + .ok() + .filter(|m| *m < 0x80) + .ok_or_else(|| ShxError::Source(self.line, format!("{v} is not an octant byte")))?; + self.out.push(if v < 0 { m | 0x80 } else { m }); + Ok(()) + } + fn word(&mut self) -> Result<(), ShxError> { + let v = self.next()?; + let w = u16::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a shape number")))?; + self.out.extend(w.to_be_bytes()); + Ok(()) + } + + fn program(mut self) -> Result, ShxError> { + while self.i < self.toks.len() { + let code = self.next()?; + let c = u8::try_from(code).map_err(|_| ShxError::Source(self.line, format!("{code} is not a code")))?; + self.out.push(c); + match c { + 0 => break, + 3 | 4 => self.byte()?, + 7 => match self.kind { + Kind::Uni => self.word()?, + Kind::Big => { + let first = self.toks.get(self.i).copied().unwrap_or(0); + if first == 0 { + self.byte()?; + self.word()?; + for _ in 0..4 { + self.byte()?; + } + } else { + self.byte()?; + } + } + Kind::Shapes => self.byte()?, + }, + 8 => { + self.signed()?; + self.signed()?; + } + 9 => loop { + let (x, y) = (self.signed()?, self.signed()?); + if x == 0 && y == 0 { + break; + } + }, + 10 => { + self.byte()?; + self.sign_magnitude()?; + } + 11 => { + for _ in 0..4 { + self.byte()?; + } + self.sign_magnitude()?; + } + 12 => { + for _ in 0..3 { + self.signed()?; + } + } + 13 => loop { + let (x, y) = (self.signed()?, self.signed()?); + if x == 0 && y == 0 { + break; + } + self.signed()?; + }, + _ => {} + } + } + if self.out.last() != Some(&0) { + self.out.push(0); + } + Ok(self.out) + } +} + +/// Compile shape source into an SHX file (a shape file or text font, a big font, or a Unicode +/// font, as its first definition says). +pub fn compile(source: &str) -> Result, ShxError> { + if source.len() > MAX_SOURCE { + return Err(ShxError::TooLarge); + } + let mut kind = Kind::Shapes; + let mut ranges: Vec<(u16, u16)> = Vec::new(); + let mut uni_info: Option<(String, Vec)> = None; + // Definitions: header (number, name, line) and the numbers that follow it. + let mut defs: Vec<(i64, String, usize, Vec)> = Vec::new(); + let mut uni_header_pending = false; + for (no, raw) in source.lines().enumerate() { + let line = no + 1; + let text = raw.split(';').next().unwrap_or_default().trim(); + if text.is_empty() { + continue; + } + if let Some(head) = text.strip_prefix('*') { + let upper = head.trim_start().to_ascii_uppercase(); + if let Some(rest) = upper.strip_prefix("BIGFONT") { + kind = Kind::Big; + let v = numbers(rest, line)?; + let n = usize::try_from(v.get(1).copied().unwrap_or(0)).unwrap_or(0); + for k in 0..n { + let lo = v.get(2 + 2 * k).copied().unwrap_or(0); + let hi = v.get(3 + 2 * k).copied().unwrap_or(lo); + let to = |x: i64| u16::try_from(x).map_err(|_| ShxError::Source(line, "bad escape range".into())); + ranges.push((to(lo)?, to(hi)?)); + } + continue; + } + if upper.starts_with("UNIFONT") { + kind = Kind::Uni; + let name = head.splitn(3, ',').nth(2).unwrap_or_default().trim().to_string(); + uni_info = Some((name, Vec::new())); + uni_header_pending = true; + continue; + } + uni_header_pending = false; + let mut parts = head.splitn(3, ','); + let num = number(parts.next().unwrap_or_default().trim(), line)?; + let _defbytes = parts.next(); + let name = parts.next().unwrap_or_default().trim().to_string(); + defs.push((num, name, line, Vec::new())); + continue; + } + let v = numbers(text, line)?; + if uni_header_pending { + if let Some((_, info)) = uni_info.as_mut() { + for x in v { + info.push(u8::try_from(x).map_err(|_| ShxError::Source(line, "bad font record".into()))?); + } + } + continue; + } + match defs.last_mut() { + Some(d) => d.3.extend(v), + None => return Err(ShxError::Source(line, "specification bytes before any *number,defbytes,NAME line".into())), + } + } + let mut shapes: Vec = Vec::new(); + for (num, name, line, toks) in defs { + let number = u16::try_from(num).map_err(|_| ShxError::Source(line, format!("shape number {num} out of range")))?; + let program = if number == 0 { + // The font record: plain bytes. + toks.iter().map(|x| u8::try_from(*x).map_err(|_| ShxError::Source(line, "bad font record".into()))).collect::, _>>()? + } else { + Enc { toks: &toks, i: 0, out: Vec::new(), kind, line }.program()? + }; + if shapes.iter().any(|s| s.number == number) { + return Err(ShxError::Source(line, format!("shape {number} is defined twice"))); + } + shapes.push(Shape { number, name, program }); + } + if shapes.is_empty() { + return Err(ShxError::Empty); + } + shapes.sort_by_key(|s| s.number); + let record = |s: &Shape| -> Result, ShxError> { + let mut r: Vec = s.name.bytes().filter(|b| *b != 0).collect(); + r.push(0); + r.extend(&s.program); + if r.len() > usize::from(u16::MAX) { Err(ShxError::TooLarge) } else { Ok(r) } + }; + let count = u16::try_from(shapes.len()).map_err(|_| ShxError::TooLarge)?; + let len16 = |r: &[u8]| u16::try_from(r.len()).unwrap_or(u16::MAX); + let mut out = Vec::new(); + match kind { + Kind::Shapes => { + out.extend(SHAPES_10); + out.extend(shapes.first().map_or(0, |s| s.number).to_le_bytes()); + out.extend(shapes.last().map_or(0, |s| s.number).to_le_bytes()); + out.extend(count.to_le_bytes()); + let recs: Vec> = shapes.iter().map(record).collect::>()?; + for (s, r) in shapes.iter().zip(&recs) { + out.extend(s.number.to_le_bytes()); + out.extend(len16(r).to_le_bytes()); + } + for r in &recs { + out.extend(r); + } + out.extend(b"EOF"); + } + Kind::Big => { + out.extend(BIGFONT); + let nranges = u16::try_from(ranges.len()).map_err(|_| ShxError::TooLarge)?; + out.extend(count.to_le_bytes()); + out.extend(count.to_le_bytes()); + out.extend(nranges.to_le_bytes()); + for (lo, hi) in &ranges { + out.extend(lo.to_le_bytes()); + out.extend(hi.to_le_bytes()); + } + let recs: Vec> = shapes.iter().map(record).collect::>()?; + let mut off = out.len() + 8 * recs.len(); + for (s, r) in shapes.iter().zip(&recs) { + out.extend(s.number.to_le_bytes()); + out.extend(len16(r).to_le_bytes()); + out.extend(u32::try_from(off).map_err(|_| ShxError::TooLarge)?.to_le_bytes()); + off += r.len(); + } + for r in &recs { + out.extend(r); + } + } + Kind::Uni => { + out.extend(UNIFONT); + let (name, info) = uni_info.unwrap_or_default(); + out.extend((u32::from(count) + 1).to_le_bytes()); + let mut rec: Vec = name.bytes().filter(|b| *b != 0).collect(); + rec.push(0); + rec.extend(&info); + out.extend(len16(&rec).to_le_bytes()); + out.extend(&rec); + for s in &shapes { + let r = record(s)?; + out.extend(s.number.to_le_bytes()); + out.extend(len16(&r).to_le_bytes()); + out.extend(r); + } + } + } + Ok(out) +} diff --git a/crates/fonts/src/shx/mod.rs b/crates/fonts/src/shx/mod.rs new file mode 100644 index 000000000..9ad352a2e --- /dev/null +++ b/crates/fonts/src/shx/mod.rs @@ -0,0 +1,248 @@ +//! SHX shape fonts: text fonts, big fonts (East Asian double-byte) and Unicode fonts that a +//! drawing's text styles name, read at run time from files the user has. None is bundled. +//! +//! - [`ShxFont::parse`] reads the compiled containers (`shapes 1.0/1.1`, `bigfont 1.0`, +//! `unifont 1.0`) and [`ShxFont::glyph`] runs a shape's pen program (the vector length and +//! direction codes and special codes 0–14 of the public shape description language) into +//! polylines in font units. Every count, offset and loop in a file is bounded: a hostile or +//! truncated file never panics, it reads as far as it is valid or not at all. +//! - [`compile`] turns shape source (`.shp`) into a compiled file, as COMPILE does. The tests +//! build every font they use with it: no font file is in this repository. +//! - Fonts are found by name through the font table (`table`): registered bytes +//! ([`register`], the web build's files opened alongside a drawing), an app-set +//! [`FontProvider`], the folders of opened drawings ([`add_drawing_dir`]) and the support +//! search path ([`set_search_path`], `CADCRAFT_SHXPATH`), after the font map +//! ([`set_font_map`]). CADCraft never looks inside another CAD program's installation. +//! - [`ShxText`] is a text style's pair of fonts (main + big font) and orientation, which the +//! text layout draws ([`crate::TextFont::Shx`]): advances are the pen's end positions, so +//! widths and extents follow the font's own metrics. +//! +//! Binary container layouts (little-endian): a signature line ending in CR LF 0x1A, then +//! - shapes: first and last shape number, count, an index of (number, record length), the +//! records (a NUL-terminated name, then the program) and `EOF`; +//! - big font: index size, count, escape-range count, the ranges (first, last lead byte), +//! an index of (number, record length, file offset) and the records; +//! - unifont: shape count (32 bits), the length of the font record, the font record (name, +//! above, below, modes, encoding, embedding, 0) and then each shape as (number, length, +//! record). + +mod compile; +mod parse; +mod program; +mod table; +#[cfg(test)] +mod tests; +mod text; + +use std::collections::HashMap; +use std::sync::{Arc, PoisonError, RwLock}; + +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, +}; +pub use text::ShxText; +pub(crate) use text::{shape, width}; + +/// Why a font file can't be read or a shape source can't be compiled. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ShxError { + /// Not an SHX file (unknown signature). + NotShx, + /// The file ends inside its header or index. + Truncated, + /// The file is larger, or has more of something, than CADCraft reads. + TooLarge, + /// The file is well-formed but holds no shape. + Empty, + /// Shape source error: line and message. + Source(usize, String), +} + +impl std::fmt::Display for ShxError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ShxError::NotShx => f.write_str("not an SHX shape or font file"), + ShxError::Truncated => f.write_str("the SHX file is truncated"), + ShxError::TooLarge => f.write_str("the SHX file is too large"), + ShxError::Empty => f.write_str("the SHX file has no shapes"), + ShxError::Source(line, msg) => write!(f, "line {line}: {msg}"), + } + } +} + +impl std::error::Error for ShxError {} + +/// The kind of SHX file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShxKind { + /// A shape file or a text font with single-byte character codes (`shapes 1.0/1.1`). + Shapes, + /// A big font: double-byte character codes after an escape (lead) byte. + BigFont, + /// A Unicode font: shape numbers are Unicode code points. + Unifont, +} + +/// A shape's program run into polylines, in font units (pen starts at the origin). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ShxGlyph { + /// Pen-down runs (two points or more). + pub strokes: Vec>, + /// Where the pen ends: the advance to the next character. + pub advance: Vec2, +} + +/// One shape record: where its name and program are in [`ShxFont::data`]. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Record { + name: (usize, usize), + program: (usize, usize), +} + +/// Glyphs cached per font, keyed by (shape, vertical). +type GlyphCache = HashMap<(u16, bool), Option>>; + +/// Most glyphs cached per font (a big font has thousands; text uses a few hundred). +const MAX_CACHED_GLYPHS: usize = 16_384; + +/// A parsed SHX file. +pub struct ShxFont { + kind: ShxKind, + name: String, + /// Shape 0 (the font record) is present: the file is a text font, not only shapes. + header: bool, + above: f64, + below: f64, + /// Modes 2: horizontal and vertical (code 14 is honoured). + dual: bool, + /// Unifont encoding: 0 Unicode, 1 packed multibyte, 2 shape file. + encoding: u8, + /// Extended big font: the font record gives a character width (subshape cell). + char_width: f64, + /// Big font escape ranges (lead bytes). + ranges: Vec<(u16, u16)>, + data: Vec, + records: HashMap, + cache: RwLock, +} + +impl std::fmt::Debug for ShxFont { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ShxFont") + .field("kind", &self.kind) + .field("name", &self.name) + .field("above", &self.above) + .field("below", &self.below) + .field("dual", &self.dual) + .field("shapes", &self.records.len()) + .finish() + } +} + +impl ShxFont { + /// Parse a compiled SHX file. + pub fn parse(bytes: &[u8]) -> Result { + parse::parse(bytes) + } + pub fn kind(&self) -> ShxKind { + self.kind + } + /// The font name in its font record (shape 0), or empty. + pub fn name(&self) -> &str { + &self.name + } + /// Whether the file has a font record (shape 0): a text font rather than a shape file. + pub fn is_font(&self) -> bool { + self.header + } + /// Vector units uppercase letters rise above the baseline (big font: the character height). + /// Text height `h` draws the font at `h / above` per unit. 0 for a shape file. + pub fn above(&self) -> f64 { + self.above + } + /// Vector units lowercase descenders drop below the baseline. + pub fn below(&self) -> f64 { + self.below + } + /// The font supports vertical text (modes 2). + pub fn is_dual(&self) -> bool { + self.dual + } + /// The units per text height: [`Self::above`], or 1 for a file without a font record. + pub fn units_per_height(&self) -> f64 { + if self.above > 0.0 { self.above } else { 1.0 } + } + /// Big font escape ranges: `(first, last)` lead bytes. + pub fn escape_ranges(&self) -> &[(u16, u16)] { + &self.ranges + } + /// Whether `b` starts a double-byte character in this big font. + pub fn is_lead_byte(&self, b: u8) -> bool { + self.ranges.iter().any(|(lo, hi)| (*lo..=*hi).contains(&u16::from(b))) + } + /// Unifont encoding (0 Unicode, 1 packed multibyte, 2 shape file); 0 for other kinds. + pub fn encoding(&self) -> u8 { + self.encoding + } + pub fn shape_count(&self) -> usize { + self.records.len() + } + pub fn has_shape(&self, number: u16) -> bool { + number != 0 && self.records.contains_key(&number) + } + /// 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(); + v.sort_unstable(); + v + } + /// The name of shape `number` as the file stores it. + pub fn shape_name(&self, number: u16) -> Option { + let r = self.records.get(&number)?; + self.data.get(r.name.0..r.name.1).map(|b| b.iter().map(|c| char::from(*c)).collect()) + } + /// The number of the shape called `name` (case-insensitive), as a linetype's + /// `[SHAPE,file.shx]` element names it. + pub fn shape_number(&self, name: &str) -> Option { + let want = name.trim(); + if want.is_empty() { + return None; + } + let mut found: Vec = self + .records + .iter() + .filter(|(n, r)| **n != 0 && self.data.get(r.name.0..r.name.1).is_some_and(|b| b.eq_ignore_ascii_case(want.as_bytes()))) + .map(|(n, _)| *n) + .collect(); + found.sort_unstable(); + found.first().copied() + } + /// The program bytes of shape `number`. + pub(crate) fn program(&self, number: u16) -> Option<&[u8]> { + let r = self.records.get(&number)?; + self.data.get(r.program.0..r.program.1) + } + /// Shape `number` drawn horizontally or vertically, in font units; `None` when the font + /// has no such shape or its program is broken. Cached. + pub fn glyph(&self, number: u16, vertical: bool) -> Option> { + if !self.has_shape(number) { + return None; + } + let vertical = vertical && self.dual; + let key = (number, vertical); + if let Some(g) = self.cache.read().unwrap_or_else(PoisonError::into_inner).get(&key) { + return g.clone(); + } + let g = program::outline(self, number, vertical).ok().map(Arc::new); + let mut c = self.cache.write().unwrap_or_else(PoisonError::into_inner); + if c.len() >= MAX_CACHED_GLYPHS { + c.clear(); + } + c.insert(key, g.clone()); + g + } +} diff --git a/crates/fonts/src/shx/parse.rs b/crates/fonts/src/shx/parse.rs new file mode 100644 index 000000000..b10e8142e --- /dev/null +++ b/crates/fonts/src/shx/parse.rs @@ -0,0 +1,224 @@ +//! Reading the compiled SHX containers (layouts in the module documentation). Every count and +//! offset comes from the file, so each is checked against its length; records that run past +//! the end are dropped and the rest kept. + +use std::collections::HashMap; +use std::sync::RwLock; + +use super::{Record, ShxError, ShxFont, ShxKind}; + +pub(super) const SHAPES_10: &[u8] = b"AutoCAD-86 shapes 1.0\r\n\x1a"; +pub(super) const SHAPES_11: &[u8] = b"AutoCAD-86 shapes 1.1\r\n\x1a"; +pub(super) const BIGFONT: &[u8] = b"AutoCAD-86 bigfont 1.0\r\n\x1a"; +pub(super) const UNIFONT: &[u8] = b"AutoCAD-86 unifont 1.0\r\n\x1a"; + +/// Largest file read (the largest big fonts are a few megabytes). +pub(super) const MAX_FILE_BYTES: usize = 32 << 20; +/// Most escape ranges in a big font (lead bytes: at most 256). +const MAX_RANGES: usize = 256; + +/// A checked little-endian reader. +struct Rd<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Rd<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8], ShxError> { + let end = self.pos.checked_add(n).ok_or(ShxError::Truncated)?; + let s = self.b.get(self.pos..end).ok_or(ShxError::Truncated)?; + self.pos = end; + Ok(s) + } + fn u16(&mut self) -> Result { + match self.take(2)? { + [a, b] => Ok(u16::from_le_bytes([*a, *b])), + _ => Err(ShxError::Truncated), + } + } + fn u32(&mut self) -> Result { + match self.take(4)? { + [a, b, c, d] => Ok(u32::from_le_bytes([*a, *b, *c, *d])), + _ => Err(ShxError::Truncated), + } + } +} + +/// A font being read. +struct Font { + kind: ShxKind, + name: String, + header: bool, + above: f64, + below: f64, + dual: bool, + encoding: u8, + char_width: f64, + ranges: Vec<(u16, u16)>, + records: HashMap, +} + +impl Font { + fn new(kind: ShxKind) -> Font { + Font { + kind, + name: String::new(), + header: false, + above: 0.0, + below: 0.0, + dual: false, + encoding: 0, + char_width: 0.0, + ranges: Vec::new(), + records: HashMap::new(), + } + } + + /// Add the record of shape `number` at `start..end` of `data`: a NUL-terminated name, then + /// the program. Shape 0 is the font record. A record without a name terminator is dropped; + /// the first record of a number wins. + fn record(&mut self, data: &[u8], number: u16, start: usize, end: usize) { + let Some(bytes) = data.get(start..end) else { return }; + let Some(nul) = bytes.iter().position(|b| *b == 0) else { return }; + let name = (start, start + nul); + let program = (start + nul + 1, end); + if number == 0 { + if !self.header { + self.font_record(data.get(program.0..program.1).unwrap_or_default(), data.get(name.0..name.1).unwrap_or_default()); + } + return; + } + self.records.entry(number).or_insert(Record { name, program }); + } + + /// The font record: above, below, modes (and for a unifont encoding and embedding); an + /// extended big font's is character height, 0, modes, character width. + fn font_record(&mut self, info: &[u8], name: &[u8]) { + self.header = true; + self.name = name.iter().take(255).map(|c| char::from(*c)).collect(); + let byte = |i: usize| info.get(i).copied().unwrap_or(0); + self.above = f64::from(byte(0)); + self.below = f64::from(byte(1)); + self.dual = byte(2) == 2; + if self.kind == ShxKind::Unifont { + self.encoding = byte(3); + } + if self.kind == ShxKind::BigFont && info.len() >= 5 && byte(1) == 0 { + // Extended: height, 0, modes, width, 0. + self.below = 0.0; + self.char_width = f64::from(byte(3)); + } + } + + fn finish(self, data: Vec) -> Result { + if self.records.is_empty() { + return Err(ShxError::Empty); + } + Ok(ShxFont { + kind: self.kind, + name: self.name, + header: self.header, + above: self.above, + below: self.below, + dual: self.dual, + encoding: self.encoding, + char_width: if self.char_width > 0.0 { self.char_width } else { self.above }, + ranges: self.ranges, + data, + records: self.records, + cache: RwLock::default(), + }) + } +} + +pub(super) fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_FILE_BYTES { + return Err(ShxError::TooLarge); + } + if bytes.starts_with(SHAPES_10) || bytes.starts_with(SHAPES_11) { + shapes(bytes) + } else if bytes.starts_with(BIGFONT) { + bigfont(bytes) + } else if bytes.starts_with(UNIFONT) { + unifont(bytes) + } else { + Err(ShxError::NotShx) + } +} + +fn shapes(bytes: &[u8]) -> Result { + let mut r = Rd { b: bytes, pos: SHAPES_10.len() }; + let _first = r.u16()?; + let _last = r.u16()?; + let count = usize::from(r.u16()?); + // The whole index must be there before anything is read from it. + let index = r.take(count.checked_mul(4).ok_or(ShxError::TooLarge)?)?; + let mut f = Font::new(ShxKind::Shapes); + let mut pos = r.pos; + for [a, b, c, d] in index.as_chunks::<4>().0 { + let (number, len) = (u16::from_le_bytes([*a, *b]), usize::from(u16::from_le_bytes([*c, *d]))); + let Some(end) = pos.checked_add(len).filter(|e| *e <= bytes.len()) else { break }; + f.record(bytes, number, pos, end); + pos = end; + } + f.finish(bytes.to_vec()) +} + +fn bigfont(bytes: &[u8]) -> Result { + let mut r = Rd { b: bytes, pos: BIGFONT.len() }; + let index_size = usize::from(r.u16()?); + let count = usize::from(r.u16()?); + let nranges = usize::from(r.u16()?); + if nranges > MAX_RANGES { + return Err(ShxError::TooLarge); + } + let mut f = Font::new(ShxKind::BigFont); + for _ in 0..nranges { + let (lo, hi) = (r.u16()?, r.u16()?); + f.ranges.push((lo.min(hi), lo.max(hi))); + } + // The index has `count` entries of 8 bytes; a file whose count doesn't fit but whose index + // size does is read by that. + let fits = |n: usize| n.checked_mul(8).and_then(|l| r.pos.checked_add(l)).is_some_and(|e| e <= bytes.len()); + let n = if fits(count) { + count + } else if fits(index_size) { + index_size + } else { + return Err(ShxError::Truncated); + }; + let index = r.take(n.checked_mul(8).ok_or(ShxError::TooLarge)?)?; + for [a, b, c, d, o0, o1, o2, o3] in index.as_chunks::<8>().0 { + let number = u16::from_le_bytes([*a, *b]); + let len = usize::from(u16::from_le_bytes([*c, *d])); + let Ok(off) = usize::try_from(u32::from_le_bytes([*o0, *o1, *o2, *o3])) else { continue }; + if len == 0 { + continue; + } + let Some(end) = off.checked_add(len).filter(|e| *e <= bytes.len()) else { continue }; + f.record(bytes, number, off, end); + } + f.finish(bytes.to_vec()) +} + +fn unifont(bytes: &[u8]) -> Result { + let mut r = Rd { b: bytes, pos: UNIFONT.len() }; + let count = r.u32()?; + let info_len = usize::from(r.u16()?); + let info = r.take(info_len)?; + let mut f = Font::new(ShxKind::Unifont); + let nul = info.iter().position(|b| *b == 0).unwrap_or(info.len()); + f.font_record(info.get(nul.saturating_add(1)..).unwrap_or_default(), info.get(..nul).unwrap_or_default()); + // `count` includes the font record; never trusted beyond the data that is there. + let mut left = count.saturating_sub(1); + while left > 0 { + left -= 1; + let Ok(number) = r.u16() else { break }; + let Ok(len) = r.u16().map(usize::from) else { break }; + let start = r.pos; + let Some(end) = start.checked_add(len).filter(|e| *e <= bytes.len()) else { break }; + r.pos = end; + f.record(bytes, number, start, end); + } + f.finish(bytes.to_vec()) +} diff --git a/crates/fonts/src/shx/program.rs b/crates/fonts/src/shx/program.rs new file mode 100644 index 000000000..ecfab3e98 --- /dev/null +++ b/crates/fonts/src/shx/program.rs @@ -0,0 +1,344 @@ +//! The shape pen program: vector length/direction bytes and special codes 0–14, run into +//! polylines. Bounded everywhere: subshape depth, location stack, steps, points, coordinates. +//! +//! - A byte with a non-zero high nibble is a vector: length (high nibble) in one of 16 +//! directions (low nibble, counter-clockwise from east in 22.5° steps; the off-axis ones +//! are half-unit or unit steps on the minor axis). +//! - 0 end, 1 pen down, 2 pen up, 3/4 divide/multiply vector lengths by the next byte, +//! 5/6 push/pop the location, 7 subshape (one byte; two bytes high first in a Unicode font; +//! `0`, a two-byte number, base point, width and height in an extended big font), +//! 8 one X-Y displacement, 9 displacements up to (0,0), 10 octant arc (radius, +//! ±0SC: sign = clockwise, S start octant, C octants, 0 = 8), 11 fractional arc (start +//! offset, end offset, high and low radius, ±0SC; offsets in 1/256 of 45° from the octant +//! boundaries), 12 bulge arc (dx, dy, bulge: ±127 = semicircle), 13 bulge arcs up to (0,0), +//! 14 the next command is for vertical text only (dual-orientation fonts). +//! - Displacements and bulges are two's complement bytes; the arc direction byte keeps its +//! sign in the high bit. + +use std::f64::consts::{FRAC_PI_4, TAU}; + +use cadcraft_geom::Vec2; + +use super::{ShxFont, ShxGlyph, ShxKind}; + +/// Subshape nesting (a cycle ends here). +const MAX_DEPTH: usize = 16; +/// Location stack (the format promises four). +const MAX_STACK: usize = 64; +/// Bytes run per glyph, subshapes included. +const MAX_STEPS: usize = 200_000; +/// Points per glyph. +const MAX_POINTS: usize = 50_000; +/// Coordinates in font units. +const MAX_COORD: f64 = 1.0e7; +/// Arc segments per full turn. +const ARC_STEPS: f64 = 64.0; + +/// Why a program stops early: the glyph is then not drawn. +#[derive(Debug)] +pub(super) struct Broken; + +type Res = Result<(), Broken>; + +struct Pen<'a> { + font: &'a ShxFont, + vertical: bool, + pos: Vec2, + down: bool, + /// Vector length factor (codes 3 and 4). + scale: f64, + /// Per-axis factor of an extended big font subshape. + axes: Vec2, + stack: Vec, + strokes: Vec>, + active: Vec, + steps: usize, + points: usize, +} + +pub(super) fn outline(font: &ShxFont, number: u16, vertical: bool) -> Result { + let mut pen = Pen { + font, + vertical, + pos: Vec2::ZERO, + down: true, + scale: 1.0, + axes: Vec2::new(1.0, 1.0), + stack: Vec::new(), + strokes: Vec::new(), + active: Vec::new(), + steps: 0, + points: 0, + }; + pen.run(number, 0)?; + pen.flush(); + Ok(ShxGlyph { strokes: pen.strokes, advance: pen.pos }) +} + +/// The 16 vector directions (unit length on the major axis). +fn direction(d: u8) -> Vec2 { + let (x, y) = match d & 15 { + 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), + }; + Vec2::new(x, y) +} + +/// A two's complement operand byte. +fn signed(b: u8) -> f64 { + f64::from(i8::from_le_bytes([b])) +} + +/// A program being read: its bytes and position. +struct Cur<'p> { + b: &'p [u8], + pos: usize, +} + +impl Cur<'_> { + fn byte(&mut self) -> Result { + let v = self.b.get(self.pos).copied().ok_or(Broken)?; + self.pos += 1; + Ok(v) + } +} + +impl Pen<'_> { + fn step(&mut self) -> Res { + self.steps += 1; + if self.steps > MAX_STEPS { Err(Broken) } else { Ok(()) } + } + + fn flush(&mut self) { + if self.active.len() >= 2 { + self.strokes.push(std::mem::take(&mut self.active)); + } else { + self.active.clear(); + } + } + + /// Move the pen by `d` font units (already scaled), drawing when the pen is down. + fn to(&mut self, target: Vec2) -> Res { + if !target.is_finite() || target.x.abs().max(target.y.abs()) > MAX_COORD { + return Err(Broken); + } + if self.down { + if self.active.is_empty() { + self.active.push(self.pos); + self.points += 1; + } + self.active.push(target); + self.points += 1; + if self.points > MAX_POINTS { + return Err(Broken); + } + } else { + self.flush(); + } + self.pos = target; + Ok(()) + } + + /// A displacement in vector units (times the length factor and the subshape axes). + fn by(&mut self, d: Vec2) -> Res { + let k = d * self.scale; + self.to(self.pos + Vec2::new(k.x * self.axes.x, k.y * self.axes.y)) + } + + /// An arc of `radius` vector units from the pen, starting at angle `start` on its circle + /// and turning `sweep` radians (positive counter-clockwise). + fn arc(&mut self, radius: f64, start: f64, sweep: f64) -> Res { + let r = radius * self.scale; + if !(r.is_finite() && r > 0.0 && sweep.is_finite()) { + return Ok(()); + } + let n = if self.down { (sweep.abs() / TAU * ARC_STEPS).ceil().clamp(1.0, ARC_STEPS) as usize } else { 1 }; + let from = self.pos; + let s0 = Vec2::new(start.cos(), start.sin()); + for i in 1..=n { + let a = start + sweep * i as f64 / n as f64; + let d = (Vec2::new(a.cos(), a.sin()) - s0) * r; + self.to(from + Vec2::new(d.x * self.axes.x, d.y * self.axes.y))?; + } + Ok(()) + } + + /// An arc to the displacement `d` with `bulge` (−127..127, ±127 a semicircle). + fn bulge(&mut self, d: Vec2, bulge: f64) -> Res { + let b = bulge.clamp(-127.0, 127.0) / 127.0; + if b == 0.0 || !self.down || d.len2() == 0.0 { + return self.by(d); + } + // Centre from the chord midpoint along its left normal; sweep 4·atan(b). + let centre = d * 0.5 + Vec2::new(-d.y, d.x) * ((1.0 - b * b) / (4.0 * b)); + let rel = -centre; + self.arc(rel.len(), rel.y.atan2(rel.x), 4.0 * b.atan()) + } + + /// The octant byte `±0SC`: (clockwise, start octant, octants with 0 = 8). + fn octants(spec: u8) -> (f64, f64, f64) { + let sign = if spec & 0x80 != 0 { -1.0 } else { 1.0 }; + let s = f64::from((spec >> 4) & 7); + let c = match spec & 7 { + 0 => 8.0, + c => f64::from(c), + }; + (sign, s, c) + } + + /// The vector unit size of an extended big font's subshape cell. + fn cell(&self) -> Vec2 { + let h = if self.font.above > 0.0 { self.font.above } else { 1.0 }; + let w = if self.font.char_width > 0.0 { self.font.char_width } else { h }; + Vec2::new(w, h) + } + + fn run(&mut self, number: u16, depth: usize) -> Res { + if depth >= MAX_DEPTH { + return Err(Broken); + } + let program = self.font.program(number).ok_or(Broken)?; + let mut r = Cur { b: program, pos: 0 }; + let mut skip = false; + while r.pos < r.b.len() { + self.step()?; + let code = r.byte()?; + // Code 14: in a dual-orientation font the next command is for vertical text only. + let exec = !skip; + skip = false; + match code { + 0 => return Ok(()), + 1 if exec => self.down = true, + 2 if exec => { + self.down = false; + self.flush(); + } + 3 | 4 => { + let k = f64::from(r.byte()?); + if exec && k > 0.0 { + let s = if code == 3 { self.scale / k } else { self.scale * k }; + if !(1e-9..=MAX_COORD).contains(&s) { + return Err(Broken); + } + self.scale = s; + } + } + 5 if exec => { + if self.stack.len() >= MAX_STACK { + return Err(Broken); + } + self.stack.push(self.pos); + } + 6 if exec => { + self.flush(); + if let Some(p) = self.stack.pop() { + self.pos = p; + } + } + 7 => self.subshape(&mut r, exec, depth)?, + 8 | 9 | 12 | 13 => loop { + self.step()?; + let d = Vec2::new(signed(r.byte()?), signed(r.byte()?)); + if matches!(code, 9 | 13) && d == Vec2::ZERO { + break; + } + let bulge = if matches!(code, 12 | 13) { signed(r.byte()?) } else { 0.0 }; + if exec { + self.bulge(d, bulge)?; + } + if matches!(code, 8 | 12) { + break; + } + }, + 10 => { + let radius = f64::from(r.byte()?); + let (sign, s, c) = Self::octants(r.byte()?); + if exec { + self.arc(radius, s * FRAC_PI_4, sign * c * FRAC_PI_4)?; + } + } + 11 => { + let start = f64::from(r.byte()?) / 256.0; + let end = match r.byte()? { + 0 => 1.0, + e => f64::from(e) / 256.0, + }; + let radius = f64::from(u16::from_be_bytes([r.byte()?, r.byte()?])); + let (sign, s, c) = Self::octants(r.byte()?); + if exec { + // From `start` past the first octant boundary to `end` past the last + // octant's. + self.arc(radius, (s + sign * start) * FRAC_PI_4, sign * (c - 1.0 + end - start) * FRAC_PI_4)?; + } + } + 14 => skip = self.font.dual && !self.vertical && exec, + 1..=15 => {} + v => { + if exec { + self.by(direction(v) * f64::from(v >> 4))?; + } + } + } + } + Ok(()) + } + + /// Code 7 and its operands. + fn subshape(&mut self, r: &mut Cur, exec: bool, depth: usize) -> Res { + match self.font.kind { + ShxKind::Unifont => { + let n = u16::from_be_bytes([r.byte()?, r.byte()?]); + if exec { + self.run(n, depth + 1)?; + } + } + ShxKind::BigFont => { + let first = r.byte()?; + if first != 0 { + if exec { + self.run(u16::from(first), depth + 1)?; + } + return Ok(()); + } + // Extended: the primitive drawn in the box (x, y, width, height) of the cell. + let n = u16::from_be_bytes([r.byte()?, r.byte()?]); + let (x, y, w, h) = (f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?)); + if !exec { + return Ok(()); + } + let (pos, axes, down) = (self.pos, self.axes, self.down); + let cell = self.cell(); + self.flush(); + self.pos = pos + Vec2::new(x * axes.x, y * axes.y) * self.scale; + self.axes = Vec2::new(axes.x * w / cell.x, axes.y * h / cell.y); + let res = self.run(n, depth + 1); + self.flush(); + self.axes = axes; + self.pos = pos; + self.down = down; + res?; + } + ShxKind::Shapes => { + let n = u16::from(r.byte()?); + if exec { + self.run(n, depth + 1)?; + } + } + } + Ok(()) + } +} diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs new file mode 100644 index 000000000..9a002afaa --- /dev/null +++ b/crates/fonts/src/shx/table.rs @@ -0,0 +1,268 @@ +//! Finding SHX files by the name a text style or linetype gives (`romans.shx`, `GBCBIG`, +//! `C:\fonts\simplex.shx`): only the file name counts, so a path stored in a drawing never +//! reaches another folder or computer. +//! +//! 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`] +//! counts the changes, so a viewer knows to regenerate). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; + +use super::parse::MAX_FILE_BYTES; +use super::{ShxError, ShxFont}; + +/// Where an app finds font files CADCraft can't reach itself (a web page's file store, an +/// app's own font folder). Called with the normalised file name (`romans.shx`); returns the +/// file's bytes. Called without the font table's lock held. +pub trait FontProvider: Send + Sync { + fn load(&self, file_name: &str) -> Option>; +} + +/// Most fonts kept loaded, and their total bytes. +const MAX_FONTS: usize = 128; +const MAX_LOADED_BYTES: usize = 256 << 20; +/// Most drawing folders and search path entries remembered. +const MAX_DIRS: usize = 32; +/// Most font map entries. +const MAX_MAP: usize = 1024; + +#[derive(Default)] +struct Table { + registered: HashMap>, + resolved: HashMap>>, + loaded_bytes: usize, + provider: Option>, + drawing_dirs: Vec, + search_path: Vec, + map: Vec<(String, String)>, + generation: u64, +} + +impl Table { + /// Forget cached results: something that changes them changed. + fn changed(&mut self) { + self.resolved.clear(); + self.loaded_bytes = self.registered.values().map(|f| f.data.len()).sum(); + self.generation = self.generation.wrapping_add(1); + } +} + +fn table() -> MutexGuard<'static, Table> { + static T: OnceLock> = OnceLock::new(); + T.get_or_init(|| { + #[cfg(not(target_arch = "wasm32"))] + let search_path = std::env::var_os("CADCRAFT_SHXPATH") + .map(|p| std::env::split_paths(&p).filter(|d| !d.as_os_str().is_empty()).take(MAX_DIRS).collect()) + .unwrap_or_default(); + #[cfg(target_arch = "wasm32")] + let search_path = Vec::new(); + Mutex::new(Table { search_path, ..Table::default() }) + }) + .lock() + .unwrap_or_else(PoisonError::into_inner) +} + +/// The lookup key of a font name: its lower-case file name with `.shx` (`romans.shx`), or +/// `None` for a name that isn't an SHX file (a TrueType font, empty, the built-in font). +pub(crate) fn key(name: &str) -> Option { + let base = name.trim().rsplit(['/', '\\']).next()?.trim(); + if base.is_empty() || base.len() > 255 || base.contains(':') || base.chars().any(char::is_control) { + return None; + } + let lower = base.to_ascii_lowercase(); + if lower.ends_with(".shx") { + return (lower.len() > 4).then_some(lower); + } + let ext = Path::new(&lower).extension().map(|e| e.to_string_lossy().to_string()); + match ext.as_deref() { + // `txt` (no extension) is a classic style font name; other extensions are other kinds. + None => (lower != crate::BUILTIN_FONT.to_ascii_lowercase() && !lower.contains(' ')).then(|| format!("{lower}.shx")), + Some(_) => None, + } +} + +/// Register font bytes under a file name (the web build's files opened alongside a drawing; +/// tests). Replaces a font registered under the same name. +pub fn register(name: &str, bytes: &[u8]) -> Result<(), ShxError> { + let k = key(name).ok_or(ShxError::NotShx)?; + let font = Arc::new(ShxFont::parse(bytes)?); + let mut t = table(); + if !t.registered.contains_key(&k) && t.registered.len() >= MAX_FONTS { + return Err(ShxError::TooLarge); + } + t.registered.insert(k, font); + t.changed(); + Ok(()) +} + +/// Forget every registered font (a web session closing its drawings). +pub fn clear_registered() { + let mut t = table(); + t.registered.clear(); + t.changed(); +} + +/// Set (or clear) the app's font provider. +pub fn set_provider(provider: Option>) { + let mut t = table(); + t.provider = provider; + t.changed(); +} + +/// Search the folder of a drawing being opened for the fonts its styles name (most recent +/// first). +pub fn add_drawing_dir(dir: &Path) { + if dir.as_os_str().is_empty() { + return; + } + let mut t = table(); + if t.drawing_dirs.first().is_some_and(|d| d == dir) { + return; + } + t.drawing_dirs.retain(|d| d != dir); + t.drawing_dirs.insert(0, dir.to_path_buf()); + t.drawing_dirs.truncate(MAX_DIRS); + t.changed(); +} + +/// The drawing folders searched, most recent first. +pub fn drawing_dirs() -> Vec { + table().drawing_dirs.clone() +} + +/// 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) { + let dirs: Vec = list + .split(';') + .flat_map(|p| if cfg!(windows) { vec![PathBuf::from(p)] } else { std::env::split_paths(p).collect() }) + .filter(|d| !d.as_os_str().is_empty() && !d.to_string_lossy().trim().is_empty()) + .take(MAX_DIRS) + .collect(); + let mut t = table(); + t.search_path = dirs; + t.changed(); +} + +/// The support search path, `;`-separated. +pub fn search_path() -> String { + table().search_path.iter().map(|p| p.to_string_lossy().to_string()).collect::>().join(";") +} + +/// Set the font map: one `font;replacement` per line (or separated by `|`), as a font mapping +/// file lists them. Lines that aren't a pair are ignored; empty clears it. +pub fn set_font_map(text: &str) { + let map: Vec<(String, String)> = text + .split(['\n', '|']) + .filter_map(|l| { + let (a, b) = l.split_once(';')?; + Some((key(a)?, b.trim().to_string())) + }) + .filter(|(_, b)| !b.is_empty()) + .take(MAX_MAP) + .collect(); + let mut t = table(); + t.map = map; + t.changed(); +} + +/// The font map, one `font;replacement` per line. +pub fn font_map() -> String { + table().map.iter().map(|(a, b)| format!("{a};{b}")).collect::>().join("\n") +} + +/// Counts changes to what fonts are found (registration, provider, folders, map). +pub fn generation() -> u64 { + table().generation +} + +/// The SHX font file a style or linetype names, if CADCraft can find and read it. +pub fn find(name: &str) -> Option> { + let mut k = key(name)?; + let (provider, dirs) = { + let t = table(); + // The font map renames once (a map can't loop). + if let Some(to) = t.map.iter().find(|(from, _)| *from == k).and_then(|(_, to)| key(to)) { + k = to; + } + if let Some(f) = t.registered.get(&k) { + return Some(f.clone()); + } + 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(); + (t.provider.clone(), dirs) + }; + let generation = generation(); + let font = provider + .and_then(|p| p.load(&k)) + .or_else(|| read_from(&dirs, &k)) + .filter(|b| b.len() <= MAX_FILE_BYTES) + .and_then(|b| ShxFont::parse(&b).ok()) + .map(Arc::new); + let mut t = table(); + // Something changed while the file was read: keep the result out of the new cache. + if t.generation != generation { + return font; + } + if t.resolved.len() >= MAX_FONTS * 4 { + t.resolved.clear(); + t.loaded_bytes = t.registered.values().map(|f| f.data.len()).sum(); + } + let size = font.as_ref().map_or(0, |f| f.data.len()); + if t.loaded_bytes.saturating_add(size) > MAX_LOADED_BYTES { + // Over the memory bound: used, not kept. + return font; + } + t.loaded_bytes += size; + t.resolved.insert(k, font.clone()); + font +} + +/// Most directory entries looked at for a font file whose name differs only in case. +#[cfg(not(target_arch = "wasm32"))] +const MAX_DIR_ENTRIES: usize = 10_000; + +/// 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). +#[cfg(not(target_arch = "wasm32"))] +fn read_from(dirs: &[PathBuf], name: &str) -> Option> { + use std::io::Read as _; + let read = |file: &Path| -> Option> { + let meta = std::fs::metadata(file).ok()?; + if !meta.is_file() || meta.len() > MAX_FILE_BYTES as u64 { + return None; + } + let mut bytes = Vec::new(); + let limit = u64::try_from(MAX_FILE_BYTES).unwrap_or(u64::MAX).saturating_add(1); + std::fs::File::open(file).and_then(|f| f.take(limit).read_to_end(&mut bytes)).ok()?; + Some(bytes) + }; + for d in dirs { + if let Some(b) = [d.join(name), d.join(name.to_ascii_uppercase())].iter().find_map(|f| read(f)) { + return Some(b); + } + let Ok(entries) = std::fs::read_dir(d) else { continue }; + let found = entries + .take(MAX_DIR_ENTRIES) + .filter_map(Result::ok) + .find(|e| e.file_name().to_str().is_some_and(|n| n.eq_ignore_ascii_case(name))) + .and_then(|e| read(&e.path())); + if found.is_some() { + return found; + } + } + None +} + +#[cfg(target_arch = "wasm32")] +fn read_from(_dirs: &[PathBuf], _name: &str) -> Option> { + None +} diff --git a/crates/fonts/src/shx/tests.rs b/crates/fonts/src/shx/tests.rs new file mode 100644 index 000000000..a6ab40c99 --- /dev/null +++ b/crates/fonts/src/shx/tests.rs @@ -0,0 +1,450 @@ +//! SHX tests. Every font here is compiled from shape source written for these tests: no font +//! file is read from disk or committed. + +use std::f64::consts::PI; + +use cadcraft_geom::Vec2; + +use super::*; +use crate::{TextFont, TextParams}; + +/// A small dual-orientation text font: 6 units above, 2 below. +pub(crate) const TEXT_FONT: &str = "\ +;; CADCraft test font (written for the tests) +*0,4,cadcraft test +6,2,2,0 +*32,3,SPACE +2,060,0 +; A: up 6, right 4, down 6, then a gap of 2 +*65,7,UCA +1,064,040,06C,2,020,0 +; B: a displacement out and back, then 5 on +*66,10,UCB +2,010,1,8,(3,4),8,(-3,-4),2,050,0 +; C: vertical-only moves (code 14) +*67,12,UCC +2,14,8,(0,-8),1,064,2,14,8,(0,-6),040,0 +; the degree sign: a full octant circle +*256,12,DEGREE +2,8,(1,4),1,10,(1,0),2,8,(2,-4),0 +*257,6,PLUSMINUS +1,040,2,020,0 +*258,6,DIAMETER +1,044,2,020,0 +"; + +/// A Unicode font with the same letters, a subshape and the diameter sign at U+2205. +const UNI_FONT: &str = "\ +*UNIFONT,6,cadcraft uni +6,2,0,0,0,0 +*00041,7,uca +1,064,040,06C,2,020,0 +*000C5,9,ring a +7,00041,2,8,(-4,7),1,040,2,8,(2,-7),0 +*02205,6,diameter +1,044,2,020,0 +"; + +/// A big font with Shift-JIS lead bytes: one square character (U+3042, 0x82A0). +const BIG_FONT: &str = "\ +*BIGFONT 2,1,081,09F +*0,4,cadcraft big +8,0,0,0 +*082A0,7,square +1,080,084,088,08C,2,080,0 +"; + +/// An extended big font: two primitives of a 16 x 16 cell drawn into one character. +const EXT_BIG_FONT: &str = "\ +*BIGFONT 2,1,081,09F +*0,5,cadcraft ext +16,0,0,16,0 +*08F01,10,box +4,2,1,080,084,088,08C,3,2,0 +*082A2,20,two boxes +7,0,08F01,0,0,8,16,7,0,08F01,8,0,8,16,2,4,2,080,3,2,0 +"; + +fn font(src: &str) -> ShxFont { + ShxFont::parse(&compile(src).unwrap()).unwrap() +} + +/// A shape file (no font record) with one shape from `spec`. +fn one(spec: &str) -> ShxFont { + font(&format!("*1,1,T\n{spec}\n")) +} + +fn adv(spec: &str) -> Vec2 { + one(spec).glyph(1, false).unwrap().advance +} + +fn close(a: Vec2, b: Vec2) -> bool { + (a - b).len() < 1e-6 +} + +fn dir(deg: f64) -> Vec2 { + let r = deg.to_radians(); + Vec2::new(r.cos(), r.sin()) +} + +#[test] +fn every_vector_direction() { + let want = [ + (1.0, 0.0), + (1.0, 0.5), + (1.0, 1.0), + (0.5, 1.0), + (0.0, 1.0), + (-0.5, 1.0), + (-1.0, 1.0), + (-1.0, 0.5), + (-1.0, 0.0), + (-1.0, -0.5), + (-1.0, -1.0), + (-0.5, -1.0), + (0.0, -1.0), + (0.5, -1.0), + (1.0, -1.0), + (1.0, -0.5), + ]; + for (d, (x, y)) in want.iter().enumerate() { + let a = adv(&format!("02{d:X},0")); + assert!(close(a, Vec2::new(2.0 * x, 2.0 * y)), "direction {d}: {a:?}"); + } + // Length 15, the longest vector. + assert!(close(adv("0F0,0"), Vec2::new(15.0, 0.0))); +} + +#[test] +fn pen_up_down_scale_push_pop() { + let f = one("2,010,1,020,2,010,1,010,0"); + let g = f.glyph(1, false).unwrap(); + assert_eq!(g.strokes, vec![vec![Vec2::new(1.0, 0.0), Vec2::new(3.0, 0.0)], vec![Vec2::new(4.0, 0.0), Vec2::new(5.0, 0.0)]]); + // 4 multiplies, 3 divides: 3 + 1. + assert!(close(adv("4,3,010,3,3,010,0"), Vec2::new(4.0, 0.0))); + // Push, draw, pop: the next run starts where the push was. + let g = one("5,040,6,014,0").glyph(1, false).unwrap(); + assert_eq!(g.strokes.len(), 2); + assert!(close(g.strokes[1][0], Vec2::ZERO) && close(g.advance, Vec2::new(0.0, 1.0))); + // An unmatched pop is ignored. + assert!(close(adv("6,010,0"), Vec2::new(1.0, 0.0))); +} + +#[test] +fn displacements() { + assert!(close(adv("8,(-3,5),0"), Vec2::new(-3.0, 5.0))); + assert!(close(adv("9,(1,1),(2,-1),(-127,0),(0,0),0"), Vec2::new(-124.0, 0.0))); +} + +#[test] +fn octant_and_fractional_arcs() { + // A full circle comes back to where it started. + let g = one("10,(2,0),0").glyph(1, false).unwrap(); + assert!(close(g.advance, Vec2::ZERO)); + let maxx = g.strokes.iter().flatten().map(|p| p.x).fold(f64::MIN, f64::max); + assert!((maxx - 0.0).abs() < 1e-9 && g.strokes.iter().flatten().any(|p| (p.x + 4.0).abs() < 1e-6), "circle left of the pen"); + // Clockwise from octant 4 (180°), three octants: ends at 45°. + assert!(close(adv("10,(1,-043),0"), dir(45.0) - dir(180.0))); + // Counter-clockwise quarter from 0°. + assert!(close(adv("10,(3,002),0"), (dir(90.0) - dir(0.0)) * 3.0)); + // The documented fractional example: 55° to 95°, radius 3 (start octant 1, two octants). + let a0 = 45.0 + 56.0 / 256.0 * 45.0; + let a1 = 90.0 + 28.0 / 256.0 * 45.0; + assert!(close(adv("11,(56,28,0,3,012),0"), (dir(a1) - dir(a0)) * 3.0)); + // High radius byte: 256 + 4. + assert!(close(adv("11,(0,0,1,4,001),0"), (dir(45.0) - dir(0.0)) * 260.0)); +} + +#[test] +fn bulge_arcs() { + // A counter-clockwise semicircle up the chord bulges to the right... of the chord's left + // normal: from (0,0) to (0,4) about (0,2), through (2,2). + let g = one("12,(0,4,127),0").glyph(1, false).unwrap(); + assert!(close(g.advance, Vec2::new(0.0, 4.0))); + assert!(g.strokes.iter().flatten().any(|p| close(*p, Vec2::new(2.0, 2.0))), "{:?}", g.strokes); + // Bulge 0 is a straight line. + assert_eq!(one("12,(3,0,0),0").glyph(1, false).unwrap().strokes, vec![vec![Vec2::ZERO, Vec2::new(3.0, 0.0)]]); + // Polyarc: two arcs, then the (0,0) end without a bulge. + let g = one("13,(4,0,127),(0,4,-127),(0,0),010,0").glyph(1, false).unwrap(); + assert!(close(g.advance, Vec2::new(5.0, 4.0))); + assert!(g.strokes.iter().flatten().any(|p| (p.y + 2.0).abs() < 1e-6), "first arc dips below"); +} + +#[test] +fn vertical_only_commands_and_text_font_record() { + let f = font(TEXT_FONT); + assert_eq!((f.kind(), f.name(), f.above(), f.below(), f.is_dual(), f.is_font()), (ShxKind::Shapes, "cadcraft test", 6.0, 2.0, true, true)); + let h = f.glyph(67, false).unwrap(); + assert_eq!(h.strokes, vec![vec![Vec2::ZERO, Vec2::new(0.0, 6.0)]]); + let v = f.glyph(67, true).unwrap(); + assert_eq!(v.strokes, vec![vec![Vec2::new(0.0, -8.0), Vec2::new(0.0, -2.0)]]); + assert!(close(v.advance, Vec2::new(4.0, -8.0))); + // A font that isn't dual runs code 14's command in horizontal text too. + let g = one("2,14,8,(0,-8),0").glyph(1, false).unwrap(); + assert!(close(g.advance, Vec2::new(0.0, -8.0))); + assert_eq!(f.shape_number("ucb"), Some(66)); + assert_eq!(f.shape_name(65).as_deref(), Some("UCA")); + assert_eq!(f.shape_numbers().first(), Some(&32)); +} + +#[test] +fn subshapes_shapes_unicode_and_extended_big_font() { + let s = font("*1,4,BAR\n1,030,0\n*2,6,TWO\n7,1,7,1,0\n"); + assert!(close(s.glyph(2, false).unwrap().advance, Vec2::new(6.0, 0.0))); + let u = font(UNI_FONT); + assert_eq!((u.kind(), u.name(), u.above(), u.encoding()), (ShxKind::Unifont, "cadcraft uni", 6.0, 0)); + let ring = u.glyph(0xC5, false).unwrap(); + assert_eq!(ring.strokes.len(), 2, "the A and the ring's bar"); + assert!(close(ring.advance, Vec2::new(8.0, 0.0))); + let e = font(EXT_BIG_FONT); + assert_eq!((e.kind(), e.above()), (ShxKind::BigFont, 16.0)); + let g = e.glyph(0x82A2, false).unwrap(); + assert_eq!(g.strokes.len(), 2); + let xs: Vec<(f64, f64)> = g.strokes.iter().map(|s| s.iter().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.x), b.max(p.x)))).collect(); + assert_eq!(xs, vec![(0.0, 8.0), (8.0, 16.0)], "each primitive squeezed into half the cell"); + let ys = g.strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y))); + assert_eq!(ys, (0.0, 16.0)); + assert!(close(g.advance, Vec2::new(16.0, 0.0))); +} + +#[test] +fn big_font_header_and_escape_ranges() { + let b = font(BIG_FONT); + assert_eq!(b.kind(), ShxKind::BigFont); + assert_eq!(b.escape_ranges(), &[(0x81, 0x9F)]); + assert!(b.is_lead_byte(0x82) && !b.is_lead_byte(0x41) && !b.is_lead_byte(0xA0)); + assert_eq!(b.above(), 8.0); + assert!(b.has_shape(0x82A0)); +} + +#[test] +fn cyclic_and_deep_subshapes_are_bounded() { + let f = font("*1,3,SELF\n7,1,0\n*2,3,A\n7,3,0\n*3,3,B\n7,2,0\n*4,3,MISSING\n7,9,0\n"); + for n in 1..=4 { + assert!(f.glyph(n, false).is_none(), "shape {n}"); + } + // A chain deeper than the bound fails; a shallow one draws. + let mut src = String::new(); + for n in 1..=40u16 { + if n == 40 { + src.push_str(&format!("*{n},2,L\n010,0\n")); + } else { + src.push_str(&format!("*{n},3,L\n7,{},0\n", n + 1)); + } + } + let f = font(&src); + assert!(f.glyph(1, false).is_none() && f.glyph(30, false).is_some()); + // Doubling with subshapes: 2^n steps are cut off by the step bound. + let mut src = String::from("*1,2,L\n010,0\n"); + for n in 2..=10u16 { + src.push_str(&format!("*{n},9,D\n7,{0},7,{0},7,{0},7,{0},0\n", n - 1)); + } + let f = font(&src); + assert!(f.glyph(10, false).is_none() && f.glyph(3, false).is_some()); + // Pushes without pops, and runaway scales. + let pushes = format!("{}0", "5,".repeat(100)); + assert!(one(&pushes).glyph(1, false).is_none()); + let scales = format!("{}010,0", "4,255,".repeat(10)); + assert!(one(&scales).glyph(1, false).is_none()); + // A zero radius or a zero factor draws nothing and doesn't fail. + assert!(one("10,(0,001),4,0,010,0").glyph(1, false).is_some()); +} + +/// Parse every prefix and many mutations of `bytes`; draw every shape of whatever parses. +fn hammer(bytes: &[u8]) { + let draw = |b: &[u8]| { + if let Ok(f) = ShxFont::parse(b) { + for n in f.shape_numbers() { + let _ = f.glyph(n, false); + let _ = f.glyph(n, true); + } + let _ = f.shape_number("X"); + } + }; + for n in 0..=bytes.len() { + draw(&bytes[..n]); + } + let mut seed: u64 = 0x5EED_1234; + for _ in 0..2000 { + let mut b = bytes.to_vec(); + for _ in 0..3 { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let i = (seed >> 33) as usize % b.len().max(1); + if let Some(x) = b.get_mut(i) { + *x = (seed >> 24) as u8; + } + } + draw(&b); + } +} + +#[test] +fn hostile_files_never_panic() { + for src in [TEXT_FONT, UNI_FONT, BIG_FONT, EXT_BIG_FONT] { + hammer(&compile(src).unwrap()); + } + // Counts far beyond the data. + let mut shapes = parse::SHAPES_10.to_vec(); + shapes.extend([1, 0, 0xFF, 0xFF, 0xFF, 0xFF]); + assert_eq!(ShxFont::parse(&shapes).err(), Some(ShxError::Truncated)); + let mut big = parse::BIGFONT.to_vec(); + big.extend([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); + assert_eq!(ShxFont::parse(&big).err(), Some(ShxError::TooLarge)); + let mut big = parse::BIGFONT.to_vec(); + big.extend([0xFF, 0xFF, 0xFF, 0xFF, 0, 0]); + assert_eq!(ShxFont::parse(&big).err(), Some(ShxError::Truncated)); + // A big font index pointing anywhere. + let mut big = parse::BIGFONT.to_vec(); + big.extend([1, 0, 1, 0, 0, 0, 0x41, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F]); + assert_eq!(ShxFont::parse(&big).err(), Some(ShxError::Empty)); + let mut uni = parse::UNIFONT.to_vec(); + uni.extend([0xFF, 0xFF, 0xFF, 0xFF, 2, 0, b'x', 0]); + assert_eq!(ShxFont::parse(&uni).err(), Some(ShxError::Empty)); + assert_eq!(ShxFont::parse(b"not a font").err(), Some(ShxError::NotShx)); + assert_eq!(ShxFont::parse(&[]).err(), Some(ShxError::NotShx)); + // Hostile shape source. + for src in ["*1,2,X\n7\n", "*1,2,X\n9,(1,1)\n", "*99999,1,X\n0\n", "*1,1,X\n300,0\n", "010,0\n", "*1,1,X\n1,0zz,0\n", "*1,1,X\n0\n*1,1,Y\n0\n"] { + assert!(compile(src).is_err(), "{src:?}"); + } + assert!(compile("").is_err()); +} + +/// Register a compiled test font under `name` (each test its own names: the table is shared). +fn reg(name: &str, src: &str) { + register(name, &compile(src).unwrap()).unwrap(); +} + +#[test] +fn text_metrics_follow_the_font() { + reg("cadcraft-test-metrics.shx", TEXT_FONT); + let f = TextFont::resolve_style("CADCRAFT-TEST-METRICS", "", false); + assert!(f.is_shx() && !f.is_outline()); + let h = 3.0; + // Advances are the pen's end positions: A 6, B 6, at h / above = 0.5. + assert!((crate::text_width(&f, "AB", h, 1.0) - 6.0).abs() < 1e-9); + assert!((crate::text_width(&f, "AB", h, 0.5) - 3.0).abs() < 1e-9); + let sh = crate::shape_line(&f, "AB", h, 1.0, 0.0); + assert!((sh.width - 6.0).abs() < 1e-9); + let ys = sh.strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y))); + assert_eq!(ys, (0.0, 3.0), "cap height = text height"); + // %%d %%p %%c come from shapes 256-258; \U+0041 is A. + assert!((crate::text_width(&f, "%%d", h, 1.0) - 1.5).abs() < 1e-9); + assert!((crate::text_width(&f, "%%p%%c", h, 1.0) - 4.0).abs() < 1e-9); + assert!((crate::text_width(&f, "\\U+0041", h, 1.0) - 3.0).abs() < 1e-9); + assert_eq!(crate::shape_line(&f, "\\U+0041", h, 1.0, 0.0), crate::shape_line(&f, "A", h, 1.0, 0.0)); + // A character the font lacks comes from the stroke font, with its advance. + let z = crate::text_width(&f, "Z", h, 1.0); + assert!((z - crate::stroke_advance('Z', h, 1.0)).abs() < 1e-9); + assert!(!crate::shape_line(&f, "Z", h, 1.0, 0.0).strokes.is_empty()); + // Widths and shapes agree, with obliquing, underline and mixed fallbacks. + for s in ["AB AZ", "%%uAB%%u", "A\u{3042}B"] { + let sh = crate::shape_line(&f, s, h, 0.8, 0.2); + assert!((sh.width - crate::text_width(&f, s, h, 0.8)).abs() < 1e-9, "{s}"); + } + // Placement: centred text sits on the alignment point by the font's own width. + let p = TextParams { h: crate::Align::Center, align_pt: Some(Vec2::new(10.0, 0.0)), ..TextParams::new(Vec2::ZERO, h) }; + let (_, bb) = crate::place(&f, "AB", &p); + assert!((bb.center().x - 10.0).abs() < 1e-9 && (bb.width() - 6.0).abs() < 1e-9); + // MTEXT with the style's SHX font, and its \U+ escape. + let mp = crate::MTextParams { font: f.clone(), ..crate::MTextParams::new(Vec2::ZERO, h) }; + let m = crate::layout_mtext_with("\\U+0041B", &mp); + assert_eq!(m.lines, vec!["AB".to_string()]); + assert_eq!(crate::space_width(&f, h, 1.0), 3.0); +} + +#[test] +fn unifont_text_and_specials() { + reg("cadcraft-test-uni.shx", UNI_FONT); + let f = TextFont::resolve("cadcraft-test-uni.shx"); + assert!((crate::text_width(&f, "A\u{C5}", 6.0, 1.0) - 14.0).abs() < 1e-9); + // %%c is the diameter sign, at U+2205 in this font. + assert!((crate::text_width(&f, "%%c", 6.0, 1.0) - 2.0).abs() < 1e-9); +} + +#[test] +fn big_font_draws_double_byte_characters() { + reg("cadcraft-test-main.shx", TEXT_FONT); + reg("cadcraft-test-big.shx", BIG_FONT); + let f = TextFont::resolve_style("cadcraft-test-main.shx", "cadcraft-test-big.shx", false); + let TextFont::Shx(t) = &f else { panic!("SHX") }; + assert_eq!(t.big_font_encoding(), "Shift_JIS"); + let h = 2.5; + // あ (Shift-JIS 82A0) fills a square cell of the text height. + let w = crate::text_width(&f, "\u{3042}", h, 1.0); + assert!((w - h).abs() < 1e-9, "{w}"); + let sh = crate::shape_line(&f, "A\u{3042}", h, 1.0, 0.0); + let big: Vec = sh.strokes.iter().flatten().copied().filter(|p| p.x > 2.5 - 1e-9).collect(); + let ys = big.iter().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y))); + assert_eq!(ys, (0.0, h)); + // Only the big font found: Latin letters from the stroke font, the big font's own. + let f = TextFont::resolve_style("cadcraft-missing-main-font.shx", "cadcraft-test-big.shx", false); + assert!(f.is_shx()); + assert!((crate::text_width(&f, "\u{3042}", h, 1.0) - h).abs() < 1e-9); + assert!((crate::text_width(&f, "A", h, 1.0) - crate::stroke_advance('A', h, 1.0)).abs() < 1e-9); + // Neither found: the stroke font as before. + assert!(!TextFont::resolve_style("cadcraft-missing-a.shx", "cadcraft-missing-b.shx", false).is_shx()); +} + +#[test] +fn big_font_code_pages() { + for (name, ranges, want) in [ + ("gbcbig.shx", vec![(0xA1, 0xFE)], "GBK"), + ("chineset.shx", vec![(0xA1, 0xFE)], "Big5"), + ("whgtxt.shx", vec![(0xA1, 0xFE)], "EUC-KR"), + ("extfont2.shx", vec![(0x81, 0x9F)], "Shift_JIS"), + ("custom.shx", vec![(0x81, 0x9F), (0xE0, 0xFC)], "Shift_JIS"), + ("custom.shx", vec![(0xA1, 0xFE)], "GBK"), + ] { + let src = format!( + "*BIGFONT 1,{},{}\n*0,4,x\n8,0,0,0\n*0FFFF,2,x\n010,0\n", + ranges.len(), + ranges.iter().map(|(a, b)| format!("0{a:X},0{b:X}")).collect::>().join(",") + ); + let b = std::sync::Arc::new(font(&src)); + assert_eq!(ShxText::new(None, Some(b), name, false).big_font_encoding(), want, "{name}"); + } +} + +#[test] +fn vertical_text_runs_down() { + reg("cadcraft-test-vertical.shx", TEXT_FONT); + let v = TextFont::resolve_style("cadcraft-test-vertical.shx", "", true); + let sh = crate::shape_line(&v, "CC", 1.0, 1.0, 0.0); + let miny = sh.strokes.iter().flatten().map(|p| p.y).fold(f64::MAX, f64::min); + // Two characters, each 8 units (8/6 of the height) down. + assert!((miny + 16.0 / 6.0).abs() < 1e-9, "{miny}"); + assert!(sh.strokes.iter().flatten().all(|p| p.y <= 1e-9), "below the insertion point"); + // A font without modes 2 stays horizontal. + reg("cadcraft-test-horizontal.shx", "*0,4,h\n6,2,0,0\n*67,3,C\n1,064,0\n"); + let h = TextFont::resolve_style("cadcraft-test-horizontal.shx", "", true); + assert!(crate::shape_line(&h, "CC", 1.0, 1.0, 0.0).strokes.iter().flatten().all(|p| p.y >= -1e-9)); +} + +#[test] +fn names_and_lookup() { + assert_eq!(table::key("ROMANS.SHX").as_deref(), Some("romans.shx")); + assert_eq!(table::key("txt").as_deref(), Some("txt.shx")); + assert_eq!(table::key(r"C:\Fonts\Simplex.shx").as_deref(), Some("simplex.shx")); + assert_eq!(table::key("../x/gbcbig.shx").as_deref(), Some("gbcbig.shx")); + for n in ["", "arial.ttf", "CADCraft Stroke", "Times New Roman", ".shx", "a\u{0}.shx"] { + assert_eq!(table::key(n), None, "{n:?}"); + } + assert!(register("not-a-font.ttf", &compile(TEXT_FONT).unwrap()).is_err()); + assert!(register("broken.shx", b"AutoCAD-86 shapes 1.0\r\n\x1a").is_err()); + // A path stored in a drawing only names the file. + reg("cadcraft-test-path.shx", TEXT_FONT); + assert!(find(r"\\server\share\CADCRAFT-TEST-PATH.SHX").is_some()); + assert!(find("cadcraft-never-registered.shx").is_none()); +} + +#[test] +fn arcs_follow_the_circle() { + // Every point of an octant arc is on its circle. + let g = one("10,(5,034),0").glyph(1, false).unwrap(); + let c = -dir(135.0) * 5.0; + for p in g.strokes.iter().flatten() { + assert!(((*p - c).len() - 5.0).abs() < 1e-9); + } + assert!(close(g.advance, (dir(135.0 + 180.0) - dir(135.0)) * 5.0)); + let _ = PI; +} diff --git a/crates/fonts/src/shx/text.rs b/crates/fonts/src/shx/text.rs new file mode 100644 index 000000000..0e7e6513e --- /dev/null +++ b/crates/fonts/src/shx/text.rs @@ -0,0 +1,202 @@ +//! Text set in SHX fonts: a text style's main font and big font, horizontal or vertical. +//! +//! Each character is drawn by the font that has it: a double-byte character of the big font's +//! code page (its lead byte in an escape range) from the big font, others from the main font +//! (character code, or Unicode in a Unicode font; `%%d` `%%p` `%%c` from shapes 256–258 or their +//! older or Unicode places). A font draws at text height / its `above` value, and its pen's end +//! position is the advance: there is no added letter gap. Characters neither font has come from +//! the built-in stroke font (and its fallback fonts), so nothing goes missing. +//! +//! Vertical text (a style flag, for fonts with modes 2) runs each shape's vertical-only +//! commands (code 14) and follows the pen downward. + +use std::sync::Arc; + +use cadcraft_geom::Vec2; +use encoding_rs::Encoding; + +use super::{ShxFont, ShxKind}; +use crate::{Shaped, bidi}; + +/// A text style's SHX fonts: the main font, the big font and the orientation. Either font may +/// be missing (not found): its characters then come from the stroke font. +#[derive(Clone, Debug)] +pub struct ShxText { + pub main: Option>, + pub big: Option>, + /// The style is vertical and the main font supports it. + pub vertical: bool, + /// The big font's code page (from its name and escape ranges). + big_encoding: &'static Encoding, +} + +impl ShxText { + /// The fonts of a style: `big_name` is the big font's file name (it picks the code page). + pub fn new(main: Option>, big: Option>, big_name: &str, vertical: bool) -> ShxText { + let big_encoding = big.as_deref().map_or(encoding_rs::GBK, |b| big_font_encoding(big_name, b.escape_ranges())); + let vertical = vertical && main.as_ref().is_some_and(|m| m.is_dual()); + ShxText { main, big, vertical, big_encoding } + } + /// The code page of the big font's double-byte codes. + pub fn big_font_encoding(&self) -> &'static str { + self.big_encoding.name() + } +} + +/// The code page a big font's double-byte codes are in: known Japanese, Chinese and Korean +/// big font names, else its escape ranges (Shift-JIS lead bytes from 0x81; the others start at +/// 0xA1 or above, read as GBK). +fn big_font_encoding(name: &str, ranges: &[(u16, u16)]) -> &'static Encoding { + let stem = name.trim().rsplit(['/', '\\']).next().unwrap_or_default().to_ascii_lowercase(); + let stem = stem.trim_end_matches(".shx").trim_start_matches('@'); + if stem.starts_with("whg") || stem.starts_with("wht") || stem.contains("kor") || stem.contains("ksc") { + return encoding_rs::EUC_KR; + } + if stem.starts_with("chineset") || stem.contains("big5") || stem.starts_with("cht") { + return encoding_rs::BIG5; + } + if stem.starts_with("gb") || stem.starts_with("hz") || stem.contains("chs") { + return encoding_rs::GBK; + } + if stem.starts_with("bigfont") || stem.starts_with("extfont") || stem.contains("jis") || stem.contains("jpn") { + return encoding_rs::SHIFT_JIS; + } + if ranges.iter().any(|(lo, _)| (0x81..0xA1).contains(lo)) { encoding_rs::SHIFT_JIS } else { encoding_rs::GBK } +} + +/// The double-byte code of `c` in `enc`, if it has one. +fn double_byte(c: char, enc: &'static Encoding) -> Option { + let mut buf = [0u8; 4]; + let (bytes, _, errors) = enc.encode(c.encode_utf8(&mut buf)); + match (errors, bytes.as_ref()) { + (false, [a, b]) => Some(u16::from_be_bytes([*a, *b])), + _ => None, + } +} + +/// The shape numbers that may draw `c` in `font`, best first. +fn candidates(c: char, font: &ShxFont) -> [Option; 4] { + let u = u32::from(c); + let unicode = font.kind() == ShxKind::Unifont && font.encoding() == 0; + let code = |x: u32| u16::try_from(x).ok(); + // The special characters of `%%d` `%%p` `%%c`: shapes 256–258, the Latin-1 or Unicode code, + // and the oldest fonts' 127–129. + let special = match c { + '°' => Some((256, 0xB0, 127)), + '±' => Some((257, 0xB1, 128)), + '⌀' | '∅' => Some((258, u, 129)), + _ => None, + }; + if let Some((s, latin, old)) = special { + return if unicode { + [code(u), code(if c == '⌀' { 0x2205 } else { latin }), Some(s), Some(old)] + } else { + [Some(s), code(latin), Some(old), None] + }; + } + if unicode || u < 0x80 { + return [code(u), None, 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]; + let (bytes, _, errors) = encoding_rs::WINDOWS_1252.encode(c.encode_utf8(&mut buf)); + match (errors, bytes.as_ref()) { + (false, [b]) if !(127..=129).contains(b) => [Some(u16::from(*b)), None, None, None], + _ => [None, None, None, None], + } +} + +/// The font and shape that draw `c`. +fn pick(t: &ShxText, c: char) -> Option<(&ShxFont, u16)> { + let from_main = || { + let m = t.main.as_deref()?; + candidates(c, m).into_iter().flatten().find(|n| m.has_shape(*n)).map(|n| (m, n)) + }; + let from_big = || { + let b = t.big.as_deref()?; + let code = double_byte(c, t.big_encoding)?; + let [lead, _] = code.to_be_bytes(); + (b.is_lead_byte(lead) && b.has_shape(code)).then_some((b, code)) + }; + if u32::from(c) < 0x100 || matches!(c, '⌀' | '∅') { from_main().or_else(from_big) } else { from_big().or_else(from_main) } +} + +fn finite_or(v: f64, d: f64) -> f64 { + if v.is_finite() { v } else { d } +} + +/// Shape one line (baseline at y = 0, x from 0). +pub(crate) fn shape(t: &ShxText, s: &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 shear = finite_or(oblique, 0.0).tan().clamp(-10.0, 10.0); + let chars = crate::decode_controls(s); + let logical: Vec = chars.iter().map(|v| v.0).collect(); + let mut out = Shaped::default(); + let mut spans: Vec<(f64, f64, bool, bool)> = Vec::new(); + let mut pen = Vec2::ZERO; + let mut max_x: f64 = 0.0; + let runs = if t.vertical { vec![(0..logical.len(), false)] } else { bidi::visual_runs(&logical, None) }; + for (run, rtl) in runs { + let order: Box> = if rtl { Box::new(run.rev()) } else { Box::new(run) }; + for i in order { + 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 x0 = pen.x; + match pick(t, c).and_then(|(f, n)| Some((f, f.glyph(n, t.vertical)?))) { + Some((f, g)) => { + let k = h / f.units_per_height(); + let place = |p: Vec2| Vec2::new(pen.x + p.x * k * wf + p.y * k * shear, pen.y + p.y * k); + for st in &g.strokes { + let pts: Vec = st.iter().map(|p| place(*p)).collect(); + max_x = pts.iter().fold(max_x, |m, p| m.max(p.x)); + out.strokes.push(pts); + } + let adv = Vec2::new(g.advance.x * k * wf, g.advance.y * k); + pen = if t.vertical { pen + adv } else { Vec2::new(pen.x + adv.x, pen.y) }; + } + None => { + // The stroke font draws it, at the pen. + let mut fb = crate::shape_stroke(&c.to_string(), h, wf, oblique); + let at = pen; + fb.map(|p| p + at); + max_x = max_x.max(at.x + fb.width); + out.extend(fb); + if t.vertical { + pen.y -= h * 1.5; + } else { + pen.x += crate::stroke_advance(c, h, wf); + } + } + } + if !t.vertical { + spans.push((x0, pen.x, under, over)); + } + } + } + out.strokes.extend(crate::decorations(&spans, h)); + out.width = if t.vertical { max_x.max(0.0) } else { pen.x.max(0.0) }; + out +} + +/// The width of one line: the sum of the advances. +pub(crate) fn width(t: &ShxText, s: &str, height: f64, width_factor: f64) -> f64 { + if t.vertical || bidi::has_rtl(s) { + return shape(t, s, 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(s) + .into_iter() + .filter(|(c, _, _)| !bidi::is_format_control(*c)) + .map(|(c, _, _)| match pick(t, c).and_then(|(f, n)| Some((f, f.glyph(n, false)?))) { + Some((f, g)) => g.advance.x * h / f.units_per_height() * wf, + None => crate::stroke_advance(c, h, wf), + }) + .sum::() + .max(0.0) +} diff --git a/crates/fonts/tests/shx_lookup.rs b/crates/fonts/tests/shx_lookup.rs new file mode 100644 index 000000000..b5feb5a70 --- /dev/null +++ b/crates/fonts/tests/shx_lookup.rs @@ -0,0 +1,76 @@ +//! How SHX fonts are found: drawing folders, the search path, the font map, an app's font +//! provider and FONTALT. Process-wide settings, so one test in its own binary. The fonts are +//! compiled here from shape source written for the test; nothing is read from a CAD install. + +use std::sync::Arc; + +use cadcraft_fonts::shx::{self, FontProvider}; +use cadcraft_fonts::{TextFont, ttf}; + +const FONT: &str = "*0,4,lookup test\n6,2,0,0\n*65,4,UCA\n1,064,0\n"; + +struct Provider; + +impl FontProvider for Provider { + fn load(&self, file_name: &str) -> Option> { + (file_name == "cadcraft-provided.shx").then(|| shx::compile(FONT).ok()).flatten() + } +} + +#[test] +fn fonts_are_found_where_the_drawing_and_the_app_keep_them() { + let bytes = shx::compile(FONT).unwrap(); + let dir = std::env::temp_dir().join(format!("cadcraft-shx-lookup-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("cadcraft-beside.shx"), &bytes).unwrap(); + + // Beside the drawing: found once the drawing's folder is known; a later change of folders + // starts a new generation (viewers regenerate). + assert!(shx::find("cadcraft-beside.shx").is_none()); + let g = shx::generation(); + shx::add_drawing_dir(&dir); + assert!(shx::generation() != g); + assert_eq!(shx::drawing_dirs().first(), Some(&dir)); + assert!(shx::find("CADCRAFT-BESIDE").is_some_and(|f| f.has_shape(65))); + assert!(TextFont::resolve("cadcraft-beside.shx").is_shx()); + // A file whose name has another case than the drawing's (found on case-sensitive systems + // too, by looking through the folder). + std::fs::write(dir.join("CadCraft-Mixed.SHX"), &bytes).unwrap(); + assert!(shx::find("cadcraft-mixed.shx").is_some()); + + // The search path, and the font map renaming a font to one that is there. + let other = dir.join("lib"); + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(other.join("cadcraft-onpath.shx"), &bytes).unwrap(); + assert!(shx::find("cadcraft-onpath.shx").is_none()); + shx::set_search_path(&other.to_string_lossy()); + assert!(shx::find("cadcraft-onpath.shx").is_some()); + shx::set_font_map("cadcraft-old.shx;cadcraft-onpath.shx\nnonsense"); + assert_eq!(shx::font_map(), "cadcraft-old.shx;cadcraft-onpath.shx"); + assert!(shx::find("cadcraft-old").is_some()); + shx::set_font_map(""); + + // An app's provider (the web build's file store). + assert!(shx::find("cadcraft-provided.shx").is_none()); + shx::set_provider(Some(Arc::new(Provider))); + assert!(shx::find("cadcraft-provided.shx").is_some()); + shx::set_provider(None); + assert!(shx::find("cadcraft-provided.shx").is_none()); + + // FONTALT replaces a missing SHX font (and may name a big font after a comma). + assert!(!TextFont::resolve("cadcraft-missing.shx").is_shx()); + ttf::set_font_alt("cadcraft-beside.shx"); + assert!(TextFont::resolve("cadcraft-missing.shx").is_shx()); + assert!(!TextFont::resolve("").is_shx(), "the built-in font is not replaced"); + ttf::set_font_alt(""); + + // Registered bytes (files opened alongside a drawing on the web) and clearing them. + shx::register("cadcraft-registered.shx", &bytes).unwrap(); + assert!(shx::find("cadcraft-registered.shx").is_some()); + shx::clear_registered(); + assert!(shx::find("cadcraft-registered.shx").is_none()); + + shx::set_search_path(""); + assert_eq!(shx::search_path(), ""); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/render/src/dim_draw.rs b/crates/render/src/dim_draw.rs index b31ff13b4..297d09b07 100644 --- a/crates/render/src/dim_draw.rs +++ b/crates/render/src/dim_draw.rs @@ -7,7 +7,7 @@ use super::*; /// The font settings of a dimension style's text style. pub fn dim_text(d: &Drawing, st: &cadcraft_doc::DimStyle) -> DimText { let ts = text_style(d, &st.text_style); - DimText { font: cadcraft_fonts::TextFont::resolve(&ts.font), fixed_height: ts.height, width_factor: ts.width_factor, oblique: ts.oblique } + DimText { font: style_font(&ts), fixed_height: ts.height, width_factor: ts.width_factor, oblique: ts.oblique } } /// Geometry of a dimension in a drawing: its style, overrides and text font. diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 5ce0bd6c0..8faf17595 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -86,7 +86,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { b.polyline(ctx, rgb, lw, &dash); } } - // Text embedded in the linetype (shapes need SHX files and are not drawn). + // Text and shapes embedded in the linetype (shapes when their SHX file is found). if b.opts.text { for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min) { b.shaped(ctx, rgb, lw, &sh); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5b9dc83a1..199d43508 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -315,7 +315,7 @@ pub use display::{DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText 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}; +pub use text_entity::{layout_mtext_entity, place_text_entity, style_font, text_align}; pub use viewports::{viewport_clip, viewport_content}; #[cfg(test)] diff --git a/crates/render/src/linetype_text.rs b/crates/render/src/linetype_text.rs index a012f0df0..97770c2b2 100644 --- a/crates/render/src/linetype_text.rs +++ b/crates/render/src/linetype_text.rs @@ -1,9 +1,10 @@ -//! Text embedded in complex linetypes (a gas line's `---- GAS ---- GAS ----`). +//! Text and shapes embedded in complex linetypes (a gas line's `---- GAS ---- GAS ----`, a +//! fence's crosses). //! -//! A dash element may carry a text (DXF `74` bit 2, `9` string). As in a `.lin` definition, -//! where the bracketed text follows the dash or gap that carries it, the text is placed where -//! that element ends, at every repeat of the pattern (laid out from the start of the run like -//! [`crate::linetype::apply`]): +//! A dash element may carry a text (DXF `74` bit 2, `9` string) or a shape (`74` bit 4, `75` +//! shape number). As in a `.lin` definition, where the bracketed text or shape follows the dash +//! or gap that carries it, it is placed where that element ends, at every repeat of the pattern +//! (laid out from the start of the run like [`crate::linetype::apply`]): //! - height: the element's scale (`46`), times the text style's fixed height when it has one, //! times the linetype scale; //! - origin: the anchor shifted by the X/Y offsets (`44`/`45`, times the linetype scale) along @@ -11,17 +12,21 @@ //! - rotation (`50`): relative to the line direction, or absolute (`74` bit 1); //! - font, width factor, oblique angle and mirroring from the text style (`340`). //! -//! Shape elements (`74` bit 4) need SHX shape files, which CADCraft does not read: they draw -//! nothing and leave their gap empty. +//! A shape comes from the SHX shape file its style (`340`) names, as the font table finds it +//! ([`cadcraft_fonts::shx::find`]): an unnamed shape-file style is read as its file name, a +//! named style by its font. It is drawn at the element's scale times the linetype scale per +//! text height of the file (its font record's `above`, else one vector unit), rotated and +//! offset like text. A shape whose file isn't found draws nothing and leaves its gap empty. use cadcraft_doc::{Drawing, Linetype}; -use cadcraft_fonts::{Shaped, TextFont, TextParams}; +use cadcraft_fonts::{Shaped, TextParams}; use cadcraft_geom::Vec2; -/// Upper bound on the texts drawn along one run (hostile scales; `apply` caps the dashes). +/// Upper bound on the texts and shapes drawn along one run (hostile scales; `apply` caps the +/// dashes). const MAX_TEXTS: usize = 10_000; -/// One text element of the pattern, shaped once at the origin. +/// One text or shape element of the pattern, shaped once at the origin. struct Element { /// Distance from the start of a pattern repeat to the anchor (where the element ends). at: f64, @@ -31,12 +36,12 @@ struct Element { offset: Vec2, } -/// The texts of `lt` along the polyline `pts`, in the coordinates of `pts`. Empty when the -/// linetype has no text or its scaled pattern is drawn continuous (shorter than `min_pattern`, -/// or repeating too often). +/// The texts and shapes of `lt` along the polyline `pts`, in the coordinates of `pts`. Empty +/// when the linetype has none or its scaled pattern is drawn continuous (shorter than +/// `min_pattern`, or repeating too often). pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec { let mut out = Vec::new(); - if pts.len() < 2 || !lt.pattern.iter().any(|e| e.text.as_deref().is_some_and(|t| !t.trim().is_empty())) { + if pts.len() < 2 || !lt.pattern.iter().any(|e| e.text.as_deref().is_some_and(|t| !t.trim().is_empty()) || e.shape.is_some()) { return out; } let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; @@ -69,12 +74,41 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: out } -/// The text elements of `lt`, scaled by `scale`, in pattern order. +/// The shape element `el` at the origin (scaled by the element's and the linetype's scale), if +/// its shape file is found and has the shape. +fn shape(d: &Drawing, el: &cadcraft_doc::DashElement, scale: f64) -> Option { + let number = el.shape.filter(|n| *n != 0)?; + let style = el.style.as_deref().map(str::trim).filter(|s| !s.is_empty())?; + let file = d.text_style(style).map_or_else(|| style.to_string(), |ts| ts.font.clone()); + let font = cadcraft_fonts::shx::find(&file)?; + let glyph = font.glyph(number, false)?; + let k = if el.scale.is_finite() && el.scale > 0.0 { el.scale } else { 1.0 } * scale / font.units_per_height(); + if !(k.is_finite() && k > 0.0) { + return None; + } + let strokes = glyph.strokes.iter().map(|s| s.iter().map(|p| *p * k).collect()).collect(); + Some(Shaped { strokes, width: glyph.advance.x * k, ..Shaped::default() }) +} + +/// The text and shape elements of `lt`, scaled by `scale`, in pattern order. fn elements(d: &Drawing, lt: &Linetype, scale: f64) -> Vec { let mut out = Vec::new(); let mut at = 0.0; + let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; for el in <.pattern { at += el.length.abs() * scale; + if el.text.is_none() + && let Some(local) = shape(d, el, scale) + { + out.push(Element { + at, + local, + rotation: finite(el.rotation), + absolute: el.absolute, + offset: Vec2::new(finite(el.offset.x), finite(el.offset.y)) * scale, + }); + continue; + } let Some(text) = el.text.as_deref().filter(|t| !t.trim().is_empty()) else { continue }; let ts = d.text_style(el.style.as_deref().unwrap_or("Standard")).cloned().unwrap_or_default(); let k = if el.scale.is_finite() && el.scale > 0.0 { el.scale } else { 1.0 }; @@ -83,7 +117,7 @@ fn elements(d: &Drawing, lt: &Linetype, scale: f64) -> Vec { if !(height.is_finite() && height > 0.0) { continue; } - let font = TextFont::resolve(&ts.font); + let font = crate::style_font(&ts); let params = TextParams { width_factor: if ts.width_factor.is_finite() && ts.width_factor > 0.0 { ts.width_factor } else { 1.0 }, oblique: if ts.oblique.is_finite() { ts.oblique } else { 0.0 }, @@ -92,7 +126,6 @@ fn elements(d: &Drawing, lt: &Linetype, scale: f64) -> Vec { ..TextParams::new(Vec2::ZERO, height) }; let (local, _) = cadcraft_fonts::place(&font, text, ¶ms); - let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; out.push(Element { at, local, @@ -175,6 +208,76 @@ mod tests { assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0).is_empty()); } + /// A shape file written for this test: shape 130 a 2 x 2 box with its pen ending at x = 2. + fn register_shapes() { + let src = "*130,7,BOX\n1,020,024,028,02C,2,020,0\n"; + cadcraft_fonts::shx::register("cadcraft-render-lt.shx", &cadcraft_fonts::shx::compile(src).unwrap()).unwrap(); + } + + fn fence(style: &str) -> Linetype { + Linetype { + name: "FENCE".into(), + description: String::new(), + pattern: vec![ + DashElement::dash(0.5), + DashElement { shape: Some(130), style: Some(style.into()), scale: 0.1, ..DashElement::dash(-0.2) }, + DashElement::dash(-0.25), + ], + } + } + + #[test] + fn shape_elements_draw_their_shape_at_each_repeat() { + register_shapes(); + let d = Drawing::new_imperial(); + // An unnamed shape-file style reads as its file name (DXF); scale 0.1 per vector unit. + let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-render-lt.shx"), 1.0, 0.0); + assert_eq!(t.len(), 2); + let x = starts(&t); + assert!((x[0] - 0.7).abs() < 1e-9 && (x[1] - 1.65).abs() < 1e-9, "{x:?}"); + let ys = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y))); + assert!((ys.0).abs() < 1e-9 && (ys.1 - 0.2).abs() < 1e-9, "{ys:?}"); + // Along a vertical line the shape turns with it; absolute rotation keeps it level. + let t = texts(&d, &[Vec2::ZERO, Vec2::new(0.0, 2.0)], &fence("cadcraft-render-lt.shx"), 2.0, 0.0); + assert_eq!(t.len(), 1); + let xs = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.x), b.max(p.x))); + assert!((xs.0 + 0.4).abs() < 1e-9 && xs.1.abs() < 1e-9, "{xs:?}"); + // A named style whose font is the shape file. + let mut d = Drawing::new_imperial(); + d.text_styles.push(cadcraft_doc::TextStyle { name: "SHAPES".into(), font: "cadcraft-render-lt.shx".into(), ..Default::default() }); + assert_eq!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("SHAPES"), 1.0, 0.0).len(), 2); + // A shape file that isn't found, or a shape it lacks, draws nothing. + assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-no-such-file.shx"), 1.0, 0.0).is_empty()); + let mut lt = fence("cadcraft-render-lt.shx"); + lt.pattern[1].shape = Some(131); + assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], <, 1.0, 0.0).is_empty()); + } + + #[test] + fn text_in_an_shx_style_uses_the_font_metrics() { + // A text font written for this test: A is 4 wide with a gap of 2, cap height 6. + let src = "*0,4,render test\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n"; + cadcraft_fonts::shx::register("cadcraft-render-text.shx", &cadcraft_fonts::shx::compile(src).unwrap()).unwrap(); + let mut d = Drawing::new_imperial(); + d.text_styles.push(cadcraft_doc::TextStyle { name: "SHX".into(), font: "cadcraft-render-text.shx".into(), ..Default::default() }); + let t = cadcraft_doc::Text { + insert: cadcraft_geom::Vec3::new(0.0, 0.0, 0.0), + align_pt: None, + height: 3.0, + value: "AA".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "SHX".into(), + halign: Default::default(), + valign: Default::default(), + }; + let (sh, bb) = crate::place_text_entity(&d, &t, "AA"); + assert!((sh.width - 6.0).abs() < 1e-9 && (bb.width() - 6.0).abs() < 1e-9); + let maxy = sh.strokes.iter().flatten().map(|p| p.y).fold(f64::MIN, f64::max); + assert!((maxy - 3.0).abs() < 1e-9); + } + #[test] fn hostile_values_never_panic() { let d = Drawing::new_imperial(); diff --git a/crates/render/src/table.rs b/crates/render/src/table.rs index 5a571feff..741ffd410 100644 --- a/crates/render/src/table.rs +++ b/crates/render/src/table.rs @@ -375,7 +375,7 @@ pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) { } for tx in &g.texts { let ts = crate::text_style(ctx.d, &tx.style); - let font = cadcraft_fonts::TextFont::resolve(&ts.font); + let font = crate::style_font(&ts); // Cell content is MTEXT (`\P`, `{\Q15;…}`, `\F…;`): laid out as such, at the cell's // alignment point (its numbering is MTEXT's attachment). let mp = cadcraft_fonts::MTextParams { diff --git a/crates/render/src/text_entity.rs b/crates/render/src/text_entity.rs index 54b556139..d0deb1505 100644 --- a/crates/render/src/text_entity.rs +++ b/crates/render/src/text_entity.rs @@ -5,10 +5,16 @@ pub(crate) fn text_style(d: &Drawing, name: &str) -> cadcraft_doc::TextStyle { d.text_style(name).cloned().unwrap_or_default() } +/// The font a text style draws with: its font file (TrueType, or an SHX font found by name), +/// its big font and its vertical flag. +pub fn style_font(ts: &cadcraft_doc::TextStyle) -> cadcraft_fonts::TextFont { + cadcraft_fonts::TextFont::resolve_style(&ts.font, &ts.big_font, ts.vertical) +} + /// Shape a TEXT / ATTRIB / ATTDEF with its style's font and generation flags. pub fn place_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> (cadcraft_fonts::Shaped, Bounds2) { let ts = text_style(d, &t.style); - let font = cadcraft_fonts::TextFont::resolve(&ts.font); + let font = style_font(&ts); let (h, v) = align(t.halign, t.valign); let p = cadcraft_fonts::TextParams { insert: t.insert.xy(), @@ -36,7 +42,7 @@ pub fn layout_mtext_entity(d: &Drawing, t: &cadcraft_doc::MText) -> cadcraft_fon rotation: t.rotation, line_spacing: t.line_spacing, line_spacing_exact: t.line_spacing_exact, - font: cadcraft_fonts::TextFont::resolve(&ts.font), + font: style_font(&ts), width_factor: ts.width_factor, oblique: ts.oblique, columns: t.columns.as_ref().map(|c| cadcraft_fonts::MTextColumnSpec { diff --git a/docs/gaps.md b/docs/gaps.md index a4a12cff8..f7e0a1cfe 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 (DIMTFILL limits in the `*D` block, EXPLODE and DXF: F7 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (SHX shape fonts, big fonts and unifonts read and drawn, linetype shape elements drawn: FF8 and FF9 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 @@ -80,8 +80,8 @@ 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 | -| 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 | +| FF8 | SHX shape fonts, big fonts and unifonts are read and drawn (2026-10-22; looked up by file name beside the drawing, in `CADCRAFT_SHXPATH`, via a font map or registered by the web app; FONTALT). Left: no Options entry for the search path or font map; no desktop drag-drop of `.shx`; big-font code page guessed from the file name; vertical text not justified along its column; extended big font box scaling unverified against real files | Medium | 2–4 | +| FF9 | `.pc3` plotter configuration files; shape elements in user `.lin` files are dropped on load (DXF/DWG linetype shape elements are drawn since 2026-10-22; templates and `.dwt`, user `.lin`/`.pat` and `.pgp` alias files landed, #552; `.ctb`/`.stb`, #410) | Low-medium | 4–8 | | 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 | | FF12 | DWG in the web build | Medium | 6–10 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | SHX fonts: shape fonts, big fonts and unifonts read (`cadcraft_fonts::shx`, every count and offset bounded) and drawn for TEXT, MTEXT, attributes, dimensions and tables, with the style's big font and vertical flag; found by file name beside the drawing, in `CADCRAFT_SHXPATH`, through a font map or from `.shx` files opened in the web app, never in another CAD program's folder; FONTALT may name a font and a big font; linetype shape elements drawn when their file is found: FF8 and FF9 narrowed | | 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 | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | From 4398a1aab12d10c29a7088963106ab7963849c60 Mon Sep 17 00:00:00 2001 From: Andrea Brandi Date: Tue, 27 Oct 2026 18:47:15 +0100 Subject: [PATCH 114/900] fix(it): correct CADCraft chamfer terminology --- ATTRIBUTION.md | 2 +- contributors/people.toml | 2 ++ crates/ui-egui/src/i18n/it.tsv | 8 ++++---- docs/localization-parity.md | 5 +++-- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index e124d102a..73ea1c0e0 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -70,7 +70,7 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker | -| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | +| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker | | `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added | | `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `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 | diff --git a/contributors/people.toml b/contributors/people.toml index 40d6ba823..7d45ed5f2 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -91,3 +91,5 @@ sync_github_name = false real_name = "Robert Lee" sync_github_name = true +[people.starise] +real_name = "Andrea Brandi" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 27786b2e5..f012f0907 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -131,7 +131,7 @@ menu Modify Edita Center, Start, Angle Centro, inizio, angolo Center, Start, End Centro, inizio, fine Center, Start, Length Centro, inizio, lunghezza - Chamfer Cima + Chamfer Smusso Change Space Cambia spazio Change to Current Layer Cambia al layer corrente Changed: {n} Modificati: {n} @@ -915,8 +915,8 @@ menu Modify Edita Specify fillet radius Specificare il raggio di raccordo Specify fillet radius for rectangles Specificare il raggio di raccordo dei rettangoli Specify first angle endpoint Specificare il primo estremo dell'angolo - Specify first chamfer distance Specificare la prima distanza di cimatura - Specify first chamfer distance for rectangles Specificare la prima distanza di cimatura dei rettangoli + Specify first chamfer distance Specificare la prima distanza di smusso + Specify first chamfer distance for rectangles Specificare la prima distanza di smusso dei rettangoli Specify first constraint point Specificare il primo punto del vincolo Specify first corner Specificare il primo angolo Specify first corner point Specificare il primo angolo @@ -1001,7 +1001,7 @@ menu Modify Edita Specify scale factor Specificare il fattore di scala Specify second angle endpoint Specificare il secondo estremo dell'angolo Specify second break point Specificare il secondo punto di interruzione - Specify second chamfer distance for rectangles Specificare la seconda distanza di cimatura dei rettangoli + Specify second chamfer distance for rectangles Specificare la seconda distanza di smusso dei rettangoli Specify second constraint point Specificare il secondo punto del vincolo Specify second destination point Specificare il secondo punto di destinazione Specify second end point of circle's diameter Specificare il secondo estremo del diametro del cerchio diff --git a/docs/localization-parity.md b/docs/localization-parity.md index b4ff05f68..b19a07eb0 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-22 · **Change:** minor (the command line enables the OS IME and handles composition/commit, so single-line TEXT edits accept CJK input; previously: Brazilian Portuguese row updated and terminology reviewed; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** patch (Italian Chamfer terminology corrected; previously: the command line enables the OS IME and handles composition/commit, so single-line TEXT edits accept CJK input; previously: Brazilian Portuguese row updated and terminology reviewed; 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). @@ -71,7 +71,7 @@ plus native review by a human; extending the catalog to the remaining English-on | 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,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 | +| 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; targeted Chamfer terminology review by Andrea Brandi (@starise), a native speaker, with OpenAI Codex; full native proofreading pending | 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 | | 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 | @@ -89,6 +89,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| +| 2026-10-27 | patch | Italian: corrected Chamfer and its three existing distance prompts to use Smusso; targeted native-speaker terminology review with OpenAI Codex assistance | | 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 | From 015fe2a18da1454e5020c56cf230f371e4f80cbb Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:17:26 -0600 Subject: [PATCH 115/900] ui: block description field ids from Ui::scope_id (egui 0.37 deprecates Ui::id) main's gate fails clippy -D warnings on the one Ui::id() call (#2113); Ui::scope_id is its new name. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/palettes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index ecf65b0d6..7e01a15d4 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -738,7 +738,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { value_box(ui, &name, false, false).on_hover_text(crate::tl!("Read-only")); }); prop_row(ui, "Description", |ui| { - if let Some(text) = edit_field(ui, ui.id().with("block_description"), description) { + if let Some(text) = edit_field(ui, ui.scope_id().with("block_description"), description) { act("blocks.description", json!({ "description": text })); } }); From 360bee4dcc40333787ba854c998a713ae4ea491d Mon Sep 17 00:00:00 2001 From: Jeremy Date: Tue, 27 Oct 2026 19:12:39 +0000 Subject: [PATCH 116/900] fix(installer): check the exact architecture-specific machine folder The pre-signing check matched any folder named Program Files, so it rejected a valid MSI when Windows resolves Program Files elsewhere, accepted the 64-bit root for an x86 package and accepted a different app name. Build the expected folder from the package architecture's resolved root and the policy name. --- packaging/windows/check-install-policy.ps1 | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packaging/windows/check-install-policy.ps1 b/packaging/windows/check-install-policy.ps1 index a4a14bc64..cc9416e9c 100644 --- a/packaging/windows/check-install-policy.ps1 +++ b/packaging/windows/check-install-policy.ps1 @@ -32,6 +32,12 @@ function Set-SessionProperty($Session, [string] $Name, [string] $Value) { function Get-SessionProperty($Session, [string] $Name) { $Session.GetType().InvokeMember('Property', 'GetProperty', $null, $Session, @($Name)) } +function Get-PackageTemplate($Database) { + # Summary information property 7 is the platform: "Intel;1033", "x64;1033" or "Arm64;1033". + $summary = $Database.GetType().InvokeMember('SummaryInformation', 'GetProperty', $null, $Database, @(0)) + try { [string]$summary.GetType().InvokeMember('Property', 'GetProperty', $null, $summary, @(7)) } + finally { [void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($summary) } +} $installer = $null; $database = $null; $session = $null try { $installer = New-Object -ComObject WindowsInstaller.Installer @@ -150,6 +156,12 @@ try { if (@(Read-Rows $database 'SELECT `Action` FROM `InstallExecuteSequence`' 1 | Where-Object { $_[0] -like 'CraftDefault*' }).Count) { throw 'Silent installs must not use the wizard-only default folder actions.' } + # The machine default comes from the environment of the package architecture, not from a folder name. + # x86 packages use Program Files (x86) on 64-bit Windows; x64 and Arm64 packages use the 64-bit root. + $machineRoot = if ((Get-PackageTemplate $database) -match '^Intel') { + if (Get-SessionProperty $session 'VersionNT64') { ${env:ProgramFiles(x86)} } else { $env:ProgramFiles } + } elseif ($env:ProgramW6432) { $env:ProgramW6432 } else { $env:ProgramFiles } + $machineFolder = (Join-Path $machineRoot "ArtCraft\$($policy.name)") + '\' foreach ($scope in @('1', '')) { Set-SessionProperty $session 'ALLUSERS' $scope Set-SessionProperty $session 'INSTALLFOLDER' '' @@ -159,8 +171,8 @@ try { if ($session.EvaluateCondition($row[2]) -eq 1 -and $session.DoAction($row[0]) -ne 1) { throw "$($row[0]) failed." } } $folder = Get-SessionProperty $session 'INSTALLFOLDER' - $wanted = if ($scope -eq '1') { '^[A-Za-z]:\\Program Files( \(x86\))?\\ArtCraft\\[^\\]+\\$' } else { '^' + [regex]::Escape($env:LOCALAPPDATA) + '\\Programs\\ArtCraft\\[^\\]+\\$' } - if ($folder -notmatch $wanted) { throw "Wizard default folder for ALLUSERS='$scope' is '$folder'." } + $wanted = if ($scope -eq '1') { $machineFolder } else { (Join-Path $env:LOCALAPPDATA "Programs\ArtCraft\$($policy.name)") + '\' } + if ($folder -ine $wanted) { throw "Wizard default folder for ALLUSERS='$scope' is '$folder', expected '$wanted'." } } $execute = @{} foreach ($row in (Read-Rows $database 'SELECT `Action`, `Sequence` FROM `InstallExecuteSequence`' 2)) { $execute[$row[0]] = [int]$row[1] } From f948acd30b52e01826c85d7033e03485cca4a236 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 27 Oct 2026 23:32:16 +0400 Subject: [PATCH 117/900] 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 118/900] 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 729f27de74539447c6f713b531819c57f2600c52 Mon Sep 17 00:00:00 2001 From: aiongg Date: Tue, 27 Oct 2026 20:51:59 +0000 Subject: [PATCH 119/900] ci: use storytold/craft-common-actions at the merged installer-policy commit --- .github/workflows/windows-arm64.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index 865f069d4..a671ff2f2 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -26,7 +26,7 @@ permissions: jobs: windows-arm64: # Immutable supporting workflow revision until the new install contract lands upstream. - uses: Jeremy8776/craft-common-actions/.github/workflows/windows-arm64.yml@f4666d5cbf35f9bdeda24f1f88c7fb5c6adf5276 + uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f with: app-name: cadcraft app-dir: CADCraft From b600293cfa7388b93efa52fa0718cf56d70bd603 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 22:42:36 +0100 Subject: [PATCH 120/900] 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 56542407292b911ad30523cfcfa987923fe2f8e2 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:28:53 -0400 Subject: [PATCH 121/900] refactor(cli): parse `cadcraft-cli` arguments with clap, following RFC-0012 (#2268) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(cli): pin today's command-line behaviour The later commits change these tests on purpose, so each behaviour change shows in their diff. * refactor(cli): split main.rs into modules, move only - output: outln!, stdout state, atomic write, export helpers, view/window helpers - args: USAGE, option validation, framing options, MCP argument parsing and its tests - info, convert, sample, mcp: one subcommand each - perf: synthetic drawing, Rng, perf subcommands - run: run subcommand and {last} handle chaining - main: crate docs, mod lines, install_io, open, main, cli, unit tests No behaviour change. * refactor(cli): typed errors and run(args, out, err) cadcraft-cli is now a library plus a thin binary. `cadcraft_cli::run(args, out, err) -> i32` is the whole program; main.rs only passes `args_os()` and the process streams. Handlers write through a `Streams` wrapper (output.rs) instead of the process streams; it keeps the closed-stdout semantics (drop later output, carry on, a closed pipe is not an error, other write errors are reported once and make the exit code 1). `mcp` still speaks MCP on the real stdin/stdout. Errors are typed (thiserror): CliError (error.rs) wraps EngineError, DocError, IoError, io::Error and the per-module WindowError, ArgsError, RunError, OutputError and PerfError. `run` prints `error: {e}` and exits 1. The usage text and the "unknown option/argument" messages stay as one transitional CliError::Usage(String), printed without the `error: ` prefix. USAGE stays a const; step 4 (clap) removes both. The engine's IoHooks take `Result<_, String>`, so the three `.map_err(|e| e.to_string())` in install_io remain. The hooks are set-once (OnceLock), so installing them on every `run` call is harmless. tests/it/usage.rs calls `run` in-process with Vec writers; the headless mcp case runs through the binary (it reads the real stdin) and a non-Unicode argument test is new. Behaviour changes (old -> new): - Every error line other than the usage-class ones gains the prefix `error: ` (e.g. `--view needs ...` -> `error: --view needs ...`, `unknown command `x`` -> `error: unknown command `x``, `invalid parameters for `open`: ...` -> `error: invalid parameters ...`, `unsupported file type` likewise). - `cadcraft-cli: cannot connect to HOST:PORT: e` -> `error: cannot connect to HOST:PORT: e` (the old prefix is replaced). - A non-Unicode argument: panic, exit 101 -> `error: argument "..." is not valid Unicode`, exit 1. - Unchanged: usage text, `X: unknown option --y`, `unknown option --y`, `mcp: unknown argument ...` (no prefix); warnings and `wrote ...` lines; the `cadcraft-cli: can't write to stdout: e` report; exit codes. * refactor(cli): parse arguments with clap Replace the hand-written parser (USAGE, validate_options, OptionSpec, framing_option, parse_mcp_args, CliError::Usage) with clap derive types in args.rs: a Cli parser and one Args struct per subcommand, with the framing flags (--window, --view) in a FramingArgs struct flattened into convert and run. USAGE's framing and --cmd chaining text moves into the subcommands' and flags' doc comments and run's long help, so --help carries it. `commands` moves from an inline closure to commands.rs. `command()` exposes the clap definition for man pages and completions. clap reads the arguments as OsStrings. Help and --version go to stdout with exit 0; usage errors are clap's, on stderr with exit 2. A bare --help or -h before `--` shows the subcommand's help even after a mistake on the line (`run --script --help`). run opens its drawings (FILEs, --sample, --metric) and runs its steps (--script, --script-file, --cmd) in command-line order, from ArgMatches::indices_of. Values stay strings checked by the handlers, with their messages and exit 1 (--window, --view, --cmd JSON, sample names, perf counts). The last of a repeated flag wins (args_override_self on every subcommand but mcp). Behaviour changes: Help and version - --help, -h, help: the USAGE page -> clap's help, first line "cadcraft-cli: headless CADCraft". - bare cadcraft-cli: USAGE on stderr, exit 1 -> clap's help on stderr, exit 2. - --help / -h, help : "unknown option --help" (exit 1), the USAGE page (convert, help ) or a file named -h (info -h, run -h) -> that subcommand's help, stdout, exit 0. - --version: "unknown option --version", exit 1 -> clap's unexpected argument, exit 2. Usage errors (exit 1 -> exit 2, clap's messages) - Unknown subcommand, empty subcommand, unknown top-level flag: USAGE -> "error: unrecognized subcommand 'foo'" / "error: unexpected argument '--bogus' found". - Unknown flag on any subcommand: "info: unknown option --bogus", "unknown option --bogus", "mcp: unknown argument --bogus" or USAGE (convert) -> "error: unexpected argument '--bogus' found". - A short flag where a file is expected (info -x): opened as a file -> unexpected argument; `--` before it keeps it a file name. - A value flag at the end or followed by a flag (--window, --view, --script, --script-file, --cmd, --save, --export, --connect): "error: --script needs text" and the like, or the next flag taken as the value (--window --view, --script --sample, --cmd --sample, --script-file --sample) -> "error: a value is required for '--script ' but none was supplied". --connect followed by an unknown flag (--connect --foo, --connect -v) names that flag instead (clap reports the unknown argument, not the missing value). - mcp --connect with an empty value: "error: --connect needs HOST:PORT ..." -> "error: invalid value ' ' for '--connect ': expected HOST:PORT (...)"; --connect=-v likewise. - mcp --connect twice: "error: --connect given more than once" -> "error: the argument '--connect ' cannot be used multiple times". - mcp --lazy / --launch without --connect: "error: --lazy and --launch need --connect HOST:PORT" -> "error: the following required arguments were not provided: --connect ". - Missing positionals (info, convert with 0 or 1 files, sample with 0 or 1 arguments): USAGE -> "error: the following required arguments were not provided". - Extra positionals: convert with three files (USAGE), and info, commands, perf, sample, which ignored the extra argument -> "error: unexpected argument 'extra' found". - perf -5: opened as a file -> unexpected argument '-5'. - A non-Unicode argument where text is expected: "error: argument ... is not valid Unicode", exit 1 -> "error: invalid UTF-8 was detected in one or more arguments", exit 2. Accepted where they were errors - --x=v is a spelling of --x v for every value flag (--window, --view, --script, --script-file, --cmd, --save, --export, --connect); before it was an unknown option or USAGE. A value starting with - needs the = form (--cmd=-x). - commands --: "unknown option --" -> `--` ends the options (all commands listed). - run --view extents --view current: "use only one of --window and --view" -> the last wins, like every other repeat. Other - run --sample --sample opens one sample drawing (was two): repeated flags are last-wins. - run checks --window/--view values before opening any drawing, so a bad framing value is reported ahead of a missing file. - `-h` after a mistake shows the long help (`--help`): the retry asks for --help. Unchanged: --window with --view, framing without an image output, --view's case-insensitivity, all value messages (--window numbers, --view values, --cmd JSON, {last}, sample names, --script-file read errors), multiple FILEs, --sample with --metric or a FILE, last-wins for --save, --export, --window, --script/--cmd order, and `\n` in --script. clap forced: exit 2 for usage errors, its message wording, and the unknown-flag-over-missing-value precedence above. * refactor(cli): reject repeated flags, long version (photocraft#7071 decisions) Behaviour changes, old -> new: - --save, --export, --window, --view, --sample, --metric, --lazy, --launch given twice: last one won -> usage error, exit 2 ("the argument ... cannot be used multiple times"). --connect was already rejected. --script, --script-file, --cmd and run's FILEs still repeat. - --version / -V: "cadcraft-cli " -> "cadcraft-cli ()", sha from CADCRAFT_BUILD_SHA or "dev", as the desktop app prints it. - "cadcraft-cli version" is an unrecognized-subcommand usage error (as before; now tested). - A value starting with "-" needs the = form for every value flag (as before, tested). --window -10,-10,10,10 stays a usage error ("unexpected argument -1"); write --window=-10,-10,10,10. clap's allow_negative_numbers does not accept a comma list, and allow_hyphen_values would let --window swallow the next flag, so neither is set. The --window help text names the = form. * refactor(cli): typed values and flag relations Step 6 of #2228: values are parsed into their types and flag relations are checked at parse time, so a bad value or combination is a usage error (exit 2) naming the flag, before any work starts. The handlers receive typed values only. Runtime failures (files, the engine, a `{last}` with no earlier handle) stay exit 1. - --window parses to a Bounds2 (parse_window plus cadcraft_io's check_window); its WindowError is the value parser's error. - --view is a ValueEnum (extents, current), case-insensitive; the long help lists what each value does. - --window conflicts_with --view. In run, --window/--view require --export (an ArgGroup "framing" with requires). A framing flag with an output that isn't an image (convert's OUT, run's --export) is a UsageError turned into a clap error by into_clap (ArgumentConflict). - sample's name is a ValueEnum (bracket, floorplan); `floor` stays a hidden alias. - perf's N|FILE is one typed positional: a value that parses as a count is one, clamped to 1..=20000000 as before (so `perf 0` still times one entity); anything else is a drawing. - --cmd 'id {json}' parses to an id and a serde_json::Value (default {}); `{last}` is still filled in when the command runs. - Paths are PathBufs (info FILE, convert IN/OUT, run FILEs, --script-file, --save, --export, sample OUT, perf FILE). The engine and io crates take file names as text, so a path that isn't valid Unicode is refused by the handler, naming the file (exit 1). - Deleted: check_framed_output, the --view match, ArgsError, CliError::Window/Args/UnknownSample, RunError::CmdJson, PerfError::BadCount. - run's FILEs, --sample and --metric still combine (each opens another drawing, the last is current): neither photocraft#7071 nor RFC-0012 requires otherwise. Behaviour changes (old -> new): - --window with a bad value (wrong count, not a number, NaN/inf, reversed corners, beyond 1e12): exit 1 `error: --window ...` -> exit 2 `error: invalid value 'V' for '--window ': `. The reasons no longer repeat the flag or the value. - --view with a bad value: exit 1 `error: --view needs `extents` or `current`` -> exit 2 `error: invalid value 'V' for '--view '` plus clap's possible-values line. - --window with --view: exit 1 `error: use only one of --window and --view` -> exit 2 `error: the argument '--window ' cannot be used with '--view '`. - run --window/--view without --export: exit 1 `error: --window/--view need an image output ...` -> exit 2 `error: the following required arguments were not provided: --export `. - A framing flag with a non-image output: exit 1 `error: --window/--view only apply to image output (png, svg, pdf), not `OUT`` -> exit 2 `error: --window only applies to image output (png, svg, pdf), not `OUT`` (or --view: the message names the flag given). - sample with an unknown name: exit 1 `error: unknown sample `X` (bracket, floorplan)` -> exit 2 `error: invalid value 'X' for ''` plus the possible values. sample's help lists the possible values. - --cmd with JSON that doesn't parse: exit 1 `error: --cmd ID: `, after the earlier steps ran -> exit 2 `error: invalid value 'V' for '--cmd ': `, before anything runs. - --cmd with an empty id (`--cmd=` or `--cmd ' {}'`): exit 1 `error: unknown command `` ` -> exit 2 `... expected a command id, then optionally its JSON parameters`. - An empty path argument (info "", sample bracket "", perf "", ...): exit 1 from the engine or io -> exit 2 `error: a value is required for '' but none was supplied` (clap's PathBuf parser). - A path that isn't valid Unicode: exit 2 `error: invalid UTF-8 was detected ...` -> exit 1 `error: PATH: the file name is not valid Unicode` (text values that aren't Unicode stay exit 2). A non-Unicode --save or --export is refused before any drawing opens. - perf's help gives the count range. Tests: usage.rs rows above moved to exit 2 with clap's messages; new rows for --view with a non-image output, run's framing with a dxf --export, an empty --cmd id, bad --cmd JSON after a good step, a `{last}` with no earlier handle, --window beyond 1e12, case-sensitive sample names and empty paths. The non-Unicode test covers both a path (exit 1) and text (exit 2). Unit tests: the --window parser tests moved to args.rs; new ones for --cmd values and perf targets; framing_options checks the clap error kinds. * refactor(cadcraft): move launch-argument parsing into launch_args Moves the hand-written parser (the argument loop, control_port_from, control_flag and their tests) from main.rs into launch_args.rs, which returns LaunchArgs. No behaviour change. * refactor(cadcraft): parse launch flags with clap (RFC-0012) Replaces the hand-written loop in launch_args.rs with clap derive types, as photocraft's launch_args.rs does. --help is generated from the doc comments and lists the other CADCRAFT_* variables. Behaviour changes (old -> new): - An unknown flag (--sampel) was opened as a file; it is now a usage error on stderr, exit 2, before the window opens. A file starting with "-" goes after "--". - A repeated --control or --sample was accepted (last wins); it is now exit 2. - A bad port (--control abc, 70000, -1) was logged and the control channel left off; it is now exit 2. The same for CADCRAFT_CONTROL_PORT, and the error names the variable when the value came from it. - A bare --control (no value) kept CADCRAFT_CONTROL_PORT's port with a warning; it is now exit 2 ("a value is required"). A following flag is never taken as the value. - An empty or blank CADCRAFT_CONTROL_PORT was logged as a bad port; it is now unset. - --control=7979 is accepted (the equals form was opened as a file before). - --version / -V and --help stop parsing at once and exit 0; version text is unchanged ("cadcraft ()"). - -psn_* (Finder process serial number) is dropped instead of opened as a file. - A file name that is not valid Unicode used to panic in std::env::args(); it is now read from args_os and reported with a log warning, not opened, because CadApp::open_path takes text. Copied from photocraft's crates/automation/src/args.rs: blank_env_is_unset and name_env_vars unchanged (name_env_vars gets a local use for ContextKind/ContextValue); control_port and NotAPort unchanged. allow_negative_numbers is set on --control as in photocraft, so -1 is a bad value rather than a missing one. * feat(cli): shell completions and man pages Adds examples/man-and-completions.rs, which writes cadcraft-cli's bash, zsh, fish, elvish and PowerShell completions (clap_complete) and man pages (clap_mangen: cadcraft-cli.1 and one per subcommand) into a directory. clap_complete and clap_mangen are dev-dependencies, so the binary is unchanged. packaging/linux/package.sh builds the example in its own cargo run, runs it (through $EMULATOR for cross builds; warns and leaves the files out without one) and installs the man pages and the bash, zsh and fish completions into the staged tree. nfpm.yaml already ships the whole usr/share tree, so it needs no change. CADCraft has no FreeBSD packaging, so there is no FreeBSD script to update. macOS and Windows packaging are untouched. tests/man_and_completions.rs checks the generated file names. * ci(cli): check the command-line code with ast-grep (RFC-0012) Adds ast-grep rules from RFC-0012, run by craft-common-actions' reusable ast-grep workflow (Linux, no Rust build, path-filtered): - clap-error-message: a string literal, format!, .to_string() or SCREAMING_CASE const passed to Command::error / Error::raw - clap-error-message-variable: the same message built into a variable first, in the same function - string-error: Result<_, String>, Err(format!(..)), Err(".."), Err(x.to_string()) - args-os: std::env::args(), which panics on non-Unicode arguments Scan paths: apps/cadcraft-cli/src, apps/cadcraft/src/launch_args.rs, apps/cadcraft/src/main.rs. Rule tests run first in CI. Source: photocraft#9750 at d16686cd. Only the scan paths and the workflow path filters differ from it. Fixes: none needed. The rule tests pass (4 passed) and the scan finds nothing in the scanned paths. * docs(cli): cadcraft-cli page, following RFC-0012 docs/cli.md: --help is the reference; exit codes, streams, usage errors, values starting with -, paths, completions and man pages; the environment variables (none for cadcraft-cli, CADCRAFT_CONTROL_PORT for the desktop app's --control); and the rules not followed yet, with the reason. The README links it. * feat(cli): refuse an output that replaces an input RFC-0012 rule 1.6: nothing destructive by default. Behaviour change: `convert a.dxf a.dxf`, `run a.dxf … --save a.dxf` and `run a.dxf … --export a.dxf` used to overwrite the input. They are now a usage error (exit 2, `error: …` on stderr, nothing opened or written) unless `--in-place` is given. "Same file" is file identity (same-file crate), so `dir/./a.dxf` and a symlink to the input count. An output that does not exist, or a failed identity check, is not refused; the open or write reports the real error. Replacing an existing file that is not an input is still allowed. Scope: `--save` and `--export` only. A save that a --cmd or script runs (for example `saveas`) is the engine's and is not checked. Every write the CLI makes (convert OUT, --save, --export, sample OUT) resolves an existing output first, so writing through a symlink updates the file it points to and the link stays a link; the atomic rename used to replace the link with a regular file, leaving the target (with --in-place, the input) unchanged. * feat(cli): --compact for JSON output RFC-0012 rule 1.3: info and commands pretty-print their JSON by default; --compact prints it on one line. run prints one JSON line per --cmd result (JSON lines, one result per step), as its help and the README document, so it takes no --compact. mcp's stdout is the MCP protocol and is unchanged. Behaviour change: info and commands accept --compact (it was an unknown flag, exit 2). Their default output is unchanged. docs/cli.md says which subcommand prints which form, and lists perf's text table (no --json) and saves a --cmd or script runs (not checked by --in-place) under "Not followed yet". * fix(cadcraft): one Switch parser for boolean environment switches CADCRAFT_VSYNC, CADCRAFT_SYSTEM_CURSOR, CADCRAFT_WAYLAND and CADCRAFT_NO_NATIVE_MENU each had their own idea of "on". They now share cadcraft_ui_egui::switch::Switch: 1/on/true/yes is On, 0/off/false/no is Off (case- and space-insensitive), unset or blank is Default, and any other value is Default and logged with the variable name. The ENVIRONMENT help text says the same for all four. Behaviour changes (old -> new): - CADCRAFT_WAYLAND=0 counted as on (any value did); now only On keeps native Wayland. - CADCRAFT_NO_NATIVE_MENU=0 counted as on (any value did); now only On keeps the menus inside the window. - CADCRAFT_SYSTEM_CURSOR treated every value except ""/0/false/off as on; now only the On spellings do, and an unknown value is logged. - CADCRAFT_VSYNC is unchanged except that an unknown value is logged. * fix(cli): keep paths as paths until a file is opened A path is now text only where text is needed. - cadcraft: FileNames.unreadable is Vec, logged with {:?} (escaped bytes) instead of a lossy rendering. - cadcraft-cli: unicode() is called only inside open(), the one place that sends a path to the engine as JSON. convert, sample and run --save/--export pass the output as &Path. write_atomic, export, export_framed and OutputError::Write take or hold a Path/PathBuf; errors use .display(), and the `wrote ...` line uses .display(). - Dropped the dead find_subcommand lookup in launch_args (LaunchArgs has no subcommands). - docs/cli.md: non-Unicode names are refused only where a drawing is opened. Behaviour change: an output name that is not valid Unicode used to be refused (exit 1); it is now written under that exact name. Opening such a drawing is still refused. Lossy strings that remain (all feed APIs that take text and only look at the extension, never at the path the bytes are written to): - cadcraft_io::write / write_framed (name picks the format) in sample.rs and output.rs::export_framed; - cadcraft_io::is_image in convert.rs, run.rs and args.rs (framing flag check); - cadcraft_engine::cmd::file::drops_unknown in export_framed. These go away when cadcraft_io and the engine take impl AsRef (the A1 follow-up). A non-Unicode extension is not a known format either way, so it is rejected as an unsupported type, as before. * refactor(cadcraft): read the environment once into Env The desktop app reads its CADCRAFT_* variables once at startup into apps/cadcraft/src/env.rs `Env` and passes the values on; no library crate reads a CADCRAFT_* variable at run time any more. - One `VARS` table (name, help line) feeds both the reader and the Environment section of `cadcraft --help`. A test checks that every variable the reader asks for is in the table, that every table entry sets a field, and that the help lists every entry. - vsync goes to `gpu::surface_config`, the system cursor to `CadApp::set_system_cursor_default` (Options reset and Reset Palettes go back to it), FONTALT/FONTFALLBACK to the `cadcraft_fonts::ttf` setters (re-exported as `cadcraft_engine::fonts`), the settings directory to the new `cadcraft_engine::settings_dir::set`, and to `Workspace::load`. - The three copies of the settings-directory rule (main.rs, workspace.rs, the engine's plotter folder) are one: `settings_dir::platform`. - `Switch::from_env` is gone; `Switch::parse` stays. - The child-process tests for CADCRAFT_CONTROL_PORT are replaced by tests that inject the variable lookup (`blank_env_is_unset`) or point `--control`'s fallback at PATH. cadcraft-cli: plotter configurations matter to its output (`run --cmd plot` or a script's PLOT with a user device, and the same through `mcp`), and the font variables change how convert/run/sample draw text. So, following RFC-0012 rule 1.7, the variables become fallbacks of flags declared with `env =`: --config-dir (CADCRAFT_CONFIG_DIR), --fontalt (CADCRAFT_FONTALT) and --fontfallback (CADCRAFT_FONTFALLBACK) on convert, run, mcp and sample. Behaviour changes: - CADCRAFT_CONFIG_DIR set but empty counts as unset everywhere: the workspace file and the plotter folder use the platform folder (was: workspace persistence and the plotter folder off). Logs and autosave already treated it so. - The workspace file and the plotter folder ignore a relative XDG_CONFIG_HOME, as logs and autosave did (was: used it). - A blank CADCRAFT_LOCALE means the system's languages (was: [""]). - cadcraft-cli: the three variables apply only to convert, run, mcp and sample, as flag fallbacks (was: read by the engine and fonts in every subcommand, perf included). A font variable that isn't valid Unicode is a usage error naming the flag (was: ignored). * refactor(io): one Format enum for file extensions `cadcraft_doc::Format` (re-exported as `cadcraft_io::Format`) is the one place that maps a file name's extension to a format: Dxf, Dwg, Dwt, Svg, Svgz, Png, Pdf. `from_path` is ASCII case-insensitive; no extension (or a trailing dot) is Dxf; an unknown extension is None. `READ` and `WRITE` list the formats `read` and `write` accept. It lives in cadcraft-doc because the engine depends on cadcraft-io only for tests. Each place used to match on its own lower-cased extension string and now matches on Format, with the same results: - io::read: svg/svgz -> SVG reader, dxf/none -> DXF reader, other -> try DXF, else Unsupported(ext). - io::write_with: dxf/none -> DXF, dwg -> DWG bridge, other with binary -> error, rest -> write_framed. - io::write_framed: dwt -> DWG; dxf/none/dwg -> write_with; svg, png, pdf -> image writers; other -> Unsupported(ext). - io::is_image: svg, png, pdf (not svgz, which is read only). - engine file.rs is_dxf, drops_unknown (dwg, dwt), is_drawing_file (dxf, dwg, dwt, none). Behaviour change (help text only): the CLI help lists the formats from Format::READ / Format::WRITE instead of hand-written lists. `info` and `convert IN` now name svg and svgz as readable, and `convert`, `sample`, `run --save` and `run --export` name dwt (and `sample` pdf) as writable. A test checks each file argument's help names every format of its list. * refactor: one version string for the app and the CLI cadcraft_engine::build_version() builds " ()" once; the desktop app's --version, its start-up log line and cadcraft-cli --version all use it. No change in output. * refactor(cli): share the environment helpers with the CLI Move blank_env_is_unset and name_env_vars from the desktop app into cadcraft_mcp::args and apply them in the CLI parser. Behaviour changes (old -> new): - Empty or blank CADCRAFT_FONTALT / CADCRAFT_FONTFALLBACK: reached clap as Some("") -> counts as unset. - A bad value from an environment variable: the error named the flag -> names the variable. - CADCRAFT_CONFIG_DIR is unchanged: empty still means no settings folder. - Desktop app: unchanged; it uses the shared helpers. * refactor: pass paths, not text, through io, engine and open_path cadcraft_io::{read, write, write_with, write_framed, is_image}, the engine's drops_unknown/is_drawing_file/read_text_file and CadApp::open_path take paths (impl AsRef / &Path). The desktop launch arguments and the CLI no longer convert paths to text to call them. Behaviour changes (old -> new): - A dropped file whose name is not valid Unicode opened with a "can't read" error naming a mangled path; it now opens natively. (Its path is not remembered for QSAVE, which then asks where to save.) - A launch argument that is not valid Unicode was logged and skipped; it now opens like any other. - A .dwt export builds the .dwg name as a path, not formatted text. - On the web, a non-Unicode path passed to open_path reports "the path is not valid Unicode" instead of a lossy name. - Opening errors print path.display(). FileNames and LaunchArgs::file_names are removed; the launch tests assert the parsed PathBufs. New io test: non-Unicode names pick the format by extension. * docs(cli): CADCRAFT_CONFIG_DIR is the one flag fallback where empty isn't unset * fix(engine): refuse a drawing path that isn't valid Unicode read_file opened such a path with no saved path, so QSAVE could not save back to it. It now returns an open error naming the file before reading it. The ui-egui opener already reports read_file errors like any other failed open. * fix(cli): report a failed write of help or version A write error on help or version output (other than a closed pipe) now exits 1 and tries to say so on stderr; it was ignored and exited with the clap code. A closed pipe keeps the clap exit code. * fix(cli): --connect needs HOST:PORT --connect example.com was accepted and failed later. It is now a usage error (exit 2) unless the value is a non-empty host (or a bracketed IPv6 address) and a u16 port. The host is not resolved. * docs(cli): run prints no line for a command with no result * refactor(cli): explicit imports and smaller functions for the stricter lints Lints: clippy::wildcard_imports, too_many_arguments, cognitive_complexity (30). Replaced the non-test `use super::*;` in args, commands, convert, info, output, perf and run with explicit imports; lib.rs keeps only the imports its non-test code uses, and its test module imports the rest itself. The `super::*` in the test modules stays. A clippy run with all three lints and threshold 30 reports nothing in apps/cadcraft-cli or in code this branch added, so no function needed splitting. --- .github/workflows/ast-grep.yml | 26 + Cargo.lock | 159 +++ Cargo.toml | 4 + README.md | 5 +- apps/cadcraft-cli/Cargo.toml | 17 + .../examples/man-and-completions.rs | 41 + apps/cadcraft-cli/src/args.rs | 786 ++++++++++++ apps/cadcraft-cli/src/commands.rs | 17 + apps/cadcraft-cli/src/convert.rs | 22 + apps/cadcraft-cli/src/error.rs | 29 + apps/cadcraft-cli/src/info.rs | 14 + apps/cadcraft-cli/src/lib.rs | 315 +++++ apps/cadcraft-cli/src/main.rs | 1113 +---------------- apps/cadcraft-cli/src/mcp.rs | 17 + apps/cadcraft-cli/src/output.rs | 177 +++ apps/cadcraft-cli/src/perf.rs | 196 +++ apps/cadcraft-cli/src/run.rs | 223 ++++ apps/cadcraft-cli/src/sample.rs | 14 + apps/cadcraft-cli/tests/it/help.rs | 14 +- apps/cadcraft-cli/tests/it/main.rs | 1 + apps/cadcraft-cli/tests/it/mcp_connect.rs | 9 +- apps/cadcraft-cli/tests/it/usage.rs | 950 ++++++++++++++ .../cadcraft-cli/tests/man_and_completions.rs | 30 + apps/cadcraft/Cargo.toml | 2 + apps/cadcraft/src/env.rs | 172 +++ apps/cadcraft/src/launch_args.rs | 158 +++ apps/cadcraft/src/logging.rs | 2 +- apps/cadcraft/src/main.rs | 171 +-- apps/cadcraft/src/workspace.rs | 43 +- crates/doc/src/format.rs | 100 ++ crates/doc/src/lib.rs | 2 + crates/engine/src/cmd/file.rs | 31 +- crates/engine/src/cmd/plotters.rs | 18 +- crates/engine/src/lib.rs | 10 + crates/engine/src/lisp/builtins/files.rs | 6 +- crates/engine/src/lisp/drawing.rs | 2 +- crates/engine/src/lisp/startup.rs | 2 +- crates/engine/src/settings_dir.rs | 82 ++ crates/engine/tests/read_file_unicode.rs | 25 + crates/engine/tests/xref.rs | 2 +- crates/fonts/src/ttf.rs | 15 +- crates/io/src/lib.rs | 58 +- crates/io/src/tests.rs | 14 + crates/mcp/Cargo.toml | 1 + crates/mcp/src/args.rs | 51 + crates/mcp/src/lib.rs | 1 + crates/ui-egui/src/chrome.rs | 2 +- crates/ui-egui/src/docking.rs | 6 +- crates/ui-egui/src/gpu.rs | 26 +- crates/ui-egui/src/lib.rs | 39 +- crates/ui-egui/src/menus.rs | 16 +- crates/ui-egui/src/opening.rs | 26 +- crates/ui-egui/src/options.rs | 4 +- crates/ui-egui/src/switch.rs | 54 + crates/ui-egui/tests/bedit_dialog.rs | 4 +- crates/ui-egui/tests/it/system_cursor.rs | 20 + crates/ui-egui/tests/recent_files.rs | 8 +- docs/cli.md | 58 + docs/control-protocol.md | 2 +- docs/plotters.md | 3 +- lint/ast-grep/rule-tests/args-os-test.yml | 19 + .../rule-tests/clap-error-message-test.yml | 13 + .../clap-error-message-variable-test.yml | 47 + .../ast-grep/rule-tests/string-error-test.yml | 14 + lint/ast-grep/rules/args-os.yml | 21 + .../rules/clap-error-message-variable.yml | 35 + lint/ast-grep/rules/clap-error-message.yml | 26 + lint/ast-grep/rules/string-error.yml | 21 + lint/ast-grep/sgconfig.yml | 6 + packaging/linux/package.sh | 25 + 70 files changed, 4228 insertions(+), 1414 deletions(-) create mode 100644 .github/workflows/ast-grep.yml create mode 100644 apps/cadcraft-cli/examples/man-and-completions.rs create mode 100644 apps/cadcraft-cli/src/args.rs create mode 100644 apps/cadcraft-cli/src/commands.rs create mode 100644 apps/cadcraft-cli/src/convert.rs create mode 100644 apps/cadcraft-cli/src/error.rs create mode 100644 apps/cadcraft-cli/src/info.rs create mode 100644 apps/cadcraft-cli/src/lib.rs create mode 100644 apps/cadcraft-cli/src/mcp.rs create mode 100644 apps/cadcraft-cli/src/output.rs create mode 100644 apps/cadcraft-cli/src/perf.rs create mode 100644 apps/cadcraft-cli/src/run.rs create mode 100644 apps/cadcraft-cli/src/sample.rs create mode 100644 apps/cadcraft-cli/tests/it/usage.rs create mode 100644 apps/cadcraft-cli/tests/man_and_completions.rs create mode 100644 apps/cadcraft/src/env.rs create mode 100644 apps/cadcraft/src/launch_args.rs create mode 100644 crates/doc/src/format.rs create mode 100644 crates/engine/src/settings_dir.rs create mode 100644 crates/engine/tests/read_file_unicode.rs create mode 100644 crates/mcp/src/args.rs create mode 100644 crates/ui-egui/src/switch.rs create mode 100644 docs/cli.md create mode 100644 lint/ast-grep/rule-tests/args-os-test.yml create mode 100644 lint/ast-grep/rule-tests/clap-error-message-test.yml create mode 100644 lint/ast-grep/rule-tests/clap-error-message-variable-test.yml create mode 100644 lint/ast-grep/rule-tests/string-error-test.yml create mode 100644 lint/ast-grep/rules/args-os.yml create mode 100644 lint/ast-grep/rules/clap-error-message-variable.yml create mode 100644 lint/ast-grep/rules/clap-error-message.yml create mode 100644 lint/ast-grep/rules/string-error.yml create mode 100644 lint/ast-grep/sgconfig.yml diff --git a/.github/workflows/ast-grep.yml b/.github/workflows/ast-grep.yml new file mode 100644 index 000000000..aab570b63 --- /dev/null +++ b/.github/workflows/ast-grep.yml @@ -0,0 +1,26 @@ +# Structural rules for the command-line code (RFC-0012): lint/ast-grep's rule tests, then a scan. +# Seconds, no Rust build. +name: ast-grep + +on: + push: + branches: [main] + paths: ["lint/ast-grep/**", "apps/cadcraft-cli/src/**", "apps/cadcraft/src/launch_args.rs", "apps/cadcraft/src/main.rs", ".github/workflows/ast-grep.yml"] + pull_request: + paths: ["lint/ast-grep/**", "apps/cadcraft-cli/src/**", "apps/cadcraft/src/launch_args.rs", "apps/cadcraft/src/main.rs", ".github/workflows/ast-grep.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ast-grep-${{ github.ref }} + cancel-in-progress: true + +jobs: + scan: + # Tracked at @main like the other shared workflows. + uses: storytold/craft-common-actions/.github/workflows/ast-grep.yml@main + with: + config: lint/ast-grep/sgconfig.yml + paths: apps/cadcraft-cli/src apps/cadcraft/src/launch_args.rs apps/cadcraft/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 0633f38f3..ab48c95da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -196,6 +196,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -571,6 +621,7 @@ dependencies = [ "cadcraft-mcp", "cadcraft-ui-egui", "chrono", + "clap", "craft-ui", "craft-update", "craft-window", @@ -583,6 +634,7 @@ dependencies = [ "rfd", "serde_json", "sys-locale", + "thiserror 2.0.21", "windows", "winit", "winresource", @@ -597,7 +649,12 @@ dependencies = [ "cadcraft-io", "cadcraft-mcp", "cadcraft-render", + "clap", + "clap_complete", + "clap_mangen", + "same-file", "serde_json", + "thiserror 2.0.21", ] [[package]] @@ -710,6 +767,7 @@ dependencies = [ "cadcraft-engine", "cadcraft-io", "cadcraft-render", + "clap", "getrandom 0.4.3", "log", "serde_json", @@ -863,6 +921,65 @@ dependencies = [ "num-traits", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "clap_mangen" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "211d617eaa4b735c96c9e0228fcbdb5120ef623f2b8cb67ffb84c3e02dbc28a4" +dependencies = [ + "clap", + "roff", +] + [[package]] name = "clipboard-win" version = "5.4.3" @@ -907,6 +1024,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "colored" version = "2.2.0" @@ -2085,6 +2208,12 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" version = "0.5.3" @@ -2387,6 +2516,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.15.0" @@ -3241,6 +3376,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "open" version = "5.4.5" @@ -3813,6 +3954,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roff" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" + [[package]] name = "ron" version = "0.12.2" @@ -4328,6 +4475,12 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subsetter" version = "0.2.6" @@ -4801,6 +4954,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.29.0" diff --git a/Cargo.toml b/Cargo.toml index 3265938f5..2b38a218f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,9 +29,13 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l # PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin # craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches). craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false } +clap = { version = "4", features = ["derive", "env"] } +clap_complete = "4.6.11" +clap_mangen = { version = "0.3.3", features = ["env"] } # foundation thiserror = "2" +same-file = "1" serde = { version = "1", features = ["derive", "rc"] } serde_json = { version = "1", features = ["float_roundtrip"] } log = "0.4" diff --git a/README.md b/README.md index 142ebb1af..c45b619dc 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,7 @@ crashed survives the next start. The file stops growing at 16 MiB. `--version` w | Variable | Effect | |---|---| -| `CADCRAFT_CONFIG_DIR` | Use this directory instead of the platform settings directory (the log goes to its `logs/`) | +| `CADCRAFT_CONFIG_DIR` | Use this directory instead of the platform settings directory (the log goes to its `logs/`); empty means no settings folder (no log file, autosave, workspace or plotters) | | `RUST_LOG` | Log levels for standard error and the log file. Default: `info` for CADCraft's own crates, `warn` for everything else. env_logger-style directives replace that, e.g. `RUST_LOG=debug`, `RUST_LOG=warn,cadcraft_io=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`cadcraft*=debug`). `cadcraft_engine=debug` also logs every command-line message. | The logger is `apps/cadcraft/src/logging.rs`; the web build logs to the browser console instead. @@ -238,6 +238,9 @@ MCP tools include `command_line` (type at the prompt), `execute` (any command wi To run LISP routines, scripts and alias files, or to drive CADCraft from your own programs, see [docs/customization.md](docs/customization.md). +`cadcraft-cli --help` documents every subcommand and flag; exit codes, streams, environment +variables and its RFC-0012 conventions are in [docs/cli.md](docs/cli.md). + ## Architecture ```text diff --git a/apps/cadcraft-cli/Cargo.toml b/apps/cadcraft-cli/Cargo.toml index b852183f4..cac076c17 100644 --- a/apps/cadcraft-cli/Cargo.toml +++ b/apps/cadcraft-cli/Cargo.toml @@ -6,6 +6,14 @@ edition.workspace = true license.workspace = true publish = false +[lib] +name = "cadcraft_cli" +path = "src/lib.rs" + +[[bin]] +name = "cadcraft-cli" +path = "src/main.rs" + [lints] workspace = true @@ -14,4 +22,13 @@ cadcraft-engine = { workspace = true } cadcraft-io = { workspace = true } cadcraft-mcp = { workspace = true } cadcraft-render = { workspace = true } +clap = { workspace = true } +same-file = { workspace = true } serde_json = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +# Shell completions and man pages (examples/man-and-completions.rs, for the Linux packages); not +# in the binary. +clap_complete = { workspace = true } +clap_mangen = { workspace = true } diff --git a/apps/cadcraft-cli/examples/man-and-completions.rs b/apps/cadcraft-cli/examples/man-and-completions.rs new file mode 100644 index 000000000..ddcfbf062 --- /dev/null +++ b/apps/cadcraft-cli/examples/man-and-completions.rs @@ -0,0 +1,41 @@ +//! Writes cadcraft-cli's shell completions ([`clap_complete`]: bash, zsh, fish, elvish, +//! PowerShell) and man pages ([`clap_mangen`]: `cadcraft-cli.1` and one per subcommand, such as +//! `cadcraft-cli-convert.1`) into a directory. The Linux packages ship them +//! (`packaging/linux/package.sh`): +//! +//! ```sh +//! cargo run -p cadcraft-cli --example man-and-completions -- +//! ``` + +use std::path::Path; +use std::process::ExitCode; + +use clap::ValueEnum; +use clap_complete::Shell; + +fn main() -> ExitCode { + let mut args = std::env::args_os().skip(1); + let (Some(dir), None) = (args.next(), args.next()) else { + eprintln!("usage: man-and-completions "); + return ExitCode::from(2); + }; + let dir = Path::new(&dir); + match generate(dir) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {}: {e}", dir.display()); + ExitCode::FAILURE + } + } +} + +pub(crate) fn generate(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let mut cmd = cadcraft_cli::command(); + for &shell in Shell::value_variants() { + clap_complete::generate_to(shell, &mut cmd, "cadcraft-cli", dir)?; + } + // A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand, + // which `clap_mangen` would otherwise give pages of its own (`cadcraft-cli-help-convert.1`). + clap_mangen::generate_to(cadcraft_cli::command(), dir) +} diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs new file mode 100644 index 000000000..16b57eeb7 --- /dev/null +++ b/apps/cadcraft-cli/src/args.rs @@ -0,0 +1,786 @@ +//! The command line, as clap types. Values are parsed into their types here and the relations +//! between flags are checked, so a bad value or combination is a usage error (exit 2) naming the +//! flag, before any work starts; the handlers receive typed values only. A flag a subcommand +//! doesn't take is a usage error too, so a typo can't be silently ignored. A value flag never takes +//! the next flag as its value: a value starting with `-` is written `--save=-out.dxf` (or +//! `./-out.dxf`). + +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; + +use cadcraft_engine::geom::{Bounds2, Vec2}; +use cadcraft_io::Format; +use cadcraft_mcp::args::{blank_env_is_unset, name_env_vars}; +use clap::builder::{OsStringValueParser, PathBufValueParser, TypedValueParser}; +use clap::error::ErrorKind; +use clap::parser::ValueSource; +use clap::{ArgAction, ArgGroup, ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; +use serde_json::Value; + +/// Help text that names the formats of `list`, built once from [`Format::READ`] or [`Format::WRITE`] +/// so it can't drift from what the code accepts. +fn with_formats(cell: &'static std::sync::OnceLock, before: &str, list: &[Format], after: &str) -> &'static str { + cell.get_or_init(|| format!("{before}({}){after}", Format::list(list))) +} + +/// The drawing an input argument names. +fn read_help() -> &'static str { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + with_formats(&C, "The drawing to read ", Format::READ, "") +} + +fn open_help() -> &'static str { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + with_formats(&C, "Drawings to open ", Format::READ, "") +} + +fn write_help() -> &'static str { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + with_formats(&C, "The file to write; its extension picks the format ", Format::WRITE, "") +} + +fn save_help() -> &'static str { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + with_formats(&C, "Save the drawing to this file; its extension picks the format ", Format::WRITE, "") +} + +fn export_help() -> &'static str { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + with_formats(&C, "Export the drawing to this file; its extension picks the format ", Format::WRITE, "") +} + +fn convert_about() -> &'static str { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + with_formats(&C, "Convert a drawing; OUT's extension picks the format ", Format::WRITE, "") +} + +fn convert_long_about() -> &'static str { + static C: std::sync::OnceLock = std::sync::OnceLock::new(); + C.get_or_init(|| { + format!( + "{}\n\nImage output (png 2400x1600, svg, pdf) shows model space, fitted to the drawing extents unless\n--window or --view says otherwise.", + convert_about() + ) + }) +} + +/// cadcraft-cli: headless CADCraft +#[derive(Parser)] +#[command(name = "cadcraft-cli", version = cadcraft_engine::build_version(), arg_required_else_help = true)] +pub(crate) struct Cli { + #[command(subcommand)] + pub(crate) command: Command, +} + +#[derive(Subcommand)] +pub(crate) enum Command { + Info(InfoArgs), + Convert(ConvertArgs), + Run(RunArgs), + Commands(CommandsArgs), + Mcp(McpArgs), + Perf(PerfArgs), + Sample(SampleArgs), +} + +/// Print a drawing's summary as JSON +#[derive(Args)] +pub(crate) struct InfoArgs { + #[arg(help = read_help())] + pub(crate) file: PathBuf, + /// One line of JSON instead of pretty-printed + #[arg(long)] + pub(crate) compact: bool, +} + +/// Convert a drawing; OUT's extension picks the format +#[derive(Args)] +#[command(about = convert_about(), long_about = convert_long_about())] +pub(crate) struct ConvertArgs { + #[arg(value_name = "IN", help = read_help())] + pub(crate) input: PathBuf, + #[arg(value_name = "OUT", help = write_help())] + pub(crate) output: PathBuf, + #[command(flatten)] + pub(crate) framing: FramingArgs, + /// Allow an output that is an input file, replacing the original + #[arg(long)] + pub(crate) in_place: bool, + #[command(flatten)] + pub(crate) settings: Settings, +} + +/// The settings the desktop app reads from its environment, for the subcommands that draw or run +/// commands. A variable is the flag's fallback; an empty one counts as unset, except +/// `CADCRAFT_CONFIG_DIR`. +#[derive(Args)] +#[command(next_help_heading = "Settings")] +pub(crate) struct Settings { + /// The settings folder; plotter configurations are in its `plotters` folder (default: the + /// platform's settings folder). An empty value means no settings folder + // Not RFC-0012 rule 1.7's "an empty variable counts as unset": an empty value is the + // documented way to run with no settings folder (isolated runs, tests), and it predates the + // CLI port. Keep it out of any blanket treatment of empty variables. + #[arg(long, value_name = "DIR", env = "CADCRAFT_CONFIG_DIR", value_parser = OsStringValueParser::new().map(PathBuf::from))] + pub(crate) config_dir: Option, + /// The font that replaces a missing one (FONTALT) + #[arg(long, value_name = "FONT", env = "CADCRAFT_FONTALT")] + pub(crate) fontalt: Option, + /// The fonts tried, in order, for characters a font lacks, comma-separated (FONTFALLBACK) + #[arg(long, value_name = "FONTS", env = "CADCRAFT_FONTFALLBACK")] + pub(crate) fontfallback: Option, +} + +impl Settings { + /// Install the settings for this run; an unset one is the default. An empty or blank + /// `--config-dir` is no settings folder. + pub(crate) fn apply(&self) { + cadcraft_engine::settings_dir::set(self.settings_dir()); + cadcraft_engine::fonts::ttf::set_font_alt(self.fontalt.as_deref().unwrap_or("")); + cadcraft_engine::fonts::ttf::set_fallback_fonts(self.fontfallback.as_deref().unwrap_or("")); + } + + /// The settings folder: `--config-dir`, else the platform's; `None` when the flag is empty or + /// blank. + fn settings_dir(&self) -> Option { + match &self.config_dir { + Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None, + Some(dir) => Some(dir.clone()), + None => cadcraft_engine::settings_dir::platform(|k| std::env::var_os(k)), + } + } +} + +// What part of model space an image shows: shared by `convert` and `run`. +#[derive(Args)] +pub(crate) struct FramingArgs { + /// Show this rectangle (drawing units, x0, + /// What part of model space the image shows (case-insensitive) + #[arg(long, value_name = "extents|current", value_enum, ignore_case = true)] + pub(crate) view: Option, +} + +/// `--view`. +#[derive(Clone, Copy, Debug, PartialEq, ValueEnum)] +pub(crate) enum ViewMode { + /// Always fit the drawing extents + Extents, + /// The current view, as last set by zoom, pan or view.set (a freshly opened drawing's view is + /// its extents plus a 10% margin) + Current, +} + +/// Open drawings (or start a new one), run scripts and commands in order, save or export the result +/// +/// Drawings open in the order given, and the last one is current; without any, a new imperial +/// drawing is used. --script, --script-file and --cmd steps run in the order given, and each +/// --cmd prints its JSON result on one line (JSON lines); a command with no result prints nothing. +/// An image --export (png 2400x1600, svg, pdf) shows model space: +/// the current view if the steps changed it (zoom, pan, view.set…), otherwise the drawing +/// extents, unless --window or --view says otherwise. +#[derive(Args)] +#[command(group(ArgGroup::new("framing").args(["window", "view"]).multiple(true).requires("export")))] +#[command(after_long_help = r#"--cmd chaining: + A --cmd parameter value of exactly "{last}" is replaced with the last object handle an + earlier --cmd in the same run returned, so a command can act on what the previous one made: + --cmd 'mview {"p1":[20,20],"p2":[200,150]}' prints {"viewports":["100"]} + --cmd 'viewport.set {"handle":"{last}","scale":1}' changes viewport 100 + It works in any parameter, at any depth (e.g. "handles":["{last}"]); every other string is + passed unchanged. With no earlier returned handle the run fails and says so."#)] +pub(crate) struct RunArgs { + #[arg(value_name = "FILE", help = open_help())] + pub(crate) files: Vec, + /// Open the built-in sample drawing + #[arg(long)] + pub(crate) sample: bool, + /// Start a new metric drawing + #[arg(long)] + pub(crate) metric: bool, + /// Command-line script text to run (`\n` separates lines) + #[arg(long, value_name = "TEXT", action = ArgAction::Append)] + pub(crate) script: Vec, + /// A script file (.scr) to run + #[arg(long, value_name = "F.scr", action = ArgAction::Append)] + pub(crate) script_file: Vec, + /// An engine command and its JSON parameters (default {}); see "--cmd chaining" in --help + #[arg(long, value_name = "id {json}", action = ArgAction::Append, value_parser = cmd_step)] + pub(crate) cmd: Vec, + #[arg(long, value_name = "OUT.dxf", help = save_help())] + pub(crate) save: Option, + #[arg(long, value_name = "OUT.png", help = export_help())] + pub(crate) export: Option, + #[command(flatten)] + pub(crate) framing: FramingArgs, + /// Allow an output that is an input file, replacing the original + #[arg(long)] + pub(crate) in_place: bool, + #[command(flatten)] + pub(crate) settings: Settings, + /// The drawings, in command-line order, set by [`parse`]. + #[arg(skip)] + pub(crate) drawings: Vec, + /// The steps, in command-line order, set by [`parse`]. + #[arg(skip)] + pub(crate) steps: Vec, +} + +/// A drawing `run` opens. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Drawing { + File(PathBuf), + Sample, + Metric, +} + +/// A `--script`, `--script-file` or `--cmd` of `run`. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Step { + Script(String), + ScriptFile(PathBuf), + Cmd(CmdStep), +} + +/// `--cmd 'id {json}'`: an engine command and its parameters. `{last}` placeholders are filled in +/// when it runs. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct CmdStep { + pub(crate) id: String, + pub(crate) params: Value, +} + +/// Print the command catalog as JSON +#[derive(Args)] +pub(crate) struct CommandsArgs { + /// Only the commands whose id or label contains this text (case-insensitive) + pub(crate) filter: Option, + /// One line of JSON instead of pretty-printed + #[arg(long)] + pub(crate) compact: bool, +} + +/// Run the MCP server on stdio: a headless drawing session, or a bridge to the running app +#[derive(Args)] +pub(crate) struct McpArgs { + /// Bridge to the app's control channel (its --control port, e.g. 127.0.0.1:7979) + #[arg(long, value_name = "HOST:PORT", value_parser = connect_addr)] + pub(crate) connect: Option, + /// Reach the app at the first call instead of at startup, so the server can start before the + /// app is open + #[arg(long, requires = "connect")] + pub(crate) lazy: bool, + /// Like --lazy, and a call that finds nothing at HOST:PORT opens the app with that control + /// port first (macOS) + #[arg(long, requires = "connect")] + pub(crate) launch: bool, + #[command(flatten)] + pub(crate) settings: Settings, +} + +/// Time the engine on a synthetic N-entity drawing (default 200000), or the canvas display-list +/// build of a drawing, zoomed in step by step +#[derive(Args)] +pub(crate) struct PerfArgs { + /// An entity count (clamped to 1-20000000), or a drawing to time + #[arg(value_name = "N|FILE", value_parser = PathBufValueParser::new().map(perf_target))] + pub(crate) target: Option, +} + +/// What `perf` times. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum PerfTarget { + /// A synthetic drawing with this many entities, within [`MAX_PERF_COUNT`]. + Count(usize), + File(PathBuf), +} + +/// The largest synthetic drawing `perf` builds. +const MAX_PERF_COUNT: usize = 20_000_000; + +/// `perf N|FILE`: a value that reads as a count is one, clamped to 1..=[`MAX_PERF_COUNT`] so `perf +/// 0` still times something; anything else is a drawing. +fn perf_target(p: PathBuf) -> PerfTarget { + match p.to_str().and_then(|t| t.parse::().ok()) { + Some(n) => PerfTarget::Count(n.clamp(1, MAX_PERF_COUNT)), + None => PerfTarget::File(p), + } +} + +/// Write a built-in sample drawing +#[derive(Args)] +pub(crate) struct SampleArgs { + /// Which sample + #[arg(value_name = "bracket|floorplan", value_enum)] + pub(crate) name: SampleName, + #[arg(value_name = "OUT", help = write_help())] + pub(crate) output: PathBuf, + #[command(flatten)] + pub(crate) settings: Settings, +} + +/// `sample`'s drawings. +#[derive(Clone, Copy, Debug, PartialEq, ValueEnum)] +pub(crate) enum SampleName { + Bracket, + #[value(alias = "floor")] + Floorplan, +} + +/// What part of model space an image export shows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Framing { + /// `run`: the current view if the commands changed it, else the extents. `convert`: extents. + Auto, + Extents, + Current, + Window(Bounds2), +} + +/// Why a `--window` value is refused: clap prints it after the flag and its value (exit 2). +#[derive(Debug, thiserror::Error)] +pub(crate) enum WindowError { + #[error("expected four numbers x0,y0,x1,y1")] + NeedsFour, + #[error("{name} must be a finite number, got `{value}`")] + NotFinite { name: &'static str, value: String }, + #[error("need x0 < x1 and y0 < y1 (lower-left corner first)")] + Order, + #[error(transparent)] + Limits(#[from] cadcraft_io::IoError), +} + +/// Why a value is refused: clap prints it after the flag and its value (exit 2). +#[derive(Debug, thiserror::Error)] +pub(crate) enum ValueError { + #[error("expected HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)")] + Connect, + #[error("expected a command id, then optionally its JSON parameters")] + CmdId, + #[error(transparent)] + CmdJson(#[from] serde_json::Error), +} + +/// Why `parse` refuses flags clap accepted: clap prints it as a usage error (exit 2). +#[derive(Debug, thiserror::Error)] +enum UsageError { + /// The framing flags choose what an image shows; a drawing file has nothing to frame. + #[error("{flag} only applies to image output (png, svg, pdf), not `{}`", .out.display())] + FramingNeedsImage { flag: &'static str, out: PathBuf }, + /// 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), +} + +impl UsageError { + fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { + let kind = match self { + Self::FramingNeedsImage { .. } | Self::OutIsInput(_) => ErrorKind::ArgumentConflict, + }; + cmd.error(kind, self) + } +} + +/// Parse `--window x0,y0,x1,y1` (min corner first). Hostile values are errors, never panics. +pub(crate) fn parse_window(text: &str) -> Result { + let parts: Vec<&str> = text.split(',').map(str::trim).collect(); + let [x0, y0, x1, y1] = parts.as_slice() else { + return Err(WindowError::NeedsFour); + }; + let num = |name: &'static str, v: &str| -> Result { + match v.parse::() { + Ok(n) if n.is_finite() => Ok(n), + _ => Err(WindowError::NotFinite { name, value: v.to_string() }), + } + }; + let (x0, y0, x1, y1) = (num("x0", x0)?, num("y0", y0)?, num("x1", x1)?, num("y1", y1)?); + if !(x0 < x1 && y0 < y1) { + return Err(WindowError::Order); + } + let w = Bounds2 { min: Vec2::new(x0, y0), max: Vec2::new(x1, y1) }; + cadcraft_io::check_window(&w)?; + Ok(w) +} + +/// `run --cmd 'id {json}'`: the id up to the first space, then JSON parameters (default `{}`). +/// Whether they suit the command is the command's to say. +fn cmd_step(s: &str) -> Result { + let (id, json) = s.split_once(' ').unwrap_or((s, "{}")); + if id.is_empty() { + return Err(ValueError::CmdId); + } + Ok(CmdStep { id: id.to_string(), params: serde_json::from_str(json)? }) +} + +impl FramingArgs { + /// The framing `--window` or `--view` asks for (clap refuses both together). + pub(crate) fn framing(&self) -> Framing { + match (self.window, self.view) { + (Some(w), _) => Framing::Window(w), + (None, Some(ViewMode::Extents)) => Framing::Extents, + (None, Some(ViewMode::Current)) => Framing::Current, + (None, None) => Framing::Auto, + } + } + + /// The framing flag given, if any. + fn flag(&self) -> Option<&'static str> { + if self.window.is_some() { + Some("--window") + } else if self.view.is_some() { + Some("--view") + } else { + None + } + } +} + +/// A framing flag given with an output that isn't an image (the extension decides). `run` without +/// `--export` is clap's `requires` error. +fn framing_error(cli: &Cli) -> Option { + let (framing, out): (&FramingArgs, Option<&Path>) = match &cli.command { + Command::Convert(c) => (&c.framing, Some(&c.output)), + Command::Run(r) => (&r.framing, r.export.as_deref()), + _ => return None, + }; + let (flag, out) = (framing.flag()?, out?); + (!cadcraft_io::is_image(out)).then(|| UsageError::FramingNeedsImage { flag, out: out.to_path_buf() }) +} + +/// 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 { + let same = |input: &Path, out: &Path| out.exists() && same_file::is_same_file(input, out).unwrap_or(false); + match &cli.command { + Command::Convert(c) if !c.in_place && same(&c.input, &c.output) => Some(UsageError::OutIsInput(c.output.clone())), + Command::Run(r) if !r.in_place => { + let inputs = r.drawings.iter().filter_map(|d| if let Drawing::File(f) = d { Some(f) } else { None }); + let inputs: Vec<&PathBuf> = inputs.collect(); + [&r.save, &r.export].into_iter().flatten().find(|out| inputs.iter().any(|i| same(i, out))).map(|out| UsageError::OutIsInput(out.clone())) + } + _ => None, + } +} + +/// The backend `cadcraft-cli mcp` serves from. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum McpTarget { + /// An in-process drawing session (no `--connect`). + Headless, + /// 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 }, +} + +impl McpArgs { + pub(crate) fn target(&self) -> McpTarget { + 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, + } + } +} + +/// `mcp --connect`: an empty, flag-like or port-less address is an error, never a silent fall back +/// to a headless session (#103). The host is not resolved here. +fn connect_addr(s: &str) -> Result { + let s = s.trim(); + let valid = !s.starts_with('-') + && s.rsplit_once(':').is_some_and(|(host, port)| { + let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host); + !host.is_empty() && port.parse::().is_ok() + }); + if valid { Ok(s.to_string()) } else { Err(ValueError::Connect) } +} + +/// The values of `id` with their command-line indices. +fn indexed<'a, T: Clone + Send + Sync + 'static>(m: &'a ArgMatches, id: &str) -> impl Iterator { + let at = m.indices_of(id).into_iter().flatten(); + let values = m.try_get_many::(id).ok().flatten().into_iter().flatten(); + at.zip(values) +} + +/// The command-line index of flag `id`, when it was given. +fn flag_index(m: &ArgMatches, id: &str) -> Option { + if m.value_source(id) == Some(ValueSource::CommandLine) { m.indices_of(id).and_then(Iterator::last) } else { None } +} + +/// `run`'s drawings and steps back in command-line order: clap keeps each flag's values apart, +/// their indices say how they interleave. +fn run_order(m: &ArgMatches) -> (Vec, Vec) { + let mut drawings: Vec<(usize, Drawing)> = indexed(m, "files").map(|(i, f): (_, &PathBuf)| (i, Drawing::File(f.clone()))).collect(); + drawings.extend(flag_index(m, "sample").map(|i| (i, Drawing::Sample))); + drawings.extend(flag_index(m, "metric").map(|i| (i, Drawing::Metric))); + drawings.sort_by_key(|d| d.0); + let mut steps: Vec<(usize, Step)> = indexed(m, "script").map(|(i, s): (_, &String)| (i, Step::Script(s.clone()))).collect(); + steps.extend(indexed(m, "script_file").map(|(i, s): (_, &PathBuf)| (i, Step::ScriptFile(s.clone())))); + steps.extend(indexed(m, "cmd").map(|(i, c): (_, &CmdStep)| (i, Step::Cmd(c.clone())))); + steps.sort_by_key(|s| s.0); + (drawings.into_iter().map(|d| d.1).collect(), steps.into_iter().map(|s| s.1).collect()) +} + +/// Parse the arguments (without the binary name). clap reads them as `OsString`s: a path need not +/// be valid Unicode, text must. A bare `--help` or `-h` is help even after a mistake on the same +/// line (`run --script --help`): clap reports the mistake first. +pub(crate) fn parse(args: &[OsString]) -> Result { + parse_with(command(|k| std::env::var_os(k)), args) +} + +/// The command line. An empty or blank variable counts as unset, except `CADCRAFT_CONFIG_DIR`: +/// empty means no settings folder. `var` looks a variable up. +fn command(var: impl Fn(&OsStr) -> Option + Copy) -> clap::Command { + let blank = move |a: clap::Arg| if a.get_id() == "config_dir" { a } else { blank_env_is_unset(a, var) }; + Cli::command().mut_args(blank).mut_subcommands(|s| s.mut_args(blank)) +} + +/// [`parse`] with `cmd` from [`command`]; a bad value from a variable is a usage error naming the +/// variable. +fn parse_with(mut cmd: clap::Command, args: &[OsString]) -> Result { + let argv = std::iter::once(OsString::from("cadcraft-cli")).chain(args.iter().cloned()); + let matches = match cmd.try_get_matches_from_mut(argv) { + // `use_stderr`: a real error, not the help `-h` asked for (a retry would make it `--help`). + Err(e) if e.use_stderr() && args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => { + let help = [OsString::from("cadcraft-cli"), args.first().cloned().unwrap_or_default(), OsString::from("--help")]; + return Err(cmd.try_get_matches_from_mut(help).err().unwrap_or(e)); + } + matches => matches.map_err(|e| name_env_vars(e, &cmd, args))?, + }; + let mut cli = Cli::from_arg_matches(&matches)?; + if let (Command::Run(r), Some((_, m))) = (&mut cli.command, matches.subcommand()) { + (r.drawings, r.steps) = run_order(m); + } + if let Some(e) = framing_error(&cli).or_else(|| out_is_input(&cli)) { + if let Some(sub) = matches.subcommand_name().and_then(|n| cmd.find_subcommand_mut(n)) { + return Err(e.into_clap(sub)); + } + return Err(e.into_clap(&mut cmd)); + } + Ok(cli) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn parse_args(a: &[&str]) -> Result { + parse(&a.iter().map(OsString::from).collect::>()) + } + + fn mcp(a: &[&str]) -> Result { + let args: Vec<&str> = std::iter::once("mcp").chain(a.iter().copied()).collect(); + match parse_args(&args)?.command { + Command::Mcp(m) => Ok(m.target()), + _ => panic!("{a:?} is not mcp"), + } + } + + /// Every file argument's help names each format of the list it uses. + #[test] + fn help_names_every_format() { + let cli = Cli::command(); + let help = |sub: &str, arg: &str| { + let a = cli.find_subcommand(sub).and_then(|c| c.get_arguments().find(|a| a.get_id() == arg)).expect("argument exists"); + a.get_help().map(|h| h.to_string()).unwrap_or_default() + }; + let cases: [(&str, &str, &[Format]); 8] = [ + ("info", "file", Format::READ), + ("convert", "input", Format::READ), + ("convert", "output", Format::WRITE), + ("run", "files", Format::READ), + ("run", "save", Format::WRITE), + ("run", "export", Format::WRITE), + ("sample", "output", Format::WRITE), + ("convert", "", Format::WRITE), + ]; + for (sub, arg, list) in cases { + let text = if arg.is_empty() { + cli.find_subcommand(sub).and_then(|c| c.get_about()).map(|a| a.to_string()).unwrap_or_default() + } else { + help(sub, arg) + }; + for f in list { + assert!(text.contains(f.extension()), "`{sub} {arg}` help `{text}` lacks {}", f.extension()); + } + } + } + + #[test] + fn mcp_without_connect_is_headless() { + assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless); + } + + #[test] + fn mcp_connect_with_address_selects_remote() { + let to = |addr: &str, lazy, launch| McpTarget::Connect { addr: addr.into(), lazy, launch }; + assert_eq!(mcp(&["--connect", "127.0.0.1:7979"]).unwrap(), to("127.0.0.1:7979", false, false)); + assert_eq!(mcp(&["--connect", " localhost:7979 "]).unwrap(), to("localhost:7979", false, false)); + assert_eq!(mcp(&["--lazy", "--connect", "localhost:7979"]).unwrap(), to("localhost:7979", true, false)); + assert_eq!(mcp(&["--connect", "localhost:7979", "--launch"]).unwrap(), to("localhost:7979", true, true)); + assert_eq!(mcp(&["--connect", "[::1]:7979"]).unwrap(), to("[::1]:7979", false, false)); + // Without an app to reach they mean nothing: never a headless session. + for flag in ["--lazy", "--launch"] { + assert_eq!(mcp(&[flag]).unwrap_err().kind(), clap::error::ErrorKind::MissingRequiredArgument, "{flag}"); + } + } + + #[test] + fn mcp_connect_without_address_is_an_error_not_headless() { + for bad in [ + &["--connect"][..], + &["--connect", ""], + &["--connect", " "], + &["--connect=-v"], + &["--connect", "example.com"], + &["--connect", ":7979"], + &["--connect", "host:99999"], + &["--connect", "[]:1"], + ] { + let r = mcp(bad); + let Err(e) = r else { panic!("{bad:?} should be rejected, got {r:?}") }; + assert_eq!(e.exit_code(), 2, "{bad:?}"); + assert!(e.to_string().contains("--connect "), "{bad:?}: {e}"); + } + } + + #[test] + fn mcp_rejects_unknown_and_repeated_arguments() { + assert!(mcp(&["--conect", "127.0.0.1:7979"]).is_err()); + assert!(mcp(&["127.0.0.1:7979"]).is_err()); + // clap names the unknown flag, not the value it left missing. + for flag in ["--foo", "-v"] { + assert_eq!(mcp(&["--connect", flag]).unwrap_err().kind(), clap::error::ErrorKind::UnknownArgument, "{flag}"); + } + assert!(mcp(&["--connect", "127.0.0.1:1", "--connect", "127.0.0.1:2"]).is_err()); + } + + #[test] + fn run_keeps_command_line_order() { + let args = + ["run", "a.dxf", "--script", "S1", "--metric", "--cmd", "c1", "b.dxf", "--script-file", "f.scr", "--sample", "--cmd", "c2 {\"n\":1}"]; + let Command::Run(r) = parse_args(&args).unwrap().command else { panic!("not run") }; + let file = |f: &str| Drawing::File(f.into()); + let cmd = |id: &str, params| Step::Cmd(CmdStep { id: id.into(), params }); + assert_eq!(r.drawings, [file("a.dxf"), Drawing::Metric, file("b.dxf"), Drawing::Sample]); + assert_eq!(r.steps, [Step::Script("S1".into()), cmd("c1", json!({})), Step::ScriptFile("f.scr".into()), cmd("c2", json!({"n": 1}))]); + } + + #[test] + fn cmd_values() { + assert_eq!(cmd_step("line").unwrap(), CmdStep { id: "line".into(), params: json!({}) }); + assert_eq!(cmd_step("line [1]").unwrap(), CmdStep { id: "line".into(), params: json!([1]) }); + for bad in ["", " {}", "line {bad json", "line "] { + assert!(cmd_step(bad).is_err(), "`{bad}` should be rejected"); + } + } + + #[test] + fn perf_targets() { + let target = |a: &[&str]| -> Option { + let args: Vec<&str> = std::iter::once("perf").chain(a.iter().copied()).collect(); + let Command::Perf(p) = parse_args(&args).unwrap().command else { panic!("not perf") }; + p.target + }; + assert_eq!(target(&[]), None); + assert_eq!(target(&["5"]), Some(PerfTarget::Count(5))); + assert_eq!(target(&["0"]), Some(PerfTarget::Count(1))); + assert_eq!(target(&["999999999"]), Some(PerfTarget::Count(MAX_PERF_COUNT))); + assert_eq!(target(&["a.dxf"]), Some(PerfTarget::File("a.dxf".into()))); + assert_eq!(target(&["1e3"]), Some(PerfTarget::File("1e3".into()))); + } + + #[test] + fn framing_options() { + let framing = |out: &str, a: &[&str]| -> Result { + let args: Vec<&str> = ["convert", "a.dxf", out].iter().chain(a).copied().collect(); + let Command::Convert(c) = parse_args(&args)?.command else { panic!("not convert") }; + Ok(c.framing.framing()) + }; + let b = |x0, y0, x1, y1| Bounds2::new(Vec2::new(x0, y0), Vec2::new(x1, y1)); + assert_eq!(framing("b.png", &[]).unwrap(), Framing::Auto); + assert_eq!(framing("b.png", &["--view", "extents"]).unwrap(), Framing::Extents); + assert_eq!(framing("b.png", &["--view", "CURRENT"]).unwrap(), Framing::Current); + assert_eq!(framing("b.png", &["--window", "0,0,2,1"]).unwrap(), Framing::Window(b(0.0, 0.0, 2.0, 1.0))); + assert_eq!(framing("b.dxf", &[]).unwrap(), Framing::Auto); + let kind = |out: &str, a: &[&str]| framing(out, a).map(|_| ()).unwrap_err().kind(); + assert_eq!(kind("b.png", &["--view", "selection"]), ErrorKind::InvalidValue); + assert_eq!(kind("b.png", &["--window", "0,0,2,1", "--view", "extents"]), ErrorKind::ArgumentConflict); + assert_eq!(kind("b.dxf", &["--view", "extents"]), ErrorKind::ArgumentConflict); + assert_eq!(kind("b.dxf", &["--window", "0,0,2,1"]), ErrorKind::ArgumentConflict); + } + + #[test] + fn window_parses() { + let b = |x0, y0, x1, y1| Bounds2::new(Vec2::new(x0, y0), Vec2::new(x1, y1)); + assert_eq!(parse_window("0,0,30,20").unwrap(), b(0.0, 0.0, 30.0, 20.0)); + assert_eq!(parse_window(" -5.5, -1e3 ,2e3,4 ").unwrap(), b(-5.5, -1000.0, 2000.0, 4.0)); + } + + #[test] + fn hostile_window_is_an_error() { + for w in [ + "", + "1,2,3", + "1,2,3,4,5", + "a,0,1,1", + "NaN,0,1,1", + "0,0,inf,1", + "0,0,1e400,1", + "0,0,0,1", + "0,0,1,0", + "5,0,1,1", + "0,5,1,1", + "-1e300,-1e300,1e300,1e300", + "0,0,1e-12,1e-12", + ] { + assert!(parse_window(w).is_err(), "`{w}` should be rejected"); + } + } + + /// The subcommands that draw or run commands take the settings flags; the others refuse them. + #[test] + fn settings_flags() { + let Command::Convert(c) = + parse_args(&["convert", "a.dxf", "b.png", "--config-dir", "/p", "--fontalt", "Noto Sans", "--fontfallback="]).unwrap().command + else { + panic!("not convert") + }; + assert_eq!(c.settings.config_dir, Some(PathBuf::from("/p"))); + assert_eq!((c.settings.fontalt.as_deref(), c.settings.fontfallback.as_deref()), (Some("Noto Sans"), Some(""))); + for empty in ["--config-dir=", "--config-dir= "] { + let Command::Run(r) = parse_args(&["run", "--sample", empty]).unwrap().command else { panic!("not run") }; + assert_eq!(r.settings.settings_dir(), None, "`{empty}` is no settings folder"); + } + let Command::Convert(c) = parse_args(&["convert", "a.dxf", "b.png", "--config-dir", "/p"]).unwrap().command else { panic!("not convert") }; + assert_eq!(c.settings.settings_dir(), Some(PathBuf::from("/p"))); + assert!(parse_args(&["sample", "bracket", "b.dxf", "--fontalt", "x"]).is_ok()); + assert!(parse_args(&["mcp", "--config-dir", "/p"]).is_ok()); + assert!(parse_args(&["info", "a.dxf", "--config-dir", "/p"]).is_err()); + } + + #[test] + fn blank_variables_count_as_unset_except_the_config_dir() { + let cmd = command(|_| Some("".into())); + for sub in cmd.get_subcommands().filter(|s| s.get_arguments().any(|a| a.get_id() == "fontalt")) { + let env = |id: &str| sub.get_arguments().find(|a| a.get_id() == id).and_then(|a| a.get_env()); + assert_eq!((env("fontalt"), env("fontfallback")), (None, None), "{}", sub.get_name()); + assert_eq!(env("config_dir"), Some(OsStr::new("CADCRAFT_CONFIG_DIR")), "{}", sub.get_name()); + } + } + + /// `--fontalt` falls back to `PATH` and rejects every value here, as a bad value from a + /// variable would; tests can't set a variable (`set_var` is unsafe). + #[test] + fn a_bad_value_from_a_variable_names_the_variable() { + // Cargo sets CARGO_PKG_NAME for every test binary, so the variable always has a value. + let reject = clap::builder::PossibleValuesParser::new(["never"]); + let cmd = || Cli::command().mut_subcommand("sample", |s| s.mut_arg("fontalt", |a| a.env("CARGO_PKG_NAME").value_parser(reject.clone()))); + let args = |a: &[&str]| a.iter().map(OsString::from).collect::>(); + let text = parse_with(cmd(), &args(&["sample"])).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(text.contains("for 'CARGO_PKG_NAME'") && !text.contains("--fontalt"), "{text}"); + let text = parse_with(cmd(), &args(&["sample", "--fontalt", "x"])).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(text.contains("--fontalt"), "{text}"); + } +} diff --git a/apps/cadcraft-cli/src/commands.rs b/apps/cadcraft-cli/src/commands.rs new file mode 100644 index 000000000..51fc06606 --- /dev/null +++ b/apps/cadcraft-cli/src/commands.rs @@ -0,0 +1,17 @@ +use super::args::CommandsArgs; +use super::error::Result; +use super::output::Streams; +use cadcraft_engine::Session; +use serde_json::Value; + +pub(crate) fn commands(a: &CommandsArgs, io: &mut Streams) -> Result { + let s = Session::new(); + let f = a.filter.as_ref().map(|x| x.to_ascii_lowercase()); + let v: Vec = cadcraft_engine::command_specs() + .iter() + .filter(|c| f.as_ref().is_none_or(|f| c.id.contains(f.as_str()) || c.label.to_ascii_lowercase().contains(f.as_str()))) + .map(|c| serde_json::to_value(c.info(&s)).unwrap_or_default()) + .collect(); + io.json(&Value::Array(v), a.compact); + Ok(()) +} diff --git a/apps/cadcraft-cli/src/convert.rs b/apps/cadcraft-cli/src/convert.rs new file mode 100644 index 000000000..6a9c4edbf --- /dev/null +++ b/apps/cadcraft-cli/src/convert.rs @@ -0,0 +1,22 @@ +use super::args::ConvertArgs; +use super::error::Result; +use super::output::{Streams, export_framed, export_window, skipped_message, undrawn_message}; +use super::{open, unicode}; +use cadcraft_engine::Session; + +pub(crate) fn convert(a: &ConvertArgs, io: &mut Streams) -> Result { + let i = unicode(&a.input)?; + let framing = a.framing.framing(); + let mut s = Session::empty(); + open(&mut s, &a.input)?; + if let Some(m) = skipped_message(s.doc()?, i) { + io.errln(format_args!("{m}")); + } + if cadcraft_io::is_image(&a.output) + && let Some(m) = undrawn_message(s.doc()?, i) + { + io.errln(format_args!("{m}")); + } + let window = export_window(&s, framing, None)?; + export_framed(&s, &a.output, window, io) +} diff --git a/apps/cadcraft-cli/src/error.rs b/apps/cadcraft-cli/src/error.rs new file mode 100644 index 000000000..51b816890 --- /dev/null +++ b/apps/cadcraft-cli/src/error.rs @@ -0,0 +1,29 @@ +use crate::output::OutputError; +use crate::perf::PerfError; +use crate::run::RunError; + +/// Why a subcommand failed: printed as `error: {e}`, exit 1. +#[derive(Debug, thiserror::Error)] +pub(crate) enum CliError { + #[error(transparent)] + Engine(#[from] cadcraft_engine::EngineError), + #[error(transparent)] + Doc(#[from] cadcraft_engine::doc::DocError), + #[error(transparent)] + Format(#[from] cadcraft_io::IoError), + #[error(transparent)] + Io(#[from] std::io::Error), + #[error(transparent)] + Run(#[from] RunError), + #[error(transparent)] + Output(#[from] OutputError), + #[error(transparent)] + Perf(#[from] PerfError), + /// The engine and io crates take file names as text. + #[error("{}: the file name is not valid Unicode", .0.display())] + NotUnicode(std::path::PathBuf), + #[error("cannot connect to {addr}: {source}")] + McpConnect { addr: String, source: std::io::Error }, +} + +pub(crate) type Result = std::result::Result; diff --git a/apps/cadcraft-cli/src/info.rs b/apps/cadcraft-cli/src/info.rs new file mode 100644 index 000000000..bac94108e --- /dev/null +++ b/apps/cadcraft-cli/src/info.rs @@ -0,0 +1,14 @@ +use super::args::InfoArgs; +use super::error::Result; +use super::open; +use super::output::Streams; +use cadcraft_engine::Session; +use serde_json::json; + +pub(crate) fn info(a: &InfoArgs, io: &mut Streams) -> Result { + let mut s = Session::empty(); + open(&mut s, &a.file)?; + let v = s.execute("drawing.inspect", &json!({ "entities": false }))?; + io.json(&v, a.compact); + Ok(()) +} diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs new file mode 100644 index 000000000..c858417e2 --- /dev/null +++ b/apps/cadcraft-cli/src/lib.rs @@ -0,0 +1,315 @@ +//! `cadcraft-cli`: headless CADCraft. The subcommands and their options are the clap types in +//! `args.rs`; `cadcraft-cli --help` lists them. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::ffi::OsString; +use std::io::Write; + +use cadcraft_engine::Session; +use serde_json::json; + +mod args; +mod commands; +mod convert; +mod error; +mod info; +mod mcp; +mod output; +mod perf; +mod run; +mod sample; + +#[cfg(test)] +use args::Framing; +use args::{Command, parse}; +use clap::CommandFactory; +use commands::commands; +use convert::convert; +use error::Result; +use info::info; +use mcp::mcp; +use output::Streams; +#[cfg(test)] +use output::{export_window, model_views, write_atomic}; +use perf::perf; +use run::run_cmds; +#[cfg(test)] +use run::{fill_last, returned_handle}; +use sample::sample; + +fn install_io() { + cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), + }); + cadcraft_engine::cmd::file::set_write_as(|d, name, o| { + cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) + }); + // AutoLISP's entget, entmake and entmod see entities as DXF groups. + cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec { + groups: cadcraft_io::entity_groups, + entity: cadcraft_io::entity_from_groups, + }); +} + +/// `path` as text, for the engine and io calls that take a file name as a string. +fn unicode(path: &std::path::Path) -> Result<&str> { + path.to_str().ok_or_else(|| error::CliError::NotUnicode(path.to_path_buf())) +} + +fn open(s: &mut Session, path: &std::path::Path) -> Result { + s.execute("open", &json!({ "path": unicode(path)? }))?; + Ok(()) +} + +/// The command line's clap definition, for generating shell completions and man pages. +pub fn command() -> clap::Command { + args::Cli::command() +} + +/// Run the CLI on its arguments (without the program name). Returns the process exit code (0 ok, +/// 1 failure, 2 usage). clap reads the arguments as they are: a value that is not valid Unicode +/// is a usage error, never a panic as with `std::env::args()`. +pub fn run(args: I, out: &mut dyn Write, err: &mut dyn Write) -> i32 +where + I: IntoIterator, + T: Into, +{ + let args: Vec = args.into_iter().map(Into::into).collect(); + // Help and `--version` (`help`, `-h`, ` --help`, `-V`) come back as errors too, + // for `out`, exit 0: the subcommand never runs. + let cli = match parse(&args) { + Ok(cli) => cli, + Err(e) => { + let to: &mut dyn Write = if e.use_stderr() { err } else { out }; + return match write!(to, "{}", e.render()) { + Err(w) if w.kind() != std::io::ErrorKind::BrokenPipe => { + let _ = writeln!(err, "error: can't write the output: {w}"); + 1 + } + _ => e.exit_code(), + }; + } + }; + // The engine's hooks are set-once, so installing them on every call is harmless. + install_io(); + match &cli.command { + Command::Convert(a) => a.settings.apply(), + Command::Run(a) => a.settings.apply(), + Command::Mcp(a) => a.settings.apply(), + Command::Sample(a) => a.settings.apply(), + Command::Info(_) | Command::Commands(_) | Command::Perf(_) => {} + } + let mut io = Streams::new(out, err); + let result = match &cli.command { + Command::Info(a) => info(a, &mut io), + Command::Convert(a) => convert(a, &mut io), + Command::Run(a) => run_cmds(a, &mut io), + Command::Commands(a) => commands(a, &mut io), + Command::Mcp(a) => mcp(a), + Command::Perf(a) => perf(a.target.as_ref(), &mut io), + Command::Sample(a) => sample(a, &mut io), + }; + let mut code = 0; + if let Err(e) = result { + io.errln(format_args!("error: {e}")); + code = 1; + } + io.finish(); + if io.stdout_failed() { 1 } else { code } +} + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_engine::doc::Space; + use cadcraft_engine::geom::{Bounds2, Vec2}; + + fn scratch_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("cadcraft-cli-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch dir"); + dir + } + + struct FailingWriter(std::io::ErrorKind); + + impl Write for FailingWriter { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(self.0.into()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + #[test] + fn a_failed_write_of_help_exits_1_unless_the_pipe_is_closed() { + let mut err = Vec::new(); + assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::StorageFull), &mut err), 1); + assert!(String::from_utf8_lossy(&err).starts_with("error: ")); + assert_eq!(run(["--help"], &mut FailingWriter(std::io::ErrorKind::BrokenPipe), &mut Vec::new()), 0); + } + + #[test] + fn write_atomic_replaces_file_and_leaves_no_staging_files() { + let dir = scratch_dir("replace"); + let out = dir.join("a.dxf"); + write_atomic(&out, b"old").expect("create"); + write_atomic(&out, b"new").expect("overwrite"); + assert_eq!(std::fs::read(&out).expect("read"), b"new"); + assert_eq!(std::fs::read_dir(&dir).expect("list").count(), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn write_atomic_failure_keeps_destination_and_cleans_up() { + let dir = scratch_dir("fail"); + let out = dir.join("target"); + std::fs::create_dir(&out).expect("dir as destination"); + std::fs::write(out.join("keep"), b"x").expect("seed"); + assert!(write_atomic(&out, b"new").is_err()); + assert_eq!(std::fs::read(out.join("keep")).expect("kept"), b"x"); + assert_eq!(std::fs::read_dir(&dir).expect("list").count(), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + fn b(x0: f64, y0: f64, x1: f64, y1: f64) -> Bounds2 { + Bounds2::new(Vec2::new(x0, y0), Vec2::new(x1, y1)) + } + + fn sample_session() -> Session { + let mut s = Session::empty(); + s.open_drawing(cadcraft_engine::sample::default_sample(), "Bracket", None); + s + } + + fn view_box(svg: &str) -> String { + let i = svg.find("viewBox=\"").map(|i| i + 9).unwrap_or(0); + svg[i..].split('"').next().unwrap_or("").to_string() + } + + fn assert_near(a: Bounds2, e: Bounds2) { + let d = (a.min - e.min).len().max((a.max - e.max).len()); + assert!(d < 1e-9, "{a:?} != {e:?}"); + } + + #[test] + fn last_placeholder_takes_the_previous_handle() { + let mut s = sample_session(); + let r = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let h = returned_handle(&s, &r).expect("LINE returns its handle"); + assert_eq!(fill_last(&json!({"handle": "{last}"}), Some(h)).unwrap(), json!({"handle": h.hex()})); + // Nested, as in a selection list. + assert_eq!(fill_last(&json!({"handles": ["{last}", "1"]}), Some(h)).unwrap(), json!({"handles": [h.hex(), "1"]})); + // Only the exact token: a name or a sentence that merely contains it stays as written. + for p in [json!("last"), json!("{last} "), json!({"name": "last"})] { + assert_eq!(fill_last(&p, Some(h)).unwrap(), p); + } + // Nothing returned yet: an error, not a token passed to the command as a bad handle. + assert!(fill_last(&json!({"handle": "{last}"}), None).unwrap_err().to_string().contains("{last}")); + } + + /// Handles are read from a result by looking the strings up in the drawing: counts and names + /// are not mistaken for handles, and `mview`'s `viewports` works like `handle`/`handles`. + #[test] + fn returned_handle_reads_only_real_handles() { + let mut s = Session::empty(); + s.new_drawing(false); + s.execute("layout.set", &json!({"name": "Layout1"})).unwrap(); + let r = s.execute("mview", &json!({"p1": [20, 20], "p2": [200, 150]})).unwrap(); + let h = returned_handle(&s, &r).expect("mview returns its viewport handle"); + assert!(r["viewports"].as_array().is_some_and(|a| a.iter().any(|v| v.as_str() == Some(h.hex().as_str()))), "{r}"); + assert_eq!(returned_handle(&s, &json!({"changed": 3, "name": "A1"})), None); + // The most recent of several. + let a = s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap(); + let b = s.execute("line", &json!({"points": [[0, 0], [2, 0]]})).unwrap(); + let (ha, hb) = (returned_handle(&s, &a).unwrap(), returned_handle(&s, &b).unwrap()); + assert_eq!(returned_handle(&s, &json!({"handles": [ha.hex(), hb.hex()]})), Some(hb)); + } + + #[test] + fn default_framing_is_extents() { + // convert: nothing ran, always the extents. + let s = sample_session(); + assert_eq!(export_window(&s, Framing::Auto, None).unwrap(), None); + // run: commands that leave the view alone keep the extents framing. + let mut s = sample_session(); + let before = model_views(&s); + s.script("LINE 0,0 10,10\n\n").unwrap(); + assert_eq!(export_window(&s, Framing::Auto, Some(&before)).unwrap(), None); + // A fresh drawing too. + let mut s = Session::empty(); + s.new_drawing(false); + let before = model_views(&s); + s.execute("circle", &json!({"center": [0, 0], "radius": 5})).unwrap(); + assert_eq!(export_window(&s, Framing::Auto, Some(&before)).unwrap(), None); + } + + #[test] + fn zoom_window_frames_export() { + let mut s = sample_session(); + let before = model_views(&s); + s.execute("zoom", &json!({"mode": "window", "p1": [0, 0], "p2": [30, 20]})).unwrap(); + let w = export_window(&s, Framing::Auto, Some(&before)).unwrap().unwrap(); + // The CLI viewport is 3:2, so a 3:2 window is shown exactly. + assert_near(w, b(0.0, 0.0, 30.0, 20.0)); + assert_eq!(export_window(&s, Framing::Current, Some(&before)).unwrap(), Some(w)); + // --view extents and --window override the zoom. + assert_eq!(export_window(&s, Framing::Extents, Some(&before)).unwrap(), None); + let explicit = b(1.0, 1.0, 2.0, 2.0); + assert_eq!(export_window(&s, Framing::Window(explicit), Some(&before)).unwrap(), Some(explicit)); + // A taller window keeps its height; the 3:2 image adds room left and right. + s.execute("zoom", &json!({"mode": "center", "center": [5, 5], "height": 4})).unwrap(); + assert_near(export_window(&s, Framing::Auto, Some(&before)).unwrap().unwrap(), b(2.0, 3.0, 8.0, 7.0)); + } + + #[test] + fn zoom_object_frames_the_selection() { + let mut s = sample_session(); + let before = model_views(&s); + // The smallest entity with an area, selected then framed with ZOOM Object. + let d = s.doc().unwrap(); + let bounds = |e: &cadcraft_engine::doc::Entity| cadcraft_engine::doc::entity_bounds(d, e, 0); + let e = d + .model + .iter() + .filter(|e| bounds(e).width() > 0.0 && bounds(e).height() > 0.0) + .min_by(|a, b| bounds(a).width().total_cmp(&bounds(b).width())) + .unwrap(); + let (h, eb, ext) = (e.handle, bounds(e), d.extents(&Space::Model)); + s.set_selection(vec![h]); + s.execute("zoom", &json!({"mode": "object"})).unwrap(); + let w = export_window(&s, Framing::Auto, Some(&before)).unwrap().unwrap(); + assert!(w.contains(eb.min) && w.contains(eb.max)); + assert!(w.width() < ext.width() && w.height() < ext.height(), "{w:?} vs extents {ext:?}"); + } + + #[test] + fn run_export_honours_zoom() { + let dir = std::env::temp_dir().join(format!("cadcraft-cli-165-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = |n: &str| dir.join(n).to_string_lossy().to_string(); + let run_svg = |extra: &[&str], out: &str| -> String { + let mut args: Vec = ["run", "--sample"].iter().chain(extra).map(|a| a.to_string()).collect(); + args.extend(["--export".to_string(), path(out)]); + assert_eq!(run(args, &mut Vec::new(), &mut Vec::new()), 0); + std::fs::read_to_string(path(out)).unwrap() + }; + let base = run_svg(&[], "base.svg"); + let zoomed = run_svg(&["--cmd", r#"zoom {"mode":"window","p1":[0,0],"p2":[30,20]}"#], "zoom.svg"); + let window = run_svg(&["--window", "0,0,30,20"], "window.svg"); + let forced = run_svg(&["--cmd", r#"zoom {"mode":"window","p1":[0,0],"p2":[30,20]}"#, "--view", "extents"], "forced.svg"); + assert_ne!(view_box(&zoomed), view_box(&base)); + assert_eq!(view_box(&zoomed), "0 0 30.000000 20.000000"); + assert_eq!(zoomed, window); + assert_eq!(forced, base); + // Hostile --window: a usage error, nothing written. + let mut err = Vec::new(); + assert_eq!(run(["run", "--sample", "--window", "0,0,NaN,1", "--export", &path("bad.png")], &mut Vec::new(), &mut err), 2); + assert!(String::from_utf8_lossy(&err).contains("--window")); + assert!(!dir.join("bad.png").exists()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/cadcraft-cli/src/main.rs b/apps/cadcraft-cli/src/main.rs index 99a8b4282..7561b96b5 100644 --- a/apps/cadcraft-cli/src/main.rs +++ b/apps/cadcraft-cli/src/main.rs @@ -1,1111 +1,8 @@ -//! `cadcraft-cli`: headless CADCraft. -//! -//! ```text -//! cadcraft-cli info FILE.dxf summary as JSON -//! cadcraft-cli convert IN.dxf OUT.(dxf|svg|png) [--window x0,y0,x1,y1 | --view extents|current] -//! cadcraft-cli run [FILE|--sample|--metric] [--script TEXT|--script-file F.scr] [--cmd 'id {json}']... [--save OUT] [--export OUT.png] [--window ... | --view ...] -//! cadcraft-cli commands [FILTER] command catalog (JSON) -//! cadcraft-cli mcp [--connect HOST:PORT [--lazy] [--launch]] MCP server on stdio (headless or bridged to the app) -//! cadcraft-cli perf [N] timing table on a synthetic N-entity drawing -//! cadcraft-cli perf FILE canvas display-list build of a drawing, zoomed in step by step -//! cadcraft-cli sample (bracket|floorplan) OUT write a built-in sample drawing -//! ``` #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -/// `println!` that doesn't panic when stdout is closed (`cadcraft-cli commands | head`) with -/// "failed printing to stdout: Broken pipe (os error 32)". Once stdout has failed, later output is -/// dropped and the work goes on: see `stdout_failed`. -macro_rules! outln { - ($($arg:tt)*) => {{ - use std::io::Write as _; - if !$crate::stdout_gone() { - if let Err(e) = writeln!(std::io::stdout(), $($arg)*) { - $crate::stdout_failed(e); - } - } - }}; -} - -use std::process::ExitCode; - -use cadcraft_engine::doc::{Handle, Space}; -use cadcraft_engine::geom::{Bounds2, Vec2}; -use cadcraft_engine::{Session, View}; -use serde_json::{Value, json}; -use std::sync::atomic::{AtomicBool, Ordering}; - -/// Set once a write to stdout has failed; later output is dropped. -static STDOUT_GONE: AtomicBool = AtomicBool::new(false); -/// Set when stdout failed for a reason other than a closed reader: the exit status becomes 1. -static STDOUT_ERROR: AtomicBool = AtomicBool::new(false); - -fn stdout_gone() -> bool { - STDOUT_GONE.load(Ordering::Relaxed) -} - -/// stdout went away. The program doesn't stop there: the rest of `run` (later `--cmd` results, -/// `--save`, `--export`) still happens, so `cadcraft-cli run … --save out.dxf | head` keeps the -/// drawing. A reader that stopped early (a closed pipe) is not an error, as in ripgrep; any other -/// write error is reported and makes the exit status 1. -fn stdout_failed(e: std::io::Error) { - if STDOUT_GONE.swap(true, Ordering::Relaxed) || e.kind() == std::io::ErrorKind::BrokenPipe { - return; - } - eprintln!("cadcraft-cli: can't write to stdout: {e}"); - STDOUT_ERROR.store(true, Ordering::Relaxed); -} - -const USAGE: &str = "usage: - cadcraft-cli info FILE.dxf - cadcraft-cli convert IN.dxf OUT.(dxf|dwg|svg|png|pdf) [FRAMING] - cadcraft-cli run [FILE | --sample | --metric] [--script TEXT] [--script-file F.scr] [--cmd 'id {json}']... [--save OUT.dxf] [--export OUT.(png|svg|pdf)] [FRAMING] - cadcraft-cli commands [FILTER] - cadcraft-cli mcp [--connect HOST:PORT [--lazy] [--launch]] - cadcraft-cli perf [N | FILE] - cadcraft-cli sample (bracket|floorplan) OUT.(dxf|dwg|svg|png) - cadcraft-cli --version - -image framing (png 2400x1600, svg, pdf; always model space): - default convert: fit the drawing extents. - run --export: the current view if the script/commands changed it - (zoom, pan, view.set...), otherwise fit the drawing extents. - --window x0,y0,x1,y1 show this rectangle (drawing units, x0 Result { - let parts: Vec<&str> = text.split(',').map(str::trim).collect(); - let [x0, y0, x1, y1] = parts.as_slice() else { - return Err(format!("--window needs four numbers x0,y0,x1,y1, got `{text}`")); - }; - let num = |name: &str, v: &str| -> Result { - match v.parse::() { - Ok(n) if n.is_finite() => Ok(n), - _ => Err(format!("--window: {name} must be a finite number, got `{v}`")), - } - }; - let (x0, y0, x1, y1) = (num("x0", x0)?, num("y0", y0)?, num("x1", x1)?, num("y1", y1)?); - if !(x0 < x1 && y0 < y1) { - return Err(format!("--window: need x0 < x1 and y0 < y1 (lower-left corner first), got {x0},{y0},{x1},{y1}")); - } - let w = Bounds2 { min: Vec2::new(x0, y0), max: Vec2::new(x1, y1) }; - cadcraft_io::check_window(&w).map_err(|e| format!("--window: {e}"))?; - Ok(w) -} - -/// Parse a framing option (`--window`, `--view`) at `a`, taking its value from `it`. `Ok(false)` -/// means `a` is not a framing option. -fn framing_option<'a>(a: &str, it: &mut impl Iterator, framing: &mut Framing) -> Result { - let f = match a { - "--window" => Framing::Window(parse_window(it.next().ok_or("--window needs x0,y0,x1,y1")?)?), - "--view" => match it.next().map(|v| v.to_ascii_lowercase()).as_deref() { - Some("extents") => Framing::Extents, - Some("current") => Framing::Current, - _ => return Err("--view needs `extents` or `current`".into()), - }, - _ => return Ok(false), - }; - if *framing != Framing::Auto && std::mem::discriminant(framing) != std::mem::discriminant(&f) { - return Err("use only one of --window and --view".into()); - } - *framing = f; - Ok(true) -} - -/// The model-space view of every open drawing, by drawing id (to tell whether commands changed it). -fn model_views(s: &Session) -> Vec<(u64, Option)> { - s.docs.iter().map(|st| (st.uid, st.views.iter().find(|(sp, _)| *sp == Space::Model).map(|(_, v)| *v))).collect() -} - -/// The active drawing's current model-space view as a rectangle with the viewport's aspect ratio -/// (the CLI viewport is 3:2 like the PNG export, so the image shows exactly this view). -fn current_window(s: &Session) -> Option { - let st = s.state().ok()?; - let v = st.views.iter().find(|(sp, _)| *sp == Space::Model).map(|(_, v)| *v)?; - let (w, h) = s.viewport_px; - let half = Vec2::new(v.height * w / h.max(1.0), v.height) * 0.5; - Some(Bounds2::new(v.center - half, v.center + half)) -} - -/// The window an image export shows, or `None` to fit the extents. `before` is [`model_views`] -/// taken before the commands ran (`None` for `convert`, where nothing ran). -fn export_window(s: &Session, framing: Framing, before: Option<&[(u64, Option)]>) -> Result, String> { - match framing { - Framing::Window(w) => Ok(Some(w)), - Framing::Extents => Ok(None), - Framing::Current => current_window(s).map(Some).ok_or_else(|| "--view current: the drawing has no model-space view".into()), - Framing::Auto => { - let Some(before) = before else { return Ok(None) }; - let Ok(st) = s.state() else { return Ok(None) }; - let now = model_views(s); - let was = before.iter().find(|(uid, _)| *uid == st.uid); - let is = now.iter().find(|(uid, _)| *uid == st.uid); - // Only a view the commands changed counts; a drawing opened by the commands keeps - // the extents framing. - match (was, is) { - (Some(a), Some(b)) if a.1 != b.1 => Ok(current_window(s)), - _ => Ok(None), - } - } - } -} - -fn install_io() { - cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks { - read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), - write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), - plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), - }); - cadcraft_engine::cmd::file::set_write_as(|d, name, o| { - cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) - }); - // AutoLISP's entget, entmake and entmod see entities as DXF groups. - cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec { - groups: cadcraft_io::entity_groups, - entity: cadcraft_io::entity_from_groups, - }); -} - -fn open(s: &mut Session, path: &str) -> Result<(), String> { - s.execute("open", &json!({ "path": path })).map(|_| ()).map_err(|e| e.to_string()) -} - -#[derive(Clone, Copy)] -struct OptionSpec { - name: &'static str, - takes_value: bool, -} - -fn validate_options(command: &str, args: &[String], specs: &[OptionSpec]) -> Result<(), String> { - let mut i = 0; - while let Some(arg) = args.get(i) { - if let Some(name) = arg.strip_prefix("--") { - let Some(spec) = specs.iter().find(|spec| spec.name == arg) else { - return Err(format!("{command}: unknown option --{name}")); - }; - if spec.takes_value && args.get(i + 1).is_some_and(|value| !value.starts_with("--")) { - i += 2; - } else { - i += 1; - } - } else { - i += 1; - } - } - Ok(()) -} - -const NO_OPTIONS: &[OptionSpec] = &[]; - -fn info(path: &str) -> Result<(), String> { - let mut s = Session::empty(); - open(&mut s, path)?; - let v = s.execute("drawing.inspect", &json!({ "entities": false })).map_err(|e| e.to_string())?; - outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()); - Ok(()) -} - -/// Write `bytes` to `out` through the engine's atomic writer (an exclusively created sibling file -/// renamed over `out`), so a failed or interrupted write leaves the previous file untouched. -fn write_atomic(out: &str, bytes: &[u8]) -> std::io::Result<()> { - cadcraft_engine::atomic_write::write_atomic(std::path::Path::new(out), bytes) -} - -fn export(s: &Session, out: &str) -> Result<(), String> { - export_framed(s, out, None) -} - -fn export_framed(s: &Session, out: &str, window: Option) -> Result<(), String> { - let d = s.doc().map_err(|e| e.to_string())?; - let bytes = cadcraft_io::write_framed(d, out, window).map_err(|e| e.to_string())?; - write_atomic(out, &bytes).map_err(|e| format!("{out}: {e}"))?; - eprintln!("wrote {out} ({} bytes)", bytes.len()); - if cadcraft_engine::cmd::file::drops_unknown(out) { - let lost = cadcraft_engine::cmd::file::not_saved(d); - if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) { - eprintln!("{m}"); - } - } - Ok(()) -} - -fn sample(args: &[String]) -> Result<(), String> { - let (Some(which), Some(out)) = (args.first(), args.get(1)) else { return Err(USAGE.into()) }; - let d = match which.as_str() { - "bracket" => cadcraft_engine::sample::bracket(), - "floorplan" | "floor" => cadcraft_engine::sample::floor_plan(), - other => return Err(format!("unknown sample `{other}` (bracket, floorplan)")), - }; - let bytes = cadcraft_io::write(&d, out).map_err(|e| e.to_string())?; - write_atomic(out, &bytes).map_err(|e| format!("{out}: {e}"))?; - eprintln!("wrote {out} ({} bytes)", bytes.len()); - Ok(()) -} - -/// Reject an explicit framing option without an image output to apply it to. -fn check_framed_output(framing: Framing, out: Option<&str>) -> Result<(), String> { - match out { - _ if framing == Framing::Auto => Ok(()), - Some(o) if !cadcraft_io::is_image(o) => Err(format!("--window/--view only apply to image output (png, svg, pdf), not `{o}`")), - Some(_) => Ok(()), - None => Err("--window/--view need an image output (--export OUT.png|svg|pdf)".into()), - } -} - -fn convert(args: &[String]) -> Result<(), String> { - let mut framing = Framing::Auto; - let mut files = Vec::new(); - let mut it = args.iter(); - while let Some(a) = it.next() { - if !framing_option(a, &mut it, &mut framing)? { - files.push(a); - } - } - let [i, o] = files.as_slice() else { return Err(USAGE.into()) }; - check_framed_output(framing, Some(o))?; - let mut s = Session::empty(); - open(&mut s, i)?; - if let Some(m) = skipped_message(s.doc().map_err(|e| e.to_string())?, i) { - eprintln!("{m}"); - } - if cadcraft_io::is_image(o) - && let Some(m) = undrawn_message(s.doc().map_err(|e| e.to_string())?, i) - { - eprintln!("{m}"); - } - let window = export_window(&s, framing, None)?; - export_framed(&s, o, window) -} - -/// The warning for the model-space entities of `path` an image can't show, by type (those kept -/// as unknown objects, `Proxy` in `info`), or `None` when there are none. -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 { - 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 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(", "))) -} - -/// The warning for the records of `path` the reader could not place, or `None` when there are none. -fn skipped_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option { - let n = d.skipped_records.values().fold(0usize, |a, n| a.saturating_add(*n)); - if n == 0 { - return None; - } - let list: Vec = d.skipped_records.iter().map(|(section, n)| format!("{section}: {n}")).collect(); - let records = if n == 1 { "record" } else { "records" }; - Some(format!("{path}: {n} {records} could not be read and are left out ({})", list.join(", "))) -} - -/// A `--cmd` parameter value of exactly `{last}` is filled in with the last object handle an -/// earlier `--cmd` in the same run returned: `mview` answers `{"viewports":["100"]}`, so -/// `viewport.set {"handle":"{last}","scale":1}` changes viewport 100. Any other string is passed -/// through unchanged, and `--script` text is never rewritten. -const LAST_HANDLE: &str = "{last}"; - -/// How deep [`result_handles`] walks a command result (results are the engine's own JSON). -const RESULT_DEPTH: usize = 16; - -/// Result keys whose values are object references: the engine's result convention for handles. -/// A handle can be a string (`handle`, `viewport`, `insert`…) or a list of them (`handles`, -/// `viewports`, `members`…). Every other field may hold a user-defined name, a message or a -/// count, and is never read as a handle — a group named `100` is a name, not object `100`. -fn handle_field(key: &str) -> bool { - matches!( - key, - "handle" - | "handles" - | "viewport" - | "viewports" - | "boundary" - | "clip" - | "insert" - | "members" - | "source" - | "objects" - | "entities" - | "selection" - | "parts" - | "refs" - | "matches" - | "line" - | "arc" - | "blocks" - ) -} - -/// Collect the handles of `v`, a value under a handle field: a handle string, an array of them, -/// or objects that carry handle fields of their own (`entities`, `parts`). -fn collect_result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec) { - if depth > RESULT_DEPTH { - return; - } - match v { - Value::String(t) => { - if let Some(h) = Handle::parse_hex(t) - && s.doc().is_ok_and(|d| d.entity(h).is_some()) - { - out.push(h); - } - } - Value::Array(a) => a.iter().for_each(|x| collect_result_handles(s, x, depth + 1, out)), - Value::Object(m) => { - for (k, x) in m { - if handle_field(k) { - collect_result_handles(s, x, depth + 1, out); - } else { - find_result_handles(s, x, depth + 1, out); - } - } - } - _ => {} - } -} - -/// Find handle fields nested in containers that are not handles themselves (`groups` in -/// `groups.list`, whose members are handles): strings here are names, never references. -fn find_result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec) { - if depth > RESULT_DEPTH { - return; - } - match v { - Value::Array(a) => a.iter().for_each(|x| find_result_handles(s, x, depth + 1, out)), - Value::Object(m) => { - for (k, x) in m { - if handle_field(k) { - collect_result_handles(s, x, depth + 1, out); - } else { - find_result_handles(s, x, depth + 1, out); - } - } - } - _ => {} - } -} - -/// The object handles a command result mentions, in the order it lists them. A handle-only result -/// (a handle string or an array of them) counts as it is; otherwise only handle fields do. -fn result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec) { - match v { - Value::String(_) => collect_result_handles(s, v, depth, out), - Value::Array(a) if a.iter().all(Value::is_string) => collect_result_handles(s, v, depth, out), - Value::Array(_) | Value::Object(_) => find_result_handles(s, v, depth, out), - _ => {} - } -} - -/// The last handle `r` returned: what a later `{last}` stands for. -fn returned_handle(s: &Session, r: &Value) -> Option { - let mut hs = Vec::new(); - result_handles(s, r, 0, &mut hs); - hs.last().copied() -} - -/// The active drawing's identity ([`cadcraft_engine::DocState::uid`]): a handle is only meaningful -/// in the drawing it came from, and `new`, `open`, `document.switch` and `close` can make another -/// drawing current. -fn active_drawing(s: &Session) -> Option { - s.docs.get(s.active).map(|st| st.uid) -} - -/// Every `{last}` in `p`, at any depth, replaced by `h`. With no handle to fill in it is an -/// error, never a token reaching the command as a (bad) handle. -fn fill_last(p: &Value, h: Option) -> Result { - match p { - Value::String(t) if t.as_str() == LAST_HANDLE => match h { - Some(h) => Ok(Value::String(h.hex())), - None => Err(format!("`{LAST_HANDLE}` needs an earlier --cmd in this run to have returned a handle")), - }, - Value::Array(a) => a.iter().map(|x| fill_last(x, h)).collect::, _>>().map(Value::Array), - Value::Object(m) => { - m.iter().map(|(k, x)| Ok((k.clone(), fill_last(x, h)?))).collect::, _>>().map(Value::Object) - } - other => Ok(other.clone()), - } -} - -fn run(args: &[String]) -> Result<(), String> { - let mut s = Session::empty(); - let mut it = args.iter(); - let mut save = None; - let mut exp: Option = None; - let mut framing = Framing::Auto; - let mut steps: Vec<(String, String)> = Vec::new(); - while let Some(a) = it.next() { - if framing_option(a, &mut it, &mut framing)? { - continue; - } - match a.as_str() { - "--sample" => { - s.open_drawing(cadcraft_engine::sample::default_sample(), "Bracket", None); - } - "--metric" => { - s.new_drawing(true); - } - "--script" => steps.push(("script".into(), it.next().ok_or("--script needs text")?.replace("\\n", "\n"))), - "--script-file" => { - let p = it.next().ok_or("--script-file needs a path")?; - steps.push(("script".into(), std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?)); - } - "--cmd" => steps.push(("cmd".into(), it.next().ok_or("--cmd needs `id {json}`")?.clone())), - "--save" => save = Some(it.next().ok_or("--save needs a path")?.clone()), - "--export" => exp = Some(it.next().ok_or("--export needs a path")?.clone()), - f if !f.starts_with("--") => open(&mut s, f)?, - other => return Err(format!("unknown option {other}")), - } - } - if s.docs.is_empty() { - s.new_drawing(false); - } - check_framed_output(framing, exp.as_deref())?; - let before = model_views(&s); - let mut last_handle: Option = None; - for (kind, body) in steps { - // A handle belongs to the drawing that returned it: if this step makes another drawing - // current (`new`, `open`, `document.switch`, `close`, or a script running one of them), - // the remembered handle is stale. A handle the step itself returns is taken afterwards, - // so it is a handle of the drawing it made current. - let drawing = active_drawing(&s); - match kind.as_str() { - "script" => { - s.script(&body).map_err(|e| e.to_string())?; - if active_drawing(&s) != drawing { - last_handle = None; - } - } - _ => { - let (id, json) = body.split_once(' ').unwrap_or((&body, "{}")); - let params: Value = serde_json::from_str(json).map_err(|e| format!("--cmd {id}: {e}"))?; - let params = fill_last(¶ms, last_handle).map_err(|e| format!("--cmd {id}: {e}"))?; - let r = s.execute(id, ¶ms).map_err(|e| e.to_string())?; - if active_drawing(&s) != drawing { - last_handle = None; - } - if let Some(h) = returned_handle(&s, &r) { - last_handle = Some(h); - } - if !r.is_null() { - outln!("{r}"); - } - } - } - } - for l in &s.log { - eprintln!("{l}"); - } - if let Some(p) = save { - export(&s, &p)?; - } - if let Some(p) = exp { - let window = if cadcraft_io::is_image(&p) { export_window(&s, framing, Some(&before))? } else { None }; - export_framed(&s, &p, window)?; - } - Ok(()) -} - -/// Small deterministic generator (xorshift64*) so perf runs are repeatable without a dependency. -struct Rng(u64); - -impl Rng { - fn next(&mut self) -> f64 { - self.0 ^= self.0 >> 12; - self.0 ^= self.0 << 25; - self.0 ^= self.0 >> 27; - (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64 - } - fn range(&mut self, lo: f64, hi: f64) -> f64 { - lo + (hi - lo) * self.next() - } -} - -/// A synthetic drawing with `n` mixed entities (lines, circles, arcs, polylines, text) spread -/// over a square whose side grows with sqrt(n), so density stays constant. -fn synthetic(n: usize, side: f64) -> Result { - use cadcraft_engine::doc::{self as d, Common, EntityKind, Space}; - use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3}; - let mut dr = d::Drawing::new_imperial(); - let mut r = Rng(0x9E37_79B9_7F4A_7C15); - let v3 = |x: f64, y: f64| Vec3::new(x, y, 0.0); - for i in 0..n { - let (x, y) = (r.range(0.0, side), r.range(0.0, side)); - let s = r.range(0.5, 8.0); - let kind = match i % 5 { - 0 => EntityKind::Line(d::Line { a: v3(x, y), b: v3(x + r.range(-s, s), y + r.range(-s, s)) }), - 1 => EntityKind::Circle(d::Circle { center: v3(x, y), radius: s * 0.5 }), - 2 => EntityKind::Arc(d::Arc { center: v3(x, y), radius: s * 0.5, start: r.range(0.0, 3.0), end: r.range(3.2, 6.2) }), - 3 => EntityKind::LwPolyline(d::LwPolyline { - vertices: (0..6) - .map(|k| PolyVertex { - p: Vec2::new(x + f64::from(k) * s * 0.3, y + r.range(-s, s) * 0.3), - bulge: if k == 2 { 0.4 } else { 0.0 }, - start_width: 0.0, - end_width: 0.0, - }) - .collect(), - closed: i % 2 == 0, - const_width: 0.0, - elevation: 0.0, - plinegen: false, - }), - _ => EntityKind::Text(d::Text { - insert: v3(x, y), - align_pt: None, - height: s * 0.2, - value: format!("T{i}"), - rotation: 0.0, - width_factor: 1.0, - oblique: 0.0, - style: "Standard".into(), - halign: d::HAlign::Left, - valign: d::VAlign::Baseline, - }), - }; - dr.add(&Space::Model, Common::default(), kind).map_err(|e| e.to_string())?; - } - Ok(dr) -} - -/// `perf FILE`: the display list built as the canvas builds it (a 1600 x 1000 px view at the -/// drawing's centre: tolerance, dash level of detail and view window from the zoom band), at -/// zoom extents and zoomed in 4x at a time, next to the full-detail build plots use. -fn perf_file(path: &str) -> Result<(), String> { - use cadcraft_engine::geom::{Bounds2, Vec2}; - use cadcraft_engine::render::{Options, build}; - use std::time::Instant; - let ms = |t: Instant| t.elapsed().as_secs_f64() * 1000.0; - let mut s = Session::empty(); - let t = Instant::now(); - open(&mut s, path)?; - let open_ms = ms(t); - let st = s.state().map_err(|e| e.to_string())?; - let (d, space) = (&st.doc, &st.space); - let ext = d.extents(space); - let size = ext.width().max(ext.height()); - if ext.is_empty() || !(size.is_finite() && size > 0.0) { - return Err("perf: the drawing is empty".into()); - } - outln!("open {open_ms:.0} ms, {} entities, extents {:.1} x {:.1}", d.entity_count(), ext.width(), ext.height()); - outln!("{:>8} {:>10} {:>10}", "zoom", "build ms", "prims"); - let mut finest = Options::default(); - for k in 0..5 { - let zoom = 4f64.powi(k); - let h = size / zoom; - let pixel = 2f64.powi((h / 1000.0).max(1e-300).log2().floor() as i32); - let half = Vec2::new(h * 0.8, h * 0.5); - let visible = Bounds2::new(ext.center() - half, ext.center() + half); - let screen = Options { tolerance: pixel * 0.5, min_dash: pixel * 2.0, view: Some(visible.expand(h * 0.8)), ..Default::default() }; - let t = Instant::now(); - let n = build(d, space, &screen).prims.len(); - outln!("{:>7}x {:>10.1} {n:>10}", zoom, ms(t)); - finest = screen; - } - // Plots: every pattern line, everywhere (last, so its large list doesn't weigh on the above). - let t = Instant::now(); - let n = build(d, space, &Options { min_dash: 0.0, view: None, ..finest }).prims.len(); - outln!("{:>8} {:>10.1} {n:>10}", "full", ms(t)); - Ok(()) -} - -fn perf(args: &[String]) -> Result<(), String> { - use cadcraft_engine::doc::Space; - use cadcraft_engine::geom::{Bounds2, Vec2}; - use cadcraft_engine::{select, snap}; - use std::time::Instant; - if let Some(path) = args.first().filter(|a| a.parse::().is_err()) { - return perf_file(path); - } - let n: usize = match args.first() { - Some(a) => a.parse().map_err(|_| format!("perf: bad entity count {a}"))?, - None => 200_000, - }; - let n = n.clamp(1, 20_000_000); - let side = (n as f64).sqrt() * 10.0; - let mut rows: Vec<(String, f64, String)> = Vec::new(); - let ms = |t: Instant| t.elapsed().as_secs_f64() * 1000.0; - - let t = Instant::now(); - let d = synthetic(n, side)?; - rows.push(("build synthetic drawing".into(), ms(t), format!("{n} entities"))); - - // Display list at a 1600 px wide "zoom extents" view (tolerance = half a pixel). - let px = side / 1600.0; - let opts = cadcraft_engine::render::Options { tolerance: px * 0.5, min_dash: px * 2.0, ..Default::default() }; - let t = Instant::now(); - let list = cadcraft_engine::render::build(&d, &Space::Model, &opts); - rows.push(("display list build".into(), ms(t), format!("{} prims, {} segments", list.prims.len(), list.segment_count()))); - - // Hit testing on a zoomed-in view (aperture = 5 px at 0.02 units/px). - let ap = 0.1; - let mut r = Rng(42); - let pts: Vec = (0..1000).map(|_| Vec2::new(r.range(0.0, side), r.range(0.0, side))).collect(); - let t = Instant::now(); - let first = select::pick(&d, &Space::Model, pts.first().copied().unwrap_or(Vec2::ZERO), ap); - rows.push(("first pick (incl. index build)".into(), ms(t), format!("{first:?}"))); - let t = Instant::now(); - let hits = pts.iter().filter(|p| select::pick(&d, &Space::Model, **p, ap).is_some()).count(); - let total = ms(t); - rows.push(("pick x1000".into(), total, format!("{hits} hits, {:.3} ms/pick", total / 1000.0))); - - // One edit, then a pick: only the touched chunk is re-indexed. - let mut edited = d.clone(); - if let Some(h) = edited.model.last().map(|e| e.handle) { - edited.model.modify(h, |e| e.common.layer = "0".into()); - } - let t = Instant::now(); - let _ = select::pick(&edited, &Space::Model, pts.first().copied().unwrap_or(Vec2::ZERO), ap); - rows.push(("pick after one edit (incremental re-index)".into(), ms(t), String::new())); - - let mut sel = 0usize; - let t = Instant::now(); - for k in 0..20 { - let c = Vec2::new(r.range(0.0, side), r.range(0.0, side)); - let half = side * 0.05; - sel += select::select_window(&d, &Space::Model, Bounds2::new(c - Vec2::new(half, half), c + Vec2::new(half, half)), k % 2 == 1).len(); - } - rows.push(("window/crossing select x20 (10% side)".into(), ms(t), format!("{sel} selected"))); - - let t = Instant::now(); - let fence: Vec = (0..4).map(|_| Vec2::new(r.range(0.0, side), r.range(0.0, side))).collect(); - let fsel = select::select_fence(&d, &Space::Model, &fence).len(); - rows.push(("fence select (3 legs)".into(), ms(t), format!("{fsel} selected"))); - - let osmode = snap::mode::END | snap::mode::MID | snap::mode::CEN | snap::mode::QUA | snap::mode::INT; - let t = Instant::now(); - let snaps = pts.iter().filter(|p| snap::osnap(&d, &Space::Model, **p, ap * 2.0, osmode, None, false).is_some()).count(); - let total = ms(t); - rows.push(("osnap x1000".into(), total, format!("{snaps} hits, {:.3} ms/query", total / 1000.0))); - - let t = Instant::now(); - let bytes = cadcraft_io::write(&d, "perf.dxf").map_err(|e| e.to_string())?; - rows.push(("DXF write".into(), ms(t), format!("{:.1} MB", bytes.len() as f64 / 1e6))); - let t = Instant::now(); - let back = cadcraft_io::read(&bytes, "perf.dxf").map_err(|e| e.to_string())?; - rows.push(("DXF read".into(), ms(t), format!("{} entities", back.entity_count()))); - - outln!("{:<40} {:>12} notes", "operation", "ms"); - outln!("{}", "-".repeat(80)); - for (name, t, note) in rows { - outln!("{name:<40} {t:>12.2} {note}"); - } - Ok(()) -} - -/// The backend `cadcraft-cli mcp` serves from. -#[derive(Debug, PartialEq, Eq)] -enum McpTarget { - /// An in-process drawing session (no `--connect`). - Headless, - /// 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 }, -} - -/// Parses the arguments after `mcp`. `--connect` must be followed by a `HOST:PORT`; a missing, -/// empty or flag-like value is an error, never a silent fall back to a headless session (#103). -fn parse_mcp_args(args: &[String]) -> Result { - let mut addr: Option = None; - let (mut lazy, mut launch) = (false, false); - let mut it = args.iter(); - while let Some(a) = it.next() { - match a.as_str() { - "--connect" => { - let a = it - .next() - .map(|v| v.trim()) - .filter(|v| !v.is_empty() && !v.starts_with('-')) - .ok_or("--connect needs HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)")?; - if addr.is_some() { - return Err("--connect given more than once".into()); - } - addr = Some(a.to_string()); - } - "--lazy" => lazy = true, - "--launch" => launch = true, - other => return Err(format!("mcp: unknown argument {other}\n{USAGE}")), - } - } - match addr { - // `--launch` connects at the first call too (the app opens then). - Some(addr) => Ok(McpTarget::Connect { addr, lazy: lazy || launch, launch }), - None if lazy || launch => Err("--lazy and --launch need --connect HOST:PORT".into()), - None => Ok(McpTarget::Headless), - } -} - -fn mcp(args: &[String]) -> Result<(), String> { - let backend: Box = match parse_mcp_args(args)? { - McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)), - McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) { - Ok(r) => Box::new(r), - Err(e) => return Err(format!("cadcraft-cli: cannot connect to {addr}: {e}")), - }, - McpTarget::Headless => Box::new(cadcraft_mcp::Headless::default()), - }; - let stdin = std::io::stdin(); - let stdout = std::io::stdout(); - cadcraft_mcp::Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string()) -} - -#[cfg(test)] -mod mcp_args_tests { - use super::*; - - fn args(a: &[&str]) -> Vec { - a.iter().map(|s| s.to_string()).collect() - } - - #[test] - fn mcp_without_connect_is_headless() { - assert_eq!(parse_mcp_args(&args(&[])), Ok(McpTarget::Headless)); - } - - #[test] - fn mcp_connect_with_address_selects_remote() { - let to = |addr: &str, lazy, launch| Ok(McpTarget::Connect { addr: addr.into(), lazy, launch }); - assert_eq!(parse_mcp_args(&args(&["--connect", "127.0.0.1:7979"])), to("127.0.0.1:7979", false, false)); - assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979"])), to("localhost:7979", false, false)); - assert_eq!(parse_mcp_args(&args(&["--lazy", "--connect", "localhost:7979"])), to("localhost:7979", true, false)); - assert_eq!(parse_mcp_args(&args(&["--connect", "localhost:7979", "--launch"])), to("localhost:7979", true, true)); - // Without an app to reach they mean nothing: never a headless session. - assert!(parse_mcp_args(&args(&["--lazy"])).is_err()); - assert!(parse_mcp_args(&args(&["--launch"])).is_err()); - } - - #[test] - fn mcp_connect_without_address_is_an_error_not_headless() { - for bad in [&["--connect"][..], &["--connect", ""], &["--connect", " "], &["--connect", "--foo"], &["--connect", "-v"]] { - let r = parse_mcp_args(&args(bad)); - let Err(e) = r else { panic!("{bad:?} should be rejected, got {r:?}") }; - assert!(e.contains("--connect needs HOST:PORT"), "{bad:?}: {e}"); - } - } - - #[test] - fn mcp_rejects_unknown_and_repeated_arguments() { - assert!(parse_mcp_args(&args(&["--conect", "127.0.0.1:7979"])).is_err()); - assert!(parse_mcp_args(&args(&["127.0.0.1:7979"])).is_err()); - assert!(parse_mcp_args(&args(&["--connect", "127.0.0.1:1", "--connect", "127.0.0.1:2"])).is_err()); - } -} - -fn main() -> ExitCode { - let code = cli(); - if STDOUT_ERROR.load(Ordering::Relaxed) { ExitCode::FAILURE } else { code } -} - -fn cli() -> ExitCode { - install_io(); - let args: Vec = std::env::args().skip(1).collect(); - let rest: Vec = args.iter().skip(1).cloned().collect(); - let r = match args.first().map(String::as_str) { - Some("info") => validate_options("info", &rest, NO_OPTIONS).and_then(|_| rest.first().ok_or_else(|| USAGE.to_string())).and_then(|p| info(p)), - Some("convert") => convert(&rest), - Some("run") => run(&rest), - Some("perf") => validate_options("perf", &rest, NO_OPTIONS).and_then(|_| perf(&rest)), - Some("sample") => validate_options("sample", &rest, NO_OPTIONS).and_then(|_| sample(&rest)), - Some("commands") => validate_options("commands", &rest, NO_OPTIONS).map(|_| { - let s = Session::new(); - let f = rest.first().map(|x| x.to_ascii_lowercase()); - let v: Vec = cadcraft_engine::command_specs() - .iter() - .filter(|c| f.as_ref().is_none_or(|f| c.id.contains(f.as_str()) || c.label.to_ascii_lowercase().contains(f.as_str()))) - .map(|c| serde_json::to_value(c.info(&s)).unwrap_or_default()) - .collect(); - outln!("{}", serde_json::to_string_pretty(&v).unwrap_or_default()); - }), - Some("mcp") => mcp(&rest), - Some("--version" | "-V") => { - outln!("cadcraft-cli {}", env!("CARGO_PKG_VERSION")); - Ok(()) - } - Some("--help" | "-h" | "help") => { - outln!("{USAGE}"); - Ok(()) - } - _ => Err(USAGE.into()), - }; - match r { - Ok(()) => ExitCode::SUCCESS, - Err(e) => { - eprintln!("{e}"); - ExitCode::FAILURE - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn scratch_dir(tag: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("cadcraft-cli-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("create scratch dir"); - dir - } - - #[test] - fn write_atomic_replaces_file_and_leaves_no_staging_files() { - let dir = scratch_dir("replace"); - let out = dir.join("a.dxf"); - let out = out.to_str().expect("utf-8 path"); - write_atomic(out, b"old").expect("create"); - write_atomic(out, b"new").expect("overwrite"); - assert_eq!(std::fs::read(out).expect("read"), b"new"); - assert_eq!(std::fs::read_dir(&dir).expect("list").count(), 1); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn write_atomic_failure_keeps_destination_and_cleans_up() { - let dir = scratch_dir("fail"); - let out = dir.join("target"); - std::fs::create_dir(&out).expect("dir as destination"); - std::fs::write(out.join("keep"), b"x").expect("seed"); - assert!(write_atomic(out.to_str().expect("utf-8 path"), b"new").is_err()); - assert_eq!(std::fs::read(out.join("keep")).expect("kept"), b"x"); - assert_eq!(std::fs::read_dir(&dir).expect("list").count(), 1); - let _ = std::fs::remove_dir_all(&dir); - } - - fn b(x0: f64, y0: f64, x1: f64, y1: f64) -> Bounds2 { - Bounds2::new(Vec2::new(x0, y0), Vec2::new(x1, y1)) - } - - fn sample_session() -> Session { - let mut s = Session::empty(); - s.open_drawing(cadcraft_engine::sample::default_sample(), "Bracket", None); - s - } - - fn view_box(svg: &str) -> String { - let i = svg.find("viewBox=\"").map(|i| i + 9).unwrap_or(0); - svg[i..].split('"').next().unwrap_or("").to_string() - } - - fn assert_near(a: Bounds2, e: Bounds2) { - let d = (a.min - e.min).len().max((a.max - e.max).len()); - assert!(d < 1e-9, "{a:?} != {e:?}"); - } - - #[test] - fn window_parses() { - assert_eq!(parse_window("0,0,30,20"), Ok(b(0.0, 0.0, 30.0, 20.0))); - assert_eq!(parse_window(" -5.5, -1e3 ,2e3,4 "), Ok(b(-5.5, -1000.0, 2000.0, 4.0))); - } - - #[test] - fn hostile_window_is_an_error() { - for w in [ - "", - "1,2,3", - "1,2,3,4,5", - "a,0,1,1", - "NaN,0,1,1", - "0,0,inf,1", - "0,0,1e400,1", - "0,0,0,1", - "0,0,1,0", - "5,0,1,1", - "0,5,1,1", - "-1e300,-1e300,1e300,1e300", - "0,0,1e-12,1e-12", - ] { - assert!(parse_window(w).is_err(), "`{w}` should be rejected"); - } - } - - #[test] - fn framing_options() { - let parse = |args: &[&str]| -> Result { - let args: Vec = args.iter().map(|a| a.to_string()).collect(); - let mut f = Framing::Auto; - let mut it = args.iter(); - while let Some(a) = it.next() { - assert!(framing_option(a, &mut it, &mut f)?, "{a} is a framing option"); - } - Ok(f) - }; - assert_eq!(parse(&["--view", "extents"]), Ok(Framing::Extents)); - assert_eq!(parse(&["--view", "CURRENT"]), Ok(Framing::Current)); - assert_eq!(parse(&["--window", "0,0,2,1"]), Ok(Framing::Window(b(0.0, 0.0, 2.0, 1.0)))); - assert!(parse(&["--view"]).is_err()); - assert!(parse(&["--view", "selection"]).is_err()); - assert!(parse(&["--window"]).is_err()); - assert!(parse(&["--window", "0,0,2,1", "--view", "extents"]).is_err()); - assert!(check_framed_output(Framing::Extents, Some("a.dxf")).is_err()); - assert!(check_framed_output(Framing::Extents, None).is_err()); - assert!(check_framed_output(Framing::Extents, Some("a.png")).is_ok()); - assert!(check_framed_output(Framing::Auto, Some("a.dxf")).is_ok()); - } - - #[test] - fn last_placeholder_takes_the_previous_handle() { - let mut s = sample_session(); - let r = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); - let h = returned_handle(&s, &r).expect("LINE returns its handle"); - assert_eq!(fill_last(&json!({"handle": "{last}"}), Some(h)), Ok(json!({"handle": h.hex()}))); - // Nested, as in a selection list. - assert_eq!(fill_last(&json!({"handles": ["{last}", "1"]}), Some(h)), Ok(json!({"handles": [h.hex(), "1"]}))); - // Only the exact token: a name or a sentence that merely contains it stays as written. - for p in [json!("last"), json!("{last} "), json!({"name": "last"})] { - assert_eq!(fill_last(&p, Some(h)), Ok(p.clone())); - } - // Nothing returned yet: an error, not a token passed to the command as a bad handle. - assert!(fill_last(&json!({"handle": "{last}"}), None).unwrap_err().contains("{last}")); - } - - /// Handles are read from a result by looking the strings up in the drawing: counts and names - /// are not mistaken for handles, and `mview`'s `viewports` works like `handle`/`handles`. - #[test] - fn returned_handle_reads_only_real_handles() { - let mut s = Session::empty(); - s.new_drawing(false); - s.execute("layout.set", &json!({"name": "Layout1"})).unwrap(); - let r = s.execute("mview", &json!({"p1": [20, 20], "p2": [200, 150]})).unwrap(); - let h = returned_handle(&s, &r).expect("mview returns its viewport handle"); - assert!(r["viewports"].as_array().is_some_and(|a| a.iter().any(|v| v.as_str() == Some(h.hex().as_str()))), "{r}"); - assert_eq!(returned_handle(&s, &json!({"changed": 3, "name": "A1"})), None); - // The most recent of several. - let a = s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap(); - let b = s.execute("line", &json!({"points": [[0, 0], [2, 0]]})).unwrap(); - let (ha, hb) = (returned_handle(&s, &a).unwrap(), returned_handle(&s, &b).unwrap()); - assert_eq!(returned_handle(&s, &json!({"handles": [ha.hex(), hb.hex()]})), Some(hb)); - } - - #[test] - fn default_framing_is_extents() { - // convert: nothing ran, always the extents. - let s = sample_session(); - assert_eq!(export_window(&s, Framing::Auto, None), Ok(None)); - // run: commands that leave the view alone keep the extents framing. - let mut s = sample_session(); - let before = model_views(&s); - s.script("LINE 0,0 10,10\n\n").unwrap(); - assert_eq!(export_window(&s, Framing::Auto, Some(&before)), Ok(None)); - // A fresh drawing too. - let mut s = Session::empty(); - s.new_drawing(false); - let before = model_views(&s); - s.execute("circle", &json!({"center": [0, 0], "radius": 5})).unwrap(); - assert_eq!(export_window(&s, Framing::Auto, Some(&before)), Ok(None)); - } - - #[test] - fn zoom_window_frames_export() { - let mut s = sample_session(); - let before = model_views(&s); - s.execute("zoom", &json!({"mode": "window", "p1": [0, 0], "p2": [30, 20]})).unwrap(); - let w = export_window(&s, Framing::Auto, Some(&before)).unwrap().unwrap(); - // The CLI viewport is 3:2, so a 3:2 window is shown exactly. - assert_near(w, b(0.0, 0.0, 30.0, 20.0)); - assert_eq!(export_window(&s, Framing::Current, Some(&before)), Ok(Some(w))); - // --view extents and --window override the zoom. - assert_eq!(export_window(&s, Framing::Extents, Some(&before)), Ok(None)); - let explicit = b(1.0, 1.0, 2.0, 2.0); - assert_eq!(export_window(&s, Framing::Window(explicit), Some(&before)), Ok(Some(explicit))); - // A taller window keeps its height; the 3:2 image adds room left and right. - s.execute("zoom", &json!({"mode": "center", "center": [5, 5], "height": 4})).unwrap(); - assert_near(export_window(&s, Framing::Auto, Some(&before)).unwrap().unwrap(), b(2.0, 3.0, 8.0, 7.0)); - } - - #[test] - fn zoom_object_frames_the_selection() { - let mut s = sample_session(); - let before = model_views(&s); - // The smallest entity with an area, selected then framed with ZOOM Object. - let d = s.doc().unwrap(); - let bounds = |e: &cadcraft_engine::doc::Entity| cadcraft_engine::doc::entity_bounds(d, e, 0); - let e = d - .model - .iter() - .filter(|e| bounds(e).width() > 0.0 && bounds(e).height() > 0.0) - .min_by(|a, b| bounds(a).width().total_cmp(&bounds(b).width())) - .unwrap(); - let (h, eb, ext) = (e.handle, bounds(e), d.extents(&Space::Model)); - s.set_selection(vec![h]); - s.execute("zoom", &json!({"mode": "object"})).unwrap(); - let w = export_window(&s, Framing::Auto, Some(&before)).unwrap().unwrap(); - assert!(w.contains(eb.min) && w.contains(eb.max)); - assert!(w.width() < ext.width() && w.height() < ext.height(), "{w:?} vs extents {ext:?}"); - } - - #[test] - fn run_export_honours_zoom() { - let dir = std::env::temp_dir().join(format!("cadcraft-cli-165-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = |n: &str| dir.join(n).to_string_lossy().to_string(); - let run_svg = |extra: &[&str], out: &str| -> String { - let mut args: Vec = ["--sample"].iter().chain(extra).map(|a| a.to_string()).collect(); - args.extend(["--export".to_string(), path(out)]); - run(&args).unwrap(); - std::fs::read_to_string(path(out)).unwrap() - }; - let base = run_svg(&[], "base.svg"); - let zoomed = run_svg(&["--cmd", r#"zoom {"mode":"window","p1":[0,0],"p2":[30,20]}"#], "zoom.svg"); - let window = run_svg(&["--window", "0,0,30,20"], "window.svg"); - let forced = run_svg(&["--cmd", r#"zoom {"mode":"window","p1":[0,0],"p2":[30,20]}"#, "--view", "extents"], "forced.svg"); - assert_ne!(view_box(&zoomed), view_box(&base)); - assert_eq!(view_box(&zoomed), "0 0 30.000000 20.000000"); - assert_eq!(zoomed, window); - assert_eq!(forced, base); - // Hostile --window: a clear error, nothing written. - let bad: Vec = ["--sample", "--window", "0,0,NaN,1", "--export", &path("bad.png")].iter().map(|a| a.to_string()).collect(); - assert!(run(&bad).unwrap_err().contains("--window")); - assert!(!dir.join("bad.png").exists()); - let _ = std::fs::remove_dir_all(&dir); - } - - fn args(values: &[&str]) -> Vec { - values.iter().map(|value| (*value).into()).collect() - } - - #[test] - fn validators_accept_only_the_documented_options() { - assert!(validate_options("info", &args(&["file.dxf"]), NO_OPTIONS).is_ok()); - assert!(validate_options("perf", &args(&["100"]), NO_OPTIONS).is_ok()); - assert!(validate_options("sample", &args(&["bracket", "out.dxf"]), NO_OPTIONS).is_ok()); - assert!(validate_options("commands", &args(&["line"]), NO_OPTIONS).is_ok()); - for (command, specs) in [("info", NO_OPTIONS), ("perf", NO_OPTIONS), ("sample", NO_OPTIONS), ("commands", NO_OPTIONS)] { - assert!(validate_options(command, &args(&["--typo"]), specs).is_err()); - } - } - - #[test] - fn unknown_options_are_rejected_before_side_effects() { - assert_eq!(validate_options("info", &args(&["missing.dxf", "--typo"]), NO_OPTIONS), Err("info: unknown option --typo".into())); - assert_eq!(validate_options("perf", &args(&["1", "--typo"]), NO_OPTIONS), Err("perf: unknown option --typo".into())); - assert_eq!(validate_options("sample", &args(&["bracket", "out.dxf", "--typo"]), NO_OPTIONS), Err("sample: unknown option --typo".into())); - } +fn main() { + // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must be + // reported as an error, not panic before anything is printed. + let code = cadcraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); + std::process::exit(code); } diff --git a/apps/cadcraft-cli/src/mcp.rs b/apps/cadcraft-cli/src/mcp.rs new file mode 100644 index 000000000..960c80a5e --- /dev/null +++ b/apps/cadcraft-cli/src/mcp.rs @@ -0,0 +1,17 @@ +use super::args::{McpArgs, McpTarget}; +use super::error::{CliError, Result}; + +pub(crate) fn mcp(a: &McpArgs) -> Result { + let backend: Box = match a.target() { + McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)), + McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) { + Ok(r) => Box::new(r), + Err(source) => return Err(CliError::McpConnect { addr, source }), + }, + McpTarget::Headless => Box::new(cadcraft_mcp::Headless::default()), + }; + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + cadcraft_mcp::Server::new(backend).serve(stdin.lock(), stdout.lock())?; + Ok(()) +} diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs new file mode 100644 index 000000000..d783267dc --- /dev/null +++ b/apps/cadcraft-cli/src/output.rs @@ -0,0 +1,177 @@ +use super::args::Framing; +use super::error::Result; +use cadcraft_engine::doc::Space; +use cadcraft_engine::geom::{Bounds2, Vec2}; +use cadcraft_engine::{Session, View}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// The process's output streams. A write to stdout that fails never stops the program: once +/// stdout has failed, later output is dropped and the work goes on, so the rest of `run` (later +/// `--cmd` results, `--save`, `--export`) still happens and `cadcraft-cli run … --save out.dxf | +/// head` keeps the drawing. A reader that stopped early (a closed pipe, `cadcraft-cli commands | +/// head`) is not an error, as in ripgrep; any other write error is reported once on stderr and +/// makes the exit status 1. +pub(crate) struct Streams<'a> { + out: &'a mut dyn Write, + err: &'a mut dyn Write, + /// Set once a write to `out` has failed; later output is dropped. + gone: bool, + /// Set when `out` failed for a reason other than a closed reader. + failed: bool, +} + +impl<'a> Streams<'a> { + pub(crate) fn new(out: &'a mut dyn Write, err: &'a mut dyn Write) -> Self { + Streams { out, err, gone: false, failed: false } + } + + /// Write a line to stdout. + pub(crate) fn outln(&mut self, args: std::fmt::Arguments) { + if !self.gone + && let Err(e) = writeln!(self.out, "{args}") + { + self.out_failed(e); + } + } + + /// Write `v` to stdout: pretty-printed, or on one line with `compact` (`--compact`). + pub(crate) fn json(&mut self, v: &serde_json::Value, compact: bool) { + if compact { + self.outln(format_args!("{v}")); + } else { + self.outln(format_args!("{v:#}")); + } + } + + /// Write a line to stderr. A failing stderr has nowhere to report to, so it is ignored. + pub(crate) fn errln(&mut self, args: std::fmt::Arguments) { + let _ = writeln!(self.err, "{args}"); + } + + /// Flush stdout (a pipe that closed during buffered output surfaces here). + pub(crate) fn finish(&mut self) { + if !self.gone + && let Err(e) = self.out.flush() + { + self.out_failed(e); + } + } + + /// Whether stdout failed for a reason other than a closed reader: the exit status is 1. + pub(crate) fn stdout_failed(&self) -> bool { + self.failed + } + + fn out_failed(&mut self, e: std::io::Error) { + if std::mem::replace(&mut self.gone, true) || e.kind() == std::io::ErrorKind::BrokenPipe { + return; + } + self.errln(format_args!("cadcraft-cli: can't write to stdout: {e}")); + self.failed = true; + } +} + +/// Why writing or framing an output failed. +#[derive(Debug, thiserror::Error)] +pub(crate) enum OutputError { + #[error("--view current: the drawing has no model-space view")] + NoModelView, + #[error("{}: {source}", path.display())] + Write { path: PathBuf, source: std::io::Error }, +} + +/// The model-space view of every open drawing, by drawing id (to tell whether commands changed it). +pub(crate) fn model_views(s: &Session) -> Vec<(u64, Option)> { + s.docs.iter().map(|st| (st.uid, st.views.iter().find(|(sp, _)| *sp == Space::Model).map(|(_, v)| *v))).collect() +} + +/// The active drawing's current model-space view as a rectangle with the viewport's aspect ratio +/// (the CLI viewport is 3:2 like the PNG export, so the image shows exactly this view). +fn current_window(s: &Session) -> Option { + let st = s.state().ok()?; + let v = st.views.iter().find(|(sp, _)| *sp == Space::Model).map(|(_, v)| *v)?; + let (w, h) = s.viewport_px; + let half = Vec2::new(v.height * w / h.max(1.0), v.height) * 0.5; + Some(Bounds2::new(v.center - half, v.center + half)) +} + +/// The window an image export shows, or `None` to fit the extents. `before` is [`model_views`] +/// taken before the commands ran (`None` for `convert`, where nothing ran). +pub(crate) fn export_window(s: &Session, framing: Framing, before: Option<&[(u64, Option)]>) -> Result, OutputError> { + match framing { + Framing::Window(w) => Ok(Some(w)), + Framing::Extents => Ok(None), + Framing::Current => current_window(s).map(Some).ok_or(OutputError::NoModelView), + Framing::Auto => { + let Some(before) = before else { return Ok(None) }; + let Ok(st) = s.state() else { return Ok(None) }; + let now = model_views(s); + let was = before.iter().find(|(uid, _)| *uid == st.uid); + let is = now.iter().find(|(uid, _)| *uid == st.uid); + // Only a view the commands changed counts; a drawing opened by the commands keeps + // the extents framing. + match (was, is) { + (Some(a), Some(b)) if a.1 != b.1 => Ok(current_window(s)), + _ => Ok(None), + } + } + } +} + +/// Write `bytes` to `out` through the engine's atomic writer (an exclusively created sibling file +/// renamed over `out`), so a failed or interrupted write leaves the previous file untouched. An +/// existing `out` is resolved first: the rename would otherwise replace a symlink with a file and +/// leave the file it points to (`--in-place` through a link) unchanged. +pub(crate) fn write_atomic(out: &Path, bytes: &[u8]) -> Result<(), OutputError> { + let target = std::fs::canonicalize(out).unwrap_or_else(|_| out.to_path_buf()); + cadcraft_engine::atomic_write::write_atomic(&target, bytes).map_err(|source| OutputError::Write { path: out.to_path_buf(), source }) +} + +pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result { + export_framed(s, out, None, io) +} + +pub(crate) fn export_framed(s: &Session, out: &Path, window: Option, io: &mut Streams) -> Result { + let d = s.doc()?; + let bytes = cadcraft_io::write_framed(d, out, window)?; + write_atomic(out, &bytes)?; + io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len())); + if cadcraft_engine::cmd::file::drops_unknown(out) { + let lost = cadcraft_engine::cmd::file::not_saved(d); + if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) { + io.errln(format_args!("{m}")); + } + } + Ok(()) +} + +/// The warning for the model-space entities of `path` an image can't show, by type (those kept +/// 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(); + for e in d.model.iter() { + if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind { + 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 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(", "))) +} + +/// The warning for the records of `path` the reader could not place, or `None` when there are none. +pub(crate) fn skipped_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option { + let n = d.skipped_records.values().fold(0usize, |a, n| a.saturating_add(*n)); + if n == 0 { + return None; + } + let list: Vec = d.skipped_records.iter().map(|(section, n)| format!("{section}: {n}")).collect(); + let records = if n == 1 { "record" } else { "records" }; + Some(format!("{path}: {n} {records} could not be read and are left out ({})", list.join(", "))) +} diff --git a/apps/cadcraft-cli/src/perf.rs b/apps/cadcraft-cli/src/perf.rs new file mode 100644 index 000000000..e52b6107b --- /dev/null +++ b/apps/cadcraft-cli/src/perf.rs @@ -0,0 +1,196 @@ +use super::args::PerfTarget; +use super::error::Result; +use super::open; +use super::output::Streams; +use cadcraft_engine::Session; + +/// Why `perf` cannot run. +#[derive(Debug, thiserror::Error)] +pub(crate) enum PerfError { + #[error("perf: the drawing is empty")] + EmptyDrawing, +} + +/// Small deterministic generator (xorshift64*) so perf runs are repeatable without a dependency. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> f64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + (self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64 + } + fn range(&mut self, lo: f64, hi: f64) -> f64 { + lo + (hi - lo) * self.next() + } +} + +/// A synthetic drawing with `n` mixed entities (lines, circles, arcs, polylines, text) spread +/// over a square whose side grows with sqrt(n), so density stays constant. +fn synthetic(n: usize, side: f64) -> Result { + use cadcraft_engine::doc::{self as d, Common, EntityKind, Space}; + use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3}; + let mut dr = d::Drawing::new_imperial(); + let mut r = Rng(0x9E37_79B9_7F4A_7C15); + let v3 = |x: f64, y: f64| Vec3::new(x, y, 0.0); + for i in 0..n { + let (x, y) = (r.range(0.0, side), r.range(0.0, side)); + let s = r.range(0.5, 8.0); + let kind = match i % 5 { + 0 => EntityKind::Line(d::Line { a: v3(x, y), b: v3(x + r.range(-s, s), y + r.range(-s, s)) }), + 1 => EntityKind::Circle(d::Circle { center: v3(x, y), radius: s * 0.5 }), + 2 => EntityKind::Arc(d::Arc { center: v3(x, y), radius: s * 0.5, start: r.range(0.0, 3.0), end: r.range(3.2, 6.2) }), + 3 => EntityKind::LwPolyline(d::LwPolyline { + vertices: (0..6) + .map(|k| PolyVertex { + p: Vec2::new(x + f64::from(k) * s * 0.3, y + r.range(-s, s) * 0.3), + bulge: if k == 2 { 0.4 } else { 0.0 }, + start_width: 0.0, + end_width: 0.0, + }) + .collect(), + closed: i % 2 == 0, + const_width: 0.0, + elevation: 0.0, + plinegen: false, + }), + _ => EntityKind::Text(d::Text { + insert: v3(x, y), + align_pt: None, + height: s * 0.2, + value: format!("T{i}"), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: d::HAlign::Left, + valign: d::VAlign::Baseline, + }), + }; + dr.add(&Space::Model, Common::default(), kind)?; + } + Ok(dr) +} + +/// `perf FILE`: the display list built as the canvas builds it (a 1600 x 1000 px view at the +/// drawing's centre: tolerance, dash level of detail and view window from the zoom band), at +/// zoom extents and zoomed in 4x at a time, next to the full-detail build plots use. +fn perf_file(path: &std::path::Path, io: &mut Streams) -> Result { + use cadcraft_engine::geom::{Bounds2, Vec2}; + use cadcraft_engine::render::{Options, build}; + use std::time::Instant; + let ms = |t: Instant| t.elapsed().as_secs_f64() * 1000.0; + let mut s = Session::empty(); + let t = Instant::now(); + open(&mut s, path)?; + let open_ms = ms(t); + let st = s.state()?; + let (d, space) = (&st.doc, &st.space); + let ext = d.extents(space); + let size = ext.width().max(ext.height()); + if ext.is_empty() || !(size.is_finite() && size > 0.0) { + return Err(PerfError::EmptyDrawing.into()); + } + io.outln(format_args!("open {open_ms:.0} ms, {} entities, extents {:.1} x {:.1}", d.entity_count(), ext.width(), ext.height())); + io.outln(format_args!("{:>8} {:>10} {:>10}", "zoom", "build ms", "prims")); + let mut finest = Options::default(); + for k in 0..5 { + let zoom = 4f64.powi(k); + let h = size / zoom; + let pixel = 2f64.powi((h / 1000.0).max(1e-300).log2().floor() as i32); + let half = Vec2::new(h * 0.8, h * 0.5); + let visible = Bounds2::new(ext.center() - half, ext.center() + half); + let screen = Options { tolerance: pixel * 0.5, min_dash: pixel * 2.0, view: Some(visible.expand(h * 0.8)), ..Default::default() }; + let t = Instant::now(); + let n = build(d, space, &screen).prims.len(); + io.outln(format_args!("{:>7}x {:>10.1} {n:>10}", zoom, ms(t))); + finest = screen; + } + // Plots: every pattern line, everywhere (last, so its large list doesn't weigh on the above). + let t = Instant::now(); + let n = build(d, space, &Options { min_dash: 0.0, view: None, ..finest }).prims.len(); + io.outln(format_args!("{:>8} {:>10.1} {n:>10}", "full", ms(t))); + Ok(()) +} + +pub(crate) fn perf(target: Option<&PerfTarget>, io: &mut Streams) -> Result { + use cadcraft_engine::doc::Space; + use cadcraft_engine::geom::{Bounds2, Vec2}; + use cadcraft_engine::{select, snap}; + use std::time::Instant; + let n = match target { + Some(PerfTarget::File(path)) => return perf_file(path, io), + Some(PerfTarget::Count(n)) => *n, + None => 200_000, + }; + let side = (n as f64).sqrt() * 10.0; + let mut rows: Vec<(String, f64, String)> = Vec::new(); + let ms = |t: Instant| t.elapsed().as_secs_f64() * 1000.0; + + let t = Instant::now(); + let d = synthetic(n, side)?; + rows.push(("build synthetic drawing".into(), ms(t), format!("{n} entities"))); + + // Display list at a 1600 px wide "zoom extents" view (tolerance = half a pixel). + let px = side / 1600.0; + let opts = cadcraft_engine::render::Options { tolerance: px * 0.5, min_dash: px * 2.0, ..Default::default() }; + let t = Instant::now(); + let list = cadcraft_engine::render::build(&d, &Space::Model, &opts); + rows.push(("display list build".into(), ms(t), format!("{} prims, {} segments", list.prims.len(), list.segment_count()))); + + // Hit testing on a zoomed-in view (aperture = 5 px at 0.02 units/px). + let ap = 0.1; + let mut r = Rng(42); + let pts: Vec = (0..1000).map(|_| Vec2::new(r.range(0.0, side), r.range(0.0, side))).collect(); + let t = Instant::now(); + let first = select::pick(&d, &Space::Model, pts.first().copied().unwrap_or(Vec2::ZERO), ap); + rows.push(("first pick (incl. index build)".into(), ms(t), format!("{first:?}"))); + let t = Instant::now(); + let hits = pts.iter().filter(|p| select::pick(&d, &Space::Model, **p, ap).is_some()).count(); + let total = ms(t); + rows.push(("pick x1000".into(), total, format!("{hits} hits, {:.3} ms/pick", total / 1000.0))); + + // One edit, then a pick: only the touched chunk is re-indexed. + let mut edited = d.clone(); + if let Some(h) = edited.model.last().map(|e| e.handle) { + edited.model.modify(h, |e| e.common.layer = "0".into()); + } + let t = Instant::now(); + let _ = select::pick(&edited, &Space::Model, pts.first().copied().unwrap_or(Vec2::ZERO), ap); + rows.push(("pick after one edit (incremental re-index)".into(), ms(t), String::new())); + + let mut sel = 0usize; + let t = Instant::now(); + for k in 0..20 { + let c = Vec2::new(r.range(0.0, side), r.range(0.0, side)); + let half = side * 0.05; + sel += select::select_window(&d, &Space::Model, Bounds2::new(c - Vec2::new(half, half), c + Vec2::new(half, half)), k % 2 == 1).len(); + } + rows.push(("window/crossing select x20 (10% side)".into(), ms(t), format!("{sel} selected"))); + + let t = Instant::now(); + let fence: Vec = (0..4).map(|_| Vec2::new(r.range(0.0, side), r.range(0.0, side))).collect(); + let fsel = select::select_fence(&d, &Space::Model, &fence).len(); + rows.push(("fence select (3 legs)".into(), ms(t), format!("{fsel} selected"))); + + let osmode = snap::mode::END | snap::mode::MID | snap::mode::CEN | snap::mode::QUA | snap::mode::INT; + let t = Instant::now(); + let snaps = pts.iter().filter(|p| snap::osnap(&d, &Space::Model, **p, ap * 2.0, osmode, None, false).is_some()).count(); + let total = ms(t); + rows.push(("osnap x1000".into(), total, format!("{snaps} hits, {:.3} ms/query", total / 1000.0))); + + let t = Instant::now(); + let bytes = cadcraft_io::write(&d, "perf.dxf")?; + rows.push(("DXF write".into(), ms(t), format!("{:.1} MB", bytes.len() as f64 / 1e6))); + let t = Instant::now(); + let back = cadcraft_io::read(&bytes, "perf.dxf")?; + rows.push(("DXF read".into(), ms(t), format!("{} entities", back.entity_count()))); + + io.outln(format_args!("{:<40} {:>12} notes", "operation", "ms")); + io.outln(format_args!("{}", "-".repeat(80))); + for (name, t, note) in rows { + io.outln(format_args!("{name:<40} {t:>12.2} {note}")); + } + Ok(()) +} diff --git a/apps/cadcraft-cli/src/run.rs b/apps/cadcraft-cli/src/run.rs new file mode 100644 index 000000000..56b4626e2 --- /dev/null +++ b/apps/cadcraft-cli/src/run.rs @@ -0,0 +1,223 @@ +use super::args::{CmdStep, Drawing, RunArgs, Step}; +use super::error::Result; +use super::open; +use super::output::{Streams, export, export_framed, export_window, model_views}; +use cadcraft_engine::Session; +use cadcraft_engine::doc::Handle; +use serde_json::Value; + +/// A `--cmd` parameter value of exactly `{last}` is filled in with the last object handle an +/// earlier `--cmd` in the same run returned: `mview` answers `{"viewports":["100"]}`, so +/// `viewport.set {"handle":"{last}","scale":1}` changes viewport 100. Any other string is passed +/// through unchanged, and `--script` text is never rewritten. +const LAST_HANDLE: &str = "{last}"; + +/// Why a `run` step fails. +#[derive(Debug, thiserror::Error)] +pub(crate) enum RunError { + #[error("{}: {source}", .path.display())] + ReadScript { path: std::path::PathBuf, source: std::io::Error }, + #[error("--cmd {id}: {source}")] + CmdLast { id: String, source: NoLastHandle }, +} + +/// A `{last}` placeholder with no handle to fill in. +#[derive(Debug, PartialEq, thiserror::Error)] +#[error("`{{last}}` needs an earlier --cmd in this run to have returned a handle")] +pub(crate) struct NoLastHandle; + +/// How deep [`result_handles`] walks a command result (results are the engine's own JSON). +const RESULT_DEPTH: usize = 16; + +/// Result keys whose values are object references: the engine's result convention for handles. +/// A handle can be a string (`handle`, `viewport`, `insert`…) or a list of them (`handles`, +/// `viewports`, `members`…). Every other field may hold a user-defined name, a message or a +/// count, and is never read as a handle — a group named `100` is a name, not object `100`. +fn handle_field(key: &str) -> bool { + matches!( + key, + "handle" + | "handles" + | "viewport" + | "viewports" + | "boundary" + | "clip" + | "insert" + | "members" + | "source" + | "objects" + | "entities" + | "selection" + | "parts" + | "refs" + | "matches" + | "line" + | "arc" + | "blocks" + ) +} + +/// Collect the handles of `v`, a value under a handle field: a handle string, an array of them, +/// or objects that carry handle fields of their own (`entities`, `parts`). +fn collect_result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec) { + if depth > RESULT_DEPTH { + return; + } + match v { + Value::String(t) => { + if let Some(h) = Handle::parse_hex(t) + && s.doc().is_ok_and(|d| d.entity(h).is_some()) + { + out.push(h); + } + } + Value::Array(a) => a.iter().for_each(|x| collect_result_handles(s, x, depth + 1, out)), + Value::Object(m) => { + for (k, x) in m { + if handle_field(k) { + collect_result_handles(s, x, depth + 1, out); + } else { + find_result_handles(s, x, depth + 1, out); + } + } + } + _ => {} + } +} + +/// Find handle fields nested in containers that are not handles themselves (`groups` in +/// `groups.list`, whose members are handles): strings here are names, never references. +fn find_result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec) { + if depth > RESULT_DEPTH { + return; + } + match v { + Value::Array(a) => a.iter().for_each(|x| find_result_handles(s, x, depth + 1, out)), + Value::Object(m) => { + for (k, x) in m { + if handle_field(k) { + collect_result_handles(s, x, depth + 1, out); + } else { + find_result_handles(s, x, depth + 1, out); + } + } + } + _ => {} + } +} + +/// The object handles a command result mentions, in the order it lists them. A handle-only result +/// (a handle string or an array of them) counts as it is; otherwise only handle fields do. +fn result_handles(s: &Session, v: &Value, depth: usize, out: &mut Vec) { + match v { + Value::String(_) => collect_result_handles(s, v, depth, out), + Value::Array(a) if a.iter().all(Value::is_string) => collect_result_handles(s, v, depth, out), + Value::Array(_) | Value::Object(_) => find_result_handles(s, v, depth, out), + _ => {} + } +} + +/// The last handle `r` returned: what a later `{last}` stands for. +pub(crate) fn returned_handle(s: &Session, r: &Value) -> Option { + let mut hs = Vec::new(); + result_handles(s, r, 0, &mut hs); + hs.last().copied() +} + +/// The active drawing's identity ([`cadcraft_engine::DocState::uid`]): a handle is only meaningful +/// in the drawing it came from, and `new`, `open`, `document.switch` and `close` can make another +/// drawing current. +fn active_drawing(s: &Session) -> Option { + s.docs.get(s.active).map(|st| st.uid) +} + +/// Every `{last}` in `p`, at any depth, replaced by `h`. With no handle to fill in it is an +/// error, never a token reaching the command as a (bad) handle. +pub(crate) fn fill_last(p: &Value, h: Option) -> Result { + match p { + Value::String(t) if t.as_str() == LAST_HANDLE => match h { + Some(h) => Ok(Value::String(h.hex())), + None => Err(NoLastHandle), + }, + Value::Array(a) => a.iter().map(|x| fill_last(x, h)).collect::, _>>().map(Value::Array), + Value::Object(m) => { + m.iter().map(|(k, x)| Ok((k.clone(), fill_last(x, h)?))).collect::, _>>().map(Value::Object) + } + other => Ok(other.clone()), + } +} + +/// A step ready to run: script text, or a command. +enum Ready<'a> { + Script(String), + Cmd(&'a CmdStep), +} + +pub(crate) fn run_cmds(a: &RunArgs, io: &mut Streams) -> Result { + let framing = a.framing.framing(); + let (save, export_to) = (a.save.as_deref(), a.export.as_deref()); + let mut s = Session::empty(); + for d in &a.drawings { + match d { + Drawing::File(f) => open(&mut s, f)?, + Drawing::Sample => { + s.open_drawing(cadcraft_engine::sample::default_sample(), "Bracket", None); + } + Drawing::Metric => { + s.new_drawing(true); + } + } + } + let mut steps: Vec = Vec::new(); + for step in &a.steps { + steps.push(match step { + Step::Script(text) => Ready::Script(text.replace("\\n", "\n")), + Step::ScriptFile(p) => Ready::Script(std::fs::read_to_string(p).map_err(|source| RunError::ReadScript { path: p.clone(), source })?), + Step::Cmd(c) => Ready::Cmd(c), + }); + } + if s.docs.is_empty() { + s.new_drawing(false); + } + let before = model_views(&s); + let mut last_handle: Option = None; + for step in steps { + // A handle belongs to the drawing that returned it: if this step makes another drawing + // current (`new`, `open`, `document.switch`, `close`, or a script running one of them), + // the remembered handle is stale. A handle the step itself returns is taken afterwards, + // so it is a handle of the drawing it made current. + let drawing = active_drawing(&s); + match step { + Ready::Script(body) => { + s.script(&body)?; + if active_drawing(&s) != drawing { + last_handle = None; + } + } + Ready::Cmd(CmdStep { id, params }) => { + let params = fill_last(params, last_handle).map_err(|source| RunError::CmdLast { id: id.clone(), source })?; + let r = s.execute(id, ¶ms)?; + if active_drawing(&s) != drawing { + last_handle = None; + } + if let Some(h) = returned_handle(&s, &r) { + last_handle = Some(h); + } + if !r.is_null() { + io.outln(format_args!("{r}")); + } + } + } + } + for l in &s.log { + io.errln(format_args!("{l}")); + } + if let Some(p) = save { + export(&s, p, io)?; + } + if let Some(p) = export_to { + let window = if cadcraft_io::is_image(p) { export_window(&s, framing, Some(&before))? } else { None }; + export_framed(&s, p, window, io)?; + } + Ok(()) +} diff --git a/apps/cadcraft-cli/src/sample.rs b/apps/cadcraft-cli/src/sample.rs new file mode 100644 index 000000000..9b6405cb5 --- /dev/null +++ b/apps/cadcraft-cli/src/sample.rs @@ -0,0 +1,14 @@ +use super::args::{SampleArgs, SampleName}; +use super::error::Result; +use super::output::{Streams, write_atomic}; + +pub(crate) fn sample(a: &SampleArgs, io: &mut Streams) -> Result { + let d = match a.name { + SampleName::Bracket => cadcraft_engine::sample::bracket(), + SampleName::Floorplan => cadcraft_engine::sample::floor_plan(), + }; + let bytes = cadcraft_io::write(&d, &a.output)?; + write_atomic(&a.output, &bytes)?; + io.errln(format_args!("wrote {} ({} bytes)", a.output.display(), bytes.len())); + Ok(()) +} diff --git a/apps/cadcraft-cli/tests/it/help.rs b/apps/cadcraft-cli/tests/it/help.rs index 24df988af..65f8bad97 100644 --- a/apps/cadcraft-cli/tests/it/help.rs +++ b/apps/cadcraft-cli/tests/it/help.rs @@ -1,23 +1,23 @@ //! `--help` is a request, not a failure (#1525): it goes to stdout with exit 0, like `--version`. -//! Bare `cadcraft-cli` keeps reporting on stderr with exit 1. +//! Bare `cadcraft-cli` is a usage error: the help on stderr, exit 2. use std::process::Command; #[test] -fn help_flags_print_usage_to_stdout_and_exit_zero() { +fn help_flags_print_help_to_stdout_and_exit_zero() { for args in [&["--help"][..], &["-h"], &["help"]] { let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().expect("run cadcraft-cli"); assert!(out.status.success(), "{args:?}: {:?}", out.status); let stdout = String::from_utf8_lossy(&out.stdout); - assert!(stdout.starts_with("usage:"), "{args:?}: {stdout:?}"); + assert!(stdout.starts_with("cadcraft-cli: headless CADCraft\n"), "{args:?}: {stdout:?}"); assert!(String::from_utf8_lossy(&out.stderr).is_empty(), "{args:?}: stderr should be empty"); } } #[test] -fn bare_invocation_still_reports_on_stderr() { +fn bare_invocation_reports_on_stderr() { let out = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).output().expect("run cadcraft-cli"); - assert_eq!(out.status.code(), Some(1)); - assert!(out.stdout.is_empty(), "bare invocation keeps its usage on stderr"); - assert!(String::from_utf8_lossy(&out.stderr).starts_with("usage:")); + assert_eq!(out.status.code(), Some(2)); + assert!(out.stdout.is_empty(), "bare invocation keeps its help on stderr"); + assert!(String::from_utf8_lossy(&out.stderr).starts_with("cadcraft-cli: headless CADCraft\n")); } diff --git a/apps/cadcraft-cli/tests/it/main.rs b/apps/cadcraft-cli/tests/it/main.rs index efd49c7dd..adb3f3749 100644 --- a/apps/cadcraft-cli/tests/it/main.rs +++ b/apps/cadcraft-cli/tests/it/main.rs @@ -4,3 +4,4 @@ mod help; mod mcp_connect; mod skipped_records; mod undrawn_entities; +mod usage; diff --git a/apps/cadcraft-cli/tests/it/mcp_connect.rs b/apps/cadcraft-cli/tests/it/mcp_connect.rs index c12e71c82..4211f3595 100644 --- a/apps/cadcraft-cli/tests/it/mcp_connect.rs +++ b/apps/cadcraft-cli/tests/it/mcp_connect.rs @@ -33,12 +33,15 @@ fn replies(out: &Output) -> Vec { #[test] fn connect_without_address_fails_before_serving() { let input = format!("{INIT}\n{CIRCLE}\n"); - for args in [&["--connect"][..], &["--connect", ""], &["--connect", "--foo"]] { + // clap names an unknown flag rather than the value it left missing. + for (args, named) in + [(&["--connect"][..], "--connect "), (&["--connect", ""], "--connect "), (&["--connect", "--foo"], "'--foo'")] + { let out = mcp(args, &input); - assert!(!out.status.success(), "{args:?} must exit non-zero"); + assert_eq!(out.status.code(), Some(2), "{args:?} is a usage error"); assert!(out.stdout.is_empty(), "{args:?} must not answer MCP requests: {}", String::from_utf8_lossy(&out.stdout)); let err = String::from_utf8_lossy(&out.stderr); - assert!(err.contains("--connect needs HOST:PORT"), "{args:?}: {err}"); + assert!(err.contains(named), "{args:?}: {err}"); } } diff --git a/apps/cadcraft-cli/tests/it/usage.rs b/apps/cadcraft-cli/tests/it/usage.rs new file mode 100644 index 000000000..2e9f6e907 --- /dev/null +++ b/apps/cadcraft-cli/tests/it/usage.rs @@ -0,0 +1,950 @@ +//! The command line's behaviour: exit codes, streams and messages for help requests, unknown and +//! malformed options, value flags in both spellings, repeats and arity. Every case goes through +//! `invoke`, so the table rows are the record of what each input does. Usage errors are clap's +//! (exit 2, stderr); a subcommand's own failures are `error: …` with exit 1. + +use std::path::{Path, PathBuf}; + +struct Invoke { + code: i32, + stdout: String, + stderr: String, +} + +fn invoke(args: &[&str]) -> Invoke { + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = cadcraft_cli::run(args, &mut out, &mut err); + Invoke { code, stdout: String::from_utf8_lossy(&out).into_owned(), stderr: String::from_utf8_lossy(&err).into_owned() } +} + +/// What a stream holds. +#[derive(Clone, Copy)] +enum Expect { + Empty, + /// The first line equals this. + Line(&'static str), + /// The first line starts with this. + Starts(&'static str), +} + +use Expect::{Empty, Line, Starts}; + +struct Case { + name: &'static str, + args: &'static [&'static str], + code: i32, + stdout: Expect, + stderr: Expect, +} + +const fn case(name: &'static str, args: &'static [&'static str], code: i32, stdout: Expect, stderr: Expect) -> Case { + Case { name, args, code, stdout, stderr } +} + +/// A scratch directory holding `b.dxf` (the bracket sample) and `s.scr` (a one-line script). +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("cc-cli-usage-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create scratch dir"); + let b = dir.join("b.dxf"); + let r = invoke(&["sample", "bracket", b.to_str().expect("utf-8 path")]); + assert_eq!(r.code, 0, "{}", r.stderr); + std::fs::write(dir.join("s.scr"), "LINE 0,0 1,1\n").expect("write script"); + Scratch(dir) + } + + /// Replaces `{dir}` with the scratch directory and `{b}` with the sample drawing. + fn expand(&self, text: &str) -> String { + let dir = self.0.to_str().expect("utf-8 path"); + text.replace("{b}", &Path::new(dir).join("b.dxf").to_string_lossy()).replace("{dir}", dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn check(what: &str, stream: &str, got: &str, expect: Expect, scratch: &Scratch) { + let first = got.lines().next().unwrap_or(""); + match expect { + Empty => assert!(got.is_empty(), "{what}: {stream} should be empty, got {got:?}"), + Line(l) => assert_eq!(first, scratch.expand(l), "{what}: {stream}"), + Starts(p) => assert!(first.starts_with(&scratch.expand(p)), "{what}: {stream} should start with {p:?}, got {first:?}"), + } +} + +fn run_cases(tag: &str, cases: &[Case]) { + let scratch = Scratch::new(tag); + for c in cases { + let args: Vec = c.args.iter().map(|a| scratch.expand(a)).collect(); + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + let what = format!("{}: {args:?}", c.name); + let r = invoke(&args); + assert_eq!(r.code, c.code, "{what}: exit code (stderr {:?})", r.stderr); + check(&what, "stdout", &r.stdout, c.stdout, &scratch); + check(&what, "stderr", &r.stderr, c.stderr, &scratch); + } +} + +#[test] +fn top_level_requests() { + run_cases( + "top", + &[ + case("--help", &["--help"], 0, Line("cadcraft-cli: headless CADCraft"), Empty), + case("-h", &["-h"], 0, Line("cadcraft-cli: headless CADCraft"), Empty), + case("help", &["help"], 0, Line("cadcraft-cli: headless CADCraft"), Empty), + case("--version", &["--version"], 0, Starts("cadcraft-cli "), Empty), + case("-V", &["-V"], 0, Starts("cadcraft-cli "), Empty), + case("version is not a subcommand", &["version"], 2, Empty, Line("error: unrecognized subcommand 'version'")), + case("bare", &[], 2, Empty, Line("cadcraft-cli: headless CADCraft")), + case("unknown subcommand", &["foo"], 2, Empty, Line("error: unrecognized subcommand 'foo'")), + case("unknown top-level flag", &["--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("empty subcommand", &[""], 2, Empty, Line("error: unrecognized subcommand ''")), + ], + ); +} + +/// Each subcommand's help, from `--help`, `-h` or `help `: its first line is the +/// subcommand's summary. +#[test] +fn subcommand_help_requests() { + run_cases( + "subhelp", + &[ + case("info --help", &["info", "--help"], 0, Line("Print a drawing's summary as JSON"), Empty), + case("info -h", &["info", "-h"], 0, Line("Print a drawing's summary as JSON"), Empty), + case( + "convert --help", + &["convert", "--help"], + 0, + Line("Convert a drawing; OUT's extension picks the format (dxf, dwg, dwt, svg, png, pdf)"), + Empty, + ), + case( + "convert -h", + &["convert", "-h"], + 0, + Line("Convert a drawing; OUT's extension picks the format (dxf, dwg, dwt, svg, png, pdf)"), + Empty, + ), + case( + "run --help", + &["run", "--help"], + 0, + Line("Open drawings (or start a new one), run scripts and commands in order, save or export the result"), + Empty, + ), + case( + "run -h", + &["run", "-h"], + 0, + Line("Open drawings (or start a new one), run scripts and commands in order, save or export the result"), + Empty, + ), + case("commands --help", &["commands", "--help"], 0, Line("Print the command catalog as JSON"), Empty), + case( + "mcp --help", + &["mcp", "--help"], + 0, + Line("Run the MCP server on stdio: a headless drawing session, or a bridge to the running app"), + Empty, + ), + case( + "perf --help", + &["perf", "--help"], + 0, + Line( + "Time the engine on a synthetic N-entity drawing (default 200000), or the canvas display-list build of a drawing, zoomed in step by step", + ), + Empty, + ), + case("sample --help", &["sample", "--help"], 0, Line("Write a built-in sample drawing"), Empty), + case( + "help run", + &["help", "run"], + 0, + Line("Open drawings (or start a new one), run scripts and commands in order, save or export the result"), + Empty, + ), + case("help info", &["help", "info"], 0, Line("Print a drawing's summary as JSON"), Empty), + case( + "help after a flag missing its value", + &["run", "--sample", "--script", "--help"], + 0, + Line("Open drawings (or start a new one), run scripts and commands in order, save or export the result"), + Empty, + ), + case( + "help after an unknown flag", + &["run", "--bogus", "--help"], + 0, + Line("Open drawings (or start a new one), run scripts and commands in order, save or export the result"), + Empty, + ), + case("help after an extra argument", &["info", "{b}", "extra", "-h"], 0, Line("Print a drawing's summary as JSON"), Empty), + case("--help after -- is a file name", &["run", "--", "--help"], 1, Empty, Starts("error: invalid parameters for `open`: --help:")), + case("run --version", &["run", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")), + case("info --version", &["info", "--version"], 2, Empty, Line("error: unexpected argument '--version' found")), + ], + ); +} + +#[test] +fn unknown_flags_on_every_subcommand() { + run_cases( + "unknown", + &[ + case("info", &["info", "{b}", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("info, flag first", &["info", "--bogus", "{b}"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("info, short flag", &["info", "-x"], 2, Empty, Line("error: unexpected argument '-x' found")), + case("info, a file name starting with - after --", &["info", "--", "-x"], 1, Empty, Starts("error: invalid parameters for `open`: -x:")), + case("convert", &["convert", "{b}", "{dir}/o.svg", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("run", &["run", "--sample", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("run, flag first", &["run", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("commands", &["commands", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("commands -- ends the options", &["commands", "--"], 0, Line("["), Empty), + case("mcp", &["mcp", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("mcp positional", &["mcp", "extra"], 2, Empty, Line("error: unexpected argument 'extra' found")), + case("perf", &["perf", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("sample", &["sample", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + case("sample after name", &["sample", "bracket", "--bogus"], 2, Empty, Line("error: unexpected argument '--bogus' found")), + ], + ); +} + +/// `--x=v` is a spelling of `--x v`, and the one a value starting with `-` needs. +#[test] +fn value_flags_in_both_forms() { + run_cases( + "forms", + &[ + case("--window v", &["convert", "{b}", "{dir}/w1.svg", "--window", "0,0,100,100"], 0, Empty, Starts("wrote {dir}/w1.svg (")), + case("--window=v", &["convert", "{b}", "{dir}/w2.svg", "--window=0,0,100,100"], 0, Empty, Starts("wrote {dir}/w2.svg (")), + case( + "run --window v", + &["run", "--sample", "--window", "0,0,100,100", "--export", "{dir}/w3.svg"], + 0, + Empty, + Starts("wrote {dir}/w3.svg ("), + ), + case( + "run --window=v", + &["run", "--sample", "--window=0,0,100,100", "--export", "{dir}/w4.svg"], + 0, + Empty, + Starts("wrote {dir}/w4.svg ("), + ), + case("--view v", &["convert", "{b}", "{dir}/v1.svg", "--view", "extents"], 0, Empty, Starts("wrote {dir}/v1.svg (")), + case("--view=v", &["convert", "{b}", "{dir}/v2.svg", "--view=extents"], 0, Empty, Starts("wrote {dir}/v2.svg (")), + case("run --view v", &["run", "--sample", "--view", "current", "--export", "{dir}/v3.svg"], 0, Empty, Starts("wrote {dir}/v3.svg (")), + case("run --view=v", &["run", "--sample", "--view=extents", "--export={dir}/v4.svg"], 0, Empty, Starts("wrote {dir}/v4.svg (")), + case("--script v", &["run", "--sample", "--script", "LINE 0,0 1,1"], 0, Empty, Line("Command: LINE")), + case("--script=v", &["run", "--sample", "--script=LINE 0,0 1,1"], 0, Empty, Line("Command: LINE")), + case("--script-file v", &["run", "--sample", "--script-file", "{dir}/s.scr"], 0, Empty, Starts("Command: LINE")), + case("--script-file=v", &["run", "--sample", "--script-file={dir}/s.scr"], 0, Empty, Starts("Command: LINE")), + case("--cmd v", &["run", "--sample", "--cmd", "nosuch"], 1, Empty, Line("error: unknown command `nosuch`")), + case("--cmd=v", &["run", "--sample", "--cmd=nosuch"], 1, Empty, Line("error: unknown command `nosuch`")), + case("--cmd=-v", &["run", "--sample", "--cmd=-x"], 1, Empty, Line("error: unknown command `-x`")), + case("--save v", &["run", "--sample", "--save", "{dir}/s1.dxf"], 0, Empty, Starts("wrote {dir}/s1.dxf (")), + case("--save=v", &["run", "--sample", "--save={dir}/s2.dxf"], 0, Empty, Starts("wrote {dir}/s2.dxf (")), + case("--export v", &["run", "--sample", "--export", "{dir}/e1.svg"], 0, Empty, Starts("wrote {dir}/e1.svg (")), + case("--export=v", &["run", "--sample", "--export={dir}/e2.svg"], 0, Empty, Starts("wrote {dir}/e2.svg (")), + case( + "--window=-v: negative coordinates need =", + &["convert", "{b}", "{dir}/w5.svg", "--window=-1000,-1000,1000,1000"], + 0, + Empty, + Starts("wrote {dir}/w5.svg ("), + ), + case( + "--window -v: a value starting with - is a flag", + &["convert", "{b}", "{dir}/w6.svg", "--window", "-1000,-1000,1000,1000"], + 2, + Empty, + Line("error: unexpected argument '-1' found"), + ), + case("--connect v", &["mcp", "--connect", "127.0.0.1:1"], 1, Empty, Starts("error: cannot connect to 127.0.0.1:1:")), + case("--connect=v", &["mcp", "--connect=127.0.0.1:1"], 1, Empty, Starts("error: cannot connect to 127.0.0.1:1:")), + ], + ); +} + +/// A value flag at the end of the arguments, or followed by another flag, is missing its value: +/// a flag is never taken as a value. +#[test] +fn flags_missing_their_value() { + run_cases( + "missing", + &[ + case( + "convert --window last", + &["convert", "{b}", "{dir}/o.svg", "--window"], + 2, + Empty, + Line("error: a value is required for '--window ' but none was supplied"), + ), + case( + "convert --view last", + &["convert", "{b}", "{dir}/o.svg", "--view"], + 2, + Empty, + Line("error: a value is required for '--view ' but none was supplied"), + ), + case( + "convert --window then flag", + &["convert", "{b}", "{dir}/o.svg", "--window", "--view", "extents"], + 2, + Empty, + Line("error: a value is required for '--window ' but none was supplied"), + ), + case( + "convert --view then flag", + &["convert", "{b}", "{dir}/o.svg", "--view", "--window", "0,0,1,1"], + 2, + Empty, + Line("error: a value is required for '--view ' but none was supplied"), + ), + case( + "run --window last", + &["run", "--sample", "--window"], + 2, + Empty, + Line("error: a value is required for '--window ' but none was supplied"), + ), + case( + "run --view last", + &["run", "--sample", "--view"], + 2, + Empty, + Line("error: a value is required for '--view ' but none was supplied"), + ), + case( + "run --script last", + &["run", "--sample", "--script"], + 2, + Empty, + Line("error: a value is required for '--script ' but none was supplied"), + ), + case( + "run --script then flag", + &["run", "--sample", "--script", "--sample"], + 2, + Empty, + Line("error: a value is required for '--script ' but none was supplied"), + ), + case( + "run --script-file last", + &["run", "--script-file"], + 2, + Empty, + Line("error: a value is required for '--script-file ' but none was supplied"), + ), + case( + "run --script-file then flag", + &["run", "--sample", "--script-file", "--sample"], + 2, + Empty, + Line("error: a value is required for '--script-file ' but none was supplied"), + ), + case( + "run --cmd last", + &["run", "--sample", "--cmd"], + 2, + Empty, + Line("error: a value is required for '--cmd ' but none was supplied"), + ), + case( + "run --cmd then flag", + &["run", "--sample", "--cmd", "--sample"], + 2, + Empty, + Line("error: a value is required for '--cmd ' but none was supplied"), + ), + case( + "run --save last", + &["run", "--sample", "--save"], + 2, + Empty, + Line("error: a value is required for '--save ' but none was supplied"), + ), + case( + "run --export last", + &["run", "--sample", "--export"], + 2, + Empty, + Line("error: a value is required for '--export ' but none was supplied"), + ), + case( + "mcp --connect last", + &["mcp", "--connect"], + 2, + Empty, + Line("error: a value is required for '--connect ' but none was supplied"), + ), + case( + "mcp --connect then flag", + &["mcp", "--connect", "--lazy"], + 2, + Empty, + Line("error: a value is required for '--connect ' but none was supplied"), + ), + case( + "mcp --connect empty", + &["mcp", "--connect", " "], + 2, + Empty, + Line("error: invalid value ' ' for '--connect ': expected HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)"), + ), + case( + "mcp --connect without a port", + &["mcp", "--connect", "example.com"], + 2, + Empty, + Line( + "error: invalid value 'example.com' for '--connect ': expected HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)", + ), + ), + case( + "mcp --connect port out of range", + &["mcp", "--connect", "host:99999"], + 2, + Empty, + Line( + "error: invalid value 'host:99999' for '--connect ': expected HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)", + ), + ), + case( + "mcp --connect=-v", + &["mcp", "--connect=-v"], + 2, + Empty, + Line("error: invalid value '-v' for '--connect ': expected HOST:PORT (the app's --control port, e.g. 127.0.0.1:7979)"), + ), + ], + ); +} + +#[test] +fn repeated_and_combined_flags() { + run_cases( + "repeat", + &[ + case( + "--save twice", + &["run", "--sample", "--save", "{dir}/a.dxf", "--save", "{dir}/b2.dxf"], + 2, + Empty, + Line("error: the argument '--save ' cannot be used multiple times"), + ), + case( + "--export twice", + &["run", "--sample", "--export", "{dir}/x1.svg", "--export", "{dir}/x2.svg"], + 2, + Empty, + Line("error: the argument '--export ' cannot be used multiple times"), + ), + case( + "--window twice", + &["run", "--sample", "--window", "0,0,1,1", "--window", "0,0,2,2", "--export", "{dir}/ww.svg"], + 2, + Empty, + Line("error: the argument '--window ' cannot be used multiple times"), + ), + case( + "convert --window twice", + &["convert", "{b}", "{dir}/cw.svg", "--window", "0,0,1,1", "--window", "0,0,2,2"], + 2, + Empty, + Line("error: the argument '--window ' cannot be used multiple times"), + ), + case( + "--view twice, different", + &["run", "--sample", "--view", "extents", "--view", "current", "--export", "{dir}/vv.svg"], + 2, + Empty, + Line("error: the argument '--view ' cannot be used multiple times"), + ), + case( + "--view twice, same", + &["run", "--sample", "--view", "extents", "--view", "extents", "--export", "{dir}/vs.svg"], + 2, + Empty, + Line("error: the argument '--view ' cannot be used multiple times"), + ), + case("--sample twice", &["run", "--sample", "--sample"], 2, Empty, Line("error: the argument '--sample' cannot be used multiple times")), + case("--metric twice", &["run", "--metric", "--metric"], 2, Empty, Line("error: the argument '--metric' cannot be used multiple times")), + case( + "--lazy twice", + &["mcp", "--connect", "127.0.0.1:1", "--lazy", "--lazy"], + 2, + Empty, + Line("error: the argument '--lazy' cannot be used multiple times"), + ), + case( + "--launch twice", + &["mcp", "--connect", "127.0.0.1:1", "--launch", "--launch"], + 2, + Empty, + Line("error: the argument '--launch' cannot be used multiple times"), + ), + case( + "--script, --script-file and --cmd repeat", + &[ + "run", + "--sample", + "--script", + "LINE 0,0 1,1", + "--script", + "LINE 0,0 2,2", + "--script-file", + "{dir}/s.scr", + "--script-file", + "{dir}/s.scr", + ], + 0, + Empty, + Starts("Command: LINE"), + ), + case( + "--window and --view", + &["run", "--sample", "--window", "0,0,1,1", "--view", "extents", "--export", "{dir}/wv.svg"], + 2, + Empty, + Line("error: the argument '--window ' cannot be used with '--view '"), + ), + case( + "convert --window and --view", + &["convert", "{b}", "{dir}/cwv.svg", "--window", "0,0,1,1", "--view", "extents"], + 2, + Empty, + Line("error: the argument '--window ' cannot be used with '--view '"), + ), + case( + "--view is case-insensitive", + &["run", "--sample", "--view", "EXTENTS", "--export", "{dir}/vu.svg"], + 0, + Empty, + Starts("wrote {dir}/vu.svg ("), + ), + case( + "--connect twice", + &["mcp", "--connect", "127.0.0.1:1", "--connect", "127.0.0.1:2"], + 2, + Empty, + Line("error: the argument '--connect ' cannot be used multiple times"), + ), + case("--lazy without --connect", &["mcp", "--lazy"], 2, Empty, Line("error: the following required arguments were not provided:")), + case("--launch without --connect", &["mcp", "--launch"], 2, Empty, Line("error: the following required arguments were not provided:")), + case("--sample --metric: both accepted", &["run", "--sample", "--metric"], 0, Empty, Empty), + case("--sample and a file", &["run", "--sample", "{b}"], 0, Empty, Empty), + case("two files", &["run", "{b}", "{b}"], 0, Empty, Empty), + case( + "--window without export", + &["run", "--sample", "--window", "0,0,1,1"], + 2, + Empty, + Line("error: the following required arguments were not provided:"), + ), + case( + "--view without export", + &["run", "--sample", "--view", "current"], + 2, + Empty, + Line("error: the following required arguments were not provided:"), + ), + case( + "--window with a dxf output", + &["convert", "{b}", "{dir}/o.dxf", "--window", "0,0,1,1"], + 2, + Empty, + Line("error: --window only applies to image output (png, svg, pdf), not `{dir}/o.dxf`"), + ), + case( + "--view with a dxf output", + &["convert", "{b}", "{dir}/o.dxf", "--view", "extents"], + 2, + Empty, + Line("error: --view only applies to image output (png, svg, pdf), not `{dir}/o.dxf`"), + ), + case( + "run --window with a dxf export", + &["run", "--sample", "--window", "0,0,1,1", "--export", "{dir}/o.dxf"], + 2, + Empty, + Line("error: --window only applies to image output (png, svg, pdf), not `{dir}/o.dxf`"), + ), + case( + "run --view with a dxf export", + &["run", "--sample", "--view", "current", "--export", "{dir}/o.dxf"], + 2, + Empty, + Line("error: --view only applies to image output (png, svg, pdf), not `{dir}/o.dxf`"), + ), + ], + ); +} + +#[test] +fn arity_and_positional_arguments() { + run_cases( + "arity", + &[ + case("info without a file", &["info"], 2, Empty, Line("error: the following required arguments were not provided:")), + case("info with two files", &["info", "{b}", "extra"], 2, Empty, Line("error: unexpected argument 'extra' found")), + case("info missing file", &["info", "missing.dxf"], 1, Empty, Starts("error: invalid parameters for `open`: missing.dxf:")), + case("convert with no files", &["convert"], 2, Empty, Line("error: the following required arguments were not provided:")), + case("convert with one file", &["convert", "{b}"], 2, Empty, Line("error: the following required arguments were not provided:")), + case( + "convert with three files", + &["convert", "{b}", "{dir}/o.svg", "{dir}/x.svg"], + 2, + Empty, + Line("error: unexpected argument '{dir}/x.svg' found"), + ), + case("run missing file", &["run", "missing.dxf"], 1, Empty, Starts("error: invalid parameters for `open`: missing.dxf:")), + case("commands, no match", &["commands", "zzzznomatch"], 0, Line("[]"), Empty), + case( + "commands with an extra argument", + &["commands", "zzzznomatch", "extra"], + 2, + Empty, + Line("error: unexpected argument 'extra' found"), + ), + case("sample without arguments", &["sample"], 2, Empty, Line("error: the following required arguments were not provided:")), + case("sample without an output", &["sample", "bracket"], 2, Empty, Line("error: the following required arguments were not provided:")), + case( + "sample with a bad name", + &["sample", "nosuch", "{dir}/o.dxf"], + 2, + Empty, + Line("error: invalid value 'nosuch' for ''"), + ), + case( + "sample names are case-sensitive", + &["sample", "Bracket", "{dir}/o.dxf"], + 2, + Empty, + Line("error: invalid value 'Bracket' for ''"), + ), + case( + "sample with an empty output", + &["sample", "bracket", ""], + 2, + Empty, + Line("error: a value is required for '' but none was supplied"), + ), + case("info with an empty file name", &["info", ""], 2, Empty, Line("error: a value is required for '' but none was supplied")), + case("perf with an empty file name", &["perf", ""], 2, Empty, Line("error: a value is required for '[N|FILE]' but none was supplied")), + case( + "sample with an extra argument", + &["sample", "bracket", "{dir}/sx.dxf", "extra"], + 2, + Empty, + Line("error: unexpected argument 'extra' found"), + ), + case("sample floor alias", &["sample", "floor", "{dir}/sf.dxf"], 0, Empty, Starts("wrote {dir}/sf.dxf (")), + case("sample with a bad extension", &["sample", "bracket", "{dir}/o.xyz"], 1, Empty, Line("error: unsupported file type `xyz`")), + case("perf with a word", &["perf", "abc"], 1, Empty, Starts("error: invalid parameters for `open`: abc:")), + case("perf with a negative number", &["perf", "-5"], 2, Empty, Line("error: unexpected argument '-5' found")), + case("perf with a missing file", &["perf", "missing.dxf"], 1, Empty, Starts("error: invalid parameters for `open`: missing.dxf:")), + case("perf 1", &["perf", "1"], 0, Starts("operation"), Empty), + case("perf 0 is raised to 1", &["perf", "0"], 0, Starts("operation"), Empty), + case("perf with two counts", &["perf", "1", "2"], 2, Empty, Line("error: unexpected argument '2' found")), + ], + ); +} + +#[test] +fn bad_values() { + run_cases( + "values", + &[ + case( + "--view sideways", + &["convert", "{b}", "{dir}/o.svg", "--view", "sideways"], + 2, + Empty, + Line("error: invalid value 'sideways' for '--view '"), + ), + case( + "run --view sideways", + &["run", "--sample", "--view", "sideways"], + 2, + Empty, + Line("error: invalid value 'sideways' for '--view '"), + ), + case( + "--view sideways before the output check", + &["convert", "{b}", "{dir}/o.dxf", "--view", "sideways"], + 2, + Empty, + Line("error: invalid value 'sideways' for '--view '"), + ), + case( + "--window 3 numbers", + &["convert", "{b}", "{dir}/o.svg", "--window", "1,2,3"], + 2, + Empty, + Line("error: invalid value '1,2,3' for '--window ': expected four numbers x0,y0,x1,y1"), + ), + case( + "--window 5 numbers", + &["convert", "{b}", "{dir}/o.svg", "--window", "1,2,3,4,5"], + 2, + Empty, + Line("error: invalid value '1,2,3,4,5' for '--window ': expected four numbers x0,y0,x1,y1"), + ), + case( + "--window reversed", + &["convert", "{b}", "{dir}/o.svg", "--window", "3,3,1,1"], + 2, + Empty, + Line("error: invalid value '3,3,1,1' for '--window ': need x0 < x1 and y0 < y1 (lower-left corner first)"), + ), + case( + "--window not numbers", + &["convert", "{b}", "{dir}/o.svg", "--window", "a,b,c,d"], + 2, + Empty, + Line("error: invalid value 'a,b,c,d' for '--window ': x0 must be a finite number, got `a`"), + ), + case( + "--window NaN", + &["convert", "{b}", "{dir}/o.svg", "--window", "NaN,0,1,1"], + 2, + Empty, + Line("error: invalid value 'NaN,0,1,1' for '--window ': x0 must be a finite number, got `NaN`"), + ), + case( + "--window too large", + &["convert", "{b}", "{dir}/o.svg", "--window", "0,0,1e13,1"], + 2, + Empty, + Line("error: invalid value '0,0,1e13,1' for '--window ': export window: coordinates must lie within ±1e12"), + ), + case( + "run --window 3 numbers", + &["run", "--sample", "--window", "1,2,3", "--export", "{dir}/o.svg"], + 2, + Empty, + Line("error: invalid value '1,2,3' for '--window ': expected four numbers x0,y0,x1,y1"), + ), + case( + "run --window reversed", + &["run", "--sample", "--window", "3,3,1,1", "--export", "{dir}/o.svg"], + 2, + Empty, + Line("error: invalid value '3,3,1,1' for '--window ': need x0 < x1 and y0 < y1 (lower-left corner first)"), + ), + case( + "--cmd bad json", + &["run", "--sample", "--cmd", "line {bad json"], + 2, + Empty, + Line("error: invalid value 'line {bad json' for '--cmd ': key must be a string at line 1 column 2"), + ), + case( + "--cmd bad json after a good step: nothing runs", + &["run", "--sample", "--cmd", "line {\"points\":[[0,0],[1,1]]}", "--cmd", "line {"], + 2, + Empty, + Starts("error: invalid value 'line {' for '--cmd ': "), + ), + case( + "--cmd without an id", + &["run", "--sample", "--cmd", " {}"], + 2, + Empty, + Line("error: invalid value ' {}' for '--cmd ': expected a command id, then optionally its JSON parameters"), + ), + case( + "--cmd empty", + &["run", "--sample", "--cmd="], + 2, + Empty, + Line("error: invalid value '' for '--cmd ': expected a command id, then optionally its JSON parameters"), + ), + case("--cmd unknown id", &["run", "--sample", "--cmd", "nosuch"], 1, Empty, Line("error: unknown command `nosuch`")), + case( + "--cmd {last} with no earlier handle", + &["run", "--sample", "--cmd", "erase {\"handles\":[\"{last}\"]}"], + 1, + Empty, + Line("error: --cmd erase: `{last}` needs an earlier --cmd in this run to have returned a handle"), + ), + case("--script-file missing", &["run", "--sample", "--script-file", "missing.scr"], 1, Empty, Starts("error: missing.scr:")), + ], + ); +} + +/// `mcp` serves on the process's real stdin and stdout, so the headless server runs through the +/// binary, with a closed stdin. +#[test] +fn mcp_headless_with_a_closed_stdin() { + let out = std::process::Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")) + .arg("mcp") + .stdin(std::process::Stdio::null()) + .output() + .expect("run cadcraft-cli"); + assert_eq!(out.status.code(), Some(0)); + assert!(out.stdout.is_empty() && out.stderr.is_empty()); +} + +/// A drawing to open whose name isn't valid Unicode reaches the handler as a path; the engine opens +/// files by text name, so it is refused there (exit 1), naming the file. Text that isn't Unicode is +/// a usage error. +#[cfg(unix)] +#[test] +fn non_unicode_arguments() { + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + let invoke_os = |args: Vec| { + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = cadcraft_cli::run(args, &mut out, &mut err); + assert!(out.is_empty()); + (code, String::from_utf8_lossy(&err).into_owned()) + }; + let latin1 = || OsString::from_vec(b"caf\xe9.dxf".to_vec()); + let (code, err) = invoke_os(vec![OsString::from("info"), latin1()]); + assert_eq!(code, 1); + assert_eq!(err.lines().next(), Some("error: caf\u{FFFD}.dxf: the file name is not valid Unicode")); + let (code, err) = invoke_os(vec![OsString::from("run"), OsString::from("--sample"), OsString::from("--cmd"), latin1()]); + assert_eq!(code, 2); + assert!(err.starts_with("error: invalid UTF-8 was detected"), "{err}"); +} + +/// An output name that isn't valid Unicode is written as given: only its extension picks the format. +#[cfg(unix)] +#[test] +fn non_unicode_output_names() { + use std::ffi::OsString; + use std::os::unix::ffi::OsStringExt; + let s = Scratch::new("nonunicode-out"); + let latin1 = |ext: &str| { + let mut n = b"caf\xe9.".to_vec(); + n.extend_from_slice(ext.as_bytes()); + s.0.join(OsString::from_vec(n)) + }; + let run = |args: Vec| { + let (mut out, mut err) = (Vec::new(), Vec::new()); + let code = cadcraft_cli::run(args, &mut out, &mut err); + (code, String::from_utf8_lossy(&err).into_owned()) + }; + let b = s.0.join("b.dxf"); + let cases: [(Vec, std::path::PathBuf); 3] = [ + (vec!["sample".into(), "bracket".into(), latin1("dxf").into()], latin1("dxf")), + (vec!["convert".into(), b.clone().into(), latin1("svg").into()], latin1("svg")), + (vec!["run".into(), "--sample".into(), "--save".into(), latin1("dwg").into()], latin1("dwg")), + ]; + for (args, path) in cases { + let (code, err) = run(args.clone()); + assert_eq!(code, 0, "{args:?}: {err}"); + assert!(path.exists(), "{path:?}"); + assert!(std::fs::metadata(&path).expect("stat output").len() > 0, "{path:?}"); + } + // An input with such a name is still refused. + let (code, err) = run(vec!["info".into(), latin1("dxf").into()]); + assert_eq!(code, 1); + assert!(err.contains("not valid Unicode"), "{err}"); +} + +/// An output that is an input file is refused before any work (exit 2, the input untouched) unless +/// `--in-place` allows it; the same file under another spelling counts, another existing file doesn't. +#[test] +fn output_that_replaces_an_input() { + let s = Scratch::new("inplace"); + let dir = s.0.to_str().expect("utf-8 path").to_string(); + let b = format!("{dir}/b.dxf"); + let original = std::fs::read(&b).expect("read input"); + std::fs::create_dir_all(format!("{dir}/sub")).expect("create sub"); + let dotted = format!("{dir}/sub/../b.dxf"); + #[allow(unused_mut)] + let mut spellings = vec![b.clone(), dotted]; + #[cfg(unix)] + { + let link = format!("{dir}/link.dxf"); + std::os::unix::fs::symlink(&b, &link).expect("symlink"); + spellings.push(link); + } + for out in &spellings { + for args in [vec!["convert", &b, out], vec!["run", &b, "--save", out], vec!["run", &b, "--export", out]] { + let r = invoke(&args); + assert_eq!(r.code, 2, "{args:?}: {}", r.stderr); + assert!(r.stdout.is_empty(), "{args:?}"); + assert!(r.stderr.starts_with(&format!("error: {out} is an input file")), "{args:?}: {}", r.stderr); + assert!(r.stderr.contains("--in-place"), "{args:?}: {}", r.stderr); + assert_eq!(std::fs::read(&b).expect("read input"), original, "{args:?}: input changed"); + } + } + + // Another existing file is replaced as before. + let other = format!("{dir}/other.dxf"); + std::fs::write(&other, "x").expect("write other"); + let r = invoke(&["convert", &b, &other]); + assert_eq!(r.code, 0, "{}", r.stderr); + assert_ne!(std::fs::read(&other).expect("read other"), b"x"); + + // --in-place allows it, for each spelling and flag: the input itself is rewritten, and a + // symlink stays a link to it. + let line = "line {\"points\":[[0,0],[1,1]]}"; + let lines = |p: &str| std::fs::read_to_string(p).expect("read input").lines().filter(|l| l.trim_end() == "LINE").count(); + let before = lines(&b); + for out in &spellings { + std::fs::write(&b, &original).expect("restore input"); + let r = invoke(&["convert", &b, out, "--in-place"]); + assert_eq!(r.code, 0, "convert {out}: {}", r.stderr); + assert_eq!(lines(&b), before, "convert {out} keeps the drawing"); + for flag in ["--save", "--export"] { + std::fs::write(&b, &original).expect("restore input"); + let r = invoke(&["run", &b, "--cmd", line, "--in-place", flag, out]); + assert_eq!(r.code, 0, "{flag} {out}: {}", r.stderr); + assert_eq!(lines(&b), before + 1, "{flag} {out}: the input gains the line"); + } + } + #[cfg(unix)] + { + let link = format!("{dir}/link.dxf"); + assert!(std::fs::symlink_metadata(&link).expect("stat link").file_type().is_symlink(), "{link} is still a symlink"); + } + + // An output that doesn't exist yet is never an input. + let new = format!("{dir}/new.dxf"); + let r = invoke(&["run", &b, "--save", &new]); + assert_eq!(r.code, 0, "{}", r.stderr); + assert!(std::path::Path::new(&new).is_file(), "{new} written"); +} + +/// JSON results are pretty-printed; `--compact` puts each on one line (RFC-0012 rule 1.3). `run` +/// prints one line per `--cmd` result either way. +#[test] +fn json_output_is_pretty_unless_compact() { + let s = Scratch::new("compact"); + let b = format!("{}/b.dxf", s.0.to_str().expect("utf-8 path")); + for args in [&["info", b.as_str()][..], &["commands", "ellipse"]] { + let help = invoke(&[args[0], "--help"]); + assert!( + help.stdout.contains("--compact") && help.stdout.contains("One line of JSON instead of pretty-printed"), + "{} --help: {}", + args[0], + help.stdout + ); + let pretty = invoke(args); + assert_eq!(pretty.code, 0, "{args:?}: {}", pretty.stderr); + assert!(pretty.stdout.lines().count() > 1, "{args:?} is pretty-printed: {}", pretty.stdout); + let compact = invoke(&[args, &["--compact"]].concat()); + assert_eq!(compact.code, 0, "{args:?} --compact: {}", compact.stderr); + assert_eq!(compact.stdout.lines().count(), 1, "{args:?} --compact is one line: {}", compact.stdout); + let a: serde_json::Value = serde_json::from_str(&pretty.stdout).expect("pretty JSON"); + let c: serde_json::Value = serde_json::from_str(&compact.stdout).expect("compact JSON"); + assert_eq!(a, c, "{args:?}: same JSON either way"); + } + let r = invoke(&["run", "--sample", "--cmd", "drawing.inspect", "--cmd", "drawing.inspect"]); + assert_eq!(r.code, 0, "{}", r.stderr); + assert_eq!(r.stdout.lines().count(), 2, "one line per --cmd result: {}", r.stdout); + assert_eq!(invoke(&["run", "--sample", "--compact"]).code, 2, "run takes no --compact"); +} diff --git a/apps/cadcraft-cli/tests/man_and_completions.rs b/apps/cadcraft-cli/tests/man_and_completions.rs new file mode 100644 index 000000000..df6dea90c --- /dev/null +++ b/apps/cadcraft-cli/tests/man_and_completions.rs @@ -0,0 +1,30 @@ +//! The clap definition is consistent, and `examples/man-and-completions.rs` writes every shell's +//! completions and every man page under the names `packaging/linux/package.sh` installs. + +// The example itself, so the test runs its code; its `main` is unused here. +#[allow(dead_code)] +#[path = "../examples/man-and-completions.rs"] +mod example; + +#[test] +fn command_is_consistent() { + cadcraft_cli::command().debug_assert(); +} + +#[test] +fn the_example_writes_the_files_the_packages_install() { + let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("man-and-completions-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + example::generate(&dir).unwrap(); + + let mut written: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().into_string().unwrap()).collect(); + written.sort(); + let completions = ["cadcraft-cli.bash", "_cadcraft-cli", "cadcraft-cli.fish", "cadcraft-cli.elv", "_cadcraft-cli.ps1"]; + let subcommands = ["info", "convert", "run", "commands", "mcp", "perf", "sample"]; + let mut expected: Vec = completions.map(String::from).into(); + expected.push("cadcraft-cli.1".into()); + expected.extend(subcommands.iter().map(|s| format!("cadcraft-cli-{s}.1"))); + expected.sort(); + assert_eq!(written, expected); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index 48c2c2d15..d8b4ef4c5 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -21,6 +21,8 @@ eframe = { workspace = true, features = ["clipboard", "wgpu", "accesskit", "wayl egui = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +clap = { workspace = true } +thiserror = { workspace = true } chrono = { workspace = true } [build-dependencies] diff --git a/apps/cadcraft/src/env.rs b/apps/cadcraft/src/env.rs new file mode 100644 index 000000000..76df8aa15 --- /dev/null +++ b/apps/cadcraft/src/env.rs @@ -0,0 +1,172 @@ +//! The `CADCRAFT_*` variables of the desktop app, read once at startup into [`Env`] and passed on +//! from there; no library crate reads them. `--help` lists them from [`VARS`]. `--control`'s +//! fallback, `CADCRAFT_CONTROL_PORT`, is clap's (see `launch_args`). + +use std::ffi::OsString; +use std::fmt::Write as _; +use std::path::PathBuf; + +use cadcraft_ui_egui::switch::Switch; + +const CONFIG_DIR: &str = "CADCRAFT_CONFIG_DIR"; +const LOCALE: &str = "CADCRAFT_LOCALE"; +const VSYNC: &str = "CADCRAFT_VSYNC"; +const WAYLAND: &str = "CADCRAFT_WAYLAND"; +const NO_NATIVE_MENU: &str = "CADCRAFT_NO_NATIVE_MENU"; +const SYSTEM_CURSOR: &str = "CADCRAFT_SYSTEM_CURSOR"; +const FONTALT: &str = "CADCRAFT_FONTALT"; +const FONTFALLBACK: &str = "CADCRAFT_FONTFALLBACK"; + +/// Every variable [`Env`] reads, with its `--help` line. +pub(crate) const VARS: &[(&str, &str)] = &[ + (CONFIG_DIR, "the settings folder (logs, autosave, workspace, plotters); empty means no settings folder"), + (LOCALE, "the interface language, instead of the system's"), + (VSYNC, "1 presents with vsync, 0 without it (default: without on Linux and BSD)"), + (WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"), + (NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"), + (SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"), + (FONTALT, "the font that replaces a missing one"), + (FONTFALLBACK, "the fonts tried, in order, for characters a font lacks"), +]; + +/// The process environment, read once at startup. A blank variable counts as unset, except +/// `CADCRAFT_CONFIG_DIR`. +#[derive(Debug, PartialEq)] +pub(crate) struct Env { + /// The settings folder (logs, autosave, workspace, plotters): `CADCRAFT_CONFIG_DIR`; else, when + /// that is unset, the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no + /// folder, because the variable is empty or blank (the way to run without one) or the + /// platform has none. + pub(crate) config_dir: Option, + /// The interface language, instead of the system's. + pub(crate) locale: Option, + /// Present with vsync (default: off on Linux and BSD, on elsewhere). + pub(crate) vsync: Switch, + /// Keep the native Wayland backend instead of XWayland. + #[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))] + pub(crate) wayland: Switch, + /// macOS: keep the menus inside the window. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) no_native_menu: Switch, + /// Use the system cursor instead of the drawn crosshair. + pub(crate) system_cursor: Switch, + /// FONTALT at startup. + pub(crate) font_alt: Option, + /// FONTFALLBACK at startup. + pub(crate) font_fallback: Option, +} + +impl Env { + pub(crate) fn read() -> Env { + Env::from_vars(|k| std::env::var_os(k)) + } + + /// [`Env::read`] with `var` looking a variable up. + pub(crate) fn from_vars(var: impl Fn(&str) -> Option) -> Env { + let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty()); + let switch = |k: &str| Switch::parse(k, var(k).map(|v| v.to_string_lossy().into_owned()).as_deref()); + Env { + config_dir: match var(CONFIG_DIR) { + Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None, + Some(dir) => Some(PathBuf::from(dir)), + None => cadcraft_engine::settings_dir::platform(&var), + }, + locale: text(LOCALE), + vsync: switch(VSYNC), + wayland: switch(WAYLAND), + no_native_menu: switch(NO_NATIVE_MENU), + system_cursor: switch(SYSTEM_CURSOR), + font_alt: text(FONTALT), + font_fallback: text(FONTFALLBACK), + } + } +} + +/// The `--help` section that lists [`VARS`]. +pub(crate) fn help() -> String { + let width = VARS.iter().map(|(name, _)| name.len()).max().unwrap_or(0) + 3; + VARS.iter().fold(String::from("Environment:"), |mut help, (name, line)| { + let _ = write!(help, "\n {name:(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { + move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v)) + } + + #[test] + fn every_variable_read_is_in_the_help_and_every_listed_one_is_read() { + let asked = RefCell::new(Vec::new()); + Env::from_vars(|k| { + asked.borrow_mut().push(k.to_owned()); + None + }); + let ours: Vec = asked.into_inner().into_iter().filter(|k| k.starts_with("CADCRAFT_")).collect(); + let help = help(); + let unset = Env::from_vars(|_| None); + for k in &ours { + assert!(VARS.iter().any(|(name, _)| name == k), "{k} is read but not in VARS"); + } + for (name, line) in VARS { + assert!(ours.iter().any(|k| k == name), "{name} is in VARS but not read"); + assert_ne!(Env::from_vars(env(&[(name, "1")])), unset, "{name} sets no field"); + assert!(help.lines().any(|l| l.trim_start().starts_with(name) && l.ends_with(line)), "{help}"); + } + } + + #[test] + fn values_are_read_and_blank_ones_are_unset() { + let vars = [ + (CONFIG_DIR, "/private/cc"), + ("HOME", "/home/u"), + ("XDG_CONFIG_HOME", "/x"), + ("APPDATA", "C:\\a"), + (LOCALE, "cs-CZ"), + (VSYNC, " On "), + (WAYLAND, "0"), + (NO_NATIVE_MENU, "yes"), + (SYSTEM_CURSOR, "maybe"), + (FONTALT, "Noto Sans"), + (FONTFALLBACK, "Vazirmatn, msjh.ttc"), + ]; + let read = Env::from_vars(env(&vars)); + assert_eq!( + read, + Env { + config_dir: Some(PathBuf::from("/private/cc")), + locale: Some("cs-CZ".into()), + vsync: Switch::On, + wayland: Switch::Off, + no_native_menu: Switch::On, + system_cursor: Switch::Default, + font_alt: Some("Noto Sans".into()), + font_fallback: Some("Vazirmatn, msjh.ttc".into()), + } + ); + let blank = vars.map(|(k, _)| (k, if k == FONTALT { " " } else { "" })); + let read = Env::from_vars(env(&blank)); + assert_eq!(read.config_dir, None, "an empty variable means no directory, not the working directory"); + assert_eq!((read.locale, read.font_alt, read.font_fallback), (None, None, None)); + assert_eq!([read.vsync, read.wayland, read.no_native_menu, read.system_cursor], [Switch::Default; 4]); + } + + #[test] + fn config_dir_unset_is_the_platform_folder_set_is_that_folder_blank_is_none() { + let platform = [("HOME", "/home/u"), ("XDG_CONFIG_HOME", "/x"), ("APPDATA", "C:\\a")]; + let expected = cadcraft_engine::settings_dir::platform(env(&platform)); + assert!(expected.is_some()); + assert_eq!(Env::from_vars(env(&platform)).config_dir, expected); + let set = [platform.as_slice(), &[(CONFIG_DIR, "/private/cc")]].concat(); + assert_eq!(Env::from_vars(env(&set)).config_dir, Some(PathBuf::from("/private/cc"))); + for blank in ["", " "] { + let vars = [platform.as_slice(), &[(CONFIG_DIR, blank)]].concat(); + assert_eq!(Env::from_vars(env(&vars)).config_dir, None, "{blank:?} means no settings folder, not the platform's"); + } + } +} diff --git a/apps/cadcraft/src/launch_args.rs b/apps/cadcraft/src/launch_args.rs new file mode 100644 index 000000000..c6329907a --- /dev/null +++ b/apps/cadcraft/src/launch_args.rs @@ -0,0 +1,158 @@ +//! The desktop app's command line, as clap types: `cadcraft --help` comes from these doc comments +//! and its Environment section from [`crate::env::VARS`], so the help and the parsers can't disagree. Anything they don't declare is a usage error naming +//! it (exit status 2), so a typo such as `--sampel` doesn't open the window and then fail to open +//! the flag as a file; so is a flag without its value, a repeated flag and a bad port, from the +//! flag or from `CADCRAFT_CONTROL_PORT`. A value never starts with `-`, and a file whose name +//! starts with `-` goes after `--`. + +use std::ffi::OsString; +use std::path::PathBuf; + +use cadcraft_mcp::args::{blank_env_is_unset, name_env_vars}; +use clap::{Command, CommandFactory, FromArgMatches, Parser}; + +/// Opens CADCraft with the given files +#[derive(Parser)] +#[command(name = "cadcraft", version = cadcraft_engine::build_version(), after_help = crate::env::help())] +pub(crate) struct LaunchArgs { + /// Files to open. Put `--` before a name that starts with `-` + pub(crate) files: Vec, + /// Start the localhost JSON-lines control server on this port + // allow_negative_numbers makes `--control -1` a bad value rather than a missing one. + #[arg(long, value_name = "PORT", env = "CADCRAFT_CONTROL_PORT", value_parser = control_port, allow_negative_numbers = true)] + pub(crate) control: Option, + /// Open with the sample drawing + #[arg(long)] + pub(crate) sample: bool, +} + +/// The command line. An empty or blank variable counts as unset. +pub(crate) fn command() -> Command { + LaunchArgs::command().mut_args(|a| blank_env_is_unset(a, |k| std::env::var_os(k))) +} + +/// Parse the launch arguments (without the binary name) with `cmd`, from [`command`]. Old macOS +/// passes a process serial number (`-psn_…`) when launched from Finder: it is dropped first, unless +/// it comes after `--`. A bad value from a variable is a usage error naming the variable. +pub(crate) fn parse(mut cmd: Command, args: impl IntoIterator) -> Result { + let mut options = true; + let args: Vec = args + .into_iter() + .filter(|a| { + options &= a != "--"; + !(options && a.to_str().is_some_and(|s| s.starts_with("-psn_"))) + }) + .collect(); + let argv = std::iter::once(OsString::from("cadcraft")).chain(args.iter().cloned()); + let matches = cmd.try_get_matches_from_mut(argv).map_err(|e| name_env_vars(e, &cmd, &args))?; + LaunchArgs::from_arg_matches(&matches) +} + +/// A control port, for clap's `value_parser`: `--control` and `CADCRAFT_CONTROL_PORT`, which may +/// carry spaces. +fn control_port(s: &str) -> Result { + s.trim().parse().map_err(|_| NotAPort) +} + +/// A [`control_port`] value that isn't a port. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("expected a port, 0-65535")] +struct NotAPort; + +#[cfg(test)] +mod tests { + use super::*; + use clap::error::ErrorKind; + + /// Parse without the variables, so one exported where the tests run can't change them. + fn parse_args(args: &[&str]) -> Result { + parse(command().mut_args(|a| a.env(None::<&str>)), args.iter().map(OsString::from)) + } + + fn usage_error(args: &[&str]) -> String { + let Err(e) = parse_args(args) else { panic!("{args:?} parsed") }; + assert_eq!(e.exit_code(), 2, "{args:?}: {e}"); + e.to_string() + } + + #[test] + fn values_are_parsed() { + let parsed = parse_args(&["--control", " 50494 ", "--sample", "a.dxf", "b.dwg"]).unwrap(); + assert_eq!((parsed.control, parsed.sample), (Some(50494), true)); + assert_eq!(parsed.files, [PathBuf::from("a.dxf"), PathBuf::from("b.dwg")]); + let parsed = parse_args(&[]).unwrap(); + assert_eq!((parsed.control, parsed.sample, parsed.files.len()), (None, false, 0)); + } + + #[test] + fn control_port_rejects_unparseable_values_naming_them() { + for bad in ["78787", "-1", "abc", "99999999999999999999"] { + assert!(usage_error(&["--control", bad]).contains(&format!("invalid value '{bad}' for '--control '")), "{bad}"); + } + assert!(usage_error(&["--control="]).contains("invalid value '' for '--control '")); + } + + #[test] + fn usage_errors_exit_2() { + assert!(usage_error(&["--sampel"]).contains("unexpected argument '--sampel'")); + assert!(usage_error(&["--control"]).contains("a value is required for '--control '")); + // A following flag is never taken as the value. + assert!(usage_error(&["--control", "--sample"]).contains("a value is required for '--control '")); + assert!(usage_error(&["--sample", "--sample"]).contains("cannot be used multiple times")); + assert!(usage_error(&["--control", "1", "--control", "2"]).contains("cannot be used multiple times")); + } + + #[test] + fn version_stops_parsing() { + let e = parse_args(&["-V", "--control"]).err().unwrap(); + assert_eq!((e.kind(), e.exit_code()), (ErrorKind::DisplayVersion, 0)); + assert_eq!(e.to_string(), format!("{}\n", crate::version_string())); + let e = parse_args(&["--version", "--bogus"]).err().unwrap(); + assert_eq!(e.kind(), ErrorKind::DisplayVersion); + } + + #[test] + fn help_stops_parsing_and_double_dash_ends_options() { + let e = parse_args(&["-h", "--sampel", "--control"]).err().unwrap(); + assert_eq!((e.kind(), e.exit_code()), (ErrorKind::DisplayHelp, 0)); + let help = parse_args(&["--help"]).err().unwrap().to_string(); + assert!(help.contains("--control ") && help.contains("CADCRAFT_CONFIG_DIR"), "{help}"); + + assert!(usage_error(&["--sampel", "--", "--help"]).contains("unexpected argument '--sampel'")); + let parsed = parse_args(&["a.dxf", "--", "--help", "-x"]).unwrap(); + assert_eq!(parsed.files, ["a.dxf", "--help", "-x"].map(PathBuf::from)); + } + + #[test] + fn a_finder_process_serial_number_is_dropped() { + let parsed = parse_args(&["-psn_0_12345", "a.dxf"]).unwrap(); + assert_eq!(parsed.files, [PathBuf::from("a.dxf")]); + let parsed = parse_args(&["--", "-psn_x.dxf"]).unwrap(); + assert_eq!(parsed.files, [PathBuf::from("-psn_x.dxf")]); + } + + /// A name that isn't valid Unicode is kept as given. + #[cfg(unix)] + #[test] + fn non_unicode_file_names_are_kept() { + use std::os::unix::ffi::OsStringExt as _; + let latin1 = OsString::from_vec(b"caf\xe9.dxf".to_vec()); + let parsed = parse(command().mut_args(|a| a.env(None::<&str>)), [latin1.clone(), OsString::from("b.dxf")]).unwrap(); + assert_eq!(parsed.files, [PathBuf::from(&latin1), PathBuf::from("b.dxf")]); + } + + /// `--control` falls back to `PATH` here instead of `CADCRAFT_CONTROL_PORT`: `PATH` is set + /// wherever the tests run and is never a port, and tests can't set a variable (`set_var` is + /// unsafe). + #[test] + fn the_flag_wins_over_its_variable_and_a_bad_value_names_the_variable() { + let Some(path) = std::env::var_os("PATH").filter(|p| !p.is_empty()) else { return }; + let path_fallback = || command().mut_args(|a| a.env(None::<&str>)).mut_arg("control", |a| a.env("PATH")); + let e = parse(path_fallback(), []).err().unwrap(); + assert_eq!(e.exit_code(), 2); + let text = e.to_string(); + assert!(text.contains(&format!("invalid value '{}' for 'PATH'", path.to_string_lossy())), "{text}"); + assert!(!text.contains("--control '"), "{text}"); + assert_eq!(parse(path_fallback(), ["--control", "7"].map(OsString::from)).unwrap().control, Some(7)); + } +} diff --git a/apps/cadcraft/src/logging.rs b/apps/cadcraft/src/logging.rs index 4113de54f..724d09c1a 100644 --- a/apps/cadcraft/src/logging.rs +++ b/apps/cadcraft/src/logging.rs @@ -3,7 +3,7 @@ //! Without a logger every `log::warn!`/`log::error!`/`log::info!` in the workspace (a broken app //! icon, the GPU canvas set-up, the control server) vanished. A launch from a desktop menu has no //! terminal, so the file is what a bug report can attach: `/logs/cadcraft.log` -//! (`CADCRAFT_CONFIG_DIR`, or the platform settings directory; see `config_dir` in `main.rs`). +//! (`CADCRAFT_CONFIG_DIR`, or the platform settings directory; empty means none; see `env.rs`). //! Each start moves the previous log to `cadcraft.1.log` (and that one to `.2`), so the log of a //! run that crashed survives the next launch. //! diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 1007fc0c1..19546d6ce 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -1,6 +1,6 @@ //! CADCraft desktop app. //! -//! Usage: `cadcraft [--control ] [--sample] [files…]` +//! Usage: `cadcraft [--control ] [--sample] [files…]` (`cadcraft --help` lists the rest; see [`launch_args`]) //! //! `--control ` (or `CADCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server: //! `{"id":1,"method":"cmdline.input","params":{"text":"circle 0,0 5"}}` → `{"id":1,"ok":true,…}`. @@ -10,14 +10,16 @@ //! present mode (`CADCRAFT_VSYNC=0` selects that elsewhere); see `cadcraft_ui_egui::gpu::surface_config`. //! //! `log` records go to standard error and `/logs/cadcraft.log` (`RUST_LOG` sets the -//! levels); see [`logging`] and [`config_dir`]. +//! levels); see [`logging`]. The `CADCRAFT_*` variables are read once, at startup; see [`env`]. #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod control_server; mod desktop_theme; +mod env; #[cfg(any(target_os = "windows", test))] mod graphics; +mod launch_args; mod logging; #[cfg(target_os = "macos")] mod native_menu; @@ -26,6 +28,7 @@ mod system_animations; mod workspace; use cadcraft_engine::Session; +use cadcraft_ui_egui::switch::Switch; use cadcraft_ui_egui::{CadApp, Services, i18n}; struct App { @@ -39,6 +42,9 @@ struct App { workspace_error: Option, #[cfg(target_os = "macos")] native_menu: Option, + /// `CADCRAFT_NO_NATIVE_MENU`: the menus stay inside the window. + #[cfg(target_os = "macos")] + menus_in_window: bool, /// The `movable` flag last set on the main window. #[cfg(target_os = "macos")] movable: Option, @@ -88,7 +94,7 @@ impl eframe::App for App { if ctx.current_pass_index() == 0 { #[cfg(target_os = "macos")] { - if self.native_menu.is_none() && std::env::var_os("CADCRAFT_NO_NATIVE_MENU").is_none() { + if self.native_menu.is_none() && !self.menus_in_window { self.native_menu = Some(native_menu::NativeMenu::install(&mut self.cad, ctx)); } if let Some(m) = &mut self.native_menu { @@ -188,30 +194,6 @@ fn filters_for_save(name: &str) -> [(&'static str, &'static str); 6] { filters } -/// The per-user settings directory (it holds `logs/` and `autosave/`): `CADCRAFT_CONFIG_DIR` if set, else -/// `$XDG_CONFIG_HOME/cadcraft` or `~/.config/cadcraft` on Linux and the BSDs, -/// `~/Library/Application Support/CADCraft` on macOS, `%APPDATA%\CADCraft` on Windows. -fn config_dir() -> Option { - config_dir_from(|k| std::env::var_os(k)) -} - -/// [`config_dir`] with the environment passed in (`var` looks a variable up). An empty variable -/// counts as unset, so a blank value never means the working directory. -fn config_dir_from(var: impl Fn(&str) -> Option) -> Option { - let set = |k: &str| var(k).filter(|v| !v.is_empty()).map(std::path::PathBuf::from); - if let Some(dir) = set("CADCRAFT_CONFIG_DIR") { - return Some(dir); - } - if cfg!(target_os = "macos") { - set("HOME").map(|h| h.join("Library/Application Support/CADCraft")) - } else if cfg!(windows) { - set("APPDATA").map(|a| a.join("CADCraft")) - } else { - // The XDG spec ignores a relative XDG_CONFIG_HOME. - set("XDG_CONFIG_HOME").filter(|p| p.is_absolute()).or_else(|| set("HOME").map(|h| h.join(".config"))).map(|c| c.join("cadcraft")) - } -} - const APP_ID: &str = "ai.storyteller.cadcraft"; /// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`). @@ -227,32 +209,7 @@ fn app_icon() -> Option { } fn version_string() -> String { - let sha = option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"); - format!("cadcraft {} ({sha})", env!("CARGO_PKG_VERSION")) -} - -/// The control port from `--control ` or `CADCRAFT_CONTROL_PORT` (`source`); a value that is -/// not a port is logged and ignored instead of silently starting no control channel. -fn control_port_from(source: &str, value: Option) -> Option { - let value = value?; - let port = value.trim().parse().ok(); - if port.is_none() { - log::warn!("{source}: {value:?} is not a port number; the control channel is off"); - } - port -} - -/// `--control` followed by `value`: a bare `--control` (last argument) keeps the port already -/// read from `CADCRAFT_CONTROL_PORT` (`current`) instead of turning the control channel off. -fn control_flag(current: Option, value: Option) -> Option { - if value.is_some() { - return control_port_from("--control", value); - } - match current { - Some(port) => log::warn!("--control: no port given; using CADCRAFT_CONTROL_PORT ({port})"), - None => log::warn!("--control: no port given; the control channel is off"), - } - current + format!("cadcraft {}", cadcraft_engine::build_version()) } /// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe. @@ -268,37 +225,33 @@ fn main() -> eframe::Result { } return Ok(()); } - // lossy, so a value that is not Unicode is reported like any other bad port instead of ignored - let mut control_port = - control_port_from("CADCRAFT_CONTROL_PORT", std::env::var_os("CADCRAFT_CONTROL_PORT").map(|p| p.to_string_lossy().into_owned())); - let mut files = Vec::new(); - let mut sample = false; - let mut args = std::env::args().skip(1); - while let Some(a) = args.next() { - match a.as_str() { - "--control" => control_port = control_flag(control_port, args.next()), - "--sample" => sample = true, - "--version" | "-V" => { - println!("{}", version_string()); - return Ok(()); - } - _ => files.push(a), - } - } + // `--help` and `--version` print to standard output and exit 0. A usage error (an unknown or + // repeated flag, a missing or bad value, a bad CADCRAFT_CONTROL_PORT) names the argument on + // standard error and exits 2 before the window opens. + let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit()); + let vars = env::Env::read(); + let (control_port, sample, files) = (launch.control, launch.sample, launch.files); // The log file lives under the settings directory; opened after the arguments, so `--version` // leaves no file behind. Records logged until now are written to it first. if let Some(logger) = logger { - match config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) { + match vars.config_dir.as_ref().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) { Some(Ok(path)) => log::info!("{} ({} {}), log file {}", version_string(), std::env::consts::OS, std::env::consts::ARCH, path.display()), Some(Err(e)) => log::warn!("no log file: {e}"), None => { logger.stderr_only(); - log::warn!("no log file: no settings directory (set CADCRAFT_CONFIG_DIR)"); + log::warn!("no log file: no settings directory (an empty CADCRAFT_CONFIG_DIR turns it off)"); } } } install_io(); - let surface = cadcraft_ui_egui::gpu::surface_config(std::env::var("CADCRAFT_VSYNC").ok().as_deref(), cfg!(all(unix, not(target_os = "macos")))); + cadcraft_engine::settings_dir::set(vars.config_dir.clone()); + if let Some(name) = &vars.font_alt { + cadcraft_engine::fonts::ttf::set_font_alt(name); + } + if let Some(list) = &vars.font_fallback { + cadcraft_engine::fonts::ttf::set_fallback_fonts(list); + } + let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos")))); let mut options = eframe::NativeOptions { // The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11 // swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync). @@ -341,7 +294,7 @@ fn main() -> eframe::Result { // manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1 // keeps the native Wayland backend. #[cfg(all(unix, not(target_os = "macos")))] - if std::env::var_os("DISPLAY").is_some() && std::env::var_os("CADCRAFT_WAYLAND").is_none() { + if std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On { options.event_loop_builder = Some(Box::new(|b| { use winit::platform::x11::EventLoopBuilderExtX11; b.with_x11(); @@ -352,15 +305,16 @@ fn main() -> eframe::Result { options, Box::new(move |cc| { let mut app = CadApp::new(Session::empty(), services()); - let (workspace, restored, workspace_error) = workspace::Workspace::load(); + let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref()); if let Some(ui) = restored { app.ui = ui; } + app.set_system_cursor_default(vars.system_cursor == Switch::On); if let Some(error) = &workspace_error { eprintln!("CADCraft workspace: {error}"); app.set_status(error); } - app.system_languages = std::env::var("CADCRAFT_LOCALE").map(|s| vec![s]).unwrap_or_else(|_| sys_locale::get_locales().collect()); + app.system_languages = vars.locale.map(|s| vec![s]).unwrap_or_else(|| sys_locale::get_locales().collect()); // The user profile (Options): drafting settings, selection sizes, drawing-area colours. if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) { app.load_profile(&profile); @@ -372,7 +326,7 @@ fn main() -> eframe::Result { cadcraft_ui_egui::autosave::load_prefs(&prefs); } // Autosave files (SAVEFILEPATH) default to `/autosave`. - if let Some(dir) = config_dir() { + if let Some(dir) = &vars.config_dir { app.enable_autosave(&dir.join("autosave")); app.enable_update_check(); // Startup LISP (acad.lsp, acaddoc.lsp) is read from `/support`; the @@ -419,6 +373,8 @@ fn main() -> eframe::Result { #[cfg(target_os = "macos")] native_menu: None, #[cfg(target_os = "macos")] + menus_in_window: vars.no_native_menu == Switch::On, + #[cfg(target_os = "macos")] movable: None, })) }), @@ -427,13 +383,7 @@ fn main() -> eframe::Result { #[cfg(test)] mod tests { - use super::{config_dir_from, control_flag, control_port_from, filters_for_save, follow_desktop}; - use std::ffi::OsString; - use std::path::PathBuf; - - fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { - move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v)) - } + use super::{filters_for_save, follow_desktop}; #[test] fn save_dialog_offers_dwg_with_the_drawing_format_first() { @@ -451,59 +401,6 @@ mod tests { } } - #[test] - fn control_port_values_that_are_not_ports_are_ignored() { - assert_eq!(control_port_from("--control", Some("7979".into())), Some(7979)); - assert_eq!(control_port_from("--control", Some(" 7979 ".into())), Some(7979)); - assert_eq!(control_port_from("--control", None), None); - for bad in ["", "abc", "-1", "65536", "99999999999999999999", "\u{0}"] { - assert_eq!(control_port_from("--control", Some(bad.into())), None, "{bad:?}"); - } - } - - #[test] - fn control_without_a_port_keeps_the_environment_port() { - // `CADCRAFT_CONTROL_PORT=47321 cadcraft --control` (#844) - assert_eq!(control_flag(Some(47321), None), Some(47321)); - assert_eq!(control_flag(None, None), None); - // A port given on the command line still wins over the variable. - assert_eq!(control_flag(Some(47321), Some("7979".into())), Some(7979)); - assert_eq!(control_flag(Some(47321), Some("abc".into())), None); - } - - #[test] - fn the_override_variable_wins_and_empty_values_are_unset() { - let vars = [("CADCRAFT_CONFIG_DIR", "/tmp/cc"), ("HOME", "/home/u"), ("XDG_CONFIG_HOME", "/x"), ("APPDATA", "C:\\a")]; - assert_eq!(config_dir_from(env(&vars)), Some(PathBuf::from("/tmp/cc"))); - let empty = [("CADCRAFT_CONFIG_DIR", ""), ("HOME", ""), ("XDG_CONFIG_HOME", ""), ("APPDATA", "")]; - assert_eq!(config_dir_from(env(&empty)), None, "no usable variable means no directory, not the working directory"); - assert_eq!(config_dir_from(env(&[])), None); - } - - #[cfg(all(unix, not(target_os = "macos")))] - #[test] - fn linux_and_bsd_follow_xdg_config_home() { - assert_eq!(config_dir_from(env(&[("XDG_CONFIG_HOME", "/x"), ("HOME", "/home/u")])), Some(PathBuf::from("/x/cadcraft"))); - assert_eq!(config_dir_from(env(&[("HOME", "/home/u")])), Some(PathBuf::from("/home/u/.config/cadcraft"))); - // The XDG spec says a relative XDG_CONFIG_HOME is ignored. - assert_eq!(config_dir_from(env(&[("XDG_CONFIG_HOME", "rel"), ("HOME", "/home/u")])), Some(PathBuf::from("/home/u/.config/cadcraft"))); - } - - #[cfg(target_os = "macos")] - #[test] - fn macos_uses_application_support() { - assert_eq!(config_dir_from(env(&[("HOME", "/Users/u")])), Some(PathBuf::from("/Users/u/Library/Application Support/CADCraft"))); - } - - #[cfg(windows)] - #[test] - fn windows_uses_appdata() { - assert_eq!( - config_dir_from(env(&[("APPDATA", "C:\\Users\\u\\AppData\\Roaming")])), - Some(PathBuf::from("C:\\Users\\u\\AppData\\Roaming").join("CADCraft")) - ); - } - /// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in; /// without one (or where winit answers and the desktop doesn't) the input is left alone. #[test] diff --git a/apps/cadcraft/src/workspace.rs b/apps/cadcraft/src/workspace.rs index b8e541ed3..b75c9bc70 100644 --- a/apps/cadcraft/src/workspace.rs +++ b/apps/cadcraft/src/workspace.rs @@ -1,6 +1,5 @@ //! Native workspace preferences. Drawing data and transient dialogs never enter this file. -use std::ffi::OsString; use std::fs::{self, File, OpenOptions}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; @@ -24,18 +23,6 @@ pub struct Workspace { last_write: Option, } -fn config_dir_from(platform: &str, get: impl Fn(&str) -> Option) -> Option { - if let Some(root) = get("CADCRAFT_CONFIG_DIR") { - return (!root.is_empty()).then(|| PathBuf::from(root)); - } - let nonempty = |key| get(key).filter(|value| !value.is_empty()).map(PathBuf::from); - match platform { - "macos" => nonempty("HOME").map(|home| home.join("Library/Application Support/CADCraft")), - "windows" => nonempty("APPDATA").map(|root| root.join("CADCraft")), - _ => nonempty("XDG_CONFIG_HOME").map(|root| root.join("cadcraft")).or_else(|| nonempty("HOME").map(|home| home.join(".config/cadcraft"))), - } -} - fn snapshot(ui: &UiState) -> Result { cadcraft_ui_egui::docking::validate(&ui.docking)?; if !matches!(ui.toolset_tab.as_str(), "Drafting" | "Modeling") { @@ -139,8 +126,9 @@ fn write(path: &Path, workspace: &Value) -> Result<(), String> { } impl Workspace { - pub fn load() -> (Self, Option, Option) { - Self::at(config_dir_from(std::env::consts::OS, |key| std::env::var_os(key)).map(|root| root.join("workspace.json"))) + /// The workspace file in the settings directory `config_dir`; without one nothing is kept. + pub fn load(config_dir: Option<&Path>) -> (Self, Option, Option) { + Self::at(config_dir.map(|root| root.join("workspace.json"))) } fn at(path: Option) -> (Self, Option, Option) { @@ -195,6 +183,7 @@ impl Workspace { #[cfg(test)] mod tests { use super::*; + use std::ffi::OsString; fn temp_dir() -> PathBuf { let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); @@ -205,20 +194,18 @@ mod tests { #[test] fn profile_override_isolated_or_explicitly_disabled() { - let get = |key: &str| match key { - "CADCRAFT_CONFIG_DIR" => Some(OsString::from("/private/test-state")), - "HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some(OsString::from("/unrelated-user-profile")), - _ => None, + let vars = |config: Option<&'static str>| { + move |key: &str| match key { + "CADCRAFT_CONFIG_DIR" => config.map(OsString::from), + "HOME" | "APPDATA" | "XDG_CONFIG_HOME" => Some(OsString::from("/unrelated-user-profile")), + _ => None, + } }; - for platform in ["macos", "windows", "linux", "freebsd"] { - assert_eq!(config_dir_from(platform, get), Some(PathBuf::from("/private/test-state"))); - assert_eq!(config_dir_from(platform, |key| if key == "CADCRAFT_CONFIG_DIR" { Some(OsString::new()) } else { get(key) }), None); - } - assert_eq!( - config_dir_from("linux", |key| (key == "XDG_CONFIG_HOME").then(|| OsString::from("/config"))), - Some(PathBuf::from("/config/cadcraft")) - ); - assert_eq!(config_dir_from("macos", |_| None), None); + let dir = |config| crate::env::Env::from_vars(vars(config)).config_dir; + assert_eq!(dir(Some("/private/test-state")), Some(PathBuf::from("/private/test-state"))); + assert_eq!(dir(Some("")), None); + let (_, restored, error) = Workspace::load(dir(Some("")).as_deref()); + assert!(restored.is_none() && error.is_none(), "no settings folder, no workspace file"); } #[test] diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs new file mode 100644 index 000000000..132a8c1aa --- /dev/null +++ b/crates/doc/src/format.rs @@ -0,0 +1,100 @@ +use std::path::Path; + +/// A file format, chosen by the file name's extension (ASCII case-insensitive). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + Dxf, + Dwg, + /// A drawing template: DWG content. + Dwt, + Svg, + /// Gzip-compressed SVG. + Svgz, + Png, + Pdf, +} + +impl Format { + /// The formats a drawing can be read from by name. DXF and DWG are also recognised by content. + pub const READ: &'static [Format] = &[Format::Dxf, Format::Dwg, Format::Svg, Format::Svgz]; + /// The formats a drawing can be written to. + pub const WRITE: &'static [Format] = &[Format::Dxf, Format::Dwg, Format::Dwt, Format::Svg, Format::Png, Format::Pdf]; + + /// The format `path`'s extension names. A name without an extension is DXF; an unknown + /// extension is `None`. + pub fn from_path(p: impl AsRef) -> Option { + let ext = p.as_ref().extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + Some(match ext.as_str() { + "dxf" | "" => Format::Dxf, + "dwg" => Format::Dwg, + "dwt" => Format::Dwt, + "svg" => Format::Svg, + "svgz" => Format::Svgz, + "png" => Format::Png, + "pdf" => Format::Pdf, + _ => return None, + }) + } + + /// The extension, lower case and without the dot. + pub fn extension(self) -> &'static str { + match self { + Format::Dxf => "dxf", + Format::Dwg => "dwg", + Format::Dwt => "dwt", + Format::Svg => "svg", + Format::Svgz => "svgz", + Format::Png => "png", + Format::Pdf => "pdf", + } + } + + /// Written as an image (model space fitted to a frame), so framing applies. SVGZ is read only. + pub fn is_image(self) -> bool { + matches!(self, Format::Svg | Format::Png | Format::Pdf) + } + + /// A drawing file (DXF, DWG, template) rather than an image. + pub fn is_drawing(self) -> bool { + matches!(self, Format::Dxf | Format::Dwg | Format::Dwt) + } + + /// Written as DWG, which drops the object types the DWG writer doesn't know. + pub fn drops_unknown(self) -> bool { + matches!(self, Format::Dwg | Format::Dwt) + } + + /// `formats` as "dxf, dwg, svg": the list help text shows. + pub fn list(formats: &[Format]) -> String { + formats.iter().map(|f| f.extension()).collect::>().join(", ") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn from_path_by_extension() { + for f in [Format::Dxf, Format::Dwg, Format::Dwt, Format::Svg, Format::Svgz, Format::Png, Format::Pdf] { + assert_eq!(Format::from_path(format!("a/b.{}", f.extension())), Some(f)); + assert_eq!(Format::from_path(format!("B.{}", f.extension().to_ascii_uppercase())), Some(f)); + } + assert_eq!(Format::from_path("Drawing1"), Some(Format::Dxf), "no extension is DXF"); + assert_eq!(Format::from_path("dir.dwg/Drawing1"), Some(Format::Dxf)); + assert_eq!(Format::from_path("a."), Some(Format::Dxf)); + assert_eq!(Format::from_path("a.txt"), None); + assert_eq!(Format::from_path("a.dxf.bak"), None); + assert_eq!(Format::from_path(std::path::Path::new("x.PnG")), Some(Format::Png)); + } + + #[test] + fn classes() { + assert!(Format::READ.contains(&Format::Svgz) && !Format::WRITE.contains(&Format::Svgz)); + assert!(Format::WRITE.contains(&Format::Dwt) && !Format::READ.contains(&Format::Dwt)); + assert!(Format::WRITE.iter().filter(|f| f.is_image()).count() == 3 && !Format::Svgz.is_image()); + assert!(Format::Dwt.drops_unknown() && Format::Dwg.drops_unknown() && !Format::Dxf.drops_unknown()); + assert!(Format::Dwt.is_drawing() && !Format::Pdf.is_drawing()); + assert_eq!(Format::list(Format::READ), "dxf, dwg, svg, svgz"); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index eafea9e27..d970a6a56 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -10,6 +10,7 @@ mod array; mod constraint; mod entity; mod extents; +mod format; mod gdt; mod header; pub mod library; @@ -27,6 +28,7 @@ pub use cadcraft_geom as geom; pub use constraint::*; pub use entity::*; pub use extents::{MAX_BLOCK_DEPTH, entity_bounds}; +pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; pub use plotstyle::*; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 95975a4e2..3a5296e88 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -7,7 +7,7 @@ mod template; use std::sync::OnceLock; -use cadcraft_doc::Drawing; +use cadcraft_doc::{Drawing, Format}; pub use cadcraft_dxf::Version; use serde_json::{Value, json}; @@ -136,8 +136,7 @@ fn save_options(cmd: &str, p: &Value) -> Result { /// Whether `path` names a DXF file (or has no extension, which saves as DXF). fn is_dxf(path: &str) -> bool { - let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - matches!(ext.as_str(), "dxf" | "") + Format::from_path(path) == Some(Format::Dxf) } /// The drawing written to `path` with `opts`: through [`IoHooks::write`] when no option is set, @@ -273,17 +272,21 @@ pub struct ReadFile { } /// Read and decode `path` (the slow half of `OPEN {path}`). Needs no session; runs anywhere. -pub fn read_file(path: &str) -> std::result::Result { +pub fn read_file(path: &std::path::Path) -> std::result::Result { #[cfg(not(target_arch = "wasm32"))] { let r = std::panic::catch_unwind(|| { - let bytes = - crate::capped_read::read_capped(std::path::Path::new(path), MAX_DRAWING_BYTES).map_err(|e| bad("open", format!("{path}: {e}")))?; - read_bytes(&bytes, path, Some(path.to_string())) + let shown = path.display(); + // The session keeps paths as text; a name that isn't Unicode could never be saved back to. + let Some(text_path) = path.to_str() else { + return Err(bad("open", format!("{shown}: the file name is not valid Unicode, so CADCraft can't save back to it"))); + }; + let bytes = crate::capped_read::read_capped(path, MAX_DRAWING_BYTES).map_err(|e| bad("open", format!("{shown}: {e}")))?; + read_bytes(&bytes, text_path, Some(text_path.to_string())) }); match r { Ok(r) => r.map_err(|e| e.to_string()), - Err(_) => Err(bad("open", format!("{path}: the file could not be read")).to_string()), + Err(_) => Err(bad("open", format!("{}: the file could not be read", path.display())).to_string()), } } #[cfg(target_arch = "wasm32")] @@ -515,7 +518,7 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result { let lost = not_saved_as(s.doc()?, version); let bytes = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?; let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() }); - if drops_unknown(&format!("drawing.{fmt}")) { + if drops_unknown(format!("drawing.{fmt}")) { report_not_saved(s, &mut r, &lost); } Ok(r) @@ -563,15 +566,13 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap) -> Op /// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG /// bridge drops types it doesn't know); DXF writes them back as read. -pub fn drops_unknown(path: &str) -> bool { - // Templates (.dwt) are written as DWG too. - std::path::Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("dwg") || e.eq_ignore_ascii_case("dwt")) +pub fn drops_unknown(path: impl AsRef) -> bool { + Format::from_path(path).is_some_and(Format::drops_unknown) } /// Whether `path` is saved as a drawing (DXF, DWG) rather than exported as an image. -fn is_drawing_file(path: &str) -> bool { - let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - matches!(ext.as_str(), "dxf" | "dwg" | "dwt" | "") +fn is_drawing_file(path: impl AsRef) -> bool { + Format::from_path(path).is_some_and(Format::is_drawing) } /// Say on the command line what the file couldn't keep, and list it in the result's `notSaved`. diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 370f03518..903ef1bc4 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -61,23 +61,13 @@ impl PlotterStore { } } - /// The `plotters` folder of the CADCraft settings directory (`CADCRAFT_CONFIG_DIR`, else - /// the platform's settings directory). + /// The `plotters` folder of the CADCraft settings directory ([`crate::settings_dir::current`]). #[cfg(not(target_arch = "wasm32"))] pub fn settings_folder() -> PlotterStore { fn dir() -> std::result::Result { - use std::path::PathBuf; - let get = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from); - let root = match std::env::var_os("CADCRAFT_CONFIG_DIR") { - Some(r) if !r.is_empty() => Some(PathBuf::from(r)), - Some(_) => None, - None => match std::env::consts::OS { - "macos" => get("HOME").map(|h| h.join("Library/Application Support/CADCraft")), - "windows" => get("APPDATA").map(|r| r.join("CADCraft")), - _ => get("XDG_CONFIG_HOME").map(|r| r.join("cadcraft")).or_else(|| get("HOME").map(|h| h.join(".config/cadcraft"))), - }, - }; - root.map(|r| r.join("plotters")).ok_or_else(|| "there is no settings folder for plotter configurations".to_string()) + crate::settings_dir::current() + .map(|r| r.join("plotters")) + .ok_or_else(|| "there is no settings folder for plotter configurations".to_string()) } /// A plain file name of ours (no separators, no parent references). fn file(n: &str) -> std::result::Result { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index caeda8d7d..dbb1d0e6b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,7 @@ pub mod prompt; mod recent; pub mod sample; pub mod select; +pub mod settings_dir; pub mod snap; pub mod spatial; pub mod sysvars; @@ -43,6 +44,7 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; pub use cadcraft_doc as doc; +pub use cadcraft_fonts as fonts; pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; @@ -64,6 +66,14 @@ pub use running::{PendingWindow, Running}; pub use settings::Settings; pub use view::{ModelTile, ModelTiles, View}; +/// ` ()`, what `--version` prints after the program name in the app and the CLI. +/// The commit comes from `CADCRAFT_BUILD_SHA` at build time, `dev` without it. +pub fn build_version() -> &'static str { + static VERSION: std::sync::LazyLock = + std::sync::LazyLock::new(|| format!("{} ({})", env!("CARGO_PKG_VERSION"), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))); + &VERSION +} + /// The editor session: open drawings, settings, the running command and the command log. pub struct Session { pub docs: Vec, diff --git a/crates/engine/src/lisp/builtins/files.rs b/crates/engine/src/lisp/builtins/files.rs index f97045a2b..44452ae89 100644 --- a/crates/engine/src/lisp/builtins/files.rs +++ b/crates/engine/src/lisp/builtins/files.rs @@ -73,17 +73,17 @@ pub(super) fn findfile(a: &[Value]) -> R { /// Read a regular text file up to 64 MiB, replacing invalid UTF-8 and returning `None` on read failure. #[cfg(not(target_arch = "wasm32"))] -pub fn read_text_file(path: &str) -> Option { +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; - let bytes = crate::capped_read::read_capped(std::path::Path::new(path), MAX).ok()?; + let bytes = crate::capped_read::read_capped(path.as_ref(), MAX).ok()?; Some(String::from_utf8_lossy(&bytes).into_owned()) } /// Return `None` on the web, where native filesystem paths are unavailable. #[cfg(target_arch = "wasm32")] -pub fn read_text_file(_path: &str) -> Option { +pub fn read_text_file(_path: impl AsRef) -> Option { None } diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index b4076fce6..0042ea434 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -1097,5 +1097,5 @@ pub fn load_source(s: &Session, name: &str) -> Option { // 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)) + candidates.iter().chain(&support).find_map(super::builtins::read_text_file) } diff --git a/crates/engine/src/lisp/startup.rs b/crates/engine/src/lisp/startup.rs index 118f4e7a1..392f88095 100644 --- a/crates/engine/src/lisp/startup.rs +++ b/crates/engine/src/lisp/startup.rs @@ -42,7 +42,7 @@ impl Session { if once && self.lisp.acad_loaded && !per_drawing { continue; } - let Some(text) = super::builtins::read_text_file(&dir.join(name).to_string_lossy()) else { continue }; + let Some(text) = super::builtins::read_text_file(dir.join(name)) else { continue }; if once { self.lisp.acad_loaded = true; } diff --git a/crates/engine/src/settings_dir.rs b/crates/engine/src/settings_dir.rs new file mode 100644 index 000000000..689a5ade2 --- /dev/null +++ b/crates/engine/src/settings_dir.rs @@ -0,0 +1,82 @@ +//! The per-user CADCraft settings directory (logs, autosave, plotter configurations). The host +//! chooses it ([`set`], possibly to none); without a choice it is the platform's ([`platform`]). + +use std::ffi::OsString; +use std::path::PathBuf; +use std::sync::Mutex; + +/// `None`: no choice yet; `Some(None)`: the host chose to have no settings directory. +static CHOSEN: Mutex>> = Mutex::new(None); + +/// The platform's settings directory, with `var` looking up the OS variables: `$XDG_CONFIG_HOME/cadcraft` +/// or `~/.config/cadcraft` on Linux and the BSDs, `~/Library/Application Support/CADCraft` on +/// macOS, `%APPDATA%\CADCraft` on Windows. An empty variable counts as unset, so a blank value +/// never means the working directory. +pub fn platform(var: impl Fn(&str) -> Option) -> Option { + let set = |k: &str| var(k).filter(|v| !v.is_empty()).map(PathBuf::from); + if cfg!(target_os = "macos") { + set("HOME").map(|h| h.join("Library/Application Support/CADCraft")) + } else if cfg!(windows) { + set("APPDATA").map(|a| a.join("CADCraft")) + } else { + // The XDG spec ignores a relative XDG_CONFIG_HOME. + set("XDG_CONFIG_HOME").filter(|p| p.is_absolute()).or_else(|| set("HOME").map(|h| h.join(".config"))).map(|c| c.join("cadcraft")) + } +} + +/// Use `dir` as the settings directory; `None` means there is none (plotter configurations are +/// neither read nor written). +pub fn set(dir: Option) { + if let Ok(mut chosen) = CHOSEN.lock() { + *chosen = Some(dir); + } +} + +/// The settings directory: the host's choice, else the platform's. +pub fn current() -> Option { + match CHOSEN.lock().ok().and_then(|c| c.clone()) { + Some(choice) => choice, + None => platform(|k| std::env::var_os(k)), + } +} + +#[cfg(test)] +mod tests { + use super::platform; + use std::ffi::OsString; + use std::path::PathBuf; + + fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { + move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v)) + } + + #[test] + fn empty_values_are_unset() { + assert_eq!(platform(env(&[("HOME", ""), ("XDG_CONFIG_HOME", ""), ("APPDATA", "")])), None, "not the working directory"); + assert_eq!(platform(env(&[])), None); + } + + #[cfg(all(unix, not(target_os = "macos")))] + #[test] + fn linux_and_bsd_follow_xdg_config_home() { + assert_eq!(platform(env(&[("XDG_CONFIG_HOME", "/x"), ("HOME", "/home/u")])), Some(PathBuf::from("/x/cadcraft"))); + assert_eq!(platform(env(&[("HOME", "/home/u")])), Some(PathBuf::from("/home/u/.config/cadcraft"))); + // The XDG spec says a relative XDG_CONFIG_HOME is ignored. + assert_eq!(platform(env(&[("XDG_CONFIG_HOME", "rel"), ("HOME", "/home/u")])), Some(PathBuf::from("/home/u/.config/cadcraft"))); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_uses_application_support() { + assert_eq!(platform(env(&[("HOME", "/Users/u")])), Some(PathBuf::from("/Users/u/Library/Application Support/CADCraft"))); + } + + #[cfg(windows)] + #[test] + fn windows_uses_appdata() { + assert_eq!( + platform(env(&[("APPDATA", "C:\\Users\\u\\AppData\\Roaming")])), + Some(PathBuf::from("C:\\Users\\u\\AppData\\Roaming").join("CADCraft")) + ); + } +} diff --git a/crates/engine/tests/read_file_unicode.rs b/crates/engine/tests/read_file_unicode.rs new file mode 100644 index 000000000..4c3c520e8 --- /dev/null +++ b/crates/engine/tests/read_file_unicode.rs @@ -0,0 +1,25 @@ +//! A drawing path that isn't valid Unicode is refused: the session keeps paths as text, so it +//! could never be saved back to. + +#![cfg(unix)] + +use std::ffi::OsString; +use std::os::unix::ffi::OsStringExt; + +use cadcraft_doc::Drawing; +use cadcraft_engine::cmd::file::{IoHooks, read_file, set_io}; + +#[test] +fn read_file_refuses_a_name_that_is_not_unicode() { + set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(Vec::new()), plot: None }); + let dir = std::env::temp_dir().join(format!("cadcraft-nonunicode-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let good = dir.join("good.dxf"); + let bad = dir.join(OsString::from_vec(b"bad-\xff.dxf".to_vec())); + std::fs::write(&good, b"0\nEOF\n").unwrap(); + std::fs::write(&bad, b"0\nEOF\n").unwrap(); + let e = read_file(&bad).err().expect("a non-Unicode name is refused"); + assert!(e.contains("not valid Unicode") && e.contains("bad-"), "{e}"); + assert!(read_file(&good).is_ok()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/xref.rs b/crates/engine/tests/xref.rs index 405f71c66..d53e37886 100644 --- a/crates/engine/tests/xref.rs +++ b/crates/engine/tests/xref.rs @@ -29,7 +29,7 @@ fn folder(tag: &str) -> PathBuf { } fn save(d: &Drawing, path: &Path) { - std::fs::write(path, cadcraft_io::write(d, &path.to_string_lossy()).unwrap()).unwrap(); + std::fs::write(path, cadcraft_io::write(d, path).unwrap()).unwrap(); } fn line(d: &mut Drawing, layer: &str, a: (f64, f64), b: (f64, f64)) { diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 52998900c..6b4c5ebdd 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -11,8 +11,7 @@ //! - [`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. //! -//! On native builds both start from the `CADCRAFT_FONTALT` / `CADCRAFT_FONTFALLBACK` -//! environment variables. +//! Both start empty; the host sets its starting values ([`set_font_alt`], [`set_fallback_fonts`]). use std::collections::HashMap; use std::path::PathBuf; @@ -524,16 +523,8 @@ struct Prefs { } fn prefs() -> MutexGuard<'static, Prefs> { - static P: OnceLock> = OnceLock::new(); - P.get_or_init(|| { - #[cfg(not(target_arch = "wasm32"))] - let env = |k: &str| std::env::var(k).unwrap_or_default(); - #[cfg(target_arch = "wasm32")] - let env = |_: &str| String::new(); - Mutex::new(Prefs { alt: clean_name(&env("CADCRAFT_FONTALT")), fallback: split_list(&env("CADCRAFT_FONTFALLBACK")) }) - }) - .lock() - .unwrap_or_else(PoisonError::into_inner) + static P: Mutex = Mutex::new(Prefs { alt: String::new(), fallback: Vec::new() }); + P.lock().unwrap_or_else(PoisonError::into_inner) } /// A font name setting: trimmed, capped, "." = none. diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ef56e6602..8cad3f24f 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -22,7 +22,9 @@ mod dxf_mline; use cadcraft_doc::{Drawing, Space}; use cadcraft_geom::Bounds2; +use std::path::{Path, PathBuf}; +pub use cadcraft_doc::Format; pub use cadcraft_dxf::Version; pub use dxf_read::entity_from_groups; pub use dxf_write::entity_groups; @@ -53,40 +55,42 @@ pub enum IoError { pub type Result = std::result::Result; -fn ext(name: &str) -> String { - std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default() +fn ext(name: impl AsRef) -> String { + name.as_ref().extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default() } /// Read a drawing; the format comes from the content (DXF ASCII/binary, DWG) or the name /// (SVG and gzip-compressed SVGZ). -pub fn read(bytes: &[u8], name: &str) -> Result { +pub fn read(bytes: &[u8], name: impl AsRef) -> Result { + let name = name.as_ref(); if cadcraft_dwg::is_dwg(bytes) { let (dxf, notes) = cadcraft_dwg::dwg_to_dxf_noted(bytes, cadcraft_dwg::Limits::DEFAULT).map_err(IoError::Format)?; let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?; d.read_notes = notes; return Ok(d); } - match ext(name).as_str() { - "svg" | "svgz" => svg_read::read(bytes), - "dxf" | "" => dxf_read::read(bytes), - e if bytes.len() > 4 => dxf_read::read(bytes).map_err(|_| IoError::Unsupported(e.to_string())), - e => Err(IoError::Unsupported(e.to_string())), + match (Format::from_path(name), ext(name).as_str()) { + (Some(Format::Svg | Format::Svgz), _) => svg_read::read(bytes), + (Some(Format::Dxf), _) => dxf_read::read(bytes), + (_, e) if bytes.len() > 4 => dxf_read::read(bytes).map_err(|_| IoError::Unsupported(e.to_string())), + (_, e) => Err(IoError::Unsupported(e.to_string())), } } /// Write a drawing in the format chosen by the name's extension. Images (PNG, SVG, PDF) show /// model space fitted to its extents. DXF and DWG are written in the drawing's version /// ([`save_version`]), DXF as ASCII. -pub fn write(d: &Drawing, name: &str) -> Result> { +pub fn write(d: &Drawing, name: impl AsRef) -> Result> { write_framed(d, name, None) } /// Like [`write`], with the DXF/DWG version and binary DXF chosen by `opts`. Binary applies to /// DXF only; asking for it with another format is an error. -pub fn write_with(d: &Drawing, name: &str, opts: &SaveOptions) -> Result> { +pub fn write_with(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Result> { + let name = name.as_ref(); let version = opts.version.unwrap_or_else(|| save_version(d)); - match ext(name).as_str() { - "dxf" | "" => { + match Format::from_path(name) { + Some(Format::Dxf) => { let tags = dxf_write::tags(d, version); Ok(if opts.binary { cadcraft_dxf::write_binary(&tags, version.utf8()) @@ -97,11 +101,11 @@ pub fn write_with(d: &Drawing, name: &str, opts: &SaveOptions) -> Result // 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. - "dwg" if !opts.binary => { + 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) } - e if opts.binary => Err(IoError::Format(format!("binary output is for DXF files, not `{e}`"))), + _ if opts.binary => Err(IoError::Format(format!("binary output is for DXF files, not `{}`", ext(name)))), _ => write_framed(d, name, None), } } @@ -110,28 +114,32 @@ pub fn write_with(d: &Drawing, name: &str, opts: &SaveOptions) -> Result /// drawing units, centred and scaled to fit the image without distortion) instead of the /// extents. Formats that are not images (DXF, DWG) ignore the window. The window is checked with /// [`check_window`]. -pub fn write_framed(d: &Drawing, name: &str, window: Option) -> Result> { +pub fn write_framed(d: &Drawing, name: impl AsRef, window: Option) -> Result> { + let name = name.as_ref(); // A drawing template (.dwt) is DWG content. - if ext(name) == "dwt" { - return write_framed(d, &format!("{name}.dwg"), None); + let format = Format::from_path(name); + if format == Some(Format::Dwt) { + let mut dwg = name.as_os_str().to_owned(); + dwg.push(".dwg"); + return write_framed(d, PathBuf::from(dwg), None); } if let Some(w) = &window && is_image(name) { check_window(w)?; } - match ext(name).as_str() { - "dxf" | "" | "dwg" => write_with(d, name, &SaveOptions::default()), - "svg" => Ok(svg::export_window(d, &Space::Model, window).into_bytes()), - "png" => png_framed(d, &Space::Model, 2400, 1600, window), - "pdf" => pdf::pdf(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() }), - e => Err(IoError::Unsupported(e.to_string())), + match format { + Some(Format::Dxf | Format::Dwg) => write_with(d, name, &SaveOptions::default()), + Some(Format::Svg) => Ok(svg::export_window(d, &Space::Model, window).into_bytes()), + Some(Format::Png) => png_framed(d, &Space::Model, 2400, 1600, window), + Some(Format::Pdf) => pdf::pdf(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() }), + _ => Err(IoError::Unsupported(ext(name))), } } /// Whether `name` is written as an image (PNG, SVG, PDF), i.e. whether framing applies to it. -pub fn is_image(name: &str) -> bool { - matches!(ext(name).as_str(), "png" | "svg" | "pdf") +pub fn is_image(name: impl AsRef) -> bool { + Format::from_path(name).is_some_and(Format::is_image) } /// Largest coordinate magnitude accepted in an export window. diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index d5fe5d2f7..977a7c184 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2813,3 +2813,17 @@ fn proxies_keep_their_class_when_classes_are_rewritten() { dxf_records(&pairs, "ACAD_PROXY_OBJECT").iter().map(|r| classes[own_91(r).parse::().unwrap() - 500].clone()).collect(); assert_eq!(names, ["VISUALSTYLE", "WIDGETX"]); } + +/// A name that isn't valid Unicode still picks its format by extension. +#[cfg(unix)] +#[test] +fn non_unicode_names_pick_the_format_by_extension() { + use std::os::unix::ffi::OsStringExt as _; + let name = |ext: &str| std::path::PathBuf::from(std::ffi::OsString::from_vec([b"caf\xe9.".as_slice(), ext.as_bytes()].concat())); + assert!(is_image(name("png")) && !is_image(name("dxf"))); + let d = sample(); + let bytes = write(&d, name("dxf")).unwrap(); + assert!(read(&bytes, name("dxf")).is_ok()); + assert!(write(&d, name("png")).unwrap().starts_with(b"\x89PNG")); + assert!(write(&d, name("dwt")).is_ok(), "a template is written as DWG"); +} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 955a6b6d2..1359fbdda 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -12,6 +12,7 @@ workspace = true cadcraft-engine = { workspace = true } cadcraft-render = { workspace = true } cadcraft-io = { workspace = true } +clap = { workspace = true } serde_json = { workspace = true } log = { workspace = true } # Secure randomness for the per-session control token (MIT OR Apache-2.0). diff --git a/crates/mcp/src/args.rs b/crates/mcp/src/args.rs new file mode 100644 index 000000000..a47a90bdd --- /dev/null +++ b/crates/mcp/src/args.rs @@ -0,0 +1,51 @@ +//! Helpers for clap parsers shared by the apps: environment variables as flag fallbacks. +//! +//! Apply [`blank_env_is_unset`] to the arguments, so an empty variable counts as unset, and pass a +//! parse error through [`name_env_vars`], so a bad value names the variable it came from. + +use std::ffi::{OsStr, OsString}; + +use clap::{Arg, Command}; + +/// For `Command::mut_args`: an empty or blank variable counts as unset, so `CADCRAFT_CONTROL_PORT=` +/// turns a fallback off without `unset`. clap would pass the empty value to the parser. `var` +/// looks the variable up. +pub fn blank_env_is_unset(arg: Arg, var: impl Fn(&OsStr) -> Option) -> Arg { + let blank = arg.get_env().and_then(var).is_some_and(|v| v.to_str().is_some_and(|v| v.trim().is_empty())); + if blank { arg.env(None::<&str>) } else { arg } +} + +/// clap names the flag when a value from its variable is bad or conflicts with another, as if the +/// flag had been given: name the variable instead when the flag isn't among `args` (without the +/// binary name; a first one naming a subcommand selects whose arguments to look in). +pub fn name_env_vars(mut error: clap::Error, cmd: &Command, args: &[OsString]) -> clap::Error { + use clap::error::{ContextKind, ContextValue}; + // `--flag value` or `--flag=value`. + let given = + |long: &str| args.iter().filter_map(|a| a.to_str()?.strip_prefix("--")?.strip_prefix(long)).any(|r| r.is_empty() || r.starts_with('=')); + let sub = args.first().and_then(|name| cmd.find_subcommand(name)).unwrap_or(cmd); + for kind in [ContextKind::InvalidArg, ContextKind::PriorArg] { + let Some(ContextValue::String(shown)) = error.get(kind) else { continue }; + let Some(arg) = sub.get_arguments().find(|a| a.to_string() == *shown) else { continue }; + let (Some(long), Some(var)) = (arg.get_long(), arg.get_env()) else { continue }; + if !given(long) { + error.insert(kind, ContextValue::String(var.to_string_lossy().into_owned())); + } + } + error +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blank_variables_count_as_unset() { + let arg = || Arg::new("control").long("control").env("CADCRAFT_CONTROL_PORT"); + for value in ["", " "] { + assert_eq!(blank_env_is_unset(arg(), |_| Some(value.into())).get_env(), None, "{value:?}"); + } + assert!(blank_env_is_unset(arg(), |_| Some(" 50494 ".into())).get_env().is_some()); + assert!(blank_env_is_unset(arg(), |_| None).get_env().is_some()); + } +} diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs index 7fcf4849d..932d855e4 100644 --- a/crates/mcp/src/lib.rs +++ b/crates/mcp/src/lib.rs @@ -8,6 +8,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod args; mod backend; pub mod control_token; mod server; diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index b8d9f09a1..7639dbba1 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -575,7 +575,7 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) { y += 46.0; } if let Some(path) = recent { - app.open_path(&path); + app.open_path(std::path::Path::new(&path)); } else if app.ui.recent_files.is_empty() { p.text( pos2(main.center().x, main.center().y), diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index bbbf08902..50fb52a25 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -350,9 +350,9 @@ pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) { #[cfg(not(target_arch = "wasm32"))] for files in std::mem::take(&mut output.window_files) { for file in files.dropped { - let path = file.path().to_string_lossy().to_string(); - if !path.is_empty() { - app.open_path(&path); + let path = file.path(); + if !path.as_os_str().is_empty() { + app.open_path(path); } } } diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 3c0be7611..30f3b0a85 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -23,6 +23,8 @@ use cadcraft_render::{DisplayList, Kind}; use egui_wgpu::wgpu; use egui_wgpu::wgpu::util::DeviceExt; +use crate::switch::Switch; + /// Line/triangle vertex: position (2 × f32, relative to the origin) + sRGB colour (4 × u8, /// premultiplied by its alpha: transparent objects blend with what is under them). const VERTEX_SIZE: usize = 12; @@ -44,12 +46,8 @@ const POINT_SIZE: f32 = 1.5; /// then Mailbox, then falls back to FIFO, so it is valid on every surface; under a compositor the /// compositor still syncs to the display. `vsync` is the `CADCRAFT_VSYNC` override: `1`/`on` /// forces FIFO (tear-free without a compositor), `0`/`off` forces the low-latency mode. -pub fn surface_config(vsync: Option<&str>, low_latency: bool) -> egui_wgpu::SurfaceConfig { - let no_vsync = match vsync.map(|v| v.trim().to_ascii_lowercase()).as_deref() { - Some("1" | "on" | "true" | "yes") => false, - Some("0" | "off" | "false" | "no") => true, - _ => low_latency, - }; +pub fn surface_config(vsync: Switch, low_latency: bool) -> egui_wgpu::SurfaceConfig { + let no_vsync = !vsync.or(!low_latency); egui_wgpu::SurfaceConfig { present_mode: if no_vsync { wgpu::PresentMode::AutoNoVsync } else { wgpu::PresentMode::AutoVsync }, desired_maximum_frame_latency: Some(1), @@ -801,17 +799,11 @@ mod tests { #[test] fn surface_config_prefers_low_latency_where_asked_and_honours_override() { use wgpu::PresentMode::{AutoNoVsync, AutoVsync}; - assert_eq!(surface_config(None, true).present_mode, AutoNoVsync); - assert_eq!(surface_config(None, false).present_mode, AutoVsync); - for on in ["1", "on", " TRUE ", "yes"] { - assert_eq!(surface_config(Some(on), true).present_mode, AutoVsync, "{on}"); - } - for off in ["0", "Off", "false", "no"] { - assert_eq!(surface_config(Some(off), false).present_mode, AutoNoVsync, "{off}"); - } - assert_eq!(surface_config(Some("maybe"), true).present_mode, AutoNoVsync); - assert_eq!(surface_config(Some(""), false).present_mode, AutoVsync); - assert_eq!(surface_config(None, true).desired_maximum_frame_latency, Some(1)); + assert_eq!(surface_config(Switch::Default, true).present_mode, AutoNoVsync); + assert_eq!(surface_config(Switch::Default, false).present_mode, AutoVsync); + assert_eq!(surface_config(Switch::On, true).present_mode, AutoVsync); + assert_eq!(surface_config(Switch::Off, false).present_mode, AutoNoVsync); + assert_eq!(surface_config(Switch::Default, true).desired_maximum_frame_latency, Some(1)); } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 017cf5a42..22e325cbe 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -27,6 +27,7 @@ pub mod hatchdlg; mod mtext_editor; mod panel_state; pub mod spacemouse; +pub mod switch; // The External References palette. pub mod xrefs; @@ -55,6 +56,7 @@ pub mod vpscale; pub mod exchange; +use std::path::Path; use std::sync::mpsc::Receiver; use cadcraft_engine::Session; @@ -88,7 +90,7 @@ pub struct UiState { /// 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 /// pointer"), screen readers, recorders and remote desktops track the system cursor and lose it - /// when it is hidden. Off by default; `CADCRAFT_SYSTEM_CURSOR=1` turns it on at startup. + /// when it is hidden. Off unless the host defaults to it ([`CadApp::set_system_cursor_default`]). pub system_cursor: bool, /// "Drafting" or "Modeling". pub toolset_tab: String, @@ -173,7 +175,7 @@ impl Default for UiState { 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")), + system_cursor: false, toolset_tab: "Drafting".into(), collapsed_groups: Vec::new(), hidden_tools: Vec::new(), @@ -211,6 +213,8 @@ pub struct CadApp { /// Whether the operating system shows animations, as the host reads it; `None` when the OS /// states nothing or the host cannot ask ([`animation`]). pub system_animations: Option, + /// What `ui.system_cursor` goes back to when the interface is reset ([`Self::set_system_cursor_default`]). + pub system_cursor_default: bool, pub session: Session, pub ui: UiState, /// The interface's own preferences from the Options dialog ([`options`]). @@ -296,6 +300,7 @@ impl CadApp { CadApp { system_languages: Vec::new(), system_animations: None, + system_cursor_default: false, session, ui: UiState::default(), options: options::UiOptions::default(), @@ -469,6 +474,15 @@ impl CadApp { } } + /// Make the system cursor the interface default (`on`) and turn it on; saved preferences and + /// resets never turn it off then. + pub fn set_system_cursor_default(&mut self, on: bool) { + self.system_cursor_default = on; + if on { + self.ui.system_cursor = true; + } + } + pub fn set_status(&mut self, s: impl Into) { self.status = Some((s.into(), now_ms())); } @@ -481,12 +495,12 @@ impl CadApp { /// Open the drawing at `path`. Natively the file is read on a worker thread while an /// "Opening ..." card shows ([`opening`]); [`Self::finish_opening`] adds it when ready. On the /// web it opens at once. - pub fn open_path(&mut self, path: &str) { + pub fn open_path(&mut self, path: &Path) { // A LISP file (dropped on the window): loaded as APPLOAD loads it. if is_lisp_file(path) { match cadcraft_engine::lisp::builtins::read_text_file(path) { - Some(text) => self.load_lisp(path, &text), - None => self.open_failed(format!("APPLOAD: can't read {path}")), + Some(text) => self.load_lisp(&path.to_string_lossy(), &text), + None => self.open_failed(format!("APPLOAD: can't read {}", path.display())), } return; } @@ -496,7 +510,10 @@ impl CadApp { } #[cfg(target_arch = "wasm32")] { - let r = self.run("open", json!({ "path": path })); + let r = match path.to_str() { + Some(text) => self.run("open", json!({ "path": text })), + None => Err(format!("open: {}: the path is not valid Unicode", path.display())), + }; self.opened(r); } } @@ -800,9 +817,9 @@ impl CadApp { { let dropped = ctx.input_mut(|input| std::mem::take(&mut input.raw.dropped_files)); for file in dropped { - let path = file.path().to_string_lossy().to_string(); - if !path.is_empty() { - self.open_path(&path); + let path = file.path(); + if !path.as_os_str().is_empty() { + self.open_path(path); } } } @@ -889,8 +906,8 @@ pub fn now_ms() -> f64 { } /// A LISP source file, by its name. -fn is_lisp_file(name: &str) -> bool { - std::path::Path::new(name).extension().is_some_and(|e| e.eq_ignore_ascii_case("lsp")) +fn is_lisp_file(name: impl AsRef) -> bool { + name.as_ref().extension().is_some_and(|e| e.eq_ignore_ascii_case("lsp")) } #[cfg(test)] diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ca287f982..58055542f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -128,7 +128,7 @@ fn run_recent_file_command(app: &mut CadApp, id: &str) -> Option().ok()) { let Some(path) = app.ui.recent_files.get(i).cloned() else { return Some(Err(format!("no recent file {i}"))) }; - app.open_path(&path); + app.open_path(std::path::Path::new(&path)); return Some(Ok(Value::Null)); } None @@ -319,7 +319,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { let picked = app.services.pick_open.as_ref().and_then(|f| f()); if let Some(p) = picked { - app.open_path(&p); + app.open_path(std::path::Path::new(&p)); } Ok(Value::Null) } @@ -404,7 +404,17 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { let (menu, theme, interface_language, save_format) = (app.ui.in_window_menu, app.ui.theme, app.ui.interface_language, app.ui.save_format); let (animations, save_version) = (app.ui.animations, std::mem::take(&mut app.ui.save_version)); - app.ui = crate::UiState { in_window_menu: menu, theme, animations, interface_language, save_format, save_version, ..Default::default() }; + let system_cursor = app.system_cursor_default; + app.ui = crate::UiState { + in_window_menu: menu, + theme, + animations, + interface_language, + save_format, + save_version, + system_cursor, + ..Default::default() + }; Ok(Value::Null) } "ui.start" => { diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index b0b2f8781..d6ae999c8 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -3,6 +3,7 @@ //! a spinner and the elapsed time and keeps painting. The finished drawing is added to the session //! on the UI thread. The web build has no threads and opens synchronously. +use std::path::{Path, PathBuf}; use std::sync::mpsc::{Receiver, TryRecvError, channel}; use std::time::{Duration, Instant}; @@ -13,7 +14,7 @@ use crate::theme::Tokens; type Outcome = Result; struct Job { - path: String, + path: PathBuf, started: Instant, rx: Receiver, } @@ -26,20 +27,20 @@ pub struct Opening { impl Opening { /// Start reading `path` on a worker thread. - pub fn start(&mut self, path: &str) { + pub fn start(&mut self, path: &Path) { let (tx, rx) = channel(); - let p = path.to_string(); + let p = path.to_path_buf(); let spawned = std::thread::Builder::new().name("cadcraft-open".into()).spawn(move || { let _ = tx.send(read_file(&p)); }); if spawned.is_err() { // No thread to read on: report it like any other failed open. let (tx, rx2) = channel(); - let _ = tx.send(Err(format!("open: {path}: could not start a reader thread"))); - self.jobs.push(Job { path: path.to_string(), started: Instant::now(), rx: rx2 }); + let _ = tx.send(Err(format!("open: {}: could not start a reader thread", path.display()))); + self.jobs.push(Job { path: path.to_path_buf(), started: Instant::now(), rx: rx2 }); return; } - self.jobs.push(Job { path: path.to_string(), started: Instant::now(), rx }); + self.jobs.push(Job { path: path.to_path_buf(), started: Instant::now(), rx }); } /// Whether any file is still being read. @@ -48,7 +49,7 @@ impl Opening { } /// The finished reads, as (path, result). A reader that died without answering is an error. - pub fn poll(&mut self) -> Vec<(String, Outcome)> { + pub fn poll(&mut self) -> Vec<(PathBuf, Outcome)> { let mut done = Vec::new(); self.jobs.retain(|j| match j.rx.try_recv() { Ok(r) => { @@ -57,7 +58,7 @@ impl Opening { } Err(TryRecvError::Empty) => true, Err(TryRecvError::Disconnected) => { - done.push((j.path.clone(), Err(format!("open: {}: the file could not be read", j.path)))); + done.push((j.path.clone(), Err(format!("open: {}: the file could not be read", j.path.display())))); false } }); @@ -67,7 +68,7 @@ impl Opening { /// The text of the card: the file and how long it has taken, or how many files are queued. fn label(&self) -> Option { let first = self.jobs.first()?; - let name = std::path::Path::new(&first.path).file_name().map_or_else(|| first.path.clone(), |n| n.to_string_lossy().to_string()); + let name = first.path.file_name().unwrap_or(first.path.as_os_str()).to_string_lossy(); let secs = first.started.elapsed().as_secs_f32(); let more = self.jobs.len() - 1; Some(if more == 0 { format!("Opening {name}... {secs:.0} s") } else { format!("Opening {name} and {more} more... {secs:.0} s") }) @@ -100,6 +101,7 @@ impl Opening { #[cfg(test)] mod tests { + use std::path::Path; use std::time::{Duration, Instant}; use cadcraft_engine::Session; @@ -114,7 +116,7 @@ mod tests { let before = app.session.docs.len(); let missing = std::env::temp_dir().join(format!("cadcraft-missing-{}.dxf", std::process::id())); let p = missing.to_string_lossy().to_string(); - app.open_path(&p); + app.open_path(&missing); assert!(app.opening.busy() || app.status.is_some(), "the read starts in the background"); let t = Instant::now(); while app.opening.busy() && t.elapsed() < Duration::from_secs(10) { @@ -133,8 +135,8 @@ mod tests { fn card_text_names_the_file_and_counts_queued_ones() { let mut o = super::Opening::default(); assert!(o.label().is_none()); - o.start("/nonexistent/dir/a.dxf"); - o.start("/nonexistent/dir/b.dxf"); + o.start(Path::new("/nonexistent/dir/a.dxf")); + o.start(Path::new("/nonexistent/dir/b.dxf")); let l = o.label().unwrap_or_default(); assert!(l.starts_with("Opening a.dxf and 1 more"), "{l}"); } diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index c8b94c310..8bf147bcf 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -310,7 +310,7 @@ fn reset_ui(app: &mut CadApp) { app.ui.animations = d.animations; app.ui.save_format = d.save_format; app.ui.save_version = d.save_version; - app.ui.system_cursor = d.system_cursor; + app.ui.system_cursor = app.system_cursor_default; app.ui.history_lines = d.history_lines; app.options = UiOptions::default(); } @@ -353,7 +353,7 @@ impl CadApp { let _ = parse_ui(key, value, &mut c); } } - // CADCRAFT_SYSTEM_CURSOR=1 turns the system cursor on whatever was saved. + // A saved `false` leaves the host's default (`set_system_cursor_default`) in place. if c.system_cursor == Some(true) { self.ui.system_cursor = true; } diff --git a/crates/ui-egui/src/switch.rs b/crates/ui-egui/src/switch.rs new file mode 100644 index 000000000..0095a14e5 --- /dev/null +++ b/crates/ui-egui/src/switch.rs @@ -0,0 +1,54 @@ +//! Boolean environment switches (`CADCRAFT_VSYNC`, `CADCRAFT_WAYLAND`, ...): one parser, so every +//! variable accepts the same spellings. + +/// `1/on/true/yes` or `0/off/false/no`, case- and space-insensitive. Blank or unset is `Default`; +/// anything else is `Default` and logged. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Switch { + On, + Off, + Default, +} + +impl Switch { + /// Parse the value of the variable `name`; `name` only appears in the warning. + pub fn parse(name: &str, value: Option<&str>) -> Switch { + let Some(value) = value else { return Switch::Default }; + match value.trim().to_ascii_lowercase().as_str() { + "1" | "on" | "true" | "yes" => Switch::On, + "0" | "off" | "false" | "no" => Switch::Off, + "" => Switch::Default, + _ => { + log::warn!("{name}={value:?} is not 1/on/true/yes or 0/off/false/no; using the default"); + Switch::Default + } + } + } + + /// Whether the switch is on, with `default` for `Default`. + pub fn or(self, default: bool) -> bool { + match self { + Switch::On => true, + Switch::Off => false, + Switch::Default => default, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_every_spelling() { + for v in ["1", "on", "true", "yes", "ON", "True", " Yes ", "\t1\n"] { + assert_eq!(Switch::parse("X", Some(v)), Switch::On, "{v:?}"); + } + for v in ["0", "off", "false", "no", "OFF", "False", " No ", " 0 "] { + assert_eq!(Switch::parse("X", Some(v)), Switch::Off, "{v:?}"); + } + for v in [None, Some(""), Some(" "), Some("maybe"), Some("2"), Some("onn")] { + assert_eq!(Switch::parse("X", v), Switch::Default, "{v:?}"); + } + } +} diff --git a/crates/ui-egui/tests/bedit_dialog.rs b/crates/ui-egui/tests/bedit_dialog.rs index 85367e407..95fdb4adc 100644 --- a/crates/ui-egui/tests/bedit_dialog.rs +++ b/crates/ui-egui/tests/bedit_dialog.rs @@ -133,7 +133,7 @@ fn opening_a_drawing_with_authoring_elements_offers_the_block_editor() { let symbol = dir.join("Symbol.dxf"); std::fs::write(&symbol, "authoring").unwrap(); let mut app = CadApp::new(Session::new(), Services::default()); - app.open_path(&symbol.to_string_lossy()); + app.open_path(&symbol); // The file is read in the background (#797): wait for it to be added. let t = std::time::Instant::now(); while app.opening.busy() && t.elapsed() < std::time::Duration::from_secs(10) { @@ -163,7 +163,7 @@ fn opening_a_drawing_with_authoring_elements_offers_the_block_editor() { let plain = dir.join("Plain.dxf"); std::fs::write(&plain, "plain").unwrap(); let mut app = CadApp::new(Session::new(), Services::default()); - app.open_path(&plain.to_string_lossy()); + app.open_path(&plain); // The file is read in the background (#797): wait for it to be added. let t = std::time::Instant::now(); while app.opening.busy() && t.elapsed() < std::time::Duration::from_secs(10) { diff --git a/crates/ui-egui/tests/it/system_cursor.rs b/crates/ui-egui/tests/it/system_cursor.rs index ff2c8942f..e2067e519 100644 --- a/crates/ui-egui/tests/it/system_cursor.rs +++ b/crates/ui-egui/tests/it/system_cursor.rs @@ -35,3 +35,23 @@ fn system_cursor_stays_visible_over_the_canvas_when_requested() { assert!(app.ui.system_cursor); assert_eq!(canvas_cursor(&mut app), egui::CursorIcon::Crosshair, "systemCursor keeps an OS cursor for magnifiers"); } + +/// The host's default (the desktop app's `CADCRAFT_SYSTEM_CURSOR`) turns it on; a saved `false` +/// and the resets keep it. +#[test] +fn the_host_default_survives_saved_profiles_and_resets() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.run("options", serde_json::json!({ "reset": true })).unwrap(); + assert!(!app.ui.system_cursor, "off without a host default"); + + app.set_system_cursor_default(true); + assert!(app.ui.system_cursor); + app.load_profile(r#"{"systemCursor": false}"#); + assert!(app.ui.system_cursor); + app.ui.system_cursor = false; + app.run("options", serde_json::json!({ "reset": true })).unwrap(); + assert!(app.ui.system_cursor); + app.ui.system_cursor = false; + app.run("ui.resetpalettes", serde_json::json!({})).unwrap(); + assert!(app.ui.system_cursor); +} diff --git a/crates/ui-egui/tests/recent_files.rs b/crates/ui-egui/tests/recent_files.rs index 6211ab899..946a6792a 100644 --- a/crates/ui-egui/tests/recent_files.rs +++ b/crates/ui-egui/tests/recent_files.rs @@ -53,15 +53,15 @@ fn opened_drawings_are_listed_newest_first_and_survive_a_restart() { let mut app = CadApp::new(Session::empty(), Services::default()); assert!(app.ui.recent_files.is_empty()); - app.open_path(&plan); + app.open_path(std::path::Path::new(&plan)); settle(&mut app); - app.open_path(§ion); + app.open_path(std::path::Path::new(§ion)); settle(&mut app); - app.open_path(&plan); + app.open_path(std::path::Path::new(&plan)); settle(&mut app); assert_eq!(app.ui.recent_files, [plan.clone(), section.clone()], "newest first, each file once"); // A file that could not be opened is not listed. - app.open_path("/nonexistent/missing.dxf"); + app.open_path(std::path::Path::new("/nonexistent/missing.dxf")); settle(&mut app); assert_eq!(app.ui.recent_files, [plan.clone(), section.clone()]); diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 000000000..ba68a1d09 --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,58 @@ +# cadcraft-cli + +`cadcraft-cli` is headless CADCraft: it reads, converts and exports drawings, runs scripts and +commands, prints the command catalog and serves MCP. It follows +[RFC-0012: Command-line conventions](https://github.com/storytold/craft-contrib/pull/18). + +`cadcraft-cli --help` and `cadcraft-cli help ` (or ` --help`) are the +reference for every subcommand, flag and value; this page doesn't repeat them. Examples are in the +[README](../README.md#drive-it-from-agents-mcp-and-the-cli), MCP setup in [mcp.md](mcp.md), +scripts and the JSON command forms in [customization.md](customization.md). + +## Conventions + +| | | +|---|---| +| Exit codes | `0` success, `1` the command failed, `2` usage error. | +| Streams | Results on stdout. `info` and `commands` print pretty JSON, or one line with `--compact`; `run` prints one JSON line per `--cmd` result (JSON lines); a command with no result (JSON `null`) prints no line. Errors (`error: …`), warnings and `wrote …` lines on stderr. `mcp` speaks MCP on stdout and writes nothing else there. | +| Usage errors | An unknown or repeated flag, a missing or malformed value (`--window`, `--view`, `--cmd` JSON, a sample name), flags that conflict (`--window` with `--view`) or that need another (`run --window` without `--export`) stop before any work, with exit 2. `--script`, `--script-file`, `--cmd` and `run`'s files repeat and run in command-line order. | +| Outputs that replace an input | `convert IN OUT` and `run FILE… --save OUT` / `--export OUT` refuse an OUT that is the same file as an input (any spelling or symlink of it): usage error, exit 2, nothing opened or written. `--in-place` allows it. A save a script or `--cmd` runs is the engine's. | +| Values starting with `-` | Written with `=`: `--window=-10,-10,10,10`, `--export=-plan.png`. | +| Paths | Read as given, including names that aren't valid Unicode. The engine opens files by text name, so such a name is reported as an error (exit 1) where a drawing is opened; an output takes any name whose extension is ASCII. | +| Completions and man pages | The Linux packages install them. To generate them yourself: `cargo run -p cadcraft-cli --example man-and-completions -- `. | + +## Environment variables + +Variables are fallbacks for flags; `--help` shows each next to its flag. An empty value counts as +unset and the flag wins over the variable, except for `CADCRAFT_CONFIG_DIR` (see below). + +| Variable | Flag | Subcommands | +|---|---|---| +| `CADCRAFT_CONFIG_DIR` | `--config-dir` (the settings folder; plotter configurations are in its `plotters` folder; empty means no settings folder) | `convert`, `run`, `mcp`, `sample` | +| `CADCRAFT_FONTALT` | `--fontalt` (FONTALT) | `convert`, `run`, `mcp`, `sample` | +| `CADCRAFT_FONTFALLBACK` | `--fontfallback` (FONTFALLBACK) | `convert`, `run`, `mcp`, `sample` | + +The desktop app's are listed by `cadcraft --help`; its one flag fallback is +`CADCRAFT_CONTROL_PORT` for `--control`, where a bad value is a usage error that names the +variable. + +## Not followed yet + +- **`CADCRAFT_CONFIG_DIR` is the one flag fallback where an empty variable doesn't count as + unset** (RFC-0012 rule 1.7): empty (or `--config-dir ""`) means no settings folder, as it did + before the port. +- **No variable for `mcp --connect`.** Photocraft's `mcp --bridge` falls back to its + `*_CONTROL_PORT` variable. Here an exported `CADCRAFT_CONTROL_PORT` would silently switch `mcp` + from a headless session to the running app, so `--connect` stays a flag only. +- **The desktop app on Windows** is built without a console, so a usage error in its launch flags + isn't visible there; the app exits with code 2. +- **The `string-error` ast-grep rule** covers the CLI code only. The engine's file hooks + (`cadcraft_engine::cmd::file::IoHooks`) still return `Result<_, String>`, so `install_io` maps + errors to strings at that boundary. +- **No AGENTS.md line for the ast-grep scan.** RFC-0012 asks an app's AGENTS.md to have coding + agents run the scan before pushing (`ast-grep scan -c lint/ast-grep/sgconfig.yml`); CI runs it + on every PR that touches the CLI code. +- **`perf` prints a text table**, with no `--json` (whether text listings get one is an open + question in RFC-0012). +- **Saves a command or script runs** (`--cmd 'saveas {…}'`, a script's `SAVEAS`) are the engine's + and are not checked against the opened drawings; only `--save` and `--export` are. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1c3f30626..98db28330 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -124,7 +124,7 @@ height and related chrome choices. It does not store drawings, command buffers, current Start tab. The default directory is `~/Library/Application Support/CADCraft` on macOS, `%APPDATA%/CADCraft` on Windows, and `$XDG_CONFIG_HOME/cadcraft` or `~/.config/cadcraft` elsewhere. Set `CADCRAFT_CONFIG_DIR` to a private directory for an isolated profile; an explicitly empty -value disables workspace reads and writes. An invalid, oversized or newer-version file is +value disables all settings reads and writes (workspace, logs, autosave, plotters). An invalid, oversized or newer-version file is reported and left untouched, with persistence disabled for that launch. Repair or move that file before restarting to resume saving workspace choices. diff --git a/docs/plotters.md b/docs/plotters.md index 7ca7c785d..92e10afce 100644 --- a/docs/plotters.md +++ b/docs/plotters.md @@ -32,7 +32,8 @@ settings directory: | macOS | `~/Library/Application Support/CADCraft/plotters` | | Windows | `%APPDATA%\CADCraft\plotters` | -`CADCRAFT_CONFIG_DIR` replaces the settings directory. On the web, devices last for the +`CADCRAFT_CONFIG_DIR` replaces the settings directory; empty means none (`cadcraft-cli`: +`--config-dir`, which falls back to the same variable). On the web, devices last for the session unless the host provides storage (`cmd::plotters::set_plotter_store`). Binary `.pc3` files are not read; we haven't found a public specification of that format. diff --git a/lint/ast-grep/rule-tests/args-os-test.yml b/lint/ast-grep/rule-tests/args-os-test.yml new file mode 100644 index 000000000..03ff2c4da --- /dev/null +++ b/lint/ast-grep/rule-tests/args-os-test.yml @@ -0,0 +1,19 @@ +id: args-os +valid: + - let code = photocraft_cli::run(std::env::args_os().skip(1), &mut out, &mut err); + - "let args: Vec = env::args_os().collect();" + - | + use std::env::args_os; + fn main() { let a: Vec<_> = args_os().collect(); } + - | + fn args() -> Vec { Vec::new() } + fn main() { let a = args(); } +invalid: + - "let args: Vec = std::env::args().collect();" + - for a in env::args().skip(1) {} + - | + use std::env::args; + fn main() { let a: Vec = args().collect(); } + - | + use std::env::{args, var}; + fn main() { for a in args() {} } diff --git a/lint/ast-grep/rule-tests/clap-error-message-test.yml b/lint/ast-grep/rule-tests/clap-error-message-test.yml new file mode 100644 index 000000000..385d46e96 --- /dev/null +++ b/lint/ast-grep/rule-tests/clap-error-message-test.yml @@ -0,0 +1,13 @@ +id: clap-error-message +valid: + - cmd.error(ErrorKind::ArgumentConflict, UsageError::BridgeRoots) + - cmd.error(ErrorKind::ArgumentConflict, Conflict { a, b }) + - sub.error(kind, self) + - log.error("not a clap error") +invalid: + - cmd.error(ErrorKind::ArgumentConflict, "configure automation roots on the desktop app") + - sub.error(ErrorKind::MissingRequiredArgument, format!("{flag} requires {transport}")) + - sub.error(ErrorKind::ArgumentConflict, BRIDGE_ROOTS) + - cmd.error(ErrorKind::InvalidValue, e.to_string()) + - cmd.error(ErrorKind::InvalidValue, String::from("bad value")) + - clap::Error::raw(ErrorKind::InvalidValue, "bad value") diff --git a/lint/ast-grep/rule-tests/clap-error-message-variable-test.yml b/lint/ast-grep/rule-tests/clap-error-message-variable-test.yml new file mode 100644 index 000000000..18d6e443a --- /dev/null +++ b/lint/ast-grep/rule-tests/clap-error-message-variable-test.yml @@ -0,0 +1,47 @@ +id: clap-error-message-variable +valid: + - | + fn conflict(cmd: &mut Command, a: String, b: String) -> clap::Error { + cmd.error(ErrorKind::ArgumentConflict, Conflict { a, b }) + } + - | + fn wrap(cmd: &mut Command, e: UsageError) -> clap::Error { + cmd.error(ErrorKind::ValueValidation, e) + } + - | + fn unrelated(cmd: &mut Command, e: UsageError) -> clap::Error { + let shown = format!("{e}"); + eprintln!("{shown}"); + cmd.error(ErrorKind::ValueValidation, e) + } + - | + fn cloned(cmd: &mut Command, e: &UsageError) -> clap::Error { + let owned = e.to_owned(); + cmd.error(ErrorKind::ValueValidation, owned) + } +invalid: + - | + fn conflict(cmd: &mut Command, a: &str, b: &str) -> clap::Error { + let message = format!("the argument '{a}' cannot be used with '{b}'"); + cmd.error(ErrorKind::ArgumentConflict, message) + } + - | + fn bad(cmd: &mut Command, e: UsageError) -> clap::Error { + let message = e.to_string(); + cmd.error(ErrorKind::ValueValidation, message) + } + - | + fn typed(cmd: &mut Command, flag: &str) -> clap::Error { + let message: String = flag.into(); + clap::Error::raw(ErrorKind::InvalidValue, message) + } + - | + fn literal(cmd: &mut Command) -> clap::Error { + let message = "bad value".to_owned(); + cmd.error(ErrorKind::InvalidValue, message) + } + - | + fn from(cmd: &mut Command) -> clap::Error { + let message = String::from("bad value"); + cmd.error(ErrorKind::InvalidValue, message) + } diff --git a/lint/ast-grep/rule-tests/string-error-test.yml b/lint/ast-grep/rule-tests/string-error-test.yml new file mode 100644 index 000000000..4f14197c8 --- /dev/null +++ b/lint/ast-grep/rule-tests/string-error-test.yml @@ -0,0 +1,14 @@ +id: string-error +valid: + - "fn parse(s: &str) -> Result { todo!() }" + - "fn name() -> Option { None }" + - "fn ok() -> Result { Ok(String::new()) }" + - Err(PortError::Range) + - Err(e) +invalid: + - "fn parse(s: &str) -> Result { todo!() }" + - "type R = Result<(), String>;" + - Err(format!("bad port {s}")) + - Err(e.to_string()) + - Err(String::from("bad port")) + - Err("bad port") diff --git a/lint/ast-grep/rules/args-os.yml b/lint/ast-grep/rules/args-os.yml new file mode 100644 index 000000000..ab1916c9e --- /dev/null +++ b/lint/ast-grep/rules/args-os.yml @@ -0,0 +1,21 @@ +id: args-os +language: rust +severity: error +message: std::env::args() panics on an argument that isn't valid Unicode +note: | + Read std::env::args_os() and let clap parse the OsStrings, so a Latin-1 file name reaches the + command (or is a usage error) instead of aborting before anything is printed (photocraft#1108). +rule: + any: + - pattern: std::env::args() + - pattern: env::args() + # A bare args() only where the file imports std::env::args, not any function named args. + - all: + - pattern: args() + - inside: + kind: source_file + stopBy: end + has: + kind: use_declaration + stopBy: end + regex: std::env::(args\b|\{[^}]*\bargs\b) diff --git a/lint/ast-grep/rules/clap-error-message-variable.yml b/lint/ast-grep/rules/clap-error-message-variable.yml new file mode 100644 index 000000000..3f476be4b --- /dev/null +++ b/lint/ast-grep/rules/clap-error-message-variable.yml @@ -0,0 +1,35 @@ +id: clap-error-message-variable +language: rust +severity: error +message: clap error built from a string held in a variable +note: | + The message was built with format!, .to_string(), String::from or a literal's .to_owned() a + few lines up. Give it a variant on a + #[derive(thiserror::Error)] enum instead, with the parts as fields, and pass the variant. +rule: + # In this order: the call binds $MSG, then the function must hold a `let` of that same name. + all: + - any: + - pattern: $CMD.error($KIND, $MSG) + - pattern: Error::raw($KIND, $MSG) + - pattern: clap::Error::raw($KIND, $MSG) + - inside: + kind: function_item + stopBy: end + has: + stopBy: end + any: + - pattern: let $MSG = format!($$$); + - pattern: "let $MSG: String = $VAL;" + - pattern: let $MSG = $SRC.to_string(); + - pattern: let $MSG = String::from($$$); + # .to_owned() only on a string literal: on anything else it may clone a typed error. + - all: + - kind: let_declaration + - regex: '=\s*"(?s:.*)"\s*\.to_owned\(\)\s*;?$' + - has: + field: pattern + pattern: $MSG +constraints: + MSG: + kind: identifier diff --git a/lint/ast-grep/rules/clap-error-message.yml b/lint/ast-grep/rules/clap-error-message.yml new file mode 100644 index 000000000..e18b824b3 --- /dev/null +++ b/lint/ast-grep/rules/clap-error-message.yml @@ -0,0 +1,26 @@ +id: clap-error-message +language: rust +severity: error +message: clap error built from a string +note: | + Give the message a variant on a #[derive(thiserror::Error)] enum and pass the variant, e.g. + `cmd.error(ErrorKind::ArgumentConflict, UsageError::BridgeRoots)`. A string literal, format!, + .to_string() or a SCREAMING_CASE const keeps the message apart from the error's type. +rule: + any: + - pattern: $CMD.error($KIND, $MSG) + - pattern: Error::raw($KIND, $MSG) + - pattern: clap::Error::raw($KIND, $MSG) +constraints: + MSG: + any: + - kind: string_literal + - all: + - kind: macro_invocation + - regex: ^format! + - all: + - kind: identifier + - regex: ^[A-Z][A-Z0-9_]*$ + - all: + - kind: call_expression + - regex: \.(to_string|to_owned)\(\)$|^String::from\( diff --git a/lint/ast-grep/rules/string-error.yml b/lint/ast-grep/rules/string-error.yml new file mode 100644 index 000000000..e79b83d05 --- /dev/null +++ b/lint/ast-grep/rules/string-error.yml @@ -0,0 +1,21 @@ +id: string-error +language: rust +severity: error +message: String as an error type +note: | + Return a #[derive(thiserror::Error)] enum, so a caller can match on what failed and the + messages live with their variants. +rule: + any: + - pattern: + context: type T = Result<$OK, String>; + selector: generic_type + - pattern: Err(format!($$$)) + - pattern: Err($S.to_string()) + - pattern: Err(String::from($$$)) + - all: + - pattern: Err($S) + - has: + kind: arguments + has: + kind: string_literal diff --git a/lint/ast-grep/sgconfig.yml b/lint/ast-grep/sgconfig.yml new file mode 100644 index 000000000..9c94bd0ae --- /dev/null +++ b/lint/ast-grep/sgconfig.yml @@ -0,0 +1,6 @@ +# Structural rules for the command-line code (RFC-0012), run by .github/workflows/ast-grep.yml. +# Each rule in rules/ has its cases in rule-tests/, which CI checks before the scan. +ruleDirs: + - rules +testConfigs: + - testDir: rule-tests diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 7ad0c4016..f9146c86a 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -44,11 +44,16 @@ BASENAME="cadcraft-$VERSION-linux-$ARCH" echo "==> CADCraft $VERSION for Linux $ARCH ($FORMATS)" +# The man-and-completions example writes cadcraft-cli's man pages and shell completions below. It +# is built in its own cargo run: built with the binaries, its dev-dependencies' features would be +# unified into them. if [[ "$SKIP_BUILD" = 0 ]]; then if [[ -n "${CROSS_TARGET:-}" ]]; then (cd "$ROOT" && cargo build --release --locked -p cadcraft -p cadcraft-cli --target "$CROSS_TARGET") + (cd "$ROOT" && cargo build --release --locked -p cadcraft-cli --example man-and-completions --target "$CROSS_TARGET") else (cd "$ROOT" && cargo build --release --locked -p cadcraft -p cadcraft-cli) + (cd "$ROOT" && cargo build --release --locked -p cadcraft-cli --example man-and-completions) fi fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" @@ -69,6 +74,26 @@ mkdir -p "$STAGE/usr/share/icons" cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/usr/share/icons/" mkdir -p "$STAGE/usr/share/doc/cadcraft" copy_docs "$STAGE/usr/share/doc/cadcraft" +# cadcraft-cli's man pages and shell completions, from its clap definition, written by the +# example built above. A cross build runs it through $EMULATOR, like the --version check at the +# end, and leaves them out without one, as a --skip-build run whose prebuilt binaries came without +# the example does. zsh reads site-functions on Fedora and openSUSE. +CLI_DOCS="$BIN/examples/man-and-completions" +if [[ -n "${CROSS_TARGET:-}" ]] && [[ -z "${EMULATOR:-}" ]]; then + warn "no EMULATOR to run the $CROSS_TARGET build, so cadcraft-cli's man pages and completions are left out" +elif [[ ! -x "$CLI_DOCS" ]]; then + warn "$CLI_DOCS is not built, so cadcraft-cli's man pages and completions are left out" +else + if [[ -n "${CROSS_TARGET:-}" ]]; then + "$EMULATOR" "$CLI_DOCS" "$WORK/cli-docs" + else + "$CLI_DOCS" "$WORK/cli-docs" + fi + install -Dm644 -t "$STAGE/usr/share/man/man1" "$WORK"/cli-docs/*.1 + install -Dm644 "$WORK/cli-docs/cadcraft-cli.bash" "$STAGE/usr/share/bash-completion/completions/cadcraft-cli" + install -Dm644 "$WORK/cli-docs/_cadcraft-cli" "$STAGE/usr/share/zsh/site-functions/_cadcraft-cli" + install -Dm644 "$WORK/cli-docs/cadcraft-cli.fish" "$STAGE/usr/share/fish/vendor_completions.d/cadcraft-cli.fish" +fi if command -v desktop-file-validate >/dev/null; then desktop-file-validate "$STAGE/usr/share/applications/$APP_ID.desktop" From 9c862c01ba259da22f5b43cdf8d69419e55e9ed6 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Wed, 28 Oct 2026 18:43:00 +1100 Subject: [PATCH 122/900] 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 123/900] 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 124/900] 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 125/900] 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 126/900] 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 127/900] 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 128/900] 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 129/900] 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 130/900] 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 131/900] 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 132/900] 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 133/900] 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 134/900] 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 d9265c924545464a3344e00060d23a34e4eece16 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Wed, 28 Oct 2026 12:09:14 -0400 Subject: [PATCH 135/900] macOS packaging: retry stapler when Apple's CloudKit drops the connection Co-Authored-By: Claude Opus 5.5 --- packaging/macos/package.sh | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index 014f91bd9..5ecb13b7a 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -80,6 +80,21 @@ sign() { codesign --force --sign "$IDENTITY" ${kc[@]+"${kc[@]}"} "${ts[@]}" "$@" } +# `stapler staple` and `stapler validate` both fetch the ticket from Apple's CloudKit, and a dropped +# connection there (NSURLErrorDomain -1005, "Error 68") fails them although notarization worked. +# Both are idempotent, so retry with a pause; a missing or bad ticket still fails every try. +stapler_retry() { + local try + for try in 1 2 3 4; do + xcrun stapler "$1" "$2" && return 0 + [[ "$try" = 4 ]] && break + echo "stapler $1 failed (try $try of 4); retrying in $((try * 20)) s" >&2 + sleep $((try * 20)) + done + echo "error: stapler $1 $(basename "$2") failed 4 times" >&2 + exit 1 +} + notarize() { local file="$1" out id status echo "==> notarizing $(basename "$file") (this can take a few minutes)" @@ -122,8 +137,8 @@ codesign --verify --strict --deep --verbose=2 "$APP" if [[ "$NOTARIZE" = 1 ]]; then ditto -c -k --keepParent "$APP" "$WORK/CADCraft-notarize.zip" notarize "$WORK/CADCraft-notarize.zip" - xcrun stapler staple "$APP" - xcrun stapler validate "$APP" + stapler_retry staple "$APP" + stapler_retry validate "$APP" spctl --assess --type execute -vvv "$APP" fi @@ -148,8 +163,8 @@ sign "$DMG" codesign --verify --strict --verbose=2 "$DMG" if [[ "$NOTARIZE" = 1 ]]; then notarize "$DMG" - xcrun stapler staple "$DMG" - xcrun stapler validate "$DMG" + stapler_retry staple "$DMG" + stapler_retry validate "$DMG" spctl --assess --type open --context context:primary-signature -vvv "$DMG" fi From fbd97d432cdf36a566c0c53739481bd6f0c32b0d Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Wed, 28 Oct 2026 12:09:15 -0400 Subject: [PATCH 136/900] Release 0.14.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 32 ++++++++++++++++---------------- Cargo.toml | 2 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab48c95da..34cfc44cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -643,7 +643,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -659,14 +659,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.13.0" +version = "0.14.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -676,7 +676,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -687,14 +687,14 @@ dependencies = [ [[package]] name = "cadcraft-dwg" -version = "0.13.0" +version = "0.14.0" dependencies = [ "acadrust", ] [[package]] name = "cadcraft-dxf" -version = "0.13.0" +version = "0.14.0" dependencies = [ "encoding_rs", "log", @@ -703,7 +703,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -724,7 +724,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-geom", "harfrust 0.14.0", @@ -734,14 +734,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.13.0" +version = "0.14.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.13.0" +version = "0.14.0" dependencies = [ "acadrust", "cadcraft-color", @@ -762,7 +762,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -775,7 +775,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -789,7 +789,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -815,7 +815,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.13.0" +version = "0.14.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -5893,7 +5893,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.13.0" +version = "0.14.0" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 2b38a218f..1d4d7c530 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.13.0" +version = "0.14.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 1e02e6f2630e8af40c002dc66f8f1b8941065810 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 10:10:04 -0600 Subject: [PATCH 137/900] 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 138/900] 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 139/900] 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 9de2b8bbdc6691830e7c15abe2cbcae45b22bedb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 13:23:09 -0400 Subject: [PATCH 140/900] Grant network access so update checks can reach GitHub (#2413) Add --share=network to the finish-args of both Flatpak manifests. Without it the sandbox cannot resolve or reach GitHub, so update checks fail with "Temporary failure in name resolution". The two manifests keep identical finish-args. --- packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml | 6 +++--- packaging/linux/flatpak/ai.storyteller.cadcraft.yml | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml index b6a64d8fb..651b9a358 100644 --- a/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml @@ -24,15 +24,15 @@ finish-args: - --share=ipc # GPU access for the wgpu canvas (Vulkan, or GL as a fallback). - --device=dri + # Outbound network access (HTTPS). + - --share=network # Open/Save dialogs go through the file-chooser portal (rfd) and drag-and-drop through the # document portal, so picked files work anywhere without broad filesystem access. Documents # and Pictures are granted so drawings passed by path (the command line, Open Recent, xrefs # and images next to a DXF) work in the usual places. - --filesystem=xdg-documents - --filesystem=xdg-pictures - # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in - # the sandbox; `flatpak override --user --share=network ai.storyteller.cadcraft` exposes it to - # host agents) and home/host filesystem access. + # Deliberately not granted: home/host filesystem access. modules: - name: cadcraft buildsystem: simple diff --git a/packaging/linux/flatpak/ai.storyteller.cadcraft.yml b/packaging/linux/flatpak/ai.storyteller.cadcraft.yml index 75a6ff690..88a49e136 100644 --- a/packaging/linux/flatpak/ai.storyteller.cadcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.cadcraft.yml @@ -25,15 +25,15 @@ finish-args: - --share=ipc # GPU access for the wgpu canvas (Vulkan, or GL as a fallback). - --device=dri + # Outbound network access (HTTPS). + - --share=network # Open/Save dialogs go through the file-chooser portal (rfd) and drag-and-drop through the # document portal, so picked files work anywhere without broad filesystem access. Documents # and Pictures are granted so drawings passed by path (the command line, Open Recent, xrefs # and images next to a DXF) work in the usual places. - --filesystem=xdg-documents - --filesystem=xdg-pictures - # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in - # the sandbox; `flatpak override --user --share=network ai.storyteller.cadcraft` exposes it to - # host agents) and home/host filesystem access. + # Deliberately not granted: home/host filesystem access. build-options: append-path: /usr/lib/sdk/rust-stable/bin modules: From e1d0a4747eeb74e2a58ae772b6d200328ee45cd3 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Wed, 28 Oct 2026 15:34:34 -0400 Subject: [PATCH 141/900] Fix imports after merging upstream/main --- crates/doc/src/entity/layout.rs | 2 ++ crates/engine/src/session/interactive.rs | 2 ++ crates/render/src/lib.rs | 2 +- crates/ui-egui/src/canvas.rs | 12 ++++++++++-- crates/ui-egui/src/canvas/draw.rs | 2 +- crates/ui-egui/src/canvas/grid.rs | 2 +- crates/ui-egui/src/canvas/list.rs | 2 +- crates/ui-egui/src/canvas/viewport.rs | 2 +- 8 files changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/entity/layout.rs b/crates/doc/src/entity/layout.rs index 802cbf77f..e63ba6c91 100644 --- a/crates/doc/src/entity/layout.rs +++ b/crates/doc/src/entity/layout.rs @@ -1,3 +1,5 @@ +use cadcraft_geom::Mat3; + use super::common::Handle; use super::{Color, Deserialize, Serialize, Vec2, Vec3, standard, yes}; diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index a68993d64..4248357b0 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -1,3 +1,5 @@ +use crate::DisplayOnly; + use super::{ Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value, Vec2, assoc, cmd, find_command, guard, pointmod, select, snap, sysvars, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5b9dc83a1..ac31ee5e0 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -316,7 +316,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}; -pub use viewports::{viewport_clip, viewport_content}; +pub use viewports::{clip_list, viewport_clip, viewport_content}; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e1c964bc0..6899de3d2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -304,7 +304,11 @@ fn handle_scroll_zoom(app: &mut CadApp, ui: &mut egui::Ui, nav: &Navigation<'_>, && let Ok(st) = app.session.state_mut() { let view = st.view(); - st.set_view_quiet(cadcraft_engine::View { center: view.center - nav.xf.screen_delta_to_world(p.scroll), height: view.height, twist: view.twist }); + st.set_view_quiet(cadcraft_engine::View { + center: view.center - nav.xf.screen_delta_to_world(p.scroll), + height: view.height, + twist: view.twist, + }); } let opts = ui.ctx().options(|o| o.input_options); let wheel = ui.input(|i| wheel_zoom_points(&i.raw.events, &opts, nav.rect.height())); @@ -339,7 +343,11 @@ fn handle_button_navigation(app: &mut CadApp, nav: &Navigation<'_>, inside: bool let delta = at - last; if let Ok(st) = app.session.state_mut() { let view = st.view(); - st.set_view_quiet(cadcraft_engine::View { center: view.center - nav.xf.screen_delta_to_world(delta), height: view.height, twist: view.twist }); + st.set_view_quiet(cadcraft_engine::View { + center: view.center - nav.xf.screen_delta_to_world(delta), + height: view.height, + twist: view.twist, + }); } } app.canvas.pan_last = Some(at); diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index 465740b62..b98dea92a 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -1,5 +1,5 @@ use super::list::preview_options; -use super::{Bounds2, CanvasState, Color32, DisplayList, Handle, Kind, ListKey, Pos2, Rect, Rgb, Shape, Stroke, Vec2, Xf, vec2}; +use super::{Bounds2, CanvasState, Color32, DisplayList, Handle, Kind, ListKey, Mat3, Pos2, Rect, Rgb, Shape, Stroke, Vec2, Xf, vec2}; fn color32(c: Rgb) -> Color32 { Color32::from_rgb(c.0, c.1, c.2) diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 2c43de297..7664b9ffb 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -1,4 +1,4 @@ -use super::{Bounds2, CadApp, Shape, Stroke, Tokens, Vec2, Xf, pos2}; +use super::{Bounds2, 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 { diff --git a/crates/ui-egui/src/canvas/list.rs b/crates/ui-egui/src/canvas/list.rs index a036ab6bc..2a975bbce 100644 --- a/crates/ui-egui/src/canvas/list.rs +++ b/crates/ui-egui/src/canvas/list.rs @@ -1,5 +1,5 @@ use super::viewport::{split_viewport, stencil_clip}; -use super::{Bounds2, CadApp, DisplayList, Handle, ListKey, Rgb, Tokens, Xf, rebuild, same_content}; +use super::{Bounds2, CadApp, DisplayList, Handle, ListKey, Rgb, Tokens, Vec2, Xf, rebuild, same_content}; /// Primitives of `list` sorted by entity handle, built on the first highlight after each list /// rebuild. Highlighting the hovered entity used to scan every primitive on every frame: ~2.5 ms diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index 668017816..4a7f79001 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -1,5 +1,5 @@ use super::draw::draw_list; -use super::{Bounds2, CadApp, DisplayList, Handle, Kind, Rect, Rgb, Vec2, Xf}; +use super::{Bounds2, CadApp, DisplayList, Handle, Kind, Mat3, Rect, Rgb, Vec2, Xf}; /// The active MSPACE viewport when its contents are drawn apart from the layout's list (see /// [`VpContent`]), with its clip outline when it is clipped. A clipped viewport is clipped with From 12fd74a60f1208cc186c1df3d1d08becdca30d5a Mon Sep 17 00:00:00 2001 From: mattlafy Date: Wed, 28 Oct 2026 15:35:20 -0400 Subject: [PATCH 142/900] Use explicit imports in DVIEW --- crates/engine/src/cmd/view/dview.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs index 7fbe2b832..468740707 100644 --- a/crates/engine/src/cmd/view/dview.rs +++ b/crates/engine/src/cmd/view/dview.rs @@ -21,7 +21,7 @@ use cadcraft_geom::{Vec2, Vec3}; use serde_json::{Value, json}; use super::super::machines::{SelOutcome, SelectPhase, number}; -use super::super::*; +use super::super::{CommandSpec, bad, f64_req}; use crate::{Accept, DisplayOnly, EngineError, Input, Interactive, Prompt, Result, Session, Snapshot, Step, View}; /// What DVIEW (and a view twist asked for anywhere) says on a layout with no active viewport. From 2a85653976a0ab8440deebd4a4df47b1ee2c3aa0 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Wed, 28 Oct 2026 15:41:01 -0400 Subject: [PATCH 143/900] Split the DVIEW prompt-steps test under the complexity limit --- crates/engine/tests/dview.rs | 118 +++++++++++++++++++---------------- 1 file changed, 65 insertions(+), 53 deletions(-) diff --git a/crates/engine/tests/dview.rs b/crates/engine/tests/dview.rs index 09656cbf5..f0e6d9b0a 100644 --- a/crates/engine/tests/dview.rs +++ b/crates/engine/tests/dview.rs @@ -54,61 +54,11 @@ fn every_prompt_step_on_the_model_tab() { let only = s.display_only().unwrap(); assert!(only.handles.is_empty()); assert!(only.extra.len() > 10 && only.extra.iter().all(|e| matches!(e.kind, EntityKind::Line(_)))); - - // TWist: the current twist is the default; a typed angle turns the view. - s.cmdline("tw").unwrap(); - assert_eq!(prompt(&s), "Specify view twist angle <0>:"); - s.cmdline("30").unwrap(); - assert!(near(twist_deg(&s), 30.0)); - assert_eq!(prompt(&s), OPTION); - s.cmdline("TWist").unwrap(); - assert_eq!(prompt(&s), "Specify view twist angle <30>:"); - // Enter keeps it. - s.cmdline("").unwrap(); - assert!(near(twist_deg(&s), 30.0)); - - // PAn: base point, second point. - s.cmdline("pa").unwrap(); - assert_eq!(prompt(&s), "Specify displacement base point:"); - s.cmdline("0,0").unwrap(); - assert_eq!(prompt(&s), "Specify second point:"); - s.cmdline("4,0").unwrap(); - assert_eq!(view(&s).center, Vec2::new(6.0, 10.0)); - assert_eq!(prompt(&s), OPTION); - - // Zoom: a scale factor of the current view. - s.cmdline("z").unwrap(); - assert_eq!(prompt(&s), "Specify zoom scale factor <1>:"); - s.cmdline("2").unwrap(); - assert!(near(view(&s).height, 10.0)); + twist_pan_and_zoom(&mut s); // The sample house stays where it was put: the view moves over it. assert_eq!(s.display_only().unwrap(), only); - - // Off: perspective is never on in a 2D view, so nothing changes. - let before = view(&s); - s.cmdline("o").unwrap(); - assert_eq!(prompt(&s), OPTION); - assert_eq!(view(&s), before); - - // The options that need a 3D camera are not available yet and stay at the option prompt. - for (typed, name) in [("ca", "CAmera"), ("ta", "TArget"), ("d", "Distance"), ("po", "POints"), ("cl", "CLip"), ("h", "Hide")] { - s.cmdline(typed).unwrap(); - assert!(logged(&s, &format!("DVIEW {name} is not available yet.")), "{name}: {:?}", s.log); - assert_eq!(prompt(&s), OPTION); - } - assert!(!s.log.iter().any(|l| l.contains("Only the view twist"))); - - // Undo takes back one DVIEW action at a time: zoom, pan, twist. - s.cmdline("u").unwrap(); - assert!(near(view(&s).height, 20.0)); - s.cmdline("u").unwrap(); - assert_eq!(view(&s).center, Vec2::new(10.0, 10.0)); - assert!(near(twist_deg(&s), 30.0)); - s.cmdline("u").unwrap(); - assert_eq!(view(&s).twist, 0.0); - // Nothing left to undo: still at the option prompt. - s.cmdline("u").unwrap(); - assert_eq!(prompt(&s), OPTION); + off_and_unavailable_options(&mut s); + undo_steps(&mut s); // An unknown option is refused and asked again. assert!(s.cmdline("bogus").is_ok()); @@ -124,6 +74,68 @@ fn every_prompt_step_on_the_model_tab() { assert_eq!(s.state().unwrap().undo.len(), undo); } +/// DVIEW's TWist, PAn and Zoom steps from the option prompt of a fresh Model tab session. +fn twist_pan_and_zoom(s: &mut Session) { + // TWist: the current twist is the default; a typed angle turns the view. + s.cmdline("tw").unwrap(); + assert_eq!(prompt(s), "Specify view twist angle <0>:"); + s.cmdline("30").unwrap(); + assert!(near(twist_deg(s), 30.0)); + assert_eq!(prompt(s), OPTION); + s.cmdline("TWist").unwrap(); + assert_eq!(prompt(s), "Specify view twist angle <30>:"); + // Enter keeps it. + s.cmdline("").unwrap(); + assert!(near(twist_deg(s), 30.0)); + + // PAn: base point, second point. + s.cmdline("pa").unwrap(); + assert_eq!(prompt(s), "Specify displacement base point:"); + s.cmdline("0,0").unwrap(); + assert_eq!(prompt(s), "Specify second point:"); + s.cmdline("4,0").unwrap(); + assert_eq!(view(s).center, Vec2::new(6.0, 10.0)); + assert_eq!(prompt(s), OPTION); + + // Zoom: a scale factor of the current view. + s.cmdline("z").unwrap(); + assert_eq!(prompt(s), "Specify zoom scale factor <1>:"); + s.cmdline("2").unwrap(); + assert!(near(view(s).height, 10.0)); +} + +/// DVIEW's Off option and the options that need a 3D camera. +fn off_and_unavailable_options(s: &mut Session) { + // Off: perspective is never on in a 2D view, so nothing changes. + let before = view(s); + s.cmdline("o").unwrap(); + assert_eq!(prompt(s), OPTION); + assert_eq!(view(s), before); + + // The options that need a 3D camera are not available yet and stay at the option prompt. + for (typed, name) in [("ca", "CAmera"), ("ta", "TArget"), ("d", "Distance"), ("po", "POints"), ("cl", "CLip"), ("h", "Hide")] { + s.cmdline(typed).unwrap(); + assert!(logged(s, &format!("DVIEW {name} is not available yet.")), "{name}: {:?}", s.log); + assert_eq!(prompt(s), OPTION); + } + assert!(!s.log.iter().any(|l| l.contains("Only the view twist"))); +} + +/// DVIEW's Undo after [`twist_pan_and_zoom`]. +fn undo_steps(s: &mut Session) { + // Undo takes back one DVIEW action at a time: zoom, pan, twist. + s.cmdline("u").unwrap(); + assert!(near(view(s).height, 20.0)); + s.cmdline("u").unwrap(); + assert_eq!(view(s).center, Vec2::new(10.0, 10.0)); + assert!(near(twist_deg(s), 30.0)); + s.cmdline("u").unwrap(); + assert_eq!(view(s).twist, 0.0); + // Nothing left to undo: still at the option prompt. + s.cmdline("u").unwrap(); + assert_eq!(prompt(s), OPTION); +} + #[test] fn selected_objects_are_the_preview_set() { let mut s = session(); From 336243e0afb3019feee58d0d4fc0d218f25530e7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 28 Oct 2026 15:53:50 -0400 Subject: [PATCH 144/900] Honor CARGO_BUILD_TARGET in FreeBSD packaging for aarch64 release builds (#2425) Add packaging/freebsd/package.sh, matching the other craft apps: an optional CARGO_BUILD_TARGET (x86_64 or aarch64 FreeBSD) names the archive and reads the cross-built binaries; unset means native. --skip-build and --dry-run supported. --- packaging/freebsd/package.sh | 130 +++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100755 packaging/freebsd/package.sh diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh new file mode 100755 index 000000000..e1718648f --- /dev/null +++ b/packaging/freebsd/package.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# Build and package CADCraft for FreeBSD: +# +# $DIST/cadcraft--freebsd-.tar.gz a /usr/local-style tree ( is x86_64, or +# aarch64 when CARGO_BUILD_TARGET=aarch64-unknown-freebsd): +# cadcraft--freebsd-/{bin, man/man1, share/applications, share/icons, +# share/mime, share/metainfo, share/doc/cadcraft, share/{bash-completion,zsh,fish}} +# +# Install by copying the tree's contents into /usr/local, e.g. +# tar -xzf cadcraft-*-freebsd-x86_64.tar.gz --strip-components 1 -C /usr/local +# +# Usage: packaging/freebsd/package.sh [--skip-build] [--dry-run] +# --dry-run print the resolved target, archive and cargo commands, then exit without building +# +# Needs: bash, cargo and the build dependencies listed in .github/workflows/freebsd.yml. FreeBSD's +# install(1) has no -D, so directories are created first. +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +LINUX="$ROOT/packaging/linux" +APP_ID=ai.storyteller.cadcraft + +SKIP_BUILD=0 +DRY_RUN=0 +while [[ $# -gt 0 ]]; do + case "$1" in + --skip-build) SKIP_BUILD=1; shift ;; + --dry-run) DRY_RUN=1; shift ;; + -h | --help) sed -n '2,12p' "$0"; exit 0 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +# FreeBSD calls x86_64 "amd64"; release names use the Rust/Linux spelling. +release_arch() { + case "$1" in + amd64 | x86_64) echo x86_64 ;; + arm64 | aarch64) echo aarch64 ;; + *) echo "unsupported architecture $1" >&2; return 2 ;; + esac +} +# The release workflow cross-compiles aarch64 in an x86_64 VM with CARGO_BUILD_TARGET set to +# aarch64-unknown-freebsd (craft-common-actions#39): name the archive after the target. +# host-tuple means the build host's triple, as rustc names it. +if [[ "${CARGO_BUILD_TARGET:-}" == host-tuple ]]; then + CARGO_BUILD_TARGET="$(rustc -vV | sed -n 's/^host: //p')" +fi +case "${CARGO_BUILD_TARGET:-}" in + "") ARCH="$(release_arch "$(uname -m)")" ;; + aarch64-unknown-freebsd | x86_64-unknown-freebsd) ARCH="$(release_arch "${CARGO_BUILD_TARGET%%-*}")" ;; + *) echo "CARGO_BUILD_TARGET=$CARGO_BUILD_TARGET is not a supported FreeBSD target" >&2; exit 2 ;; +esac +# Only binaries for this machine run here (the --version check at the end); a FreeBSD target built +# on another OS never does. +HOST_ARCH="$(release_arch "$(uname -m)" 2>/dev/null)" || HOST_ARCH="$(uname -m)" +if [[ -n "${CARGO_BUILD_TARGET:-}" ]] && [[ "$(uname -s)" != FreeBSD ]]; then + HOST_ARCH="$(uname -s) $HOST_ARCH" +fi +BASENAME="cadcraft-$VERSION-freebsd-$ARCH" + +echo "==> CADCraft $VERSION for FreeBSD $ARCH" + +# cadcraft-cli's man-and-completions example is built on its own, not with the binaries: its +# dev-dependencies would otherwise be unified into them (packaging/linux/package.sh). It runs on +# this machine, so a cross build builds it without the target. +CARGO_BUILD_FLAGS=(--release --locked ${CARGO_BUILD_TARGET:+--target "$CARGO_BUILD_TARGET"}) +if [[ "$DRY_RUN" = 1 ]]; then + echo "dry run: archive $DIST/$BASENAME.tar.gz" + echo "dry run: (cd $ROOT && cargo build ${CARGO_BUILD_FLAGS[*]} -p cadcraft -p cadcraft-cli)" + echo "dry run: (cd $ROOT && env -u CARGO_BUILD_TARGET cargo build --release --locked -p cadcraft-cli --example man-and-completions)" + exit 0 +fi +if [[ "$SKIP_BUILD" = 0 ]]; then + (cd "$ROOT" && cargo build "${CARGO_BUILD_FLAGS[@]}" -p cadcraft -p cadcraft-cli) + (cd "$ROOT" && env -u CARGO_BUILD_TARGET cargo build --release --locked -p cadcraft-cli --example man-and-completions) +fi +# Cargo puts a cross build under target//release. +BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release" +WORK="$CARGO_TARGET_DIR/freebsd-package" +STAGE="$WORK/$BASENAME" +rm -rf "$WORK" + +# ---- stage a /usr/local-style tree --------------------------------------------------------------- +mkdir -p "$STAGE/bin" "$STAGE/share/applications" "$STAGE/share/mime/packages" "$STAGE/share/metainfo" \ + "$STAGE/share/icons" "$STAGE/share/doc/cadcraft" +install -m 755 "$BIN/cadcraft" "$BIN/cadcraft-cli" "$STAGE/bin/" +strip "$STAGE/bin/cadcraft" "$STAGE/bin/cadcraft-cli" 2>/dev/null || true +# The desktop entry, MIME type and metainfo are the freedesktop files the Linux packages use. +install -m 644 "$LINUX/$APP_ID.desktop" "$STAGE/share/applications/$APP_ID.desktop" +install -m 644 "$LINUX/$APP_ID.mime.xml" "$STAGE/share/mime/packages/$APP_ID.xml" +sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$CADCRAFT_BUILD_DATE/g" \ + "$LINUX/$APP_ID.metainfo.xml.in" >"$STAGE/share/metainfo/$APP_ID.metainfo.xml" +cp -R "$ROOT/assets/app-icon/hicolor" "$STAGE/share/icons/" +copy_docs "$STAGE/share/doc/cadcraft" +# cadcraft-cli's man pages and shell completions, from its clap definition, written by the +# example built above. +CLI_DOCS="$CARGO_TARGET_DIR/release/examples/man-and-completions" +if [[ ! -x "$CLI_DOCS" ]]; then + echo "error: $CLI_DOCS is missing: build it with the binaries (without --skip-build)" >&2 + exit 1 +fi +"$CLI_DOCS" "$WORK/cli-docs" +mkdir -p "$STAGE/man/man1" "$STAGE/share/bash-completion/completions" \ + "$STAGE/share/zsh/site-functions" "$STAGE/share/fish/vendor_completions.d" +install -m 644 "$WORK"/cli-docs/*.1 "$STAGE/man/man1/" +install -m 644 "$WORK/cli-docs/cadcraft-cli.bash" "$STAGE/share/bash-completion/completions/cadcraft-cli" +install -m 644 "$WORK/cli-docs/_cadcraft-cli" "$STAGE/share/zsh/site-functions/_cadcraft-cli" +install -m 644 "$WORK/cli-docs/cadcraft-cli.fish" "$STAGE/share/fish/vendor_completions.d/cadcraft-cli.fish" + +# ---- .tar.gz ------------------------------------------------------------------------------------- +mkdir -p "$DIST" +tar -C "$WORK" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME" +echo "wrote $DIST/$BASENAME.tar.gz" + +if [[ -z "${CARGO_BUILD_TARGET:-}" ]] && [[ "$ARCH" = "$HOST_ARCH" ]]; then + "$STAGE/bin/cadcraft-cli" --version +else + # They cannot run here, so check what they are instead: executables, not libraries or objects. + # An older file(1) calls a PIE a shared object; its interpreter still marks it as a program. + want="$ARCH"; [[ "$ARCH" != x86_64 ]] || want=x86-64 + for b in "$STAGE"/bin/*; do + case "$(file -b "$b")" in + ELF*" executable, "*"$want"*FreeBSD* | ELF*"$want"*FreeBSD*interpreter*) ;; + *) echo "error: $b is not a FreeBSD $ARCH executable: $(file -b "$b")" >&2; exit 1 ;; + esac + done + echo "skipping --version: a CARGO_BUILD_TARGET=$CARGO_BUILD_TARGET build does not run on this $HOST_ARCH machine" +fi +echo "==> done" +ls -lh "$DIST" From b5f0890b95dcda79ab4f8e27ac017ab96da4a52a Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Thu, 29 Oct 2026 00:58:26 +0400 Subject: [PATCH 145/900] 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 146/900] 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 147/900] 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 148/900] 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 149/900] 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 150/900] 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 151/900] 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 152/900] 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 153/900] 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 154/900] 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 b17ae78cec362ac42ccf8929afcc6593202a2a0d Mon Sep 17 00:00:00 2001 From: austin62jake <340374338+austin62jake@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:01:18 -0500 Subject: [PATCH 155/900] fix(fonts): place Middle and bottom-justified text as AutoCAD does (#2229) A justified TEXT's insertion point (group 10) is computed from its alignment point, and AutoCAD takes it from a DWG as it is (it recomputes it only for DXF). CADCraft placed a Middle (M) text at half its height and a bottom-justified one a third of its height below the baseline, whatever the string or font, so in AutoCAD those texts were drawn off their alignment points: 0.35 at height 2.5 for "Tg 1234 ABC" justified M, 0.09 for BL with Arial (#2229). - Middle (M) now centres the text on its own ink, descenders included, as AutoCAD does. Text that draws nothing keeps half the height. Middle Center (MC) and the others are unchanged. - Bottom justifications with a TrueType face put the alignment point at the face's descent (its descent over its cap height, the text height): 0.296 of the height for Arial, where AutoCAD puts it. The stroke font keeps a third, which matches AutoCAD's SHX fonts. `frame` (the DWG insertion point) and `place` (drawing) share the new `justify_offset`, so what is drawn and what is saved agree. With the reporter's commands, the saved points are now within 0.0006 of AutoCAD's: M -0.9032 (AutoCAD -0.9038), BL -19.2604 (-19.2599). Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/lib.rs | 156 ++++++++++++++++++++++++++++++------- crates/fonts/src/ttf.rs | 10 +++ docs/file-format-parity.md | 5 +- 3 files changed, 139 insertions(+), 32 deletions(-) diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 13af05646..8ca1bc62f 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -502,6 +502,42 @@ pub fn baseline_start(font: &TextFont, s: &str, p: &TextParams) -> Vec2 { origin + Vec2::new(local.x * mirror.x, local.y * mirror.y).rotate(rot) } +/// How far below the baseline a bottom-justified text's alignment point lies: a third of the +/// height for the stroke font (as AutoCAD places it with SHX fonts), the face's descent for an +/// outline font (#2229). +fn bottom_depth(font: &TextFont, height: f64) -> f64 { + match font { + TextFont::Outline(face) => ttf::descent_ratio(face).map_or(height / 3.0, |r| r * height), + TextFont::Stroke => height / 3.0, + } +} + +/// The vertical middle of shaped text's ink (its strokes and outlines), above the baseline; +/// `None` when it draws nothing. A Middle (M) text is centred there: AutoCAD centres it on the +/// string's own extents, descenders included, not at half the height (#2229). +fn ink_middle(sh: &Shaped) -> Option { + let ys = sh.strokes.iter().flatten().chain(sh.glyphs.iter().flatten().flatten()).map(|q| q.y).filter(|y| y.is_finite()); + let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); + (lo <= hi).then_some((lo + hi) / 2.0) +} + +/// The offset of a line's baseline start from its alignment point, for justification `h`/`v`. +fn justify_offset(font: &TextFont, sh: &Shaped, height: f64, h: Align, v: VAlign) -> Vec2 { + let dx = match h { + Align::Left | Align::Aligned | Align::Fit => 0.0, + Align::Center | Align::Middle => -sh.width / 2.0, + Align::Right => -sh.width, + }; + let dy = match (h, v) { + (Align::Middle, _) => -ink_middle(sh).unwrap_or(height / 2.0), + (_, VAlign::Baseline) => 0.0, + (_, VAlign::Bottom) => bottom_depth(font, height), + (_, VAlign::Middle) => -height / 2.0, + (_, VAlign::Top) => -height, + }; + Vec2::new(dx, dy) +} + /// How [`place`] puts a line in the world: the point it is placed by, the offset of its baseline /// start from that point (along the text), its rotation and its mirroring (backwards, upside /// down). Aligned and fit text are placed by their insertion point. @@ -512,25 +548,13 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) { let rot = p.align_pt.map_or(rot, |p2| p.insert.angle_to(p2)); return (p.insert, Vec2::ZERO, rot, Vec2::new(1.0, 1.0)); } - let width = shape_line(font, s, height, p.width_factor, p.oblique).width; + let sh = shape_line(font, s, height, p.width_factor, p.oblique); let origin = match (p.h, p.v) { (Align::Left, VAlign::Baseline) => p.insert, _ => p.align_pt.unwrap_or(p.insert), }; - let dx = match p.h { - Align::Left | Align::Aligned | Align::Fit => 0.0, - Align::Center | Align::Middle => -width / 2.0, - Align::Right => -width, - }; - let dy = match (p.h, p.v) { - (Align::Middle, _) => -height / 2.0, - (_, VAlign::Baseline) => 0.0, - (_, VAlign::Bottom) => height / 3.0, - (_, VAlign::Middle) => -height / 2.0, - (_, VAlign::Top) => -height, - }; let mirror = Vec2::new(if p.backwards { -1.0 } else { 1.0 }, if p.upside_down { -1.0 } else { 1.0 }); - (origin, Vec2::new(dx, dy), rot, mirror) + (origin, justify_offset(font, &sh, height, p.h, p.v), rot, mirror) } /// Place a single-line TEXT in world coordinates with any font. Returns the shaped text and its @@ -563,28 +587,15 @@ pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { (Align::Left, VAlign::Baseline) | (Align::Aligned | Align::Fit, _) => insert, _ => p.align_pt.unwrap_or(insert), }; - let dx = match p.h { - Align::Left | Align::Aligned | Align::Fit => 0.0, - Align::Center | Align::Middle => -width / 2.0, - Align::Right => -width, - }; - let dy = match (p.h, p.v) { - (Align::Middle, _) => -height / 2.0, - (_, VAlign::Baseline) => 0.0, - (_, VAlign::Bottom) => height / 3.0, - (_, VAlign::Middle) => -height / 2.0, - (_, VAlign::Top) => -height, - }; - let local = Vec2::new(dx, dy); + let local = justify_offset(font, &sh, height, p.h, p.v); let (mx, my) = (if p.backwards { -1.0 } else { 1.0 }, if p.upside_down { -1.0 } else { 1.0 }); let xf = |q: Vec2| { let l = q + local; origin + Vec2::new(l.x * mx, l.y * my).rotate(rot) }; sh.map(xf); - let bb = Bounds2::from_points( - [Vec2::new(0.0, -height / 3.0), Vec2::new(width, -height / 3.0), Vec2::new(width, height), Vec2::new(0.0, height)].map(xf), - ); + let depth = bottom_depth(font, height); + let bb = Bounds2::from_points([Vec2::new(0.0, -depth), Vec2::new(width, -depth), Vec2::new(width, height), Vec2::new(0.0, height)].map(xf)); (sh, bb) } @@ -797,3 +808,88 @@ mod ttf_tests { assert!(crate::is_wide('\u{3042}') && crate::is_wide('\u{AC00}') && crate::is_wide('\u{FF21}') && !crate::is_wide('A')); } } + +#[cfg(test)] +mod justify_tests { + use super::*; + + const H: f64 = 2.5; + + /// `s` placed by the alignment point (0, 0) with justification `h`/`v` in `font`. + fn placed(font: &TextFont, s: &str, h: Align, v: VAlign) -> (Shaped, Vec2) { + let p = TextParams { align_pt: Some(Vec2::ZERO), h, v, ..TextParams::new(Vec2::ZERO, H) }; + (place(font, s, &p).0, baseline_start(font, s, &p)) + } + + /// The lowest and highest point of placed text's ink. + fn ink_y(sh: &Shaped) -> (f64, f64) { + let ys = sh.strokes.iter().flatten().chain(sh.glyphs.iter().flatten().flatten()).map(|q| q.y); + ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))) + } + + /// A Middle (M) text is centred on its own ink, descenders included, as AutoCAD centres it, + /// not at half the height: lowercase and descenders move the baseline (#2229). + #[test] + fn a_middle_text_is_centred_on_its_ink() { + let font = TextFont::Stroke; + let mut baselines = Vec::new(); + for s in ["ABC 123", "gjpqy", "Tg 1234 ABC", "ace"] { + let (sh, start) = placed(&font, s, Align::Middle, VAlign::Baseline); + let (lo, hi) = ink_y(&sh); + assert!(((lo + hi) / 2.0).abs() < 1e-9, "{s}: ink {lo}..{hi} is centred on the alignment point"); + // The insertion point a DWG keeps (group 10) is the baseline start, below the ink's + // middle by as much as the unplaced text's ink middle is above its baseline. + let (lo0, hi0) = ink_y(&shape_line(&font, s, H, 1.0, 0.0)); + assert!((start.y + (lo0 + hi0) / 2.0).abs() < 1e-9, "{s}: baseline start {start:?}"); + baselines.push((s, start.y)); + } + // Capitals and digits span the height, so they stay at half of it. + assert!((baselines[0].1 + H / 2.0).abs() < 1e-9, "{baselines:?}"); + // Descenders, or lowercase alone, bring the ink's middle down, so the baseline sits higher. + for (s, y) in &baselines[1..] { + if *s != "Tg 1234 ABC" { + assert!(*y > -H / 2.0 + 0.1, "{s}: {baselines:?}"); + } + } + } + + /// Text that draws nothing has no ink to centre: it keeps half the height. + #[test] + fn a_middle_text_without_ink_keeps_half_the_height() { + let (_, start) = placed(&TextFont::Stroke, " ", Align::Middle, VAlign::Baseline); + assert!((start.y + H / 2.0).abs() < 1e-9, "{start:?}"); + } + + /// With the stroke font (as with AutoCAD's SHX fonts), a bottom-justified text's baseline is + /// a third of the height above its alignment point, and Middle Center still uses half. + #[test] + fn stroke_font_bottom_and_middle_center_are_unchanged() { + let font = TextFont::Stroke; + for h in [Align::Left, Align::Center, Align::Right] { + let (_, start) = placed(&font, "gjpqy", h, VAlign::Bottom); + assert!((start.y - H / 3.0).abs() < 1e-9, "{h:?}: {start:?}"); + } + let (_, start) = placed(&font, "gjpqy", Align::Center, VAlign::Middle); + assert!((start.y + H / 2.0).abs() < 1e-9, "MC: {start:?}"); + } + + /// With a TrueType font, a bottom-justified text's alignment point is at the face's descent, + /// where its descenders end, as AutoCAD places it (#2229: Arial's is 0.296 of the height). + /// Skips when Arial isn't installed. + #[test] + fn a_bottom_justified_truetype_text_sits_on_its_descent() { + let Some(face) = ttf::find("Arial") else { return }; + let ratio = ttf::descent_ratio(&face).unwrap(); + assert!((ratio - 0.296).abs() < 0.01, "Arial's descent over cap height: {ratio}"); + let font = TextFont::Outline(face); + let (sh, start) = placed(&font, "gjpqy", Align::Left, VAlign::Bottom); + assert!((start.y - ratio * H).abs() < 1e-9, "{start:?}"); + // The descenders reach the alignment point's line: h/3 left them 0.1 above it. + let (lo, _) = ink_y(&sh); + assert!(lo.abs() < 0.02 * H, "descender bottom {lo} from the alignment point"); + // And Middle centres the ink, as with the stroke font. + let (sh, _) = placed(&font, "Tg 1234 ABC", Align::Middle, VAlign::Baseline); + let (lo, hi) = ink_y(&sh); + assert!(((lo + hi) / 2.0).abs() < 1e-9, "{lo}..{hi}"); + } +} diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 6b4c5ebdd..9c1888aa8 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -709,6 +709,16 @@ impl OutlinePen for Pen { } } +/// How far below the baseline a face reaches, as a fraction of the text height (which is the +/// face's cap height): its descent over its cap height. A bottom-justified text's alignment +/// point is there, as AutoCAD places it (#2229). `None` when the face has no usable descent. +pub fn descent_ratio(face: &Face) -> Option { + let f = face.font()?; + let descent = -f64::from(f.metrics(Size::new(UPEM), LocationRef::default()).descent); + let r = descent / cap_height(&f); + (r.is_finite() && r > 0.0 && r < 2.0).then_some(r) +} + /// Cap height of a font in font units at 1000 units per em: the OS/2 value, else the height /// of its "H", else an estimate from the ascent. fn cap_height(f: &FontRef) -> f64 { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2bfea4a51..51d4ac74c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LAYOUT SAveas writes a layout as a DWT template) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (a Middle or bottom-justified TEXT's insertion point as AutoCAD computes it) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -75,7 +75,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137) | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137); 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) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | TEXT placement: a Middle (M) text is centred on its own extents, descenders included, and a bottom-justified text with a TrueType font sits on the face's descent, as AutoCAD places them; the stroke font's bottom stays at a third of the height. A DWG's group 10 for these texts now matches AutoCAD's within 0.001 at height 2.5 (it was up to 0.35 off) (#2229) | | 2026-10-25 | minor | LAYOUT SAveas (`layout.saveas`) writes a layout as a drawing template: its page setup and paper space objects, no model space objects or other layouts, and only the named objects they use | | 2026-10-22 | minor | DXF/DWG save: angular, diametric and radial dimensions get standard DIMASSOC objects (one centre reference to the circle for radial/diametric, the definition points for angular), so AutoCAD follows their geometry; the standard objects of those kinds are read back too, without CADCraft's xdata (#1651) | | 2026-10-19 | minor | DXF/DWG save: angular dimension block text honors DIMDSEP, including per-dimension overrides (#1646) | From 263eba2ef6430c570cd3cce5c2266a495075d95f Mon Sep 17 00:00:00 2001 From: austin62jake <340374338+austin62jake@users.noreply.github.com> Date: Thu, 29 Oct 2026 10:15:20 -0500 Subject: [PATCH 156/900] Test bottom-justified TrueType text with any common installed font The test used Arial only, so it skipped on Linux and macOS CI. It now uses the first of Arial, Helvetica, DejaVuSans, Verdana or Liberation Sans that is installed (as the fonts crate's other TrueType tests do), and keeps the Arial-specific checks for Arial. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/lib.rs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 8ca1bc62f..5bbae6883 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -875,21 +875,25 @@ mod justify_tests { /// With a TrueType font, a bottom-justified text's alignment point is at the face's descent, /// where its descenders end, as AutoCAD places it (#2229: Arial's is 0.296 of the height). - /// Skips when Arial isn't installed. + /// Uses the first of these common fonts that is installed (Windows, macOS and Linux each have + /// one); skips without any. #[test] fn a_bottom_justified_truetype_text_sits_on_its_descent() { - let Some(face) = ttf::find("Arial") else { return }; + let found = ["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find_map(|n| ttf::find(n).map(|f| (n, f))); + let Some((name, face)) = found else { return }; let ratio = ttf::descent_ratio(&face).unwrap(); - assert!((ratio - 0.296).abs() < 0.01, "Arial's descent over cap height: {ratio}"); let font = TextFont::Outline(face); let (sh, start) = placed(&font, "gjpqy", Align::Left, VAlign::Bottom); - assert!((start.y - ratio * H).abs() < 1e-9, "{start:?}"); - // The descenders reach the alignment point's line: h/3 left them 0.1 above it. - let (lo, _) = ink_y(&sh); - assert!(lo.abs() < 0.02 * H, "descender bottom {lo} from the alignment point"); + assert!((start.y - ratio * H).abs() < 1e-9, "{name}: {start:?}"); + if name == "Arial" { + assert!((ratio - 0.296).abs() < 0.01, "Arial's descent over cap height: {ratio}"); + // The descenders reach the alignment point's line: h/3 left them 0.1 above it. + let (lo, _) = ink_y(&sh); + assert!(lo.abs() < 0.02 * H, "descender bottom {lo} from the alignment point"); + } // And Middle centres the ink, as with the stroke font. let (sh, _) = placed(&font, "Tg 1234 ABC", Align::Middle, VAlign::Baseline); let (lo, hi) = ink_y(&sh); - assert!(((lo + hi) / 2.0).abs() < 1e-9, "{lo}..{hi}"); + assert!(((lo + hi) / 2.0).abs() < 1e-9, "{name}: {lo}..{hi}"); } } From 4226a2610abc648880c7be0fc7768641fa805b97 Mon Sep 17 00:00:00 2001 From: assamaral Date: Thu, 29 Oct 2026 15:37:34 -0300 Subject: [PATCH 157/900] test(io): an MTEXT's R2018 embedded column object is read and written (#2248) Co-Authored-By: Claude Sonnet 5.5 --- crates/io/tests/it/mtext_columns_roundtrip.rs | 87 ++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/crates/io/tests/it/mtext_columns_roundtrip.rs b/crates/io/tests/it/mtext_columns_roundtrip.rs index 7db9ed685..633fb1396 100644 --- a/crates/io/tests/it/mtext_columns_roundtrip.rs +++ b/crates/io/tests/it/mtext_columns_roundtrip.rs @@ -3,7 +3,7 @@ use cadcraft_doc::{Common, Drawing, EntityKind, MText, MTextColumnType, MTextColumns, Space}; use cadcraft_geom::Vec3; -use cadcraft_io::{read_dxf, write_dxf}; +use cadcraft_io::{SaveOptions, Version, entity_from_groups, read_dxf, write_dxf, write_with}; fn mtext(contents: &str, rotation: f64, columns: Option) -> MText { MText { @@ -91,3 +91,88 @@ fn hostile_column_groups_do_not_panic() { let _ = read_dxf(bad.as_bytes()); } } + +// ---- #2248: R2018 embedded column object ---- + +fn embedded_tags(count: i64, width: f64, gutter: f64, heights: &[f64]) -> Vec { + use cadcraft_dxf::Tag; + let mut v = vec![ + Tag::s(8, "0"), + Tag::f(10, 10.0), + Tag::f(20, 10.0), + Tag::f(30, 0.0), + Tag::f(40, 2.5), + Tag::f(41, width), + Tag::i(71, 5), + Tag::i(72, 5), + Tag::s(1, "Hello"), + Tag::s(101, "Embedded Object"), + Tag::i(70, 1), + Tag::f(10, 1.0), + Tag::f(20, 0.0), + Tag::f(30, 0.0), + Tag::f(11, 10.0), + Tag::f(21, 10.0), + Tag::f(31, 0.0), + Tag::f(40, width), + Tag::f(41, 0.0), + Tag::f(42, width), + Tag::f(43, 0.0), + Tag::i(71, 1), + Tag::i(72, count), + Tag::f(44, width), + Tag::f(45, gutter), + Tag::i(73, 0), + Tag::i(74, 0), + ]; + v.extend(heights.iter().map(|h| Tag::f(46, *h))); + v +} + +fn mtext_from_groups(tags: &[cadcraft_dxf::Tag]) -> (Common, MText) { + let Some((common, EntityKind::MText(t))) = entity_from_groups("MTEXT", tags) else { panic!("MTEXT was not read") }; + (common, t) +} + +fn dxf_as(t: &MText, version: Version) -> String { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::MText(t.clone())).unwrap(); + let bytes = write_with(&d, "x.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap(); + String::from_utf8_lossy(&bytes).into_owned() +} + +#[test] +fn embedded_object_does_not_leak_into_the_entity() { + // A single column (the usual R2018 block of a plain MTEXT): 44 is the column width, not the + // line spacing factor, and the columns are kept. + let (_, t) = mtext_from_groups(&embedded_tags(1, 38.8, 12.5, &[0.0])); + assert_eq!(t.line_spacing, 1.0, "44 of the embedded object is the column width"); + assert_eq!(t.attach, 5); + assert_eq!(t.width, 38.8); + let c = MTextColumns { kind: MTextColumnType::Static, count: 1, gutter: 12.5, height: 0.0, ..Default::default() }; + assert_eq!(t.columns, Some(c)); +} + +#[test] +fn embedded_static_columns_are_read() { + let (_, t) = mtext_from_groups(&embedded_tags(3, 12.5, 2.5, &[20.0, 20.0, 20.0])); + let c = MTextColumns { kind: MTextColumnType::Static, count: 3, gutter: 2.5, height: 20.0, ..Default::default() }; + assert_eq!(t.columns, Some(c)); +} + +#[test] +fn r2018_writes_the_embedded_object_and_older_versions_the_legacy_groups() { + let (_, t) = mtext_from_groups(&embedded_tags(3, 12.5, 2.5, &[20.0, 20.0, 20.0])); + let r2018 = dxf_as(&t, Version::R2018); + assert!(r2018.contains("101\r\nEmbedded Object\r\n"), "R2018 keeps the embedded object"); + assert!(!r2018.contains(" 75\r\n"), "no legacy column groups in R2018"); + assert!(r2018.contains(" 72\r\n5\r\n"), "the flow direction (72) is kept"); + assert!(r2018.contains(" 44\r\n12.5\r\n 45\r\n2.5\r\n"), "column width and gutter"); + assert!(!r2018.contains(" 44\r\n1.0\r\n"), "the entity's line spacing is not the column width"); + let back = read_dxf(r2018.as_bytes()).unwrap(); + let Some(EntityKind::MText(b)) = back.model.iter().map(|e| e.kind.clone()).find(|k| matches!(k, EntityKind::MText(_))) else { panic!("no mtext") }; + assert_eq!(b.columns, t.columns); + let r2000 = dxf_as(&t, Version::R2000); + assert!(!r2000.contains("Embedded Object"), "R2000 has no embedded object"); + assert!(r2000.contains(" 75\r\n1\r\n"), "R2000 keeps the legacy column groups"); +} From c2cb5b86109b4df3a822a29ac0d706284e0c7b54 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <236787783+midasmatterhorn@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:49:48 +0300 Subject: [PATCH 158/900] engine: propagate create_dir_all errors and route render PNG writes through write_atomic --- crates/engine/src/atomic_write.rs | 4 +--- crates/mcp/src/backend.rs | 3 ++- crates/ui-egui/src/control.rs | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/atomic_write.rs b/crates/engine/src/atomic_write.rs index cd7d0fb4b..2d05e019d 100644 --- a/crates/engine/src/atomic_write.rs +++ b/crates/engine/src/atomic_write.rs @@ -37,9 +37,7 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { Err(e) => return Err(e), }; let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf); - if let Err(e) = std::fs::create_dir_all(&dir) { - return Err(e); - } + std::fs::create_dir_all(&dir)?; let (mut file, tmp) = create_temp(&dir, permissions.as_ref())?; let write = (|| { if let Some(permissions) = permissions { diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 9d012076a..d27012418 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -395,7 +395,8 @@ impl Backend for Headless { let png = cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()).ok_or("render failed")?; if let Some(path) = str_p("path") { - std::fs::write(&path, &png).map_err(|e| format!("{path}: {e}"))?; + cadcraft_engine::atomic_write::write_atomic(std::path::Path::new(&path), &png) + .map_err(|e| format!("{path}: {e}"))?; } Ok(json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h})) } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2dc1f898a..4370b5de1 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -489,7 +489,7 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou }; #[cfg(not(target_arch = "wasm32"))] if let Some(path) = s("path") { - if let Err(e) = std::fs::write(path, &png) { + if let Err(e) = cadcraft_engine::atomic_write::write_atomic(std::path::Path::new(&path), &png) { return err(e); } return ok(render_reply(&png, w, h, Some(path))); From 9ff37ba2622ef365dead8693a79455244542635b Mon Sep 17 00:00:00 2001 From: assamaral Date: Thu, 29 Oct 2026 15:55:52 -0300 Subject: [PATCH 159/900] fix(io): an MTEXT's R2018 embedded column object is kept and its groups stay out of the entity (#2248) The reader took the embedded object's 44 (column width) as the MTEXT's line spacing factor and dropped its columns; the writer wrote no embedded object, the legacy column groups (which R2018 ignores) and a drawing direction of 1 instead of 5 (by style). Now the embedded object is read (type, count, width, gutter, heights), written for R2018 and later, and the MTEXT's own groups are the ones before it. AutoLISP entget keeps the legacy groups. Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/dxf_read/mtext_dxf.rs | 61 +++++++++++++++++-- crates/io/src/dxf_read/text.rs | 5 +- crates/io/src/dxf_write.rs | 2 +- crates/io/src/dxf_write/ctx.rs | 2 + crates/io/src/dxf_write/entity.rs | 5 +- crates/io/tests/it/mtext_columns_roundtrip.rs | 22 ++++--- 6 files changed, 82 insertions(+), 15 deletions(-) diff --git a/crates/io/src/dxf_read/mtext_dxf.rs b/crates/io/src/dxf_read/mtext_dxf.rs index f955603e6..5a7b6ec55 100644 --- a/crates/io/src/dxf_read/mtext_dxf.rs +++ b/crates/io/src/dxf_read/mtext_dxf.rs @@ -56,7 +56,7 @@ pub(crate) fn encode_contents(s: &str) -> String { } /// The MTEXT's own tags: up to an embedded object (group 101), whose groups reuse MTEXT's codes. -fn own(tags: &[Tag]) -> &[Tag] { +pub(crate) fn own(tags: &[Tag]) -> &[Tag] { let end = tags.iter().position(|t| t.code == 101).unwrap_or(tags.len()); tags.get(..end).unwrap_or(tags) } @@ -74,8 +74,8 @@ fn finite(v: f64) -> f64 { /// The columns of an MTEXT, and the column width (group 48) when there are columns. pub(crate) fn read_columns(tags: &[Tag]) -> Option<(MTextColumns, f64)> { + let Some(start) = own(tags).iter().position(|t| t.code == 75) else { return read_embedded_columns(tags) }; let tags = own(tags); - let start = tags.iter().position(|t| t.code == 75)?; let kind = match tags.get(start).map(Tag::i64) { Some(1) => MTextColumnType::Static, Some(2) => MTextColumnType::Dynamic, @@ -101,12 +101,65 @@ pub(crate) fn read_columns(tags: &[Tag]) -> Option<(MTextColumns, f64)> { Some((c, first(48).map(|t| finite(t.f64()).max(0.0)).unwrap_or(0.0))) } -/// The column groups of an MTEXT with columns. -pub(crate) fn column_tags(t: &MText) -> Vec { +/// The columns of an R2018 MTEXT, from its embedded object (group 101), whose groups reuse +/// MTEXT's codes: 71 type, 72 count, 44 column width, 45 gutter, 73 auto height, 74 flow +/// reversed, 46 heights. The column width is also the MTEXT's width. +fn read_embedded_columns(tags: &[Tag]) -> Option<(MTextColumns, f64)> { + let obj = tags.get(tags.iter().position(|t| t.code == 101)? + 1..)?; + let first = |code: i32| obj.iter().find(|t| t.code == code); + let kind = match first(71).map(Tag::i64) { + Some(1) => MTextColumnType::Static, + Some(2) => MTextColumnType::Dynamic, + _ => return None, + }; + let heights: Vec = obj.iter().filter(|t| t.code == 46).take(MAX_COLUMNS).map(|t| finite(t.f64()).max(0.0)).collect(); + let auto_height = first(73).map(Tag::i64).unwrap_or(0) != 0; + let manual = kind == MTextColumnType::Dynamic && !auto_height; + let c = MTextColumns { + kind, + count: u16::try_from(first(72).map(Tag::i64).unwrap_or(1).clamp(1, MAX_COLUMNS as i64)).unwrap_or(1), + gutter: first(45).map(|t| finite(t.f64()).max(0.0)).unwrap_or(0.0), + height: if manual { heights.iter().copied().fold(0.0, f64::max) } else { heights.first().copied().unwrap_or(0.0) }, + auto_height, + heights: if manual { heights } else { Vec::new() }, + flow_reversed: first(74).map(Tag::i64).unwrap_or(0) != 0, + }; + Some((c, first(44).map(|t| finite(t.f64()).max(0.0)).unwrap_or(0.0))) +} + +/// The column groups of an MTEXT with columns: the legacy groups 75/76/78/79/48/49/50 before +/// R2018, an embedded object (group 101) from R2018 on, which reads those as the entity's own. +pub(crate) fn column_tags(t: &MText, embedded: bool) -> Vec { let Some(c) = &t.columns else { return Vec::new() }; let manual = c.kind == MTextColumnType::Dynamic && !c.auto_height; let heights: Vec = if manual { c.heights.clone() } else { vec![c.height; usize::from(c.count.max(1))] }; let count = if manual { heights.len().max(1) } else { usize::from(c.count.max(1)) }; + if embedded { + let (sin, cos) = t.rotation.sin_cos(); + let total_width = t.width * count as f64 + c.gutter * (count as f64 - 1.0); + let mut v = vec![ + Tag::s(101, "Embedded Object"), + Tag::i(70, 1), + Tag::f(10, cos), + Tag::f(20, sin), + Tag::f(30, 0.0), + Tag::f(11, t.insert.x), + Tag::f(21, t.insert.y), + Tag::f(31, t.insert.z), + Tag::f(40, t.width), + Tag::f(41, 0.0), + Tag::f(42, total_width), + Tag::f(43, heights.iter().copied().fold(0.0, f64::max)), + Tag::i(71, if c.kind == MTextColumnType::Dynamic { 2 } else { 1 }), + Tag::i(72, count as i64), + Tag::f(44, t.width), + Tag::f(45, c.gutter), + Tag::i(73, i64::from(c.auto_height)), + Tag::i(74, i64::from(c.flow_reversed)), + ]; + v.extend(heights.into_iter().map(|h| Tag::f(46, h))); + return v; + } let mut v = vec![ Tag::i(75, if c.kind == MTextColumnType::Dynamic { 2 } else { 1 }), Tag::i(76, count as i64), diff --git a/crates/io/src/dxf_read/text.rs b/crates/io/src/dxf_read/text.rs index 10d770c0e..158015169 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -42,6 +42,10 @@ pub(super) fn multiline_attrib(embedded: Option<&[Tag]>, c: &Common) -> Option MText { + // The MTEXT's own groups: an embedded object (group 101) reuses their codes (44 is its + // column width, not the line spacing factor). + let columns = mtext_dxf::read_columns(tags); + let tags = mtext_dxf::own(tags); let t = T(tags); // Contents: code 3 chunks followed by code 1. let mut contents = String::new(); @@ -50,7 +54,6 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText { } contents.push_str(&t.s(1).unwrap_or_default()); let contents = mtext_dxf::decode_contents(&contents); - let columns = mtext_dxf::read_columns(tags); // The direction comes from the MTEXT's own groups only: in an R2018+ embedded object // (group 101), 11 is the insertion point, not the X-axis direction (#667, as in #834). let own = T(mtext_dxf::before_columns(tags)); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 4ec9fc636..dba29c7f7 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -146,7 +146,7 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec) { layers: HashMap::new(), reactors: HashMap::new(), }; - let cx = Ctx { target: Version::R2018, ..Ctx::default() }; + let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() }; let paper = d.space_of(e.handle).is_some_and(|s| !matches!(s, cadcraft_doc::Space::Model)); entity(&mut w, d, e, "0", paper, &cx); let mut tags = w.t.into_iter(); diff --git a/crates/io/src/dxf_write/ctx.rs b/crates/io/src/dxf_write/ctx.rs index ce9c38b7a..157dcd441 100644 --- a/crates/io/src/dxf_write/ctx.rs +++ b/crates/io/src/dxf_write/ctx.rs @@ -53,6 +53,8 @@ pub(super) struct Ctx { /// The version the file ends up in (the DWG version for a DWG save): it decides which /// entity types exist (MULTILEADER from 2007). pub(super) target: Version, + /// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists). + pub(super) legacy_columns: bool, } impl Ctx { diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index cd41cdf91..fa4c0f3e5 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -256,7 +256,8 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo w.f(40, t.height); w.f(41, t.width); w.i(71, i64::from(t.attach)); - w.i(72, 1); + // Drawing direction: 5, by style. + w.i(72, 5); // Long contents go in 250-char 3-chunks, the remainder in 1. let chars: Vec = crate::dxf_read::mtext_dxf::encode_contents(&t.contents).chars().collect(); let chunks: Vec = chars.chunks(250).map(|c| c.iter().collect()).collect(); @@ -274,7 +275,7 @@ fn write_text_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo // Line spacing style: 1 = at least, 2 = exactly. w.i(73, if t.line_spacing_exact { 2 } else { 1 }); w.f(44, t.line_spacing); - w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t)); + w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t, cx.target >= Version::R2018 && !cx.legacy_columns)); } _ => {} } diff --git a/crates/io/tests/it/mtext_columns_roundtrip.rs b/crates/io/tests/it/mtext_columns_roundtrip.rs index 633fb1396..d9a692a8e 100644 --- a/crates/io/tests/it/mtext_columns_roundtrip.rs +++ b/crates/io/tests/it/mtext_columns_roundtrip.rs @@ -134,11 +134,16 @@ fn mtext_from_groups(tags: &[cadcraft_dxf::Tag]) -> (Common, MText) { (common, t) } -fn dxf_as(t: &MText, version: Version) -> String { +/// The DXF of `t` written as `version` and its MTEXT record only (other sections reuse the codes). +fn dxf_as(t: &MText, version: Version) -> (String, String) { let mut d = Drawing::new_metric(); d.add(&Space::Model, Common::default(), EntityKind::MText(t.clone())).unwrap(); let bytes = write_with(&d, "x.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap(); - String::from_utf8_lossy(&bytes).into_owned() + let text = String::from_utf8_lossy(&bytes).into_owned(); + let from = text.find(" 0\r\nMTEXT\r\n").expect("an MTEXT"); + let len = text[from + 5..].find(" 0\r\n").map_or(text.len() - from, |n| n + 5); + let record = text[from..from + len].to_string(); + (text, record) } #[test] @@ -163,16 +168,19 @@ fn embedded_static_columns_are_read() { #[test] fn r2018_writes_the_embedded_object_and_older_versions_the_legacy_groups() { let (_, t) = mtext_from_groups(&embedded_tags(3, 12.5, 2.5, &[20.0, 20.0, 20.0])); - let r2018 = dxf_as(&t, Version::R2018); + let (full, r2018) = dxf_as(&t, Version::R2018); assert!(r2018.contains("101\r\nEmbedded Object\r\n"), "R2018 keeps the embedded object"); assert!(!r2018.contains(" 75\r\n"), "no legacy column groups in R2018"); assert!(r2018.contains(" 72\r\n5\r\n"), "the flow direction (72) is kept"); assert!(r2018.contains(" 44\r\n12.5\r\n 45\r\n2.5\r\n"), "column width and gutter"); - assert!(!r2018.contains(" 44\r\n1.0\r\n"), "the entity's line spacing is not the column width"); - let back = read_dxf(r2018.as_bytes()).unwrap(); - let Some(EntityKind::MText(b)) = back.model.iter().map(|e| e.kind.clone()).find(|k| matches!(k, EntityKind::MText(_))) else { panic!("no mtext") }; + let own = r2018.split("Embedded Object").next().unwrap_or_default(); + assert!(own.contains(" 44\r\n1.0\r\n") && !own.contains(" 44\r\n12.5\r\n"), "the entity's line spacing is not the column width"); + let back = read_dxf(full.as_bytes()).unwrap(); + let Some(EntityKind::MText(b)) = back.model.iter().map(|e| e.kind.clone()).find(|k| matches!(k, EntityKind::MText(_))) else { + panic!("no mtext") + }; assert_eq!(b.columns, t.columns); - let r2000 = dxf_as(&t, Version::R2000); + let (_, r2000) = dxf_as(&t, Version::R2000); assert!(!r2000.contains("Embedded Object"), "R2000 has no embedded object"); assert!(r2000.contains(" 75\r\n1\r\n"), "R2000 keeps the legacy column groups"); } From c5d186ae92520b554e42d87d1fc6a88cb1c90ae4 Mon Sep 17 00:00:00 2001 From: assamaral Date: Thu, 29 Oct 2026 16:07:47 -0300 Subject: [PATCH 160/900] fix(io): the embedded column object carries the column height like AutoCAD's (#2248) Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/dxf_read/mtext_dxf.rs | 16 ++++++++++++---- crates/io/tests/it/mtext_columns_roundtrip.rs | 10 ++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/io/src/dxf_read/mtext_dxf.rs b/crates/io/src/dxf_read/mtext_dxf.rs index 5a7b6ec55..e7752f711 100644 --- a/crates/io/src/dxf_read/mtext_dxf.rs +++ b/crates/io/src/dxf_read/mtext_dxf.rs @@ -115,11 +115,14 @@ fn read_embedded_columns(tags: &[Tag]) -> Option<(MTextColumns, f64)> { let heights: Vec = obj.iter().filter(|t| t.code == 46).take(MAX_COLUMNS).map(|t| finite(t.f64()).max(0.0)).collect(); let auto_height = first(73).map(Tag::i64).unwrap_or(0) != 0; let manual = kind == MTextColumnType::Dynamic && !auto_height; + // The column height: the entity's own 46 (defined height), else the object's 41 or first 46. + let own_46 = own(tags).iter().find(|t| t.code == 46).map(|t| finite(t.f64()).max(0.0)); + let defined = [own_46, first(41).map(|t| finite(t.f64())), heights.first().copied()].into_iter().flatten().find(|h| *h > 0.0).unwrap_or(0.0); let c = MTextColumns { kind, count: u16::try_from(first(72).map(Tag::i64).unwrap_or(1).clamp(1, MAX_COLUMNS as i64)).unwrap_or(1), gutter: first(45).map(|t| finite(t.f64()).max(0.0)).unwrap_or(0.0), - height: if manual { heights.iter().copied().fold(0.0, f64::max) } else { heights.first().copied().unwrap_or(0.0) }, + height: if manual { heights.iter().copied().fold(0.0, f64::max) } else { defined }, auto_height, heights: if manual { heights } else { Vec::new() }, flow_reversed: first(74).map(Tag::i64).unwrap_or(0) != 0, @@ -137,7 +140,10 @@ pub(crate) fn column_tags(t: &MText, embedded: bool) -> Vec { if embedded { let (sin, cos) = t.rotation.sin_cos(); let total_width = t.width * count as f64 + c.gutter * (count as f64 - 1.0); + // The column height (static, and dynamic with auto height) is the entity's group 46. + let height = if manual { heights.iter().copied().fold(0.0, f64::max) } else { c.height }; let mut v = vec![ + Tag::f(46, height), Tag::s(101, "Embedded Object"), Tag::i(70, 1), Tag::f(10, cos), @@ -147,9 +153,9 @@ pub(crate) fn column_tags(t: &MText, embedded: bool) -> Vec { Tag::f(21, t.insert.y), Tag::f(31, t.insert.z), Tag::f(40, t.width), - Tag::f(41, 0.0), + Tag::f(41, height), Tag::f(42, total_width), - Tag::f(43, heights.iter().copied().fold(0.0, f64::max)), + Tag::f(43, height), Tag::i(71, if c.kind == MTextColumnType::Dynamic { 2 } else { 1 }), Tag::i(72, count as i64), Tag::f(44, t.width), @@ -157,7 +163,9 @@ pub(crate) fn column_tags(t: &MText, embedded: bool) -> Vec { Tag::i(73, i64::from(c.auto_height)), Tag::i(74, i64::from(c.flow_reversed)), ]; - v.extend(heights.into_iter().map(|h| Tag::f(46, h))); + if manual { + v.extend(heights.into_iter().map(|h| Tag::f(46, h))); + } return v; } let mut v = vec![ diff --git a/crates/io/tests/it/mtext_columns_roundtrip.rs b/crates/io/tests/it/mtext_columns_roundtrip.rs index d9a692a8e..3525c8d29 100644 --- a/crates/io/tests/it/mtext_columns_roundtrip.rs +++ b/crates/io/tests/it/mtext_columns_roundtrip.rs @@ -165,6 +165,16 @@ fn embedded_static_columns_are_read() { assert_eq!(t.columns, Some(c)); } +#[test] +fn embedded_column_height_is_the_entitys_defined_height() { + // As ezdxf and AutoCAD write static columns: the height in the entity's 46, none in the object. + let mut tags = embedded_tags(3, 12.5, 2.5, &[]); + let at = tags.iter().position(|t| t.code == 101).unwrap(); + tags.insert(at, cadcraft_dxf::Tag::f(46, 20.0)); + let (_, t) = mtext_from_groups(&tags); + assert_eq!(t.columns.map(|c| c.height), Some(20.0)); +} + #[test] fn r2018_writes_the_embedded_object_and_older_versions_the_legacy_groups() { let (_, t) = mtext_from_groups(&embedded_tags(3, 12.5, 2.5, &[20.0, 20.0, 20.0])); 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 161/900] 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 b2ebb3958d65450a4ddf779de3500d607eac06bd Mon Sep 17 00:00:00 2001 From: mattlafy Date: Thu, 29 Oct 2026 15:46:01 -0400 Subject: [PATCH 162/900] Place no point on the release of a realtime PAN or ZOOM drag A primary drag that moved the view is marked while it lasts; its release reaches no point prompt, also when Enter ended the transparent PAN or ZOOM mid-drag and handed the prompt back to the drawing command. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 11 ++- crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/realtime_nav_release.rs | 77 +++++++++++++++++++ 3 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/tests/it/realtime_nav_release.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f65c5be05..4d71058c2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -149,6 +149,9 @@ pub struct CanvasState { 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 drag in progress moved the view (realtime PAN or ZOOM): its release is no + /// point, even once the command has ended. + nav_drag: bool, /// 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, @@ -252,10 +255,12 @@ fn navigate_canvas(app: &mut CadApp, ui: &mut egui::Ui, nav: &Navigation<'_>) -> handle_scroll_zoom(app, ui, nav, inside); handle_button_navigation(app, nav, inside); if nav.response.dragged_by(egui::PointerButton::Primary) && app.session.realtime_zoom_active() { + app.canvas.nav_drag = true; let _ = app.session.realtime_zoom(f64::from(nav.response.drag_delta().y)); } // PAN (realtime): the drawing follows a left-button drag. if nav.response.dragged_by(egui::PointerButton::Primary) && app.session.realtime_pan_active() { + app.canvas.nav_drag = true; let d = nav.response.drag_delta(); let _ = app.session.realtime_pan(f64::from(d.x), f64::from(d.y)); } @@ -695,7 +700,11 @@ fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickCo && app.session.pending_window.is_none() && !app.session.realtime_zoom_active() && !app.session.realtime_pan_active(); - let pressed_primary = context.primary_clicked || (point_prompt && context.response.drag_stopped_by(egui::PointerButton::Primary)); + let drag_stopped = context.response.drag_stopped_by(egui::PointerButton::Primary); + // The release of a drag that panned or zoomed (Enter can end the command mid-drag) places + // nothing in the command it returns to. + let nav_release = drag_stopped && std::mem::take(&mut app.canvas.nav_drag); + let pressed_primary = context.primary_clicked || (point_prompt && drag_stopped && !nav_release); if point_prompt && context.inside && pressed_primary && !context.middle_down && app.cmd.options.is_none() && app.cmd.buffer.is_empty() { let releases: Vec = ui.input(|i| { i.events diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c32012e1a..846bb2fa9 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -26,6 +26,7 @@ mod parameters_rename; mod pickdrag; mod properties_units; mod rapid_clicks; +mod realtime_nav_release; mod selection_cycling; mod shared_controls; mod shortcut_menus; diff --git a/crates/ui-egui/tests/it/realtime_nav_release.rs b/crates/ui-egui/tests/it/realtime_nav_release.rs new file mode 100644 index 000000000..6305d8401 --- /dev/null +++ b/crates/ui-egui/tests/it/realtime_nav_release.rs @@ -0,0 +1,77 @@ +//! A drag that pans in realtime places no point when it is let go, even after Enter ended the +//! transparent PAN mid-drag and handed the prompt back to the drawing command. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Drawing, EntityKind, Space}; +use cadcraft_engine::geom::Vec2; +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(), "Realtime release", None); + session.execute("view.set", &json!({"center":[50,50],"height":100})).unwrap(); + session.settings.osmode = 0; + session.settings.snapmode = false; + session.settings.orthomode = false; + 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)).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::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +fn lines(h: &Harness<'_, CadApp>) -> usize { + let st = h.state().session.state().unwrap(); + st.doc.space(&Space::Model).unwrap().iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count() +} + +#[test] +fn enter_mid_drag_ends_pan_and_the_release_places_no_point() { + let mut h = harness(); + h.state_mut().start("line"); + h.run_steps(2); + let first = screen(&h, Vec2::new(10.0, 10.0)); + button(&mut h, first, true); + button(&mut h, first, false); + h.run_steps(2); + h.state_mut().session.cmdline("'PAN").unwrap(); + h.run_steps(1); + assert!(h.state().session.realtime_pan_active()); + let (a, b) = (screen(&h, Vec2::new(40.0, 40.0)), screen(&h, Vec2::new(60.0, 30.0))); + button(&mut h, a, true); + for i in 1..=4 { + h.event(Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))); + h.run_steps(1); + } + h.state_mut().session.cmdline("").unwrap(); + h.run_steps(1); + assert_eq!(h.state().session.running.as_ref().map(|r| r.id.as_str()), Some("line")); + button(&mut h, b, false); + h.run_steps(2); + assert_eq!(lines(&h), 0, "the release of the pan drag placed a point"); + assert_eq!(h.state().session.running.as_ref().map(|r| r.id.as_str()), Some("line")); + // A click after it still places the next point. + button(&mut h, b, true); + button(&mut h, b, false); + h.run_steps(2); + assert_eq!(lines(&h), 1); +} 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 163/900] 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 164/900] 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 b6c1ab74f99dc4c66ab38ba63178fed5a1e441ba Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 10:38:00 +1100 Subject: [PATCH 165/900] DXF: leave SAT-text solids out of files of 2013 and later, with a save note (#2334) REGION, 3DSOLID and BODY read from a DXF 2000 hold SAT text; DXF 2013 and later keep ACIS geometry in the data store section, so writing the text there made a file other readers reject. Those entities are now left out of 2013+ DXF output and counted in the save note; 2010 and earlier, and DWG, are unchanged. Test: sat_text_solids_are_left_out_of_dxf_2013_and_later. --- crates/doc/src/foreign.rs | 26 +++++++++++++++++++++++++ crates/engine/src/cmd/file.rs | 26 +++++++++++++++++++++++++ crates/io/src/dxf_raw.rs | 16 ++++++++++++--- crates/io/src/dxf_write/sections.rs | 2 +- crates/io/tests/it/acis_data_store.rs | 28 +++++++++++++++++++++++++++ 5 files changed, 94 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index e0ebb81a4..3b6aa8ef9 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -94,3 +94,29 @@ impl Foreign { self.data_store.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim())).collect() } } + +/// Whether a solid modeler entity (3DSOLID, REGION, BODY) holds its ACIS geometry as SAT text +/// (groups 1 and 3), which DXF 2013 and later no longer has: those files keep it in the data +/// store section, so an entity with SAT text and no record there can't be written to one (#2334). +pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collections::BTreeSet) -> bool { + ["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) + && !stored.contains(&handle) + && u.tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 1 || r.code == 3) +} + +/// The entities a DXF of 2013 or later leaves out because they hold SAT-text ACIS data +/// ([`sat_text_acis`]), counted by DXF type, across model space, layouts and block definitions. +pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap { + let stored = d.foreign.data_store_entities(); + let mut out = BTreeMap::new(); + 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 crate::EntityKind::Unknown(u) = &e.kind + && sat_text_acis(u, e.handle, &stored) + { + let n: &mut usize = out.entry(u.dxf_type.to_ascii_uppercase()).or_default(); + *n = n.saturating_add(1); + } + } + out +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 3a5296e88..5b012bb4e 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -520,6 +520,8 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result { let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() }); if drops_unknown(format!("drawing.{fmt}")) { report_not_saved(s, &mut r, &lost); + } else if version >= Version::R2013 && is_dxf_file(format!("drawing.{fmt}")) { + report_sat_text_dropped(s, &mut r); } Ok(r) } @@ -575,6 +577,28 @@ fn is_drawing_file(path: impl AsRef) -> bool { Format::from_path(path).is_some_and(Format::is_drawing) } +/// Whether `path` is a DXF file. +fn is_dxf_file(path: impl AsRef) -> bool { + Format::from_path(path) == Some(Format::Dxf) +} + +/// Say on the command line which solid modeler entities a DXF of 2013 or later left out because +/// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334). +fn report_sat_text_dropped(s: &mut Session, r: &mut Value) { + let lost = s.doc().map(cadcraft_doc::foreign::sat_text_dropped).unwrap_or_default(); + if lost.is_empty() { + return; + } + let list: Vec = lost.iter().map(|(t, n)| format!("{n} {t}")).collect(); + s.echo(format!( + "Not saved in the DXF file (2013 and later keep ACIS geometry in a data store these entities have no record in; save as 2010 or earlier to keep them): {}", + list.join(", ") + )); + if let Some(o) = r.as_object_mut() { + o.insert("notSaved".into(), json!(lost)); + } +} + /// Say on the command line what the file couldn't keep, and list it in the result's `notSaved`. fn report_not_saved(s: &mut Session, r: &mut Value, lost: &std::collections::BTreeMap) { let Some(msg) = not_saved_message(lost) else { return }; @@ -593,6 +617,8 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R let mut r = run(s, p)?; if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) { report_not_saved(s, &mut r, &lost); + } else if version >= Version::R2013 && r.get("path").and_then(Value::as_str).is_some_and(is_dxf_file) { + report_sat_text_dropped(s, &mut r); } Ok(r) } diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 0154b01d3..5a2aa398c 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -848,7 +848,7 @@ fn unknown_handles(d: &Drawing) -> HashSet { } /// Put the drawing's foreign data back into a written file's tags (see the module comment). -pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { +pub(crate) fn finish(tags: &mut Vec, d: &Drawing, modern: bool) { let f = d.foreign.as_ref(); let unknown = unknown_handles(d); let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect(); @@ -877,7 +877,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { } let renumber = |old: Option| class_index(old).and_then(|i| f.class_order.get(i)).and_then(|n| numbers.get(n).copied()); // Entities of types CADCraft doesn't model, placed among the written ones. - let mut planned = plan_unknown(d, &recs, tags, &roles); + let mut planned = plan_unknown(d, &recs, tags, &roles, modern); for list in planned.values_mut() { list.retain_mut(|(_, t)| { if !t.first().is_some_and(|z| is_proxy(&z.str())) { @@ -1019,7 +1019,14 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { /// 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. -fn plan_unknown(d: &Drawing, recs: &[Rec], tags: &[Tag], roles: &HashMap) -> HashMap)>> { +fn plan_unknown( + d: &Drawing, + recs: &[Rec], + tags: &[Tag], + roles: &HashMap, + modern: bool, +) -> HashMap)>> { + let stored = d.foreign.data_store_entities(); let mut out: HashMap)>> = HashMap::new(); let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]); let mut at: HashMap = HashMap::new(); @@ -1057,6 +1064,9 @@ fn plan_unknown(d: &Drawing, recs: &[Rec], tags: &[Tag], roles: &HashMap { + if modern && cadcraft_doc::foreign::sat_text_acis(u, e.handle, &stored) { + continue; + } let t = unknown_entity(u, e, &owner, paper); if !t.is_empty() { pending.push((sec.to_string(), t)); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index fe865515b..90214b401 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1115,7 +1115,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec= Version::R2013); crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013); add_class_instance_counts(&mut w.t); mark_xrefs(&mut w.t, d); diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index 74b9809ce..36c947892 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -101,3 +101,31 @@ fn dwg_keeps_the_solids_geometry() { let again = cadcraft_io::read(&dwg, "x.dwg").unwrap(); assert_eq!(again.foreign.data_store_entities().len(), 2); } + +/// A solid with SAT-text ACIS data (an R2000-style file) can't be written to a DXF of 2013 or +/// later, whose files keep that data in the data store: it is left out there and counted, while +/// 2010 and earlier keep it, and solids with a data store record are kept everywhere (#2334). +#[test] +fn sat_text_solids_are_left_out_of_dxf_2013_and_later() { + let sat = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n\ + 0\nREGION\n5\n2B\n100\nAcDbEntity\n8\n0\n100\nAcDbModelerGeometry\n70\n1\n1\n400 1 1 0\n1\n16 ZWCAD\n3\nEnd-of-ACIS-data\n\ + 0\n3DSOLID\n5\n2C\n100\nAcDbEntity\n8\n0\n100\nAcDbModelerGeometry\n70\n1\n1\n400 1 1 0\n3\nEnd-of-ACIS-data\n\ + 0\nLINE\n5\n2D\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nENDSEC\n0\nEOF\n"; + let d = cadcraft_io::read_dxf(sat.as_bytes()).unwrap(); + let count = |v: cadcraft_io::Version, ty: &str| { + let out = cadcraft_io::write_with(&d, "x.dxf", &cadcraft_io::SaveOptions { version: Some(v), binary: false }).unwrap(); + let t = String::from_utf8(out).unwrap().replace("\r\n", "\n"); + t.matches(&format!("\n0\n{ty}\n")).count() + t.matches(&format!("\n 0\n{ty}\n")).count() + }; + assert_eq!(cadcraft_doc::foreign::sat_text_dropped(&d), [("3DSOLID".to_string(), 1), ("REGION".to_string(), 1)].into()); + for v in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] { + assert_eq!((count(v, "REGION"), count(v, "3DSOLID")), (1, 1), "{v:?} keeps them"); + } + for v in [cadcraft_io::Version::R2013, cadcraft_io::Version::R2018] { + assert_eq!((count(v, "REGION"), count(v, "3DSOLID")), (0, 0), "{v:?} leaves them out"); + assert_eq!(count(v, "LINE"), 1, "{v:?} keeps the rest"); + } + // Solids with a data store record keep their geometry in 2013 and later. + let stored = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap(); + assert!(cadcraft_doc::foreign::sat_text_dropped(&stored).is_empty()); +} From 2eecaef6c2958cc78422c9600426fdc0f5b81004 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 10:41:07 +1100 Subject: [PATCH 166/900] 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 a6250d5dc..162a59e3b 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,10 +1,10 @@ # Parity checklist -> **Generated:** 2026-10-25 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-29 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: 298 / 491 items (61%)** · 444 registered commands. | Menu | Items | Covered | % | |---|---|---|---| From a06bb18b587f9e9aee373bd6fb0b15bfd60a47c0 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 10:57:53 +1100 Subject: [PATCH 167/900] 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 49fdbff529dea0f64e7d88a77dfedabe632a939d Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 11:23:09 +1100 Subject: [PATCH 168/900] Test: saving SAT-text solids as DXF 2013 reports them, 2010 does not (#2334) --- crates/engine/tests/save_reports_not_saved.rs | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 615028a21..f231f8ace 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -3,7 +3,7 @@ //! writes them back as read: nothing to report. use cadcraft_engine::Session; -use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::cmd::file::{IoHooks, SaveAs, set_io, set_write_as}; use cadcraft_engine::doc::{Block, Common, Drawing, EntityKind, RawTag, Space, Unknown}; use serde_json::json; @@ -82,3 +82,33 @@ 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()); } + +/// A DXF of 2013 or later can't hold a solid's SAT-text geometry (it lives in the data store +/// there), so the save leaves it out and says so; 2010 and earlier keep it (#2334). +#[test] +fn saving_sat_text_solids_as_dxf_2013_reports_them() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec())); + let mut d = Drawing::new_imperial(); + let sat = EntityKind::Unknown(Unknown { + dxf_type: "REGION".into(), + tags: vec![ + RawTag { code: 8, value: "0".into() }, + RawTag { code: 1, value: "400 1 1 0".into() }, + RawTag { code: 3, value: "End-of-ACIS-data".into() }, + ], + }); + d.add(&Space::Model, Common::default(), sat).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "region.dxf", None); + + let path = std::env::temp_dir().join(format!("cadcraft-sat-note-{}.dxf", std::process::id())); + let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2018 })).unwrap(); + assert_eq!(r["notSaved"], json!({ "REGION": 1 })); + assert!(s.log.iter().any(|l| l.contains("Not saved in the DXF file") && l.contains("1 REGION")), "{:?}", s.log); + + let n = s.log.len(); + let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap(); + let _ = std::fs::remove_file(&path); + assert!(r.get("notSaved").is_none() && s.log.len() == n); +} From 89771962fcbe5f238613d107c3dfe2a1a82292a8 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 11:26:25 +1100 Subject: [PATCH 169/900] 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 162a59e3b..53ffffc96 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Parity checklist -> **Generated:** 2026-10-29 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 afc12e4dce92a07921a3e2391f5508e5b3483278 Mon Sep 17 00:00:00 2001 From: aldozar Date: Thu, 29 Oct 2026 19:20:58 -0600 Subject: [PATCH 170/900] PEDIT Multiple at the command line (#2225) * PEDIT Multiple at the command line (#2182) `M` at "Select polyline" answered that Multiple was only available through the JSON form. It now works as in AutoCAD: select objects (polylines, lines and arcs), turn the lines and arcs into polylines on Yes (left out on No), then each option applies to all of them: Close, Open, Width, Fit, Spline, Decurve, Ltype gen and Reverse. Join joins the selected objects with each other, ends within a fuzz distance, and reports how many it added. Undo takes the last option back. Co-Authored-By: Claude Opus 5.5 * Geometry parity status line for PEDIT Multiple Co-Authored-By: Claude Opus 5.5 * PEDIT Multiple: objects selected first, and Decurve after Fit or Spline Several objects selected before PEDIT go straight into Multiple, as in AutoCAD, and M keeps a selection made first. Decurve gives back each polyline's vertices from before its first Fit or Spline, as single-polyline PEDIT does; a Join drops that record for the joined polylines. Co-Authored-By: Claude Opus 5.5 * PEDIT Multiple: the Decurve record follows Undo and survives a Join that joins nothing Each Undo step keeps the record of the vertices from before Fit or Spline, so Fit, Join, Undo, Decurve gives them back; a Join drops the record only for a polyline that took on segments. Co-Authored-By: Claude Opus 5.5 * PEDIT: Yes/No asked again on another answer; Decurve keeps a later Width The convert questions (single and Multiple) take Y/Yes, N/No or Enter and ask again for any other answer instead of treating it as Yes. Width clears the per-vertex widths of the vertices kept for Decurve too, so Decurve after Fit or Spline and Width keeps the new width. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/modify2.rs | 1 + crates/engine/src/cmd/modify2/pedit.rs | 52 +++- crates/engine/src/cmd/modify2/pedit_multi.rs | 235 +++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/pedit_multiple.rs | 197 ++++++++++++++++ docs/geometry-parity.md | 3 +- 6 files changed, 484 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/modify2/pedit_multi.rs create mode 100644 crates/engine/tests/it/pedit_multiple.rs diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index 8d814ebe0..0198a962d 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -122,6 +122,7 @@ pub(crate) fn as_lwpoly(k: &EntityKind) -> Option { } } +mod pedit_multi; mod pedit_vertex; // ===================================================================================== diff --git a/crates/engine/src/cmd/modify2/pedit.rs b/crates/engine/src/cmd/modify2/pedit.rs index ae9110e48..0c1b64879 100644 --- a/crates/engine/src/cmd/modify2/pedit.rs +++ b/crates/engine/src/cmd/modify2/pedit.rs @@ -164,7 +164,7 @@ pub(crate) fn pedit_join(s: &mut Session, h: Handle, others: &[Handle], fuzz: f6 Ok(joined.len()) } -fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result { +pub(super) fn pedit_apply(s: &mut Session, h: Handle, opt: &str, p: &Value) -> Result { let e = curves::entity(s, h)?; if curves::is_locked(s, h) { return Err(other("The object is on a locked layer.")); @@ -287,6 +287,13 @@ pub(super) enum PPhase { /// The second marker of Break / Straighten. VMark, VTangent, + /// Multiple ([`super::pedit_multi`]): selecting the objects, converting lines and arcs, the + /// options, the width for all, Join's fuzz distance. + MSelect, + MConvert, + MMain, + MWidth, + MFuzz, } #[derive(Default)] @@ -305,6 +312,34 @@ pub(super) struct PeditM { pub(super) tangents: Vec<(Vec2, Vec2)>, /// Pieces split off by Break, with the history length after it (erased again by Undo). pub(super) split_off: Vec<(usize, Vec)>, + /// Multiple: the polylines being edited, their selection, and the drawing before each option + /// (with those polylines and their Decurve record) for Undo. + pub(super) multi: Vec, + pub(super) msel: SelectPhase, + pub(super) mundo: Vec<(cadcraft_doc::Drawing, Vec, std::collections::HashMap>)>, + /// Multiple: each polyline's vertices before its first Fit or Spline, which Decurve restores. + pub(super) morig: std::collections::HashMap>, +} + +/// A Yes/No answer: Enter is Yes, anything but Y/Yes/N/No is refused so the question is asked again. +pub(super) fn yes_no(i: &Input) -> Result { + match i { + Input::Enter => Ok(true), + Input::Keyword(k) | Input::Text(k) => match k.trim().to_ascii_lowercase().as_str() { + "y" | "yes" => Ok(true), + "n" | "no" => Ok(false), + _ => Err(other("Enter Yes or No.")), + }, + _ => Err(other("Enter Yes or No.")), + } +} + +/// Width sets one width for the whole polyline, so the vertices Decurve gives back take it too. +pub(super) fn clear_widths(vs: &mut [PolyVertex]) { + for v in vs { + v.start_width = 0.0; + v.end_width = 0.0; + } } impl PeditM { @@ -339,6 +374,10 @@ impl Interactive for PeditM { } fn begin(&mut self, s: &mut Session) -> Result { let sel = s.selection(); + // Several objects selected first: straight into Multiple, as in AutoCAD. + if sel.len() > 1 && s.settings.pickfirst { + return self.start_multi(s); + } if let [h] = sel.as_slice() { let k = curves::entity(s, *h)?.kind; match k { @@ -358,6 +397,7 @@ impl Interactive for PeditM { } fn prompt(&self, s: &Session) -> Prompt { match self.phase { + PPhase::MSelect | PPhase::MConvert | PPhase::MMain | PPhase::MWidth | PPhase::MFuzz => self.multi_prompt(), PPhase::Select => Prompt::new("Select polyline or", Accept::POINT).kw(&["Multiple"]), PPhase::Convert => { Prompt::new("Object selected is not a polyline. Do you want to turn it into one?", curves::KW).kw(&["Yes", "No"]).default("Y") @@ -398,6 +438,7 @@ impl Interactive for PeditM { _ => None, }; match self.phase { + PPhase::MSelect | PPhase::MConvert | PPhase::MMain | PPhase::MWidth | PPhase::MFuzz => self.multi_input(s, i), PPhase::Select => match i { Input::Point(p) => { let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; @@ -417,13 +458,13 @@ impl Interactive for PeditM { s.set_selection(vec![h]); Ok(Step::Continue) } - Input::Keyword(_) => Err(other("Select one polyline (Multiple is available through the JSON form).")), + Input::Keyword(k) if k.eq_ignore_ascii_case("multiple") || k.eq_ignore_ascii_case("m") => self.start_multi(s), + Input::Keyword(_) => Err(other("Invalid option keyword.")), Input::Enter => Ok(Step::Cancel), _ => Ok(Step::Continue), }, PPhase::Convert => { - let no = kw(&i).is_some_and(|k| k.starts_with('n')); - if no { + if !yes_no(&i)? { return Ok(Step::Done); } let h = self.h.ok_or_else(|| other("No object."))?; @@ -487,6 +528,9 @@ impl Interactive for PeditM { if let Input::Text(t) = &i { let w = number(t).filter(|w| *w >= 0.0).ok_or_else(|| other("Requires a non-negative width."))?; self.apply(s, "width", json!({ "width": w }))?; + if let Some(o) = &mut self.original { + clear_widths(o); + } } self.phase = PPhase::Main; Ok(Step::Continue) diff --git a/crates/engine/src/cmd/modify2/pedit_multi.rs b/crates/engine/src/cmd/modify2/pedit_multi.rs new file mode 100644 index 000000000..5a599cb1b --- /dev/null +++ b/crates/engine/src/cmd/modify2/pedit_multi.rs @@ -0,0 +1,235 @@ +//! PEDIT Multiple: edit several polylines (and lines and arcs turned into polylines) at once, as +//! AutoCAD does after `M` at "Select polyline". Join joins the selected objects with each other. + +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_geom::PolyVertex; +use serde_json::json; + +use super::super::curves; +use super::super::machines::{SelOutcome, SelectPhase, number}; +use super::pedit::{PPhase, PeditM, clear_widths, pedit_apply, pedit_join, yes_no}; +use super::{as_lwpoly, other, set_kind}; +use crate::{Accept, Input, Prompt, Result, Session, Step}; + +/// Most option steps Undo can take back. +const MAX_UNDO: usize = 64; + +/// The options of the Multiple menu. +const OPTIONS: [&str; 10] = ["Close", "Open", "Join", "Width", "Fit", "Spline", "Decurve", "Ltype gen", "Reverse", "Undo"]; + +impl PeditM { + /// Start Multiple: select the objects to edit, or take the ones selected first. + pub(super) fn start_multi(&mut self, s: &mut Session) -> Result { + self.phase = PPhase::MSelect; + self.msel = SelectPhase::begin(s); + if self.msel.done { + let hs = std::mem::take(&mut self.msel.picked); + return self.take_multi(s, hs); + } + s.set_selection(Vec::new()); + Ok(Step::Continue) + } + + /// The objects selected for Multiple: polylines, lines and arcs not on locked layers. + fn take_multi(&mut self, s: &mut Session, hs: Vec) -> Result { + let d = s.doc()?; + let kinds = |h: &Handle| d.entity(*h).map(|e| e.kind.clone()); + let editable: Vec = hs + .iter() + .copied() + .filter(|h| matches!(kinds(h), Some(EntityKind::LwPolyline(_) | EntityKind::Line(_) | EntityKind::Arc(_)))) + .filter(|h| !curves::is_locked(s, *h)) + .collect(); + let convert = editable.iter().any(|h| matches!(kinds(h), Some(EntityKind::Line(_) | EntityKind::Arc(_)))); + self.multi = editable; + if self.multi.is_empty() { + s.echo("No polylines, lines or arcs selected."); + return Ok(Step::Done); + } + self.phase = if convert { PPhase::MConvert } else { PPhase::MMain }; + s.set_selection(self.multi.clone()); + Ok(Step::Continue) + } + + /// The prompt of a Multiple phase. + pub(super) fn multi_prompt(&self) -> Prompt { + match self.phase { + PPhase::MConvert => Prompt::new("Convert Lines and Arcs to polylines", curves::KW).kw(&["Yes", "No"]).default("Y"), + PPhase::MMain => Prompt::new("Enter an option", curves::KW).kw(&OPTIONS), + PPhase::MWidth => Prompt::new("Specify new width for all segments", Accept::NUMBER), + PPhase::MFuzz => Prompt::new("Enter fuzz distance", Accept::NUMBER).default("0.0000"), + _ => self.msel.prompt(), + } + } + + /// Input in a Multiple phase. + pub(super) fn multi_input(&mut self, s: &mut Session, i: Input) -> Result { + let kw = |i: &Input| match i { + Input::Keyword(k) | Input::Text(k) => Some(k.trim().to_ascii_lowercase()), + _ => None, + }; + match self.phase { + PPhase::MSelect => match self.msel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.take_multi(s, hs), + }, + PPhase::MConvert => { + let no = !yes_no(&i)?; + let mut kept = Vec::new(); + for h in std::mem::take(&mut self.multi) { + let kind = curves::entity(s, h)?.kind; + match kind { + EntityKind::LwPolyline(_) => kept.push(h), + _ if no => {} + k => { + if let Some(pl) = as_lwpoly(&k) { + set_kind(s, h, EntityKind::LwPolyline(pl))?; + kept.push(h); + } + } + } + } + self.multi = kept; + if self.multi.is_empty() { + s.echo("No polylines to edit."); + return Ok(Step::Done); + } + s.set_selection(self.multi.clone()); + self.phase = PPhase::MMain; + Ok(Step::Continue) + } + PPhase::MMain => { + let Some(k) = kw(&i) else { + if i == Input::Enter { + s.set_selection(Vec::new()); + return Ok(Step::Done); + } + return Ok(Step::Continue); + }; + match k.as_str() { + "close" | "c" => self.apply_all(s, "close", &json!({}))?, + "open" | "o" => self.apply_all(s, "open", &json!({}))?, + "join" | "j" => self.phase = PPhase::MFuzz, + "width" | "w" => self.phase = PPhase::MWidth, + "fit" | "f" => self.curve_all(s, "fit")?, + "spline" | "s" => self.curve_all(s, "spline")?, + "decurve" | "d" => self.decurve_all(s)?, + "ltype gen" | "l" => { + // One setting for all: the opposite of the first one's. + let on = self.multi.first().and_then(|h| curves::entity(s, *h).ok()).is_some_and(|e| match e.kind { + EntityKind::LwPolyline(p) => !p.plinegen, + _ => true, + }); + self.apply_all(s, "ltypegen", &json!({ "on": on }))?; + } + "reverse" | "r" => self.apply_all(s, "reverse", &json!({}))?, + "undo" | "u" => match self.mundo.pop() { + Some((d, multi, morig)) => { + *s.doc_mut()? = d; + self.multi = multi; + self.morig = morig; + s.set_selection(self.multi.clone()); + } + None => s.echo("Nothing to undo."), + }, + _ => return Err(other("Invalid option keyword.")), + } + Ok(Step::Continue) + } + PPhase::MWidth => { + if let Input::Text(t) = &i { + let w = number(t).filter(|w| *w >= 0.0).ok_or_else(|| other("Requires a non-negative width."))?; + self.apply_all(s, "width", &json!({ "width": w }))?; + self.morig.values_mut().for_each(|o| clear_widths(o)); + } + self.phase = PPhase::MMain; + Ok(Step::Continue) + } + PPhase::MFuzz => { + let fuzz = match &i { + Input::Text(t) => number(t).filter(|f| *f >= 0.0 && f.is_finite()).ok_or_else(|| other("Requires a non-negative distance."))?, + _ => 0.0, + }; + self.join_all(s, fuzz)?; + self.phase = PPhase::MMain; + Ok(Step::Continue) + } + _ => Ok(Step::Continue), + } + } + + /// Keep the drawing as it is for Undo (and the polylines being edited, with their Decurve + /// record). + fn remember(&mut self, s: &Session) -> Result<()> { + let d: Drawing = s.doc()?.clone(); + if self.mundo.len() >= MAX_UNDO { + self.mundo.remove(0); + } + self.mundo.push((d, self.multi.clone(), self.morig.clone())); + Ok(()) + } + + /// Apply option `opt` to every polyline being edited. + fn apply_all(&mut self, s: &mut Session, opt: &str, p: &serde_json::Value) -> Result<()> { + self.remember(s)?; + self.multi.retain(|h| s.doc().is_ok_and(|d| d.entity(*h).is_some())); + for h in self.multi.clone() { + pedit_apply(s, h, opt, p)?; + } + Ok(()) + } + + /// Fit or Spline all of them, first keeping each one's vertices for Decurve. + fn curve_all(&mut self, s: &mut Session, opt: &str) -> Result<()> { + for h in &self.multi { + if !self.morig.contains_key(h) + && let Ok(EntityKind::LwPolyline(p)) = curves::entity(s, *h).map(|e| e.kind) + { + self.morig.insert(*h, p.vertices); + } + } + self.apply_all(s, opt, &json!({})) + } + + /// Decurve all of them: one fitted or splined here gets back its vertices from before (as + /// single-polyline PEDIT does), the others lose their arcs. + fn decurve_all(&mut self, s: &mut Session) -> Result<()> { + self.apply_all(s, "decurve", &json!({}))?; + for h in self.multi.clone() { + if let Some(orig) = self.morig.get(&h) + && let Ok(EntityKind::LwPolyline(mut p)) = curves::entity(s, h).map(|e| e.kind) + { + p.vertices = orig.iter().map(|v| PolyVertex { bulge: 0.0, ..*v }).collect(); + set_kind(s, h, EntityKind::LwPolyline(p))?; + } + } + Ok(()) + } + + /// Join the polylines being edited with each other, ends within `fuzz`: each one still open + /// takes the others that meet it, and those go into it. + fn join_all(&mut self, s: &mut Session, fuzz: f64) -> Result<()> { + self.remember(s)?; + let mut rest: Vec = self.multi.iter().copied().filter(|h| s.doc().is_ok_and(|d| d.entity(*h).is_some())).collect(); + let before = rest.len(); + let mut kept = Vec::new(); + while !rest.is_empty() { + let h = rest.remove(0); + let open = matches!(curves::entity(s, h)?.kind, EntityKind::LwPolyline(p) if !p.closed); + if open { + // A polyline that took on segments no longer goes back past the Join on Decurve. + if pedit_join(s, h, &rest, fuzz)? > 0 { + self.morig.remove(&h); + } + rest.retain(|o| s.doc().is_ok_and(|d| d.entity(*o).is_some())); + } + kept.push(h); + } + let added = before - kept.len(); + s.echo(format!("{added} segments added to polyline")); + self.multi = kept; + s.set_selection(self.multi.clone()); + Ok(()) + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6..4a2a829a7 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -85,6 +85,7 @@ mod offset_move; mod options_profile; mod overkill; mod parallel_display_list; +mod pedit_multiple; mod pedit_splinedit; mod pick_text; mod pickdrag; diff --git a/crates/engine/tests/it/pedit_multiple.rs b/crates/engine/tests/it/pedit_multiple.rs new file mode 100644 index 000000000..70a1a8bec --- /dev/null +++ b/crates/engine/tests/it/pedit_multiple.rs @@ -0,0 +1,197 @@ +//! #2182: PEDIT Multiple at the command line, as AutoCAD: select several objects, turn lines and +//! arcs into polylines, then each option applies to all of them; Join joins them with each other. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +fn polylines(s: &Session) -> Vec<(usize, bool, f64)> { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some((p.vertices.len(), p.closed, p.const_width)) } else { None }) + .collect() +} + +fn count(s: &Session) -> usize { + s.doc().unwrap().model.len() +} + +fn lines(s: &mut Session, pts: &[[f64; 4]]) { + for p in pts { + s.execute("line", &json!({ "points": [[p[0], p[1]], [p[2], p[3]]] })).unwrap(); + } +} + +#[test] +fn join_turns_four_lines_into_one_closed_polyline() { + let mut s = Session::new(); + lines(&mut s, &[[0.0, 0.0, 10.0, 0.0], [10.0, 0.0, 10.0, 5.0], [10.0, 5.0, 0.0, 5.0], [0.0, 5.0, 0.0, 0.0]]); + for t in ["PEDIT", "M", "ALL", "", "Y", "J", "", ""] { + s.cmdline(t).unwrap(); + } + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(polylines(&s), vec![(4, true, 0.0)]); + assert_eq!(count(&s), 1); + assert!(s.log.iter().any(|l| l.contains("3 segments added to polyline")), "{:?}", s.log); +} + +#[test] +fn join_bridges_gaps_within_the_fuzz_distance_only() { + // Two chains with a 0.5 gap between them. + let gap = |s: &mut Session| lines(s, &[[0.0, 0.0, 10.0, 0.0], [10.5, 0.0, 20.0, 0.0]]); + let mut s = Session::new(); + gap(&mut s); + for t in ["PE", "M", "ALL", "", "Y", "J", "0", ""] { + s.cmdline(t).unwrap(); + } + assert_eq!(polylines(&s).len(), 2, "no fuzz: still two"); + let mut s = Session::new(); + gap(&mut s); + for t in ["PE", "M", "ALL", "", "Y", "J", "1", ""] { + s.cmdline(t).unwrap(); + } + assert_eq!(polylines(&s).len(), 1, "a fuzz of 1 joins them"); +} + +#[test] +fn options_apply_to_all_and_undo_takes_one_back() { + let mut s = Session::new(); + s.cmdline("pline 0,0 10,0 10,10").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("pline 20,0 30,0 30,10").unwrap(); + s.cmdline("").unwrap(); + for t in ["PEDIT", "M", "ALL", "", "W", "0.5", "C"] { + s.cmdline(t).unwrap(); + } + assert_eq!(polylines(&s), vec![(3, true, 0.5), (3, true, 0.5)], "width and close on both"); + s.cmdline("U").unwrap(); + assert_eq!(polylines(&s), vec![(3, false, 0.5), (3, false, 0.5)], "Undo opens them again"); + s.cmdline("").unwrap(); + assert!(s.running.is_none()); +} + +#[test] +fn lines_left_out_when_not_converted() { + let mut s = Session::new(); + s.cmdline("pline 0,0 10,0 10,10").unwrap(); + s.cmdline("").unwrap(); + lines(&mut s, &[[20.0, 0.0, 30.0, 0.0]]); + for t in ["PEDIT", "M", "ALL", "", "N", "C", ""] { + s.cmdline(t).unwrap(); + } + assert_eq!(polylines(&s), vec![(3, true, 0.0)], "only the polyline is edited"); + assert!(s.doc().unwrap().model.iter().any(|e| matches!(e.kind, EntityKind::Line(_))), "the line stays a line"); +} + +#[test] +fn objects_selected_first_go_straight_to_multiple() { + let mut s = Session::new(); + s.cmdline("pline 0,0 10,0 10,10").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("pline 20,0 30,0 30,10").unwrap(); + s.cmdline("").unwrap(); + let all: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle).collect(); + s.set_selection(all); + for t in ["PEDIT", "W", "0.5", ""] { + s.cmdline(t).unwrap(); + } + assert_eq!(polylines(&s), vec![(3, false, 0.5), (3, false, 0.5)], "no second selection asked for"); + assert!(s.running.is_none()); +} + +#[test] +fn decurve_after_fit_gives_back_the_vertices() { + let mut s = Session::new(); + s.cmdline("pline 0,0 10,0 10,10 20,10").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("pline 0,20 10,20 10,30").unwrap(); + s.cmdline("").unwrap(); + for t in ["PEDIT", "M", "ALL", "", "S"] { + s.cmdline(t).unwrap(); + } + assert!(polylines(&s).iter().all(|p| p.0 > 4), "Spline adds vertices: {:?}", polylines(&s)); + s.cmdline("D").unwrap(); + assert_eq!(polylines(&s), vec![(4, false, 0.0), (3, false, 0.0)], "Decurve gives back each one's vertices"); + s.cmdline("").unwrap(); +} + +#[test] +fn decurve_still_gives_back_the_vertices_after_a_join_that_joins_nothing_or_is_undone() { + let mut s = Session::new(); + s.cmdline("pline 0,0 10,0 10,10 20,10").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("pline 0,20 10,20 10,30").unwrap(); + s.cmdline("").unwrap(); + // Join with nothing in reach joins nothing: Decurve still gives back the vertices. + for t in ["PEDIT", "M", "ALL", "", "S", "J", "0", "D"] { + s.cmdline(t).unwrap(); + } + assert_eq!(polylines(&s), vec![(4, false, 0.0), (3, false, 0.0)], "after a Join that joined nothing"); + // Spline, a Join that joins them, Undo: Decurve gives back the vertices again. + for t in ["S", "J", "100", "U", "D"] { + s.cmdline(t).unwrap(); + } + assert_eq!(polylines(&s), vec![(4, false, 0.0), (3, false, 0.0)], "after an undone Join"); + s.cmdline("").unwrap(); +} + +fn widths(s: &Session) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p) } else { None }) + .flat_map(|p| p.vertices.iter().flat_map(|v| [v.start_width, v.end_width])) + .collect() +} + +#[test] +fn convert_asks_again_for_an_answer_that_is_not_yes_or_no() { + let mut s = Session::new(); + lines(&mut s, &[[0.0, 0.0, 10.0, 0.0]]); + for t in ["PEDIT", "M", "ALL", ""] { + s.cmdline(t).unwrap(); + } + s.cmdline("foo").unwrap(); + assert!(s.prompt_text().contains("Convert"), "{}", s.prompt_text()); + assert_eq!(polylines(&s), vec![], "nothing converted on a wrong answer"); + s.cmdline("Y").unwrap(); + assert_eq!(polylines(&s).len(), 1); + s.cmdline("").unwrap(); + + // Single-polyline PEDIT asks again too. + lines(&mut s, &[[0.0, 5.0, 10.0, 5.0]]); + let l = s.doc().unwrap().model.last().unwrap().handle; + s.set_selection(vec![l]); + s.cmdline("PEDIT").unwrap(); + s.cmdline("foo").unwrap(); + assert!(s.prompt_text().contains("turn it into one"), "{}", s.prompt_text()); + s.cmdline("N").unwrap(); + assert!(s.running.is_none()); +} + +#[test] +fn decurve_after_width_keeps_the_new_width() { + let mut s = Session::new(); + for t in ["PLINE", "0,0", "W", "0", "2", "10,0", "10,10", "20,10", ""] { + s.cmdline(t).unwrap(); + } + assert!(widths(&s).iter().any(|w| *w > 0.0), "{:?}", widths(&s)); + for t in ["PEDIT", "M", "ALL", "", "S", "W", "0", "D", ""] { + s.cmdline(t).unwrap(); + } + assert!(widths(&s).iter().all(|w| *w == 0.0), "Multiple: {:?}", widths(&s)); + + let mut s = Session::new(); + for t in ["PLINE", "0,0", "W", "0", "2", "10,0", "10,10", "20,10", ""] { + s.cmdline(t).unwrap(); + } + let h = s.doc().unwrap().model.last().unwrap().handle; + s.set_selection(vec![h]); + for t in ["PEDIT", "S", "W", "0", "D", ""] { + s.cmdline(t).unwrap(); + } + assert!(widths(&s).iter().all(|w| *w == 0.0), "single: {:?}", widths(&s)); +} diff --git a/docs/geometry-parity.md b/docs/geometry-parity.md index 74dfc1585..3809c637f 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-26 · **Change:** minor (PEDIT Multiple at the command line) · **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 @@ -157,6 +157,7 @@ Total ≈ 90–140 h; items 1–6 parallelise across two or three agents. | Date | Change | Summary | |---|---|---| +| 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) | | 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 ab8953067a05025f0ac6b5498ca2ab3ca0b182ea Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:21:02 +0100 Subject: [PATCH 171/900] Reject out-of-range LUNITS, LUPREC, AUNITS and AUPREC in SETVAR (#2269) Found while testing crates/engine/src/sysvars.rs:379-420 (generic fallthrough in set); the valid ranges are enforced only in crates/engine/src/cmd/props.rs:611-616 (run_units) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/props.rs | 5 ++++- crates/engine/src/sysvars.rs | 9 +++++++++ crates/engine/src/tests.rs | 11 +++++++++++ 4 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 1856c6a15..172e416d1 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -33,6 +33,7 @@ pub mod plotters; mod props; pub use draw2::breakline::BreaklineOptions; pub use props::MatchProps; +pub(crate) use props::UNIT_RANGES; pub(crate) use props::{current_color_value, set_current_color_value}; mod qselect; mod selecttools; diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 817ff77a2..617d29756 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -645,9 +645,12 @@ impl Interactive for ThicknessM { } } +/// The unit variables (lower-case name, lowest, highest value) shared by UNITS and SETVAR. +pub(crate) const UNIT_RANGES: [(&str, i64, i64); 5] = [("lunits", 1, 5), ("luprec", 0, 8), ("aunits", 0, 4), ("auprec", 0, 8), ("insunits", 0, 24)]; + fn run_units(s: &mut Session, p: &Value) -> Result { let d = s.doc_mut()?; - for (k, lo, hi) in [("lunits", 1, 5), ("luprec", 0, 8), ("aunits", 0, 4), ("auprec", 0, 8), ("insunits", 0, 24)] { + for (k, lo, hi) in UNIT_RANGES { if let Some(v) = p.get(k).and_then(Value::as_i64) { d.header.set_i64(&k.to_ascii_uppercase(), v.clamp(lo, hi)); } diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index e22529aac..945a694bc 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -375,6 +375,15 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { let a = a.filter(|a| a.is_finite()).ok_or_else(bad)?; s.doc_mut()?.header.set_f64("ANGBASE", cadcraft_geom::norm_angle(a)); } + // Whole numbers inside the range UNITS clamps to. + "LUNITS" | "LUPREC" | "AUNITS" | "AUPREC" => { + let (_, lo, hi) = crate::cmd::UNIT_RANGES.iter().find(|(k, ..)| k.eq_ignore_ascii_case(&n)).copied().ok_or_else(bad)?; + let i = as_i(v) + .or_else(|| as_f64(v).filter(|f| f.fract() == 0.0 && f.abs() < 1e15).map(|f| f as i64)) + .filter(|i| (lo..=hi).contains(i)) + .ok_or_else(bad)?; + s.doc_mut()?.header.set_i64(&n, i); + } "CONSTRAINTINFER" => s.doc_mut()?.parametric.settings.infer = as_bool(v).ok_or_else(bad)?, _ => { if let Some(r) = table::set(s, &n, v) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8c590dd97..066df250b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -633,6 +633,17 @@ fn setvar_keeps_header_types() { assert_eq!(s.doc().unwrap().header.f64("LTSCALE", 0.0), 1.0); } +#[test] +fn setvar_rejects_out_of_range_units() { + let mut s = Session::new(); + for (name, v) in [("LUPREC", 100), ("LUNITS", 9), ("LUNITS", 0), ("AUPREC", -5), ("AUNITS", 5)] { + assert!(s.execute("setvar", &json!({"name": name, "value": v})).is_err(), "{name} {v}"); + } + s.execute("setvar", &json!({"name": "LUPREC", "value": 8})).unwrap(); + assert_eq!(s.doc().unwrap().header.i64("LUPREC", 0), 8); + assert_ne!(s.doc().unwrap().header.i64("LUNITS", 2), 9); +} + #[test] fn dynamic_input_pointer_settings() { let mut s = Session::new(); From 7efb32b455017318c368f11cd2e91e4725e41044 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:21:06 +0100 Subject: [PATCH 172/900] Cap autosave file names at 255 bytes for multibyte titles (#2289) Found while testing crates/engine/src/autosave.rs:61-66 (file_name) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/autosave.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index 14b363996..480d14c3b 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -59,10 +59,22 @@ pub fn set_savefilepath(path: &str) { /// The autosave file name for drawing `uid` titled `title`, written by app instance `instance`. pub fn file_name(title: &str, instance: &str, uid: u64) -> String { - let stem: String = title.chars().map(|c| if c.is_alphanumeric() || " .-_()".contains(c) { c } else { '-' }).take(80).collect(); + // File systems limit a name to 255 bytes, so the stem gets what the suffix leaves, cut at a character boundary. + let suffix = format!("_{instance}_{uid}.{EXT}"); + let budget = 255usize.saturating_sub(suffix.len()); + let mut used = 0; + let stem: String = title + .chars() + .map(|c| if c.is_alphanumeric() || " .-_()".contains(c) { c } else { '-' }) + .take(80) + .take_while(|c| { + used += c.len_utf8(); + used <= budget + }) + .collect(); let stem = stem.trim().trim_matches('.'); let stem = if stem.is_empty() { "Drawing" } else { stem }; - format!("{stem}_{instance}_{uid}.{EXT}") + format!("{stem}{suffix}") } /// Whether `s` has the form of an app instance id (`-`, see @@ -478,3 +490,20 @@ mod native { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_name_fits_255_bytes_for_multibyte_titles() { + let instance = "12345-abcdef0123456789"; + for title in ["图".repeat(100), "😀".repeat(100), "aé图😀".repeat(40), "a".repeat(300)] { + let name = file_name(&title, instance, u64::MAX); + assert!(name.len() <= 255, "{} bytes", name.len()); + let (t, i, u) = parse_file_name(&name).expect("round trips"); + assert_eq!((i, u), (instance, u64::MAX)); + assert!(!t.is_empty()); + } + } +} From c2695f6ab0ecbb8e566bbb154b3d8bac4871c754 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:21:10 +0100 Subject: [PATCH 173/900] Refuse invalid counts in JSON arraypolar and arrayrect (#2399) Found while testing crates/engine/src/cmd/array.rs:332-334 (count_or, used by run_arrayrect at 338-340 and run_arraypolar at 363-365) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd/array.rs | 21 ++++++++++++--------- crates/engine/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 479b7873a..9d4a2fd9c 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -328,16 +328,19 @@ fn run_array(s: &mut Session, p: &Value) -> Result { (spec.run)(s, p) } -/// A count parameter (at least 1). -fn count_or(p: &Value, key: &str, default: u64) -> u64 { - p.get(key).and_then(Value::as_u64).unwrap_or(default).max(1) +/// A count parameter (at least 1); a missing key gives the default, an invalid value is refused. +fn count_or(cmd: &str, p: &Value, key: &str, default: u64) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of at least 1"))), + } } fn run_arrayrect(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; - let rows = count_or(p, "rows", 3); - let cols = count_or(p, "cols", 4); - let levels = count_or(p, "levels", 1); + let rows = count_or("arrayrect", p, "rows", 3)?; + let cols = count_or("arrayrect", p, "cols", 4)?; + let levels = count_or("arrayrect", p, "levels", 1)?; check_size(s, rows.saturating_mul(cols).saturating_mul(levels), hs.len())?; let kind = ArrayKind::Rect(RectArray { cols: count32(cols), @@ -360,9 +363,9 @@ fn run_arrayrect(s: &mut Session, p: &Value) -> Result { fn run_arraypolar(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let c = point_req("arraypolar", p, "center")?; - let n = count_or(p, "count", 6); - let rows = count_or(p, "rows", 1); - let levels = count_or(p, "levels", 1); + let n = count_or("arraypolar", p, "count", 6)?; + let rows = count_or("arraypolar", p, "rows", 1)?; + let levels = count_or("arraypolar", 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 row_spacing = f64_or(p, "rowSpacing", 1.0); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 066df250b..b06641fbb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1444,3 +1444,22 @@ fn hostile_variable_like_input_never_panics() { s.cmdline("pickadd").unwrap(); assert!(setvar_prompt_open(&s)); } + +#[test] +fn array_counts_reject_invalid_values() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap(); + for bad in [json!(-3), json!(0), json!(2.5)] { + for key in ["count", "rows", "levels"] { + let mut p = json!({"center": [0, 0], "associative": false}); + p[key] = bad.clone(); + assert!(s.execute("arraypolar", &p).is_err(), "arraypolar {key}={bad}"); + } + for key in ["rows", "cols", "levels"] { + let mut p = json!({"associative": false}); + p[key] = bad.clone(); + assert!(s.execute("arrayrect", &p).is_err(), "arrayrect {key}={bad}"); + } + } + s.execute("arraypolar", &json!({"center": [0, 0], "count": 1, "associative": false})).unwrap(); +} From bcf0dbc5e8bfba025fb46344b826d2b8da9c960d Mon Sep 17 00:00:00 2001 From: Books Date: Fri, 30 Oct 2026 12:21:15 +1100 Subject: [PATCH 174/900] DWG: keep the current layer (CLAYER) through a save and reopen (#2252) (#2407) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * DWG: keep the current layer (CLAYER) through a save and reopen (#2252) The DWG header stores the current layer as a handle, and the one read from the DXF needn't be the layer's in the document, so the drawing reopened on layer 0. The bridge now resolves CLAYER by name to the layer's handle before writing, like the current text and dimension styles. Test: the_current_layer_round_trips_through_dwg. * Parity checklist: regenerated after merging main * DWG: resolve $CLAYER through the layer table's Unicode-aware lookup (#2252) eq_ignore_ascii_case missed non-ASCII case differences such as Survey_Ä / Survey_ä, leaving layer 0 current. acadrust's Table::get normalises names with to_uppercase. * DWG: test a current layer named in other letter case (#2252) --- crates/dwg/src/lib.rs | 12 ++++++++++++ crates/io/tests/it/dwg_header_vars.rs | 28 +++++++++++++++++++++++++++ docs/parity-checklist.md | 4 ++-- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index b81bd00d1..8abb696b5 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -512,6 +512,17 @@ mod native { } } + /// 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). + fn current_layer(doc: &mut acadrust::CadDocument) { + let name = doc.header.current_layer_name.clone(); + // The table's own lookup compares Unicode case-insensitively ("Survey_Ä" = "Survey_ä"). + if let Some(layer) = doc.layers.get(&name) { + doc.header.current_layer_handle = layer.handle; + } + } + fn convert(dxf: &[u8], version: 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 @@ -543,6 +554,7 @@ mod native { current_dimstyle(&mut doc); add_variable_dictionary(&mut doc); current_text_style(&mut doc); + current_layer(&mut doc); std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) .map_err(|_| "the DWG writer failed on this drawing".to_string())? .map_err(|e| format!("DWG write: {e}")) diff --git a/crates/io/tests/it/dwg_header_vars.rs b/crates/io/tests/it/dwg_header_vars.rs index d1850278f..1bebee75e 100644 --- a/crates/io/tests/it/dwg_header_vars.rs +++ b/crates/io/tests/it/dwg_header_vars.rs @@ -59,3 +59,31 @@ fn header_settings_round_trip_through_dwg() { let r = cadcraft_io::read(&dwg, "x.dwg").unwrap(); check("DWG", &r); } + +/// The current layer (`$CLAYER`) survives a DWG save and reopen, ASCII or not. A DWG stores a +/// handle to the layer, and the writer used the null handle, so the drawing came back on "0" (#2252). +#[test] +fn the_current_layer_round_trips_through_dwg() { + for name in ["Survey_B", "Survey_\u{c4}"] { + let mut d = Drawing::new_metric(); + d.layers.push(cadcraft_doc::Layer::new(name)); + d.header.set_str("CLAYER", name); + let dxf = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(dxf.header.str("CLAYER", "?"), name, "DXF keeps it"); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let r = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(r.header.str("CLAYER", "?"), name, "DWG"); + } +} + +/// `$CLAYER` naming the layer in other letter case still finds it: the DWG comes back on the +/// layer, under the layer's own spelling, not on "0" (#2252). +#[test] +fn a_current_layer_in_other_case_resolves_to_the_layer() { + let mut d = Drawing::new_metric(); + d.layers.push(cadcraft_doc::Layer::new("Survey_\u{c4}")); + d.header.set_str("CLAYER", "Survey_\u{e4}"); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let r = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(r.header.str("CLAYER", "?"), "Survey_\u{c4}"); +} diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index a6250d5dc..ee0358f9e 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,10 +1,10 @@ # 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: 298 / 491 items (61%)** · 444 registered commands. | Menu | Items | Covered | % | |---|---|---|---| From 9a1f200795f9b2618cf197b2bb2e8c6acbb833ea Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Fri, 30 Oct 2026 08:21:20 +0700 Subject: [PATCH 175/900] xtask: the test suite and clippy pass on Windows (#2198) * xtask: the test suite and clippy pass on Windows Two Windows-only failures stopped `cargo xtask ci` before it got going on a Windows checkout (CI runs the gate on Linux only, so neither showed): - parity::tests::civil_dates built a SystemTime 115,740,740 days after the epoch (year 318857). Windows' SystemTime ends in the year 30828, so the addition panicked ("overflow when adding duration to `SystemTime`"). That case now checks `civil_from_days` on the day count, which is what it was about, on every platform. - stats.rs imported `walk` for a test that only exists on Unix, so the import was unused on Windows and `clippy -D warnings` refused it. The Unix test calls `super::walk`, as its neighbour calls `super::walk_inner`. Checked on Windows 11 x64: `cargo test --workspace` and `cargo clippy --workspace --all-targets -- -D warnings` both pass. Co-Authored-By: Claude Opus 5.5 * Contributors: add 2ez4gcx (Doan Huynh Huu Khuong) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- contributors/people.toml | 5 +++++ xtask/src/parity.rs | 4 +++- xtask/src/stats.rs | 4 ++-- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 40d6ba823..101a329ac 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -91,3 +91,8 @@ sync_github_name = false real_name = "Robert Lee" sync_github_name = true +[people.2ez4gcx] +real_name = "Doan Huynh Huu Khuong" +display_name = "Doan Huynh Huu Khuong" +sync_github_name = false + diff --git a/xtask/src/parity.rs b/xtask/src/parity.rs index 39f8e8713..8c174d290 100644 --- a/xtask/src/parity.rs +++ b/xtask/src/parity.rs @@ -136,7 +136,9 @@ mod tests { assert_eq!(day(20_736), "2026-10-10"); assert_eq!(date(std::time::UNIX_EPOCH - std::time::Duration::from_secs(86_400)), "1970-01-01"); // Past chrono's range keeps the proleptic Gregorian date, not the epoch (old `civil_from_days`). - assert_eq!(day(115_740_740), "318857-05-20"); + // Checked on the day count: Windows' SystemTime ends in the year 30828, so building that + // SystemTime panics there. + assert_eq!(civil_from_days(115_740_740), (318_857, 5, 20)); // Windows' SystemTime can't hold u64::MAX / 2 seconds, so it is only checked where it exists. if let Some(far) = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_secs(u64::MAX / 2)) { assert_eq!(date(far), "292277026596-12-04"); diff --git a/xtask/src/stats.rs b/xtask/src/stats.rs index c2c6de3d2..6136de15a 100644 --- a/xtask/src/stats.rs +++ b/xtask/src/stats.rs @@ -134,7 +134,7 @@ pub fn run(_root: &Path, exact: bool) -> Result<(), String> { #[cfg(test)] mod tests { - use super::{Counts, count_tests, walk}; + use super::{Counts, count_tests}; #[test] fn counts_attributes_and_proptest_blocks() { @@ -155,7 +155,7 @@ mod tests { // A directory symlink pointing back at `real` would be re-scanned if followed. symlink(&real, base.join("alias")).unwrap(); let mut c = Counts::default(); - walk(&base, &mut c).unwrap(); + super::walk(&base, &mut c).unwrap(); assert_eq!(c.files, 1, "the aliased directory was followed and counted twice"); std::fs::remove_dir_all(&base).ok(); } From 35b4332ee2968de75e7da2ec0a8661338acb77a7 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Fri, 30 Oct 2026 08:21:24 +0700 Subject: [PATCH 176/900] MEASURE picks its starting end by the curve's parameter, as AutoCAD does (#2207) * MEASURE picks its starting end by the curve's parameter, as AutoCAD does MEASURE started from whichever end was nearer the pick in a straight line, and a closed curve always ran forwards from its first vertex. AutoCAD (2024, black-box: synthetic objects in accoreconsole, every POINT read back with entget) decides by the curve parameter of the pick, the segment index plus the fraction along it: - an open curve is measured from its end once the pick is halfway or further: an L-shaped polyline picked at (10, 30) on its long leg (parameter 1.3 of 2) runs from the end, although that end is the farther one; a U-shape picked at (90, 0) (parameter 0.9 of 3) runs from the start, although the end is nearer; - a closed polyline runs from its first vertex, forwards before half its parameter and backwards from then on; - a circle always runs counterclockwise from angle 0. Chain::param_of gives that parameter. The new test divide_and_measure_match_autocad pins nine measured DIVIDE and MEASURE cases (lines, arcs, circles, open and closed polylines with an arc segment), every point to 1e-9. Co-Authored-By: Claude Opus 5.5 * MEASURE: a spline's starting end comes from its own parameter A spline's chain is a tessellation with zero-length pieces dropped, so its segment count is not the spline's parameter range: a degree-1 spline whose first span has zero length spends half its parameter there, and a pick at x = 3 on its 10-unit run (parameter 1.3 of 0..2, past the middle) was measured from the start because it is short of the drawn middle. Splines now compare spline_param_of with the middle of their domain; other curves keep Chain::param_of. Pointed out in review. Co-Authored-By: Claude Opus 5.5 * MEASURE: polylines count coincident vertices in their parameter; ellipses pinned AutoCAD's polyline parameter is the vertex index, so a coincident vertex still takes one unit of the range. The chain drops zero-length spans, so its segment index and count shifted the middle: (0,0) (1,0) (101,0) (101,0) picked at x = 1.1 (parameter 1.001 of 3) was measured from the end, and (0,0) (0,0) (10,0) (20,0) picked at x = 7 (1.7 of 3) from the start. LWPOLYLINEs and 3D polylines now take the parameter from their source vertices (curves::vertex_param_of). Pointed out in review. Ellipses keep the parameter rule, which AutoCAD follows for them too: a full ellipse picked at t = pi and an elliptical arc picked past its middle both run from the end in AutoCAD 2024 (MEASURE-032 and -033 of the measured set; the other direction is 200 and 4 units off). The new test pins both, within the 1e-4 tessellation CADCraft measures along. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/curves.rs | 36 ++++ crates/engine/src/cmd/draw2/divide.rs | 40 +++- crates/engine/src/cmd/draw2/tests.rs | 273 ++++++++++++++++++++++++++ 3 files changed, 343 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/curves.rs b/crates/engine/src/cmd/curves.rs index 7fe05239d..2ef2e24f2 100644 --- a/crates/engine/src/cmd/curves.rs +++ b/crates/engine/src/cmd/curves.rs @@ -479,6 +479,19 @@ impl Chain { } best.1 } + /// The curve parameter of the point on the chain nearest `p`: the index of its segment plus + /// the fraction along it (AutoCAD's polyline parameter; 0..1 along a line or an arc). + pub fn param_of(&self, p: Vec2) -> f64 { + let mut best = (f64::INFINITY, 0.0); + for (i, s) in self.segs.iter().enumerate() { + let c = s.closest(p); + let dd = c.dist(p); + if dd < best.0 { + best = (dd, i as f64 + seg_param(s, c)); + } + } + best.1 + } /// Reversed copy. pub fn reversed(&self) -> Chain { Chain { segs: self.segs.iter().rev().map(Segment::reversed).collect(), closed: self.closed } @@ -506,6 +519,29 @@ impl Chain { } } +/// The polyline parameter of the point nearest `p` on spans `(start, end, bulge)` taken from the +/// source vertices: the span's index plus the fraction along it. Unlike [`Chain::param_of`] it +/// counts zero-length spans, which a polyline's parameter range includes (one per vertex) but its +/// chain drops. +pub fn vertex_param_of(spans: &[(Vec2, Vec2, f64)], p: Vec2) -> f64 { + let mut best = (f64::INFINITY, 0.0); + for (i, &(a, b, bulge)) in spans.iter().enumerate() { + if a.near(b, EPS) { + continue; + } + let seg = match cadcraft_geom::bulge_to_arc(a, b, bulge) { + Some((arc, ccw)) => Segment::Arc { arc, ccw }, + None => Segment::Line(Line::new(a, b)), + }; + let c = seg.closest(p); + let dd = c.dist(p); + if dd < best.0 { + best = (dd, i as f64 + seg_param(&seg, c)); + } + } + best.1 +} + /// Parameter (0..1 along travel) of a point on a segment. pub fn seg_param(s: &Segment, p: Vec2) -> f64 { match s { diff --git a/crates/engine/src/cmd/draw2/divide.rs b/crates/engine/src/cmd/draw2/divide.rs index 6b6ea28e3..65e7ab06c 100644 --- a/crates/engine/src/cmd/draw2/divide.rs +++ b/crates/engine/src/cmd/draw2/divide.rs @@ -74,12 +74,40 @@ pub(super) fn run_measure(s: &mut Session, p: &Value) -> Result { } let block = str_param(p, "block").map(str::to_string); check_block(s, block.as_deref())?; - if let Some(from) = point_param(p, "from") - && !c.closed - && let (Some(a), Some(b)) = (c.start(), c.end()) - && from.dist(b) < from.dist(a) - { - c = c.reversed(); + // AutoCAD measures from the end the pick is nearer by the curve's parameter (segment index + // plus the fraction along it), not by distance: an open curve from its end once the pick is + // halfway or further, a closed one from its first vertex, backwards from halfway on. A + // circle always runs counterclockwise from angle 0. + if let Some(from) = point_param(p, "from") { + let past_half = match curves::entity(s, h)?.kind { + EntityKind::Circle(_) => false, + // A spline by its own parameter: its tessellation drops zero-length pieces, so the + // segment count is not the spline's parameter range. + EntityKind::Spline(sp) => { + let (lo, hi) = sp.domain(); + curves::spline_param_of(&sp, from) >= (lo + hi) / 2.0 + } + // Polylines by their vertices, coincident ones included (one parameter unit each, + // as in AutoCAD), which the chain drops. + EntityKind::LwPolyline(pl) => { + let n = pl.vertices.len(); + let spans: Vec<_> = (0..if pl.closed { n } else { n.saturating_sub(1) }) + .filter_map(|i| Some((pl.vertices.get(i)?.p, pl.vertices.get((i + 1) % n)?.p, pl.vertices.get(i)?.bulge))) + .collect(); + curves::vertex_param_of(&spans, from) >= spans.len() as f64 / 2.0 + } + EntityKind::Polyline3d(pl) => { + let n = pl.points.len(); + let spans: Vec<_> = (0..if pl.closed { n } else { n.saturating_sub(1) }) + .filter_map(|i| Some((pl.points.get(i)?.xy(), pl.points.get((i + 1) % n)?.xy(), 0.0))) + .collect(); + curves::vertex_param_of(&spans, from) >= spans.len() as f64 / 2.0 + } + _ => c.param_of(from) >= c.segs.len() as f64 / 2.0, + }; + if past_half { + c = c.reversed(); + } } let pts = measure_points(&c, step); let hs = place_markers(s, &pts, block.as_deref(), bool_or(p, "align", true))?; diff --git a/crates/engine/src/cmd/draw2/tests.rs b/crates/engine/src/cmd/draw2/tests.rs index a28d92b4d..b5585e381 100644 --- a/crates/engine/src/cmd/draw2/tests.rs +++ b/crates/engine/src/cmd/draw2/tests.rs @@ -302,6 +302,279 @@ fn divide_and_measure_json() { assert!(s.execute("measure", &json!({"handle": l, "length": 1e-300})).is_err()); } +/// DIVIDE and MEASURE against the points AutoCAD 2024 places for the same object and pick +/// (black-box: synthetic objects in accoreconsole, `(command "_.MEASURE" (list ename point) …)`, +/// every POINT read back with `entget`). The pick chooses the end by the curve's parameter, not +/// by distance; a closed polyline runs from its first vertex, a circle from angle 0. +#[test] +fn divide_and_measure_match_autocad() { + type Case = ((&'static str, serde_json::Value), &'static str, f64, [f64; 2], usize, &'static [[f64; 2]]); + // ((seed command, params), command, segments or length, pick, POINT count, AutoCAD points) + let cases: Vec = vec![ + // DIVIDE-001: (list ename point). + ( + ("arc", json!({"center": [0.0, 0.0], "radius": 20.0, "start": 30.0, "end": 250.0})), + "divide", + 5.0, + [-2.090569265353071, 19.890437907365467], + 4, + &[ + [-19.021130325903, 6.180339887499], + [-17.975880925983, -8.767422935782], + [-9.389431255718, 17.658951857179], + [5.51274711634, 19.225233918766], + ], + ), + // DIVIDE-002: (list ename point). + ( + ("circle", json!({"center": [0.0, 0.0], "radius": 15.0})), + "divide", + 5.0, + [-4.63525491562421, 14.265847744427305], + 5, + &[ + [-12.135254915624, -8.816778784387], + [-12.135254915624, 8.816778784387], + [4.635254915624, -14.265847744427], + [4.635254915624, 14.265847744427], + [15.0, 0.0], + ], + ), + // MEASURE-016: (list ename point). + ( + ("line", json!({"points": [[0.0, 0.0], [37.0, 13.0]]})), + "measure", + 7.688652713279647, + [25.9, 9.1], + 5, + &[ + [0.730313187001, 0.256596525162], + [7.984250549601, 2.80527722013], + [15.2381879122, 5.353957915097], + [22.4921252748, 7.902638610065], + [29.7460626374, 10.451319305032], + ], + ), + // MEASURE-024: (list ename point). + ( + ( + "pline", + json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [100.0, 0.0], "bulge": 0.0}, {"p": [100.0, 10.0], "bulge": 0.0}, {"p": [5.0, 10.0], "bulge": 0.0}], "closed": false}), + ), + "measure", + 7.0, + [90.0, 0.0], + 29, + &[[7.0, 0.0], [7.0, 10.0], [14.0, 0.0], [98.0, 0.0], [98.0, 10.0], [100.0, 5.0]], + ), + // MEASURE-026: (list ename point). + ( + ( + "pline", + json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [10.0, 0.0], "bulge": 0.0}, {"p": [10.0, 100.0], "bulge": 0.0}], "closed": false}), + ), + "measure", + 7.0, + [10.0, 30.0], + 15, + &[[5.0, 0.0], [10.0, 2.0], [10.0, 9.0], [10.0, 79.0], [10.0, 86.0], [10.0, 93.0]], + ), + // MEASURE-030: (list ename point). + ( + ( + "pline", + json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [10.0, 35.0], "bulge": 0.0}], "closed": true}), + ), + "measure", + 7.5, + [5.0, 17.5], + 17, + &[ + [2.06040845923, 7.211429607306], + [4.120816918461, 14.422859214612], + [5.957390538273, 0.0], + [41.854257779673, 5.445746712402], + [45.137412221497, 19.497902817843], + [45.215233654661, 12.07010340037], + ], + ), + // DIVIDE-028: (list ename point). + ( + ( + "pline", + json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [10.0, 35.0], "bulge": 0.0}], "closed": true}), + ), + "divide", + 5.0, + [37.5, 10.0], + 5, + &[ + [0.0, 0.0], + [7.332712970983, 25.664495398441], + [25.609294779385, 28.310302237406], + [26.691478107655, 0.0], + [45.58190593662, 14.465330916891], + ], + ), + // MEASURE-041: (list ename point). + ( + ( + "pline", + json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [10.0, 35.0], "bulge": 0.0}], "closed": true}), + ), + "measure", + 7.5, + [45.54951565955276, 17.15901034980981], + 17, + &[ + [1.636621047999, 5.728173667998], + [3.69702950723, 12.939603275304], + [5.75743796646, 20.15103288261], + [42.799868254703, 6.663750217618], + [44.060611317761, 20.402595149531], + [45.491536690495, 13.587129550966], + ], + ), + // MEASURE-042: (list ename point). + ( + ( + "pline", + json!({"vertices": [{"p": [0.0, 0.0], "bulge": 0.0}, {"p": [30.0, 0.0], "bulge": 0.5}, {"p": [45.0, 20.0], "bulge": 0.0}, {"p": [10.0, 35.0], "bulge": 0.0}], "closed": true}), + ), + "measure", + 7.5, + [44.0, 20.5], + 17, + &[ + [2.06040845923, 7.211429607306], + [4.120816918461, 14.422859214612], + [5.957390538273, 0.0], + [41.854257779673, 5.445746712402], + [45.137412221497, 19.497902817843], + [45.215233654661, 12.07010340037], + ], + ), + ]; + for ((seed, params), what, value, pick, count, want) in cases { + let mut s = Session::new(); + let r = s.execute(seed, ¶ms).unwrap(); + let handle = r.get("handle").or_else(|| r["handles"].get(0)).and_then(serde_json::Value::as_str).unwrap().to_string(); + // AutoLISP's (list ename point): the object and where it was picked. + let params = if what == "divide" { + json!({"handle": handle, "segments": value as u64, "from": pick}) + } else { + json!({"handle": handle, "length": value, "from": pick}) + }; + s.execute(what, ¶ms).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(); + assert_eq!(pts.len(), count, "{what} {pick:?}: {pts:?}"); + for w in want { + let tol = 1e-9 * w[0].abs().max(w[1].abs()).max(1.0); + assert!(pts.iter().any(|p| p.near(Vec2::new(w[0], w[1]), tol)), "{what} {pick:?}: no point at {w:?} in {pts:?}"); + } + } +} + +/// A spline's end is chosen by its own parameter: this one spends half its parameter range on a +/// zero-length first span, so a pick at x = 3 is already past its middle (parameter 1.3 of 0..2) and +/// MEASURE runs from the end, though x = 3 is short of the middle of the drawn length. +#[test] +fn measure_spline_by_its_own_parameter() { + let mut s = Session::new(); + let sp = h(&s.execute("spline", &json!({"control": [[0, 0], [0, 0], [10, 0]], "degree": 1})).unwrap()); + s.execute("measure", &json!({"handle": sp, "length": 3, "from": [3, 0]})).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(); + assert!(pts.len() == 3 && [7.0, 4.0, 1.0].iter().all(|x| pts.iter().any(|p| near(*p, *x, 0.0))), "{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 +/// the end (black-box, accoreconsole, POINTs read back with `entget`). +#[test] +fn measure_counts_coincident_vertices_and_runs_ellipses_by_parameter() { + let pts = |s: &Session| -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p.xy()) } else { None }).collect() + }; + // (0,0) (1,0) (101,0) (101,0) picked at x = 1.1: parameter 1.001 of 3, before the middle, so + // from the start (the chain alone, 1.001 of 2, ran it from the end). + let mut s = Session::new(); + let pl = h(&s.execute("pline", &json!({"vertices": [[0, 0], [1, 0], [101, 0], [101, 0]]})).unwrap()); + s.execute("measure", &json!({"handle": pl, "length": 30, "from": [1.1, 0]})).unwrap(); + assert!(pts(&s).iter().any(|p| near(*p, 30.0, 0.0)), "{:?}", pts(&s)); + // (0,0) (0,0) (10,0) (20,0) picked at x = 7: parameter 1.7 of 3, past the middle, so from the + // end; the same as a 3D polyline. + for (cmd, params) in [ + ("pline", json!({"vertices": [[0, 0], [0, 0], [10, 0], [20, 0]]})), + ("3dpoly", json!({"points": [[0, 0, 0], [0, 0, 0], [10, 0, 0], [20, 0, 0]]})), + ] { + let mut s = Session::new(); + let pl = h(&s.execute(cmd, ¶ms).unwrap()); + s.execute("measure", &json!({"handle": pl, "length": 3, "from": [7, 0]})).unwrap(); + assert!(pts(&s).iter().any(|p| near(*p, 17.0, 0.0)), "{cmd}: {:?}", pts(&s)); + } + // AutoCAD's points. CADCraft measures along a tessellation (1e-4 of the major axis), so its + // points sit within 2e-4 of the axis of AutoCAD's; the other end is 4 to 200 units away. + type Ellipse = ([f64; 2], [f64; 2], f64, f64, f64); + let cases: [((Ellipse, f64, [f64; 2]), &[[f64; 2]]); 2] = [ + // MEASURE-032-TO: a full ellipse picked at t = pi. + ( + (([-35000.0, 81000.0], [1000.0, 250.0], 0.5, 0.0, std::f64::consts::TAU), 325.0, [-36000.0, 80750.0]), + &[ + [-36005.13895764338, 80852.59066530415], + [-35871.99367437639, 80574.74515309861], + [-35846.48143804769, 81129.79467385833], + [-35585.0606965763, 81321.20806711384], + [-35570.69066464184, 80460.16118260568], + [-35288.01208649818, 81451.990340526], + [-35246.80459288685, 80443.34080344986], + [-34973.3365764063, 81531.8855660685], + [-34925.28109250207, 80488.09750605426], + [-34649.89308676404, 81558.94977503068], + [-34615.08169799787, 80583.88008545575], + [-34328.55263503237, 81517.06267451325], + [-34326.49236487653, 80732.20222770158], + [-34085.24055588816, 80947.67206458953], + [-34052.78599900089, 81354.8654746607], + ], + ), + // MEASURE-033: an elliptical arc picked past its middle. + ( + (([0.0, 0.0], [20.0, 5.0], 0.5, 0.5, 4.0), 4.25, [-14.28970951093154, -10.073417468999274]), + &[ + [-20.14815072114992, -3.432193431111516], + [-18.74987859459168, -7.329883069345779], + [-18.68559214389327, 0.5029121733397516], + [-15.81338990685036, 3.617741906558092], + [-15.26656288688172, -9.70206428611582], + [-12.33992351852055, 6.057945492888583], + [-8.547503008323163, 7.9699830580747], + [-4.557798848614094, 9.428419587410612], + [-0.4368018715850841, 10.45983604769949], + [3.769519107506058, 11.05284388252232], + [8.015496424961295, 11.15319778065308], + [12.22912105170455, 10.6383262710487], + [16.23125506912425, 9.247174221779819], + ], + ), + ]; + for (((center, major, ratio, t0, t1), length, from), want) in cases { + let mut s = Session::new(); + let e = h(&s + .execute("ellipse", &json!({"center": center, "major": major, "ratio": ratio, "start": t0.to_degrees(), "end": t1.to_degrees()})) + .unwrap()); + s.execute("measure", &json!({"handle": e, "length": length, "from": from})).unwrap(); + let got = pts(&s); + let tol = 2e-4 * major[0].hypot(major[1]); + assert_eq!(got.len(), want.len(), "{got:?}"); + for w in want { + assert!(got.iter().any(|p| p.dist(Vec2::new(w[0], w[1])) < tol), "no point near {w:?} in {got:?}"); + } + } +} + #[test] fn divide_and_measure_command_line() { let mut s = Session::new(); From 3ccfad60dca364fd9d44c0daf5168b66143263a9 Mon Sep 17 00:00:00 2001 From: Coast Date: Thu, 29 Oct 2026 19:21:27 -0600 Subject: [PATCH 177/900] Block Editor: BEDIT inside it switches to another block, asking to save first (#2219) * Block Editor: BEDIT inside it switches to another block, asking to save first BEDIT (typed, Edit Block, Tools > Block Editor) no longer refuses while the Block Editor is open: the Edit Block Definition dialog opens on the block being edited, and choosing another block switches to it. With changes not saved yet it first asks whether to save them (Yes saves, No discards, Cancel stays), at the command line as BCLOSE does and in the dialog. The JSON form takes `save: true|false` and refuses to switch away from unsaved changes without it; the block to switch to is checked before anything is saved or closed. Co-Authored-By: Claude Opus 5.5 * Block Editor: the save question is one translatable sentence The block name and punctuation were added around a translated fragment, so a translation couldn't place the name or use its own quotation marks. Co-Authored-By: Claude Opus 5.5 * BEDIT: a block the Block Editor can't switch to is refused before the save question --------- Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/bedit.rs | 122 +++++++++++++++++++----- crates/engine/tests/block_editor.rs | 129 +++++++++++++++++++++++++- crates/ui-egui/src/bedit.rs | 81 ++++++++++++++-- crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/tests/bedit_dialog.rs | 67 ++++++++++++- docs/gaps.md | 5 +- 6 files changed, 370 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/blocks/bedit.rs b/crates/engine/src/cmd/blocks/bedit.rs index 5b5d0b1cc..c570fa107 100644 --- a/crates/engine/src/cmd/blocks/bedit.rs +++ b/crates/engine/src/cmd/blocks/bedit.rs @@ -2,6 +2,8 @@ //! drawing's own tab, its base point at the origin; the block's objects are edited with the //! ordinary commands; BSAVE saves them into the definition, so every reference to the block in the //! drawing shows the change; BCLOSE goes back to the drawing, saving or discarding what isn't saved. +//! BEDIT while the Block Editor is open switches it to another block: changes not saved yet are +//! saved or discarded first (asked at the command line; `save` in JSON). //! The state is [`crate::blockedit`]. use cadcraft_doc::{Drawing, EntityKind, Handle}; @@ -16,10 +18,9 @@ pub(super) fn specs() -> Vec { CommandSpec::new("bedit", "Block Editor", run_bedit) .menu(&["Tools", "Block Editor"]) .alias(&["be", "-bedit"]) - .params("{name? (\"\": the drawing itself, a dynamic block's own drawing) | handle? (a block reference: edits its block); default the one selected block reference, create?: bool (a name no block has yet starts a new block; BSAVE creates it)} → {block, new}") - .enabled(not_editing) + .params("{name? (\"\": the drawing itself, a dynamic block's own drawing) | handle? (a block reference: edits its block); default the one selected block reference, create?: bool (a name no block has yet starts a new block; BSAVE creates it), save?: bool (in the Block Editor, switching to another block: save (true) or discard (false) the changes not saved yet; required when there are some), check?: bool (in the Block Editor: only check that the block can be switched to)} → {block, new, saved?}") .noundo() - .interactive(|_| Ok(Box::new(BeditM))), + .interactive(|_| Ok(Box::new(BeditM::default()))), CommandSpec::new("bsave", "Save Block", run_bsave).params("{} → {block}").enabled(editing).noundo(), CommandSpec::new("bsaveas", "Save Block As", run_bsaveas) .params("{name, replace?: bool (redefine an existing block of that name)} → {block}") @@ -53,16 +54,6 @@ fn editing_a_block(s: &Session) -> std::result::Result<(), String> { } } -fn not_editing(s: &Session) -> std::result::Result<(), String> { - match s.state() { - Ok(st) => match st.block_editor() { - Some(name) => Err(format!("The Block Editor is already open on \"{name}\"; close it first (BCLOSE).")), - None => Ok(()), - }, - Err(e) => Err(e.to_string()), - } -} - /// Commands that leave model space, which the Block Editor is: not available while it is open. const NOT_IN_EDITOR: &[&str] = &[ "layout", @@ -106,8 +97,53 @@ fn dynamic_definition(d: &Drawing, name: &str) -> Option { (kind == "BLOCK_RECORD").then(|| d.block(block).map(|b| b.name.clone())).flatten() } -/// Open the Block Editor on block `name` and frame its objects. -fn open(s: &mut Session, name: &str, create: bool) -> Result { +/// Whether the open Block Editor can switch to block `name`: the block is there (or `create` makes +/// it) and isn't one the editor refuses. Checked before anything is saved or closed, or asked. +fn check_target(s: &Session, name: &str, create: bool) -> Result<()> { + let host = s.state()?.block_edit.as_ref().map(|b| b.host.doc.clone()).ok_or_else(|| bad("bedit", "the Block Editor is not open"))?; + if name.trim().eq_ignore_ascii_case(crate::blockedit::CURRENT_DRAWING) { + return Ok(()); + } + match host.block(name) { + None if !create => Err(bad("bedit", format!("Block \"{name}\" not found."))), + None => Ok(()), + Some(_) => crate::blockedit::refusal(&host, name).map_or(Ok(()), |why| Err(bad("bedit", why))), + } +} + +/// Open the Block Editor on block `name` and frame its objects. While it is open on another +/// block it switches: the changes not saved yet are saved first with `save` Some(true), +/// discarded with Some(false); with None there must be none. The block to switch to is checked +/// before anything is saved or closed, so a refused switch leaves the editor as it was. +fn open(s: &mut Session, name: &str, create: bool, save: Option) -> Result { + let mut saved = None; + if let Some(current) = s.state()?.block_editor().map(str::to_string) { + if current.eq_ignore_ascii_case(name.trim()) { + s.echo(format!("The Block Editor is already editing \"{current}\".")); + return Ok(json!({ "block": current, "new": false })); + } + check_target(s, name, create)?; + let save = match (s.state()?.block_unsaved(), save) { + (false, _) => false, + (true, Some(save)) => save, + (true, None) => { + return Err(bad( + "bedit", + format!("Block \"{current}\" has changes not saved; pass `save: true` to save them or `save: false` to discard them"), + )); + } + }; + saved = close(s, save)?.get("saved").cloned(); + } + let mut r = open_closed(s, name, create)?; + if let (Some(v), Some(o)) = (saved, r.as_object_mut()) { + o.insert("saved".into(), v); + } + Ok(r) +} + +/// [`open`] with the Block Editor closed. +fn open_closed(s: &mut Session, name: &str, create: bool) -> Result { let new = create && !name.eq_ignore_ascii_case(crate::blockedit::CURRENT_DRAWING) && s.doc()?.block(name).is_none(); s.state_mut()?.open_block_editor(name, create)?; let name = s.state()?.block_editor().unwrap_or(name).to_string(); @@ -153,7 +189,15 @@ fn run_bedit(s: &mut Session, p: &Value) -> Result { if create && !current && s.doc()?.block(name).is_none() && !super::valid_block_name(name) { return Err(bad("bedit", format!("\"{name}\" is not a valid block name"))); } - open(s, name, create) + if p.get("save").is_some_and(|v| !v.is_null() && !v.is_boolean()) { + return Err(bad("bedit", "`save` must be true or false")); + } + // Only whether the Block Editor, when open, can switch to the block: nothing opens or closes. + if bool_or(p, "check", false) && s.state()?.block_editor().is_some() { + check_target(s, name, create)?; + return Ok(json!({ "block": name, "checked": true })); + } + open(s, name, create, p.get("save").and_then(Value::as_bool)) } fn run_bsave(s: &mut Session, _p: &Value) -> Result { @@ -206,7 +250,27 @@ fn run_bclose(s: &mut Session, p: &Value) -> Result { // ---------------- interactive ---------------- /// BEDIT: the selected block reference's block, else a block name typed or a reference picked. -struct BeditM; +/// In the Block Editor with changes not saved yet, it asks whether to save them before switching. +#[derive(Default)] +struct BeditM { + /// The block to switch to, waiting for the answer to "Save changes?". + pending: Option, +} + +impl BeditM { + /// Go to block `name`: at once, or after asking about the changes not saved yet. + fn go(&mut self, s: &mut Session, name: &str) -> Result { + let st = s.state()?; + let other = st.block_editor().is_some_and(|b| !b.eq_ignore_ascii_case(name.trim())); + if other && st.block_unsaved() { + // A block it can't switch to is refused before the question, which would trap the user. + check_target(s, name.trim(), false)?; + self.pending = Some(name.trim().to_string()); + return Ok(Step::Continue); + } + open(s, name, false, Some(false)).map(|_| Step::Done) + } +} impl Interactive for BeditM { fn name(&self) -> &'static str { @@ -214,14 +278,30 @@ impl Interactive for BeditM { } fn begin(&mut self, s: &mut Session) -> Result { match selected_reference(s) { - Some(name) => open(s, &name, false).map(|_| Step::Done), + Some(name) => self.go(s, &name), None => Ok(Step::Continue), } } - fn prompt(&self, _s: &Session) -> Prompt { + fn prompt(&self, s: &Session) -> Prompt { + if self.pending.is_some() { + let name = s.state().ok().and_then(|st| st.block_editor().map(str::to_string)).unwrap_or_default(); + return Prompt::new(format!("Save changes to block \"{name}\"?"), KW).kw(&["Yes", "No"]).default("Y"); + } Prompt::new("Enter block name or select a block reference [?]", Accept { point: true, number: false, text: true, select: true, enter: true }) } fn input(&mut self, s: &mut Session, i: Input) -> Result { + if let Some(name) = self.pending.clone() { + let answer = match i { + Input::Enter => "Y".to_string(), + Input::Keyword(k) | Input::Text(k) => k, + _ => return Ok(Step::Continue), + }; + return match answer.trim().chars().next().map(|c| c.to_ascii_uppercase()) { + Some('Y') => open(s, &name, false, Some(true)).map(|_| Step::Done), + Some('N') => open(s, &name, false, Some(false)).map(|_| Step::Done), + _ => Err(EngineError::Other("Enter Yes or No.".into())), + }; + } match i { Input::Text(t) if t.trim() == "?" => { let names: Vec = { @@ -231,14 +311,14 @@ impl Interactive for BeditM { s.echo(if names.is_empty() { "No blocks to edit.".to_string() } else { names.join(", ") }); Ok(Step::Continue) } - Input::Text(t) | Input::Keyword(t) => open(s, t.trim(), false).map(|_| Step::Done), + Input::Text(t) | Input::Keyword(t) => self.go(s, t.trim()), Input::Pick(hs) => { let name = { let d = s.doc()?; hs.iter().find_map(|h| block_of(d, *h)) }; match name { - Some(n) => open(s, &n, false).map(|_| Step::Done), + Some(n) => self.go(s, &n), None => Err(EngineError::Other("Select a block reference.".into())), } } diff --git a/crates/engine/tests/block_editor.rs b/crates/engine/tests/block_editor.rs index 711bcd796..4eb8a2a2f 100644 --- a/crates/engine/tests/block_editor.rs +++ b/crates/engine/tests/block_editor.rs @@ -140,7 +140,8 @@ fn what_the_block_editor_refuses() { assert!(s.execute("bclose", &json!({})).is_err(), "not open"); s.execute("bedit", &json!({ "name": "Door" })).unwrap(); - assert!(s.execute("bedit", &json!({ "name": "Door" })).is_err(), "already open"); + s.execute("bedit", &json!({ "name": "DOOR" })).unwrap(); + assert_eq!(editor(&s).as_deref(), Some("Door"), "the block already open stays open"); let r = s.execute("layout.set", &json!({ "name": "Layout1" })); assert!(r.is_err_and(|e| e.to_string().contains("Block Editor"))); assert_eq!(s.layout_space(), cadcraft_engine::doc::Space::Model); @@ -370,3 +371,129 @@ fn the_current_drawing_opens_in_the_block_editor() { s.undo().unwrap(); assert_eq!(s.doc().unwrap().model.len(), 1); } + +/// BEDIT in the Block Editor switches to another block, as AutoCAD's does: changes not saved yet +/// are saved or discarded first (`save`), and a block it can't open leaves the editor as it was. +#[test] +fn bedit_in_the_block_editor_switches_blocks() { + let mut s = Session::new(); + door(&mut s); + let l = line(&mut s, [0.0, 50.0], [5.0, 50.0]); + s.execute("block", &json!({ "name": "Frame", "base": [0, 50], "handles": [l] })).unwrap(); + let model = s.doc().unwrap().model.len(); + + s.execute("bedit", &json!({ "name": "Door" })).unwrap(); + line(&mut s, [0.0, 0.0], [0.0, 3.0]); + // Changes not saved: JSON must say what to do with them. + let e = s.execute("bedit", &json!({ "name": "Frame" })).unwrap_err().to_string(); + assert!(e.contains("save"), "{e}"); + assert_eq!(editor(&s).as_deref(), Some("Door")); + assert!(s.state().unwrap().block_unsaved(), "nothing was lost"); + // A block that isn't there, or `save` that isn't a bool: refused, nothing changes. + assert!(s.execute("bedit", &json!({ "name": "Nope", "save": true })).is_err()); + assert!(s.execute("bedit", &json!({ "name": "Frame", "save": "yes" })).is_err()); + assert_eq!(editor(&s).as_deref(), Some("Door")); + assert!(s.state().unwrap().block_unsaved()); + + // Saved, then switched. + let r = s.execute("bedit", &json!({ "name": "frame", "save": true })).unwrap(); + assert_eq!((r["block"].as_str(), r["saved"].as_bool()), (Some("Frame"), Some(true))); + assert_eq!(editor(&s).as_deref(), Some("Frame")); + assert_eq!(lines_of(&s, "Door").len(), 2, "Door keeps the new line"); + + // Discarded, then switched; with nothing to save `save` isn't needed. + line(&mut s, [1.0, 1.0], [2.0, 2.0]); + s.execute("bedit", &json!({ "name": "Door", "save": false })).unwrap(); + assert_eq!(lines_of(&s, "Frame").len(), 1, "Frame's change was discarded"); + s.execute("bedit", &json!({ "name": "Frame" })).unwrap(); + assert_eq!(editor(&s).as_deref(), Some("Frame")); + // A new block, and the drawing itself. + s.execute("bedit", &json!({ "name": "Gate", "create": true })).unwrap(); + assert_eq!(editor(&s).as_deref(), Some("Gate")); + s.execute("bedit", &json!({ "name": "" })).unwrap(); + s.execute("bclose", &json!({ "save": false })).unwrap(); + assert!(editor(&s).is_none()); + assert_eq!(s.doc().unwrap().model.len(), model, "the drawing as it was"); +} + +/// A block BEDIT can't switch to is refused before it asks about the changes not saved, so the +/// question never traps the user; `check` asks the same of JSON callers. +#[test] +fn bedit_refuses_a_bad_target_before_asking_to_save() { + let mut s = Session::new(); + door(&mut s); + s.execute("bedit", &json!({ "name": "Door" })).unwrap(); + line(&mut s, [1.0, 1.0], [2.0, 2.0]); + assert!(s.state().unwrap().block_unsaved()); + s.script( + "BEDIT +Nope +", + ) + .unwrap(); + let message = s.current_prompt().map(|p| p.message).unwrap_or_default(); + assert!(!message.contains("Save changes"), "no question for a block it can't open: {message}"); + s.input(cadcraft_engine::Input::Cancel).unwrap(); + assert_eq!(editor(&s).as_deref(), Some("Door")); + assert!(s.state().unwrap().block_unsaved(), "nothing lost"); + // The check, without switching or saving. + assert!(s.execute("bedit", &json!({ "name": "Nope", "check": true })).is_err()); + assert!(s.execute("bedit", &json!({ "name": "Nope", "create": true, "check": true })).is_ok(), "a new name is fine"); + assert_eq!(editor(&s).as_deref(), Some("Door")); + assert!(s.state().unwrap().block_unsaved()); +} + +/// Typed, BEDIT in the Block Editor asks whether to save the changes before it switches. +#[test] +fn bedit_typed_in_the_block_editor_asks_to_save_first() { + let mut s = Session::new(); + door(&mut s); + let l = line(&mut s, [0.0, 50.0], [5.0, 50.0]); + s.execute("block", &json!({ "name": "Frame", "base": [0, 50], "handles": [l] })).unwrap(); + s.execute("bedit", &json!({ "name": "Door" })).unwrap(); + + // Nothing changed: it switches at once. + s.script( + "BEDIT +Frame +", + ) + .unwrap(); + assert!(s.running.is_none()); + assert_eq!(editor(&s).as_deref(), Some("Frame")); + + line(&mut s, [1.0, 1.0], [2.0, 2.0]); + s.script( + "BEDIT +Door +", + ) + .unwrap(); + assert_eq!(s.current_prompt().unwrap().message, "Save changes to block \"Frame\"?"); + // Escape keeps the editor on Frame with its change. + s.input(cadcraft_engine::Input::Cancel).unwrap(); + assert_eq!(editor(&s).as_deref(), Some("Frame")); + assert!(s.state().unwrap().block_unsaved()); + + s.script( + "BEDIT +Door +Y +", + ) + .unwrap(); + assert!(s.running.is_none()); + assert_eq!(editor(&s).as_deref(), Some("Door")); + assert_eq!(lines_of(&s, "Frame").len(), 2, "saved before switching"); + + line(&mut s, [3.0, 3.0], [4.0, 4.0]); + s.script( + "BEDIT +Frame +N +", + ) + .unwrap(); + assert_eq!(editor(&s).as_deref(), Some("Frame")); + assert_eq!(lines_of(&s, "Door").len(), 1, "discarded"); +} diff --git a/crates/ui-egui/src/bedit.rs b/crates/ui-egui/src/bedit.rs index 6137d5ccc..fa51656ac 100644 --- a/crates/ui-egui/src/bedit.rs +++ b/crates/ui-egui/src/bedit.rs @@ -1,7 +1,9 @@ //! The Edit Block Definition dialog: BEDIT typed or started from a menu or the Tool Sets with no //! block reference selected. It lists the drawing's blocks with a preview and description; a name //! no block has yet starts a new block. OK runs BEDIT with that name; the dialog itself never -//! changes the drawing. JSON calls (`bedit {name}`) and a selected block reference skip it. +//! changes the drawing. In the Block Editor it switches to the block chosen, first asking whether +//! to save the changes not saved yet. JSON calls (`bedit {name}`) and a selected block reference +//! skip it. use std::sync::Arc; @@ -24,6 +26,8 @@ pub struct State { pub name: String, /// Why the last OK failed, shown until the name changes. pub error: Option, + /// OK in the Block Editor with changes not saved: asking whether to save them first. + pub ask_save: bool, /// The preview of the block named, for (drawing uid, revision, block name). preview: Option<((u64, u64, String), Arc)>, } @@ -86,22 +90,19 @@ pub fn authoring_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) } /// BEDIT typed or from a menu without parameters opens the dialog, unless exactly one block -/// reference is selected (it opens at once) or the Block Editor is open (BEDIT says why not). +/// reference is selected (it opens at once). In the Block Editor it starts on the block edited. pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { if !matches!(id, "bedit" | "be") || !params.is_null() { return None; } let st = app.session.state().ok()?; - if st.block_edit.is_some() { - return None; - } let refs = st.selection.iter().filter(|h| st.doc.entity(**h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))).count(); if refs == 1 && st.selection.len() == 1 { return None; } // Start on the block last edited if it is still there, else the first one. let names = editable_blocks(&st.doc); - let last = app.bedit.name.clone(); + let last = st.block_editor().map(str::to_string).unwrap_or_else(|| app.bedit.name.clone()); let name = if names.iter().any(|n| n.eq_ignore_ascii_case(&last)) { last } else { names.first().cloned().unwrap_or_default() }; app.bedit = State { name, ..State::default() }; app.ui.dialog = Some("bedit".into()); @@ -164,6 +165,10 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let list = existing.as_deref().and_then(|n| preview(app, n)); let description = existing.as_deref().and_then(|n| d.block(n)).map(|b| b.description.clone()).unwrap_or_default(); let (mut ok, mut cancel) = (false, false); + if app.bedit.ask_save { + save_question(app, ctx, open); + return; + } egui::Window::new(crate::tl!("Edit Block Definition")) .id(egui::Id::unique("Edit Block Definition")) .open(open) @@ -236,14 +241,72 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } } -/// OK: open the Block Editor on the name given (a new name starts a new block). Returns whether -/// it opened; if not, the dialog shows why and stays open. +/// In the Block Editor with changes not saved: whether to save them before switching to the +/// block chosen. Yes saves, No discards, Cancel goes back to the list. +fn save_question(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let current = app.session.state().ok().and_then(|st| st.block_editor().map(str::to_string)).unwrap_or_default(); + let mut answer: Option> = None; + egui::Window::new(crate::tl!("Edit Block Definition")) + .id(egui::Id::unique("Edit Block Definition")) + .collapsible(false) + .resizable(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.set_max_width(420.0); + ui.label(crate::tf!("Save changes to block \"{name}\"?", name = current)); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(crate::tl!("Yes")).clicked() { + answer = Some(Some(true)); + } + if ui.button(crate::tl!("No")).clicked() { + answer = Some(Some(false)); + } + if ui.button(crate::tl!("Cancel")).clicked() { + answer = Some(None); + } + }); + }); + let Some(answer) = answer else { return }; + app.bedit.ask_save = false; + if let Some(save) = answer + && run(app, Some(save)) + { + *open = false; + } +} + +/// OK: open the Block Editor on the name given (a new name starts a new block). In the Block +/// Editor with changes not saved, it asks first whether to save them. Returns whether it opened; +/// if not, the dialog shows why (or asks) and stays open. pub fn confirm(app: &mut CadApp) -> bool { let name = app.bedit.name.trim().to_string(); if name.is_empty() { return false; } - match app.run("bedit", json!({ "name": name, "create": true })) { + let ask = app.session.state().is_ok_and(|st| st.block_unsaved() && st.block_editor().is_some_and(|b| !b.eq_ignore_ascii_case(&name))); + if ask { + // A block it can't switch to is refused before the question, which would trap the user. + if let Err(e) = app.run("bedit", json!({ "name": name, "create": true, "check": true })) { + app.bedit.error = Some(e); + return false; + } + app.bedit.ask_save = true; + return false; + } + run(app, None) +} + +/// Run BEDIT on the name given, saving (`Some(true)`) or discarding (`Some(false)`) the Block +/// Editor's changes not saved yet. Returns whether it went through; if not, the dialog shows why. +fn run(app: &mut CadApp, save: Option) -> bool { + let name = app.bedit.name.trim().to_string(); + let mut p = json!({ "name": name, "create": true }); + if let (Some(save), Some(o)) = (save, p.as_object_mut()) { + o.insert("save".into(), json!(save)); + } + match app.run("bedit", p) { Ok(_) => true, Err(e) => { app.bedit.error = Some(e); diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d71b3ccd7..3f2de02df 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1373,3 +1373,4 @@ Check for Updates… Перевірити оновлення… CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. + Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? diff --git a/crates/ui-egui/tests/bedit_dialog.rs b/crates/ui-egui/tests/bedit_dialog.rs index 95fdb4adc..21cd32155 100644 --- a/crates/ui-egui/tests/bedit_dialog.rs +++ b/crates/ui-egui/tests/bedit_dialog.rs @@ -95,9 +95,10 @@ fn a_selected_reference_and_json_calls_skip_the_dialog() { app.start("bedit"); assert!(app.ui.dialog.is_none()); assert_eq!(app.session.state().unwrap().block_editor(), Some("Window")); - // In the editor BEDIT says why it can't run instead of opening the dialog. + // In the editor BEDIT opens the dialog, to switch to another block. app.start("bedit"); - assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.dialog.as_deref(), Some("bedit")); + app.ui.dialog = None; app.run("bclose", json!({})).unwrap(); app.run("bedit", json!({ "name": "door" })).unwrap(); @@ -175,3 +176,65 @@ fn opening_a_drawing_with_authoring_elements_offers_the_block_editor() { assert!(app.ui.dialog.is_none()); let _ = std::fs::remove_dir_all(&dir); } + +/// A name the Block Editor can't switch to is refused before the dialog asks about the changes not +/// saved, so the question never traps the user. +#[test] +fn a_bad_name_is_refused_before_the_dialog_asks_to_save() { + let mut app = app_with_blocks(); + app.run("bedit", json!({ "name": "door" })).unwrap(); + app.run("line", json!({ "points": [[0, 0], [0, 4]] })).unwrap(); + app.start("bedit"); + app.bedit.name = "*U1".into(); + assert!(!bedit::confirm(&mut app)); + assert!(!app.bedit.ask_save, "no question"); + assert!(app.bedit.error.is_some(), "the dialog says why"); + assert!(app.session.state().unwrap().block_unsaved(), "nothing lost"); +} + +/// In the Block Editor, BEDIT opens the dialog on the block being edited; OK on another block +/// switches to it, first asking whether to save the changes not saved yet (Cancel goes back). +#[test] +fn in_the_block_editor_the_dialog_switches_blocks_asking_to_save_first() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + let mut app = app_with_blocks(); + app.run("bedit", json!({ "name": "door" })).unwrap(); + app.start("bedit"); + assert_eq!((app.ui.dialog.as_deref(), app.bedit.name.as_str()), (Some("bedit"), "door"), "starts on the block edited"); + // Nothing changed: OK switches at once. + app.bedit.name = "Window".into(); + assert!(bedit::confirm(&mut app)); + assert_eq!(app.session.state().unwrap().block_editor(), Some("Window")); + + app.run("line", json!({ "points": [[0, 0], [0, 4]] })).unwrap(); + app.start("bedit"); + app.bedit.name = "door".into(); + assert!(!bedit::confirm(&mut app), "asks first"); + assert!(app.bedit.ask_save); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(2); + assert!(h.query_by_label_contains("Save changes to block \"Window\"").is_some()); + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(!h.state().bedit.ask_save, "back to the list"); + assert_eq!(h.state().session.state().unwrap().block_editor(), Some("Window")); + assert!(h.state().session.state().unwrap().block_unsaved(), "nothing lost"); + + assert!(!bedit::confirm(h.state_mut())); + h.run_steps(2); + h.get_by_label("Yes").click(); + h.run_steps(2); + let st = h.state().session.state().unwrap(); + assert_eq!(st.block_editor(), Some("door")); + assert!(h.state().ui.dialog.is_none(), "the dialog closed"); + let window = h.state().session.doc().unwrap().block("Window").map(|b| b.entities.len()); + assert_eq!(window, Some(2), "Window saved with its new line before switching"); +} diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..b270525d6 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-28 · **Change:** minor (BEDIT in the Block Editor switches blocks: F3 updated) · **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 @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | 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 | +| 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 and, in the Block Editor, switches to another block after asking to save), 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 | | 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 | @@ -152,6 +152,7 @@ Detail: [localization-parity.md](localization-parity.md). |---|---|---| | 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-26 | minor | BEDIT in the Block Editor (typed, Edit Block, or the Edit Block Definition dialog) switches to another block as AutoCAD's does, asking whether to save the changes not saved yet; the JSON form takes `save`: F3 evidence | | 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 | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | From 58687dda2dc904ce0c1572a1d0b58a7ee2dffc01 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:21:31 +0100 Subject: [PATCH 178/900] Reject out-of-range numeric colours in properties.set (#2286) Found while testing crates/engine/src/cmd/props.rs:155-157 (parse_color), with crates/color/src/lib.rs:60-66 (Color::from_aci) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd/props.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 617d29756..dfe69fd8f 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -153,7 +153,9 @@ fn run_get(s: &mut Session, p: &Value) -> Result { } fn parse_color(v: &Value) -> Option { - v.as_str().and_then(Color::parse).or_else(|| v.as_i64().and_then(|i| i16::try_from(i).ok()).map(Color::from_aci)) + v.as_str() + .and_then(Color::parse) + .or_else(|| v.as_i64().filter(|i| (0..=256).contains(i)).and_then(|i| i16::try_from(i).ok()).map(Color::from_aci)) } /// A transparency as JSON, in the form `properties.set` takes: "ByLayer", "ByBlock" or a percentage. @@ -1221,6 +1223,24 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn properties_set_rejects_out_of_range_colour() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [50, 0]] })).unwrap(); + let h = s.doc().unwrap().model.last().unwrap().handle.hex(); + s.execute("properties.set", &json!({ "handles": [h], "color": 1 })).unwrap(); + let col = |s: &Session| s.doc().unwrap().model.last().unwrap().common.color; + for bad in [300, -5, 257] { + let e = s.execute("properties.set", &json!({ "handles": [h], "color": bad })).unwrap_err(); + assert!(e.to_string().contains("bad colour"), "{e}"); + assert_eq!(col(&s), Color::Index(1)); + } + s.execute("properties.set", &json!({ "handles": [h], "color": 256 })).unwrap(); + assert_eq!(col(&s), Color::ByLayer); + s.execute("properties.set", &json!({ "handles": [h], "color": 0 })).unwrap(); + assert_eq!(col(&s), Color::ByBlock); + } + #[test] fn properties_set_rejects_unloaded_linetype() { let mut s = Session::new(); From 31dba6e7a77d94b218e0e3c63e605adbd2f18df8 Mon Sep 17 00:00:00 2001 From: Ayoze Torres <53948812+ayozetr@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:21:35 +0000 Subject: [PATCH 179/900] Command line: a LISP value at a prompt is the answer, not another expression (#1920) (#2338) An expression typed at a command's prompt is evaluated, and its value answers the prompt. That value went back through typed(), which treated it as typed text and evaluated it again when it looked like LISP. So `circle (setq q "!q")` returned "!q", which evaluated to "!q" again, forever, until the native stack overflowed and the process aborted (a stack overflow is not a panic, so the catch_unwind guards cannot help), losing unsaved work in every open drawing. It is reachable from the command line, .scr scripts, the control channel and MCP. The value now goes back with LISP evaluation off: a string that looks like an expression is taken as text, as AutoCAD does. --- crates/engine/src/lisp/tests.rs | 25 +++++++++++++++++++++++++ crates/engine/src/session/cmdline.rs | 15 +++++++++++---- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index d65795631..58f421765 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -876,3 +876,28 @@ fn angtof_reads_the_string_in_the_given_units() { assert_eq!(ok(&mut s, "(angtof \"180\" 7)"), "nil"); assert_eq!(ok(&mut s, "(angtof \"180\" \"x\")"), "nil"); } + +/// #1920: the value of an expression typed at a prompt is the answer, not another expression. +/// `(setq q "!q")` returned `"!q"`, which was evaluated again as `!q`, forever, until the stack +/// overflowed and the process aborted (no `catch_unwind` catches that). +#[test] +fn a_lisp_value_at_a_prompt_is_not_evaluated_again() { + let mut s = session(); + s.cmdline("circle (setq q \"!q\")").unwrap(); + assert_eq!(ok(&mut s, "q"), "\"!q\""); + // "!q" is no centre point, so CIRCLE still asks for one; the session carries on. + assert!(s.running.is_some()); + s.cancel(); + // A value that is itself an expression stays text too: `(+ 1 2)` is not evaluated to 3. + s.cmdline("circle 0,0 (setq r \"(+ 1 2)\")").unwrap(); + assert!(s.running.is_some(), "\"(+ 1 2)\" is no radius"); + s.cancel(); + // Values that answer the prompt still do. + s.cmdline("(setq r \"4\")").unwrap(); + s.cmdline("circle 0,0 !r").unwrap(); + let r = s.doc().unwrap().model.iter().find_map(|e| match &e.kind { + cadcraft_doc::EntityKind::Circle(c) => Some(c.radius), + _ => None, + }); + assert_eq!(r, Some(4.0)); +} diff --git a/crates/engine/src/session/cmdline.rs b/crates/engine/src/session/cmdline.rs index 7b9bd53a2..2a1b45836 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -69,6 +69,13 @@ impl Session { /// One token typed while a command runs. pub(crate) fn typed(&mut self, t: &str) -> Result<()> { + self.typed_token(t, true) + } + + /// One token typed while a command runs; `lisp` evaluates a LISP expression first. The value + /// of that expression is the answer, so it comes back with `lisp` off: re-evaluating it would + /// let `(setq q "!q")` evaluate itself forever and overflow the stack (#1920). + fn typed_token(&mut self, t: &str, lisp: bool) -> Result<()> { let Some(prompt) = self.current_prompt() else { return Ok(()) }; let tt = t.trim(); if tt.is_empty() { @@ -84,7 +91,7 @@ impl Session { } // A LISP expression typed at a command's prompt: its value is the answer. // Not at a free-text prompt: there the text is the answer (CAL takes "(3+4)*2"). - if lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() { + if lisp && lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() { let src = tt.strip_prefix('!').unwrap_or(tt).to_string(); let v = match self.lisp_eval(&src, false, true, Vec::new()) { Ok(Some(Ok(v))) => v, @@ -96,9 +103,9 @@ impl Session { }; return match v { lisp::value::Value::Nil => Ok(()), - lisp::value::Value::Int(i) => self.typed(&i.to_string()), - lisp::value::Value::Real(r) => self.typed(&format!("{r}")), - lisp::value::Value::Str(s) => self.typed(&s), + lisp::value::Value::Int(i) => self.typed_token(&i.to_string(), false), + lisp::value::Value::Real(r) => self.typed_token(&format!("{r}"), false), + lisp::value::Value::Str(s) => self.typed_token(&s, false), other => match other.as_point() { Some(p) => self.input(Input::Point(Vec2::new(p[0], p[1]))), None => { From f817ea9a3a14be5ac582fa176f921d6ddf9a02e1 Mon Sep 17 00:00:00 2001 From: heejunB <125256444+heejunB@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:21:38 +0900 Subject: [PATCH 180/900] fix(render): fill font glyphs with the nonzero winding rule (#2189) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TrueType and OpenType outlines are defined with the nonzero rule, but glyph meshes were tessellated even-odd, so any area covered by two contours came out empty. Arial Unicode (the macOS fallback CADCraft picks for Hangul) builds 진 (U+C9C4) from a component that already contains the final ㄴ plus a second copy of that ㄴ; even-odd cancelled the pair and 진 rendered as 지. Overlapping contours in other fonts lost their overlaps the same way. Tessellate glyph outlines with FillOptions::non_zero(). Outlines placed in drawing coordinates without a TextGlyph (complex-script runs) go through the same tessellator, offset to their first point to keep f32 precision, instead of the even-odd slab filler. --- crates/render/src/lib.rs | 2 +- crates/render/src/text.rs | 79 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5b9dc83a1..6fa236e4c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -235,7 +235,7 @@ impl Builder<'_> { self.tris_at(ctx, color, &mesh.triangles, xf); mesh.triangles.len() } else { - let tris = fill::triangulate_evenodd(g); + let tris = crate::text::triangulate_placed(g); self.tris(ctx, color, &tris); tris.len() }; diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 6595e145f..1f80d7af4 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -163,8 +163,10 @@ fn simplify(contour: &[Vec2], tolerance: f64) -> Vec { if result.len() >= 4 { result } else { contour.to_vec() } } -/// Monotone tessellation with even-odd holes and intersections. Work in font units so f32 -/// precision is independent of drawing coordinates; the placement stays f64. The existing +/// Monotone tessellation with the nonzero winding rule that TrueType and OpenType outlines are +/// defined with: overlapping contours stay filled (Arial Unicode's 진 draws its final ㄴ twice, +/// which even-odd cancelled out) and holes are contours wound the other way. Work in font units +/// so f32 precision is independent of drawing coordinates; the placement stays f64. The existing /// slab filler remains the fallback when tessellation fails (including its u16 vertex limit). fn triangulate(contours: &[Vec]) -> Vec { let mut path = Path::builder(); @@ -179,7 +181,7 @@ fn triangulate(contours: &[Vec]) -> Vec { let mut buffers: VertexBuffers = VertexBuffers::new(); let result = FillTessellator::new().tessellate_path( &path.build(), - &FillOptions::even_odd(), + &FillOptions::non_zero(), &mut BuffersBuilder::new(&mut buffers, |v: FillVertex<'_>| { let p = v.position(); Vec2::new(f64::from(p.x), f64::from(p.y)) @@ -190,3 +192,74 @@ fn triangulate(contours: &[Vec]) -> Vec { } buffers.indices.into_iter().filter_map(|i| buffers.vertices.get(usize::from(i)).copied()).collect() } + +/// [`triangulate`] for a glyph outline already placed in drawing coordinates (complex-script +/// runs carry no [`TextGlyph`]): tessellated relative to its first point so f32 keeps the +/// precision. Outlines past the limits [`mesh`] applies keep the slab filler. +pub(super) fn triangulate_placed(contours: &[Vec]) -> Vec { + let Some(&origin) = contours.iter().flatten().next() else { return Vec::new() }; + let points = contours.iter().map(Vec::len).try_fold(0usize, usize::checked_add); + let out_of_range = |p: &Vec2| { + let d = *p - origin; + !p.is_finite() || d.x.abs().max(d.y.abs()) > 1.0e6 + }; + if !points.is_some_and(|n| n <= MAX_POINTS) || contours.iter().flatten().any(out_of_range) { + return crate::fill::triangulate_evenodd(contours); + } + let local: Vec> = contours.iter().map(|c| c.iter().map(|&p| p - origin).collect()).collect(); + triangulate(&local).into_iter().map(|p| p + origin).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(x: f64, y: f64, s: f64) -> Vec { + // Clockwise, as TrueType draws outer contours. + vec![Vec2::new(x, y), Vec2::new(x, y + s), Vec2::new(x + s, y + s), Vec2::new(x + s, y), Vec2::new(x, y)] + } + + fn area(tris: &[Vec2]) -> f64 { + tris.chunks(3) + .filter_map(|t| match t { + [a, b, c] => Some(((*b - *a).x * (*c - *a).y - (*b - *a).y * (*c - *a).x).abs() / 2.0), + _ => None, + }) + .sum() + } + + #[test] + fn duplicated_contour_stays_filled() { + // A composite glyph that draws one component twice (Arial Unicode's 진 and its ㄴ). + let s = square(0.0, 0.0, 10.0); + assert!((area(&triangulate(&[s.clone(), s])) - 100.0).abs() < 1e-6); + } + + #[test] + fn overlapping_contours_fill_their_union() { + let tris = triangulate(&[square(0.0, 0.0, 10.0), square(5.0, 5.0, 10.0)]); + assert!((area(&tris) - 175.0).abs() < 1e-6); + } + + #[test] + fn counter_wound_contour_is_still_a_hole() { + let mut hole = square(4.0, 4.0, 2.0); + hole.reverse(); + assert!((area(&triangulate(&[square(0.0, 0.0, 10.0), hole])) - 96.0).abs() < 1e-6); + } + + #[test] + fn placed_outline_far_from_the_origin_keeps_its_place_and_fill() { + let s = square(5.0e5, -3.0e5, 2.0); + let tris = triangulate_placed(&[s.clone(), s]); + assert!((area(&tris) - 4.0).abs() < 1e-6); + assert!(tris.iter().all(|p| (5.0e5..=5.0e5 + 2.0).contains(&p.x) && (-3.0e5..=-3.0e5 + 2.0).contains(&p.y))); + } + + #[test] + fn hostile_placed_outline_never_panics() { + assert!(triangulate_placed(&[]).is_empty()); + let _ = triangulate_placed(&[vec![Vec2::new(f64::NAN, 0.0), Vec2::X, Vec2::Y]]); + let _ = triangulate_placed(&[vec![Vec2::ZERO, Vec2::new(1.0e300, 0.0), Vec2::Y]]); + } +} From 74e77f8a929e43e5d5bb0af57da34c0cb0bbe777 Mon Sep 17 00:00:00 2001 From: smacdmac101 <152641296+smacdmac101@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:21:42 -0400 Subject: [PATCH 181/900] feat(web): persist validated browser panel layouts (#2258) * xtask: the test suite and clippy pass on Windows Two Windows-only failures stopped `cargo xtask ci` before it got going on a Windows checkout (CI runs the gate on Linux only, so neither showed): - parity::tests::civil_dates built a SystemTime 115,740,740 days after the epoch (year 318857). Windows' SystemTime ends in the year 30828, so the addition panicked ("overflow when adding duration to `SystemTime`"). That case now checks `civil_from_days` on the day count, which is what it was about, on every platform. - stats.rs imported `walk` for a test that only exists on Unix, so the import was unused on Windows and `clippy -D warnings` refused it. The Unix test calls `super::walk`, as its neighbour calls `super::walk_inner`. Checked on Windows 11 x64: `cargo test --workspace` and `cargo clippy --workspace --all-targets -- -D warnings` both pass. Co-Authored-By: Claude Opus 5.5 * feat(web): persist validated browser panel layouts CC-053: keep embedded floating, docked and hidden panels across reloads through the existing host save cycle. Reject malformed/versioned records atomically; native workspaces and drawings remain unchanged. Validation: all seven cargo xtask ci gates passed (2558 pass, 0 fail, 1 ignored) on a2dd814 plus this exact change. Actual release Trunk bundle and Edge floating/close/reload/reset/reload passed. Forced WebGL startup, render and recovered layout passed; full edit cycle used default mode. Dependency: original #2198 Windows test prerequisite. No #2226 dependency. Revert this commit independently to stop using the optional storage key. Upstream c3b8e7b adds nextest minimum configuration only; no runtime overlap. --------- Co-authored-by: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- apps/cadcraft-web/src/main.rs | 14 +++- apps/cadcraft-web/src/panel_layout.rs | 104 ++++++++++++++++++++++++++ docs/ui-parity.md | 4 +- packaging/web/README.md | 12 +++ 4 files changed, 132 insertions(+), 2 deletions(-) create mode 100644 apps/cadcraft-web/src/panel_layout.rs diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index f69e02d8a..a25782d6e 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -14,6 +14,9 @@ pub mod download; #[cfg(target_arch = "wasm32")] mod host; +#[cfg(any(target_arch = "wasm32", test))] +mod panel_layout; + #[cfg(target_arch = "wasm32")] mod web { use cadcraft_engine::Session; @@ -59,10 +62,14 @@ mod web { self.0.raw_input_hook(ctx, raw); cadcraft_ui_egui::cmdline::capture_tab(ctx, raw); } - /// Preferences (interface theme and language) survive reloads; egui state is not kept. + /// Preferences and validated panel placement survive reloads; egui memory is not kept. fn save(&mut self, storage: &mut dyn eframe::Storage) { storage.set_string(cadcraft_ui_egui::options::PROFILE_KEY, self.0.profile_json()); storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.0.prefs_json()); + match crate::panel_layout::save(&self.0.ui) { + Ok(layout) => storage.set_string(crate::panel_layout::KEY, layout), + Err(error) => log::warn!("panel layout was not saved: {error}"), + } } fn persist_egui_memory(&self) -> bool { false @@ -160,6 +167,11 @@ mod web { if let Some(prefs) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::PREFS_KEY)) { app.load_prefs(&prefs); } + if let Some(layout) = cc.storage.and_then(|s| s.get_string(crate::panel_layout::KEY)) + && let Err(error) = crate::panel_layout::restore(&mut app.ui, &layout) + { + log::warn!("panel layout was not restored: {error}"); + } // `?cpu`: no render state for the app, so the canvas draws with egui shapes. if !crate::wants_cpu(&query()) && let Some(rs) = &cc.wgpu_render_state diff --git a/apps/cadcraft-web/src/panel_layout.rs b/apps/cadcraft-web/src/panel_layout.rs new file mode 100644 index 000000000..766879c83 --- /dev/null +++ b/apps/cadcraft-web/src/panel_layout.rs @@ -0,0 +1,104 @@ +//! Browser panel layout storage, independent of drawings and native workspace files. + +use cadcraft_ui_egui::{UiState, docking}; +use serde_json::{Value, json}; + +#[cfg(target_arch = "wasm32")] +pub const KEY: &str = "cadcraft.panel-layout"; +const MAX_BYTES: usize = 64 * 1024; + +/// Serialize only validated panel placement and visibility, with a bounded record size. +pub fn save(ui: &UiState) -> Result { + docking::validate(&ui.docking)?; + let saved = json!({ + "version": docking::LAYOUT_VERSION, + "docking": ui.docking, + "showToolsets": ui.show_toolsets, + "showPalettes": ui.show_palettes, + }) + .to_string(); + if saved.len() > MAX_BYTES { + return Err("panel layout exceeds 64 KiB".into()); + } + Ok(saved) +} + +/// Validate the entire optional record before changing any UI field. +pub fn restore(ui: &mut UiState, saved: &str) -> Result<(), String> { + if saved.len() > MAX_BYTES { + return Err("panel layout exceeds 64 KiB".into()); + } + let value: Value = serde_json::from_str(saved).map_err(|error| error.to_string())?; + if value.get("version").and_then(Value::as_u64) != Some(u64::from(docking::LAYOUT_VERSION)) { + return Err("unsupported panel layout version".into()); + } + let workspace: docking::Workspace = + serde_json::from_value(value.get("docking").cloned().ok_or("missing panel layout")?).map_err(|error| error.to_string())?; + docking::validate(&workspace)?; + let tools = value.get("showToolsets").and_then(Value::as_bool).ok_or("invalid Tool Sets visibility")?; + let palettes = value.get("showPalettes").and_then(Value::as_bool).ok_or("invalid palette visibility")?; + ui.docking = workspace; + ui.show_toolsets = tools; + ui.show_palettes = palettes; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_engine::Session; + use cadcraft_ui_egui::{CadApp, Services}; + + #[test] + fn floating_and_hidden_panels_survive_storage_without_replacing_drawing_state() { + let mut source = CadApp::new(Session::default(), Services::default()); + source.run("ui.dock", json!({"operation":"float","panel":"toolSets","rect":[120,90,340,410]})).unwrap(); + source.run("ui.dock", json!({"operation":"close","panel":"properties"})).unwrap(); + let saved = save(&source.ui).unwrap(); + let mut destination = CadApp::new(Session::default(), Services::default()); + destination.session.start("line").unwrap(); + let before = destination.session.doc().unwrap().clone(); + restore(&mut destination.ui, &saved).unwrap(); + assert_eq!(destination.ui.docking, source.ui.docking); + assert_eq!(destination.ui.show_toolsets, source.ui.show_toolsets); + assert_eq!(destination.ui.show_palettes, source.ui.show_palettes); + assert_eq!(destination.session.running.as_ref().map(|command| command.id.as_str()), Some("line")); + assert_eq!(destination.session.doc().unwrap(), &before); + } + + #[test] + fn malformed_or_unsupported_storage_is_rejected_atomically() { + let mut ui = UiState::default(); + let before = serde_json::to_value(&ui).unwrap(); + let valid: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap(); + for (field, bad) in [ + ("version", json!(0)), + ("version", json!(docking::LAYOUT_VERSION + 1)), + ("docking", json!({})), + ("showToolsets", json!("false")), + ("showPalettes", Value::Null), + ] { + let mut invalid = valid.clone(); + invalid[field] = bad; + assert!(restore(&mut ui, &invalid.to_string()).is_err()); + assert_eq!(serde_json::to_value(&ui).unwrap(), before); + } + for invalid in ["not json".to_string(), " ".repeat(MAX_BYTES + 1)] { + assert!(restore(&mut ui, &invalid).is_err()); + assert_eq!(serde_json::to_value(&ui).unwrap(), before); + } + } + + #[test] + fn storage_cannot_remove_the_document_view() { + let mut ui = UiState::default(); + let before = serde_json::to_value(&ui).unwrap(); + let mut invalid = ui.clone(); + invalid.docking.layout.root = None; + assert!(save(&invalid).is_err()); + let mut record: Value = serde_json::from_str(&save(&ui).unwrap()).unwrap(); + record["docking"] = serde_json::to_value(&invalid.docking).unwrap(); + assert!(restore(&mut ui, &record.to_string()).is_err()); + assert_eq!(serde_json::to_value(&ui).unwrap(), before); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c06e8f242..6bf0c20f8 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-26 · **Change:** minor (browser panel layout storage) · **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,6 +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 | +| 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 | | Themes | Dark, Light | Dark, Light, System (#179) | @@ -203,6 +204,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Browser host stores bounded, validated panel layout separately from drawing state; malformed or unsupported records retain defaults. Native workspace storage is unchanged. | | 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) | diff --git a/packaging/web/README.md b/packaging/web/README.md index 024e00c01..73a74f493 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -50,6 +50,18 @@ location /cadcraft/ { Local test: `python3 -m http.server 8765` inside the folder, then open http://localhost:8765/. +## Panel layout storage + +The browser host saves docked, floating and hidden palette arrangements alongside interface +preferences in its local storage. Floating palettes remain embedded in the browser canvas; +they do not become native operating-system windows. Window > Reset Palettes restores the +default arrangement. This record contains panel placement and visibility, not drawing data. + +The optional `cadcraft.panel-layout` record uses the shared docking layout version and is +limited to 64 KiB. Malformed, incompatible or invalid arrangements are ignored atomically, +leaving the startup defaults usable. Storage availability and autosave follow the browser +host's existing eframe persistence; clearing site data removes the saved layout. + ## Embedding in a page (iframe) ```html From 61fefc3ed931fe645432da8fb694409d881009bd Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:21:46 +0100 Subject: [PATCH 182/900] Skip a leading UTF-8 BOM when parsing ASCII DXF (#2287) Found while testing crates/dxf/src/lib.rs:189 and 267-274 (parse_with_limit via decode_ascii_file, then parse_ascii_with_limit) Co-authored-by: Claude Haiku 5.5 --- crates/dxf/src/lib.rs | 2 +- crates/dxf/tests/ascii_bom.rs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 crates/dxf/tests/ascii_bom.rs diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 907c5abf7..4e888bdc0 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -264,7 +264,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 = text.strip_prefix('\u{feff}').unwrap_or(text).lines().enumerate(); loop { let Some((ln, code_line)) = lines.next() else { break }; let ct = code_line.trim(); diff --git a/crates/dxf/tests/ascii_bom.rs b/crates/dxf/tests/ascii_bom.rs new file mode 100644 index 000000000..e39b9b84c --- /dev/null +++ b/crates/dxf/tests/ascii_bom.rs @@ -0,0 +1,19 @@ +//! A UTF-8 byte order mark at the start of an ASCII DXF is skipped. + +const BODY: &str = " 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + +#[test] +fn utf8_bom_bytes_are_skipped() { + let plain = cadcraft_dxf::parse(BODY.as_bytes()).expect("plain parses"); + let mut bytes = vec![0xEF, 0xBB, 0xBF]; + bytes.extend_from_slice(BODY.as_bytes()); + let with_bom = cadcraft_dxf::parse(&bytes); + assert!(with_bom.is_ok(), "{with_bom:?}"); + assert_eq!(with_bom.map(|t| t.len()).unwrap_or(0), plain.len()); +} + +#[test] +fn bom_text_is_skipped() { + let text = format!("\u{feff}{BODY}"); + assert!(cadcraft_dxf::parse_ascii(&text).is_ok()); +} From 1d6c72db119382214b55e06a84db541b0d71df53 Mon Sep 17 00:00:00 2001 From: Books Date: Fri, 30 Oct 2026 12:21:50 +1100 Subject: [PATCH 183/900] Bound the MCP client's reply read and the control server's total buffered bytes (#1925) (#2398) * Bound the MCP client's reply read and the control server's total buffered bytes (#1925) The MCP client read replies with an unbounded read_line; a process squatting on the control port could make it allocate without limit. It now reads through take() with a 256 MiB cap (the server's own request cap) and fails with a clear error. The control server allowed max_clients x max_line (16 x 256 MiB) buffered at once. Request-line bytes are now charged against a shared 512 MiB budget; a request that would pass it gets an error reply and the connection closes. * Parity checklist: regenerated after merging main * control_server: drop unused Read import (#1925) * control_server: tests import Read themselves (#1925) The unused-import cleanup removed std::io::Read from the module, but a test still calls read_to_end, so the test build failed on CI. --- apps/cadcraft/src/control_server.rs | 171 +++++++++++++++++++++++----- crates/mcp/src/backend.rs | 60 +++++++++- 2 files changed, 196 insertions(+), 35 deletions(-) diff --git a/apps/cadcraft/src/control_server.rs b/apps/cadcraft/src/control_server.rs index 14283e6fd..d502e1408 100644 --- a/apps/cadcraft/src/control_server.rs +++ b/apps/cadcraft/src/control_server.rs @@ -7,7 +7,7 @@ //! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a //! socket may sit idle or blocked on a write. -use std::io::{BufRead, BufReader, ErrorKind, Read, Write}; +use std::io::{BufRead, BufReader, ErrorKind, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -24,6 +24,9 @@ struct Limits { max_clients: usize, /// Longest request line in bytes (newline excluded); a longer one closes the connection. max_line: usize, + /// Request-line bytes buffered at once across all connections; a request that would pass it + /// is refused with an error reply. + total_bytes: usize, /// Requests waiting for the app at once; more are answered `busy`. queue: usize, /// How long a connection may go without sending a byte before it is closed. @@ -40,6 +43,8 @@ impl Default for Limits { max_clients: 16, // Generous, so requests that carry whole drawings or images as base64 still fit. max_line: 256 * 1024 * 1024, + // Room for one maximal request plus smaller ones, not `max_clients` maximal ones. + total_bytes: 512 * 1024 * 1024, queue: 64, idle_timeout: Duration::from_secs(600), write_timeout: Duration::from_secs(30), @@ -106,6 +111,7 @@ impl Drop for Slot { /// Accept clients within the connection limit and give each worker the same session token. fn accept_loop(listener: TcpListener, tx: SyncSender, ctx: egui::Context, limits: Limits, token: Arc) { let open = Arc::new(AtomicUsize::new(0)); + let budget = Budget::new(limits.total_bytes); for mut stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) { let _ = stream.set_write_timeout(Some(limits.write_timeout)); if open.fetch_add(1, Ordering::SeqCst) >= limits.max_clients { @@ -117,39 +123,102 @@ fn accept_loop(listener: TcpListener, tx: SyncSender, ctx: egui: let tx = tx.clone(); let ctx = ctx.clone(); let token = Arc::clone(&token); + let budget = budget.clone(); let _ = std::thread::Builder::new().spawn(move || { let _slot = slot; - serve(stream, &tx, &ctx, limits, &token); + serve(stream, &tx, &ctx, limits, &token, budget); }); } } -/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped). -/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails. -fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize) -> Result { +/// A total-bytes budget for request lines buffered across all connections, so +/// [`Limits::max_clients`] peers can't each hold a [`Limits::max_line`] line at once (#1925). +#[derive(Clone, Debug)] +struct Budget { + used: Arc, + total: usize, +} + +impl Budget { + fn new(total: usize) -> Self { + Self { used: Arc::new(AtomicUsize::new(0)), total } + } + + /// Reserve `n` more bytes, or `false` (nothing reserved) when that would pass the total. + fn reserve(&self, n: usize) -> bool { + self.used.try_update(Ordering::SeqCst, Ordering::SeqCst, |u| u.checked_add(n).filter(|&t| t <= self.total)).is_ok() + } +} + +/// Bytes a connection holds from the [`Budget`] for its current request line; given back when the +/// next line starts or the connection ends. +struct Held { + budget: Budget, + bytes: usize, +} + +impl Held { + fn new(budget: Budget) -> Self { + Self { budget, bytes: 0 } + } + + fn release(&mut self) { + self.budget.used.fetch_sub(self.bytes, Ordering::SeqCst); + self.bytes = 0; + } +} + +impl Drop for Held { + fn drop(&mut self) { + self.release(); + } +} + +/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped), charging +/// the bytes buffered to `held`. `Ok(false)` at end of stream; `Err` when the line is too long, +/// the shared budget is used up, or the read fails. +fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec, max: usize, held: &mut Held) -> Result { buf.clear(); - // `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`. - let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); - let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() { - // The idle timeout ran out (Windows reports it as TimedOut, Unix as WouldBlock). - ErrorKind::TimedOut | ErrorKind::WouldBlock => "request line not completed in time; closing the connection".to_string(), - _ => e.to_string(), - })?; - if n == 0 { - return Ok(false); - } - if buf.last() == Some(&b'\n') { - buf.pop(); - if buf.last() == Some(&b'\r') { + held.release(); + // A line is at most `max` bytes plus its newline; never buffer more than that. + let cap = max.saturating_add(1); + loop { + let chunk = match reader.fill_buf() { + Ok(c) => c, + Err(e) if e.kind() == ErrorKind::Interrupted => continue, + Err(e) => { + return Err(match e.kind() { + // The idle timeout ran out (Windows reports it as TimedOut, Unix as WouldBlock). + ErrorKind::TimedOut | ErrorKind::WouldBlock => "request line not completed in time; closing the connection".to_string(), + _ => e.to_string(), + }); + } + }; + if chunk.is_empty() { + // End of stream: nothing read, or a last line without a newline. + return Ok(!buf.is_empty()); + } + let line_end = chunk.iter().position(|&b| b == b'\n').map(|i| i + 1); + let n = line_end.unwrap_or(chunk.len()).min(cap.saturating_sub(buf.len())); + buf.extend_from_slice(chunk.get(..n).unwrap_or(chunk)); + reader.consume(n); + // The chunk is already buffered (a few KiB), so it is added before it is charged: a + // refusal still leaves `buf` non-empty and the connection gets an error reply. + if !held.budget.reserve(n) { + return Err("too many large requests in flight; try again later".to_string()); + } + held.bytes += n; + if buf.last() == Some(&b'\n') { buf.pop(); + if buf.last() == Some(&b'\r') { + buf.pop(); + } + return Ok(true); + } + if buf.len() > max { + return Err(format!("request line longer than {max} bytes; closing the connection")); } - return Ok(true); } - if buf.len() > max { - return Err(format!("request line longer than {max} bytes; closing the connection")); - } - // Last line without a newline, then end of stream. - Ok(true) } /// One request line, parsed. @@ -204,7 +273,7 @@ fn is_http_request_line(text: &str) -> bool { /// Serve bounded JSON lines, authenticating each request before enqueueing it for the UI. /// Invalid credentials close the connection; queue and reply limits report whether a request ran. -fn serve(stream: TcpStream, tx: &SyncSender, ctx: &egui::Context, limits: Limits, token: &str) { +fn serve(stream: TcpStream, tx: &SyncSender, ctx: &egui::Context, limits: Limits, token: &str, budget: Budget) { if stream.set_read_timeout(Some(limits.idle_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() { return; } @@ -212,8 +281,9 @@ fn serve(stream: TcpStream, tx: &SyncSender, ctx: &egui::Context let mut out = stream; let mut reader = BufReader::new(read); let mut buf = Vec::new(); + let mut held = Held::new(budget); loop { - let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line) { + let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) { Ok(false) => break, // Nothing of a line arrived (idle timeout, or the peer is gone): close without a word. // A line nobody asked for would be read as the reply to the client's next request. @@ -264,6 +334,7 @@ fn serve(stream: TcpStream, tx: &SyncSender, ctx: &egui::Context #[cfg(test)] mod tests { use super::*; + use std::io::Read; /// A failed accept is followed by a wait before the next one, so a listener that keeps /// failing does not spin, and the connections around the failures still come through. @@ -281,13 +352,13 @@ mod tests { fn lines_are_read_up_to_the_limit() { let mut buf = Vec::new(); let mut input: &[u8] = b"aaaaaaaaaa\nbb\r\ncc"; - assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true)); + assert_eq!(read_bounded_line(&mut input, &mut buf, 10, &mut held()), Ok(true)); assert_eq!(buf, b"aaaaaaaaaa", "a line exactly at the limit is accepted"); - assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true)); + assert_eq!(read_bounded_line(&mut input, &mut buf, 10, &mut held()), Ok(true)); assert_eq!(buf, b"bb", "CRLF is stripped"); - assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(true)); + assert_eq!(read_bounded_line(&mut input, &mut buf, 10, &mut held()), Ok(true)); assert_eq!(buf, b"cc", "a last line without a newline is still read"); - assert_eq!(read_bounded_line(&mut input, &mut buf, 10), Ok(false), "then end of stream"); + assert_eq!(read_bounded_line(&mut input, &mut buf, 10, &mut held()), Ok(false), "then end of stream"); } #[test] @@ -295,11 +366,15 @@ mod tests { let mut buf = Vec::new(); let long = [b'x'; 100]; let mut input: &[u8] = &long; - assert!(read_bounded_line(&mut input, &mut buf, 10).is_err()); + assert!(read_bounded_line(&mut input, &mut buf, 10, &mut held()).is_err()); assert!(buf.len() <= 11, "at most limit + 1 bytes are buffered, got {}", buf.len()); assert_eq!(input.len(), 100 - 11, "the rest of the line is left unread"); } + fn held() -> Held { + Held::new(Budget::new(usize::MAX)) + } + fn short() -> Limits { Limits { queue: 1, @@ -414,6 +489,40 @@ mod tests { drop(rx); } + /// Connections can't together buffer more request-line bytes than the budget: a second large + /// request is refused with an error reply while the first still holds its bytes (#1925). + #[test] + fn requests_past_the_total_budget_are_refused() { + let (addr, _rx) = serve_with(Limits { max_line: 1000, total_bytes: 300, idle_timeout: Duration::from_secs(5), ..short() }); + // The first peer sends 200 bytes of an unfinished line and keeps the connection open. + let mut first = TcpStream::connect(addr).unwrap(); + first.write_all(&[b'a'; 200]).unwrap(); + std::thread::sleep(Duration::from_millis(200)); + // The second would take 200 more, past the 300 byte total. + let mut second = TcpStream::connect(addr).unwrap(); + second.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + second.write_all(&[b'b'; 200]).unwrap(); + let mut line = String::new(); + BufReader::new(second).read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["ok"], json!(false)); + assert!(v["error"].as_str().unwrap_or("").contains("too many large requests"), "{line}"); + drop(first); + } + + #[test] + fn the_budget_is_given_back_when_the_connection_ends() { + let budget = Budget::new(100); + { + let mut h = Held::new(budget.clone()); + let mut buf = Vec::new(); + let mut input: &[u8] = &[b'x'; 80]; + assert_eq!(read_bounded_line(&mut input, &mut buf, 1000, &mut h), Ok(true)); + assert!(!budget.reserve(30), "80 of 100 bytes are held"); + } + assert!(budget.reserve(100), "all given back on drop"); + } + /// Replies on one authenticated connection preserve the ID of each request. #[test] fn requests_are_answered_with_their_ids() { diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 9d012076a..20a86fce7 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -1,6 +1,6 @@ //! Where MCP tool calls end up: a control-channel method call. -use std::io::{BufRead, BufReader, Write}; +use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::time::Duration; @@ -28,6 +28,8 @@ pub struct Remote { /// The per-session control token for this port, read from the owner-only token file on first /// use so requests can authenticate (CWE-306). token: Option, + /// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests). + max_reply: usize, } /// The port component of a `HOST:PORT` address, for locating the token file. @@ -38,10 +40,29 @@ fn port_of(addr: &str) -> Option { /// How long a launched app has to open its control port. const LAUNCH_WAIT: Duration = Duration::from_secs(30); +/// Longest reply line in bytes the client will buffer. It matches the control server's request +/// cap (256 MiB, room for whole drawings and images as base64), so a peer squatting on the port +/// can't make the client allocate without bound (#1925). +const MAX_REPLY_LINE: usize = 256 * 1024 * 1024; + +/// Read one `\n`-terminated reply of at most `max` bytes (newline excluded). `Ok(0)` is end of +/// stream; a longer line is an `InvalidData` error and the rest of it stays unread. +fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) -> std::io::Result { + let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); + let n = reader.take(limit).read_line(reply)?; + if n > max && !reply.ends_with('\n') { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("reply from the control port is longer than {max} bytes; is that CADCraft's control server?"), + )); + } + Ok(n) +} + impl Remote { /// Connect to a running control server; its session token is read lazily when the first request is sent. pub fn connect(addr: &str) -> std::io::Result { - let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None }; + let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, max_reply: MAX_REPLY_LINE }; r.reconnect()?; Ok(r) } @@ -49,7 +70,7 @@ impl Remote { /// the server before the app is open. With `launch`, a call that finds nothing at `addr` /// opens the app with that control port first (macOS) and waits for it. pub fn lazy(addr: &str, launch: bool) -> Self { - Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None } + Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, max_reply: MAX_REPLY_LINE } } /// The per-session token for this port, read (and cached) from the owner-only token file. A @@ -120,7 +141,7 @@ impl Remote { return Err((e, true)); } let mut reply = String::new(); - match reader.read_line(&mut reply) { + match read_reply_line(reader, &mut reply, self.max_reply) { Ok(0) => { self.conn = None; Err((std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "connection closed"), true)) @@ -430,6 +451,37 @@ mod tests { use std::net::TcpListener; use std::sync::Arc; + /// A peer squatting on the control port can't make the client buffer an endless reply line (#1925). + #[test] + fn an_overlong_reply_is_refused_without_buffering_it() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let server = std::thread::spawn(move || { + let (mut conn, _) = listener.accept().unwrap(); + let mut line = String::new(); + BufReader::new(conn.try_clone().unwrap()).read_line(&mut line).unwrap(); + // No newline: the reply never ends. A bounded client gives up after the limit. + let _ = conn.write_all(&[b'x'; 4096]); + let _ = conn.flush(); + std::thread::sleep(Duration::from_millis(500)); + }); + let mut remote = Remote::connect(&addr).unwrap(); + remote.max_reply = 100; + let err = remote.roundtrip("{}").unwrap_err().0; + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData, "{err}"); + assert!(err.to_string().contains("longer than 100 bytes"), "{err}"); + assert!(remote.conn.is_none()); + server.join().unwrap(); + } + + #[test] + fn replies_up_to_the_limit_are_read() { + let mut input: &[u8] = b"0123456789\nrest\n"; + let mut reply = String::new(); + assert_eq!(read_reply_line(&mut input, &mut reply, 10).unwrap(), 11); + assert_eq!(reply, "0123456789\n"); + } + /// A server that reads one request per connection and closes without replying must not see the request twice. #[test] fn lost_reply_to_a_mutation_is_not_resent() { From 1d987904f9064b8e712a4abbd4e065f3a238c1fa Mon Sep 17 00:00:00 2001 From: bmh129 Date: Thu, 29 Oct 2026 20:21:54 -0500 Subject: [PATCH 184/900] Tests remove the temp files they write (#2232) * Tests remove the temp files they write Every test run left about 22 folders and files in the system temp directory: xref, alias, template, insert, linetype, script and recent-file fixtures, plus the pathless screenshot folder. The PDFBOOK test also wrote its second book to `$TMPDIR/b.pdf`, because `a^b.pdf` splits into `-a.pdf` and `b.pdf`, and then removed a file that was never written. Tests that write files now use a `TempDir` guard (`tests/support/temp_dir.rs`, shared by the engine's unit and integration tests and copied for the UI crate). It gives each test its own folder and removes it on drop, even when an assertion fails. The PDFBOOK test also checks that both books land in its folder. The five tests that write pathless screenshots hold a test-only lock, so the shared screenshot folder can be removed once empty without racing another test's write. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012FFPi6hJVyaEKV4PyE2fKq * Pathless screenshot cleanup survives failed tests and writes The test lock's guard now empties and removes the per-process screenshot directory when dropped, so a test that panics no longer leaves files behind, and the per-test remove calls are gone. A failed PNG write or flush removes the partial file, since the reply carries no path for anyone else to clean up. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: bmh129 <11478682+bmh129@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/exchange.rs | 9 ++--- crates/engine/src/cmd/file.rs | 18 +++++----- crates/engine/src/lib.rs | 4 +++ crates/engine/tests/aliases.rs | 11 +++--- crates/engine/tests/insert_file.rs | 22 ++++++------ crates/engine/tests/lin_pat_files.rs | 25 +++++++------ crates/engine/tests/support/temp_dir.rs | 46 ++++++++++++++++++++++++ crates/engine/tests/templates.rs | 37 ++++++++++--------- crates/engine/tests/xref.rs | 16 +++++---- crates/ui-egui/src/capture/tests.rs | 12 +++---- crates/ui-egui/src/control.rs | 42 +++++++++++++++++++--- crates/ui-egui/tests/recent_files.rs | 25 ++++++------- crates/ui-egui/tests/support/temp_dir.rs | 46 ++++++++++++++++++++++++ crates/ui-egui/tests/xref_palette.rs | 16 ++++----- 14 files changed, 230 insertions(+), 99 deletions(-) create mode 100644 crates/engine/tests/support/temp_dir.rs create mode 100644 crates/ui-egui/tests/support/temp_dir.rs diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index f9acc909e..e28de89fc 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -754,19 +754,20 @@ mod tests { s.cmdline("").unwrap(); s.cmdline("pline 0,900 50,900 50,950 0,950 c").unwrap(); s.cmdline("").unwrap(); - let r = s.execute("pdfbook", &json!({ "path": temp("a^b.pdf").to_string_lossy() })); + // `a^b.pdf` names one book per row, both in the folder of the path. + let dir = crate::temp_dir::TempDir::new("pdfbook"); + let r = s.execute("pdfbook", &json!({ "path": dir.path_str("a^b.pdf") })); let r = r.unwrap(); let books = r["books"].as_array().unwrap(); assert_eq!(books.len(), 2); assert_eq!(books[0]["pages"], 3); assert_eq!(books[1]["pages"], 1); - let first = temp("a.pdf"); + let first = dir.join("a.pdf"); let text = String::from_utf8(std::fs::read(&first).unwrap()).unwrap(); let (a4, a3) = (text.find("ISO A4").unwrap(), text.find("ISO A3").unwrap()); assert!(a4 < a3, "frames go left to right: {text}"); assert!(text.contains("\"landscape\":true")); - let _ = std::fs::remove_file(first); - let _ = std::fs::remove_file(temp("b.pdf")); + assert!(dir.join("b.pdf").is_file(), "the second row's book is written beside the first"); // No frames: an error, not a panic. assert!(Session::new().execute("pdfbook", &json!({})).is_err()); } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 3a5296e88..7c26a71f9 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -652,20 +652,16 @@ mod tests { use serde_json::json; use crate::Session; + use crate::temp_dir::TempDir; fn active_title(s: &Session) -> String { s.state().unwrap().title.clone() } - fn temp_script(name: &str, text: &str) -> String { - let path = std::env::temp_dir().join(format!("cadcraft-script-{}-{name}", std::process::id())); - std::fs::write(&path, text).unwrap(); - path.to_string_lossy().into_owned() - } - #[test] fn script_command_runs_a_scr_file() { - let path = temp_script("run.scr", "; a comment\ncircle 50,25 20\nrectang 0,0 100,60\n"); + let dir = TempDir::new("script"); + let path = dir.file("run.scr", "; a comment\ncircle 50,25 20\nrectang 0,0 100,60\n"); let mut s = Session::new(); let r = s.execute("script", &json!({ "path": path })).unwrap(); assert_eq!(r["lines"], 3); @@ -683,8 +679,9 @@ mod tests { /// A script that runs itself must be refused, not recurse until the stack dies. #[test] fn a_script_cannot_start_a_script() { - let inner = temp_script("inner.scr", "circle 0,0 1\n"); - let outer = temp_script("outer.scr", &format!("script {}\ncircle 0,0 2\n", json!({ "path": inner }))); + let dir = TempDir::new("script"); + let inner = dir.file("inner.scr", "circle 0,0 1\n"); + let outer = dir.file("outer.scr", format!("script {}\ncircle 0,0 2\n", json!({ "path": inner }))); let mut s = Session::new(); let e = s.execute("script", &json!({ "path": outer })).unwrap_err().to_string(); assert!(e.contains("already running"), "{e}"); @@ -692,7 +689,8 @@ mod tests { #[test] fn typed_script_prompts_for_the_file_then_runs_or_reports_it() { - let good = temp_script("typed.scr", "circle 0,0 1\n"); + let dir = TempDir::new("script"); + let good = dir.file("typed.scr", "circle 0,0 1\n"); let mut s = Session::new(); s.cmdline("script").unwrap(); assert!(s.running.is_some(), "SCRIPT asks for the file name"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dbb1d0e6b..2dea12394 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -324,3 +324,7 @@ impl Session { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "../tests/support/temp_dir.rs"] +mod temp_dir; diff --git a/crates/engine/tests/aliases.rs b/crates/engine/tests/aliases.rs index 7587a9ffb..d1b39bb81 100644 --- a/crates/engine/tests/aliases.rs +++ b/crates/engine/tests/aliases.rs @@ -8,6 +8,11 @@ use cadcraft_engine::Session; use cadcraft_engine::cmd::resolve_alias; use serde_json::json; +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); const PGP: &str = "\ @@ -55,10 +60,8 @@ fn an_alias_file_adds_and_overrides_aliases() { #[test] fn reinit_reads_the_alias_file_again() { let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let dir = std::env::temp_dir().join(format!("cadcraft-aliases-{}", 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, "ZZR, *RECTANG\n").unwrap(); + let dir = TempDir::new("aliases"); + let file = dir.file("mine.pgp", "ZZR, *RECTANG\n"); let mut s = Session::new(); s.execute("aliasedit", &json!({ "file": file })).unwrap(); assert_eq!(resolve_alias("zzr"), "rectang"); diff --git a/crates/engine/tests/insert_file.rs b/crates/engine/tests/insert_file.rs index 77bfd9d85..41f7a92a7 100644 --- a/crates/engine/tests/insert_file.rs +++ b/crates/engine/tests/insert_file.rs @@ -8,6 +8,11 @@ use cadcraft_engine::doc::geom::Vec3; use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, HVal, Handle, Insert, Layer, Line}; use serde_json::json; +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + /// A drawing file in a test format: its bytes are "x,y", the $INSBASE. Model space: a line from /// 10,10 to 20,10 on layer PARTS (colour 1), and a reference to block NUT (a circle) at 10,10. fn read(bytes: &[u8], _name: &str) -> Result { @@ -44,15 +49,6 @@ fn hooks() { set_io(IoHooks { read, write: |_, _| Err("no writer in this test".into()), plot: None }); } -/// Write a test drawing file with $INSBASE `base`; returns its path. -fn file(name: &str, base: &str) -> String { - let dir = std::env::temp_dir().join(format!("cadcraft-insert-file-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let p = dir.join(name); - std::fs::write(&p, base).unwrap(); - p.to_string_lossy().into_owned() -} - /// Lines in model space as (ax, ay, bx, by), rounded. fn lines(s: &Session) -> Vec<(f64, f64, f64, f64)> { let r = |v: f64| (v * 1e6).round() / 1e6; @@ -105,7 +101,9 @@ fn star_name_inserts_the_blocks_objects_with_one_scale_factor() { #[test] fn a_drawing_file_becomes_a_block_with_its_insbase_and_tables() { hooks(); - let bolt = file("bolt.dxf", "10,10"); + // Test drawing files hold their $INSBASE. + let dir = TempDir::new("insert-file"); + let bolt = dir.file("bolt.dxf", "10,10"); let mut s = Session::new(); // This drawing's own layer PARTS keeps its colour. s.execute("layer.new", &json!({ "name": "PARTS", "color": 3 })).unwrap(); @@ -128,7 +126,7 @@ fn a_drawing_file_becomes_a_block_with_its_insbase_and_tables() { assert_eq!(inserts(&s).len(), 2); // NAME=path defines the block under that name without asking; *path inserts the file's objects. - let pin = file("pin.dxf", "10,10"); + let pin = dir.file("pin.dxf", "10,10"); s.script(&format!("-INSERT M8={bolt} 0,0 1 1 0\n-INSERT *{pin} 50,0 1 0\n")).unwrap(); assert!(s.running.is_none(), "INSERT finished: {}", s.prompt_text()); assert!(s.doc().unwrap().block("M8").is_some()); @@ -138,7 +136,7 @@ fn a_drawing_file_becomes_a_block_with_its_insbase_and_tables() { assert!(inserts(&s).iter().any(|i| i.0 == "NUT" && i.1 == 50.0 && i.2 == 0.0)); // JSON: `file` with an optional block name, never a dialog. - let r = s.execute("insert", &json!({ "file": file("washer.dxf", "0,0"), "at": [5, 5] })).unwrap(); + let r = s.execute("insert", &json!({ "file": dir.file("washer.dxf", "0,0"), "at": [5, 5] })).unwrap(); assert!(r["handle"].is_string(), "{r}"); assert!(inserts(&s).iter().any(|i| i.0 == "washer")); diff --git a/crates/engine/tests/lin_pat_files.rs b/crates/engine/tests/lin_pat_files.rs index 1c57d9f25..b09b504d4 100644 --- a/crates/engine/tests/lin_pat_files.rs +++ b/crates/engine/tests/lin_pat_files.rs @@ -6,16 +6,12 @@ use cadcraft_engine::Session; use cadcraft_engine::doc::{EntityKind, Hatch}; use serde_json::json; -const LIN: &str = "*MYDASH,My dash __ __\nA,.5,-.25\n*MYTEXT,My text --MY--\nA,.5,-.2,[\"MY\",Standard,S=.1,X=-.1,Y=-.05],-.2\n"; +#[path = "support/temp_dir.rs"] +mod temp_dir; -/// A user file in the test's temp folder; returns its path. -fn file(name: &str, text: &str) -> String { - let dir = std::env::temp_dir().join(format!("cadcraft-lin-pat-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let p = dir.join(name); - std::fs::write(&p, text).unwrap(); - p.to_string_lossy().into_owned() -} +use temp_dir::TempDir; + +const LIN: &str = "*MYDASH,My dash __ __\nA,.5,-.25\n*MYTEXT,My text --MY--\nA,.5,-.2,[\"MY\",Standard,S=.1,X=-.1,Y=-.05],-.2\n"; fn linetype_pattern(s: &Session, name: &str) -> Option> { s.doc().unwrap().linetype(name).map(|l| l.pattern.iter().map(|e| e.length).collect()) @@ -46,7 +42,8 @@ fn linetype_json_loads_named_linetypes_from_file_text() { #[test] fn linetype_json_reads_a_lin_file_by_path() { - let path = file("mine.lin", LIN); + let dir = TempDir::new("lin-pat"); + let path = dir.file("mine.lin", LIN); let mut s = Session::new(); s.execute("linetype", &json!({ "load": "MYTEXT", "file": path })).unwrap(); assert!(linetype_pattern(&s, "MYTEXT").is_some()); @@ -58,7 +55,8 @@ fn linetype_json_reads_a_lin_file_by_path() { #[test] fn dash_linetype_loads_from_a_file_and_the_library_at_the_command_line() { - let path = file("cmdline.lin", LIN); + let dir = TempDir::new("lin-pat"); + let path = dir.file("cmdline.lin", LIN); let mut s = Session::new(); s.cmdline("-linetype").unwrap(); for line in ["l", "MYDASH,MYTEXT", path.as_str(), "s", "MYTEXT"] { @@ -72,7 +70,7 @@ fn dash_linetype_loads_from_a_file_and_the_library_at_the_command_line() { assert!(s.log.iter().any(|l| l.contains("Linetype MYDASH loaded")), "{:?}", s.log); // Already loaded: asked whether to reload, in the file's order. - let changed = file("changed.lin", &LIN.replace(".5,-.25", "2,-2")); + let changed = dir.file("changed.lin", LIN.replace(".5,-.25", "2,-2")); s.cmdline("-linetype").unwrap(); for line in ["l", "*", changed.as_str()] { s.cmdline(line).unwrap(); @@ -132,7 +130,8 @@ fn hatch_uses_a_pattern_from_a_pat_file_and_keeps_its_definition() { #[test] fn hatch_pattern_prompt_takes_a_pat_file_name() { - let path = file("MYSTAIRS.pat", "*MYOTHER\n0,0,0,0,1\n*MYSTAIRS,Stairs\n0,0,0,.5,.5,.5,-.5\n90,.5,0,.5,.5,.5,-.5\n"); + let dir = TempDir::new("lin-pat"); + let path = dir.file("MYSTAIRS.pat", "*MYOTHER\n0,0,0,0,1\n*MYSTAIRS,Stairs\n0,0,0,.5,.5,.5,-.5\n90,.5,0,.5,.5,.5,-.5\n"); let mut s = Session::new(); s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); s.cmdline("hatch").unwrap(); diff --git a/crates/engine/tests/support/temp_dir.rs b/crates/engine/tests/support/temp_dir.rs new file mode 100644 index 000000000..3b4662e0d --- /dev/null +++ b/crates/engine/tests/support/temp_dir.rs @@ -0,0 +1,46 @@ +//! A test's own folder in the system temp directory, removed when the test ends, even when an +//! assertion fails. Shared by the integration tests (`#[path]`) and the crate's unit tests. +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// `cadcraft---`: the process id keeps parallel test binaries apart and the counter +/// keeps the tests of one binary apart, so no two tests ever share (or delete) one folder. +pub struct TempDir(PathBuf); + +impl TempDir { + pub fn new(tag: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("cadcraft-{tag}-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create the test's temp folder"); + Self(dir) + } + + /// Write `contents` to `name` in the folder; returns the file's path as text. + pub fn file(&self, name: &str, contents: impl AsRef<[u8]>) -> String { + let p = self.0.join(name); + std::fs::write(&p, contents).expect("write a test file"); + p.to_string_lossy().into_owned() + } + + /// The path of `name` in the folder as text, without creating it. + pub fn path_str(&self, name: &str) -> String { + self.0.join(name).to_string_lossy().into_owned() + } +} + +impl std::ops::Deref for TempDir { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} diff --git a/crates/engine/tests/templates.rs b/crates/engine/tests/templates.rs index c518e3b06..cb8636061 100644 --- a/crates/engine/tests/templates.rs +++ b/crates/engine/tests/templates.rs @@ -9,6 +9,11 @@ use cadcraft_engine::cmd::file::{IoHooks, set_io}; use cadcraft_engine::doc::Drawing; use serde_json::json; +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + static FILES: Mutex> = Mutex::new(Vec::new()); fn write(d: &Drawing, name: &str) -> Result, String> { @@ -27,17 +32,11 @@ fn hooks() { set_io(IoHooks { read, write, plot: None }); } -fn path(name: &str) -> String { - let dir = std::env::temp_dir().join(format!("cadcraft-templates-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir.join(name).to_string_lossy().into_owned() -} - /// A drawing with an office layer and a title block circle, saved as a template. -fn office_template(s: &mut Session, name: &str) -> String { +fn office_template(s: &mut Session, dir: &TempDir, name: &str) -> String { s.execute("layer.new", &json!({ "name": "A-WALL", "color": 3 })).unwrap(); s.execute("circle", &json!({ "center": [5, 5], "radius": 2 })).unwrap(); - let p = path(name); + let p = dir.path_str(name); s.execute("saveas", &json!({ "path": p })).unwrap(); p } @@ -46,7 +45,8 @@ fn office_template(s: &mut Session, name: &str) -> String { fn saveas_dwt_then_new_from_the_template() { hooks(); let mut s = Session::new(); - let dwt = office_template(&mut s, "office.dwt"); + let dir = TempDir::new("templates"); + let dwt = office_template(&mut s, &dir, "office.dwt"); // A template is saved like a drawing: the format sees the .dwt name, the drawing is saved. assert!(FILES.lock().unwrap().iter().any(|(n, _)| n.ends_with("office.dwt"))); let st = s.state().unwrap(); @@ -68,7 +68,8 @@ fn saveas_dwt_then_new_from_the_template() { fn qnewtemplate_is_the_default_for_new_and_qnew() { hooks(); let mut s = Session::new(); - let dwt = office_template(&mut s, "default.dwt"); + let dir = TempDir::new("templates"); + let dwt = office_template(&mut s, &dir, "default.dwt"); let docs = s.docs.len(); s.execute("setvar", &json!({ "name": "QNEWTEMPLATE", "value": dwt })).unwrap(); @@ -99,8 +100,8 @@ fn a_template_that_cannot_be_read_makes_no_drawing() { let docs = s.docs.len(); let err = s.execute("new", &json!({ "template": "/no/such/folder/office.dwt" })).unwrap_err().to_string(); assert!(err.contains("office.dwt"), "{err}"); - let junk = path("junk.dwt"); - std::fs::write(&junk, b"not a drawing at all").unwrap(); + let dir = TempDir::new("templates"); + let junk = dir.file("junk.dwt", b"not a drawing at all"); assert!(s.execute("new", &json!({ "template": junk })).is_err()); assert!(s.execute("new", &json!({ "template": 42 })).is_err()); assert_eq!(s.docs.len(), docs); @@ -121,6 +122,7 @@ fn layout_names(d: &Drawing) -> Vec { fn layout_saveas_writes_the_layout_and_the_named_objects_it_uses() { hooks(); let mut s = Session::new(); + let dir = TempDir::new("templates"); for name in ["TITLE", "PARTS-LAYER", "UNUSED", "WALLS", "NOTES"] { s.execute("layer.new", &json!({ "name": name })).unwrap(); } @@ -138,7 +140,7 @@ fn layout_saveas_writes_the_layout_and_the_named_objects_it_uses() { s.execute("layer.current", &json!({ "name": "0" })).unwrap(); let sheet_objects = s.doc().unwrap().layout("Sheet").unwrap().entities.iter().count(); - let p = path("sheet.dwt"); + let p = dir.path_str("sheet.dwt"); let r = s.execute("layout.saveas", &json!({ "path": p })).unwrap(); assert_eq!(r["name"], json!("Sheet"), "the current layout by default"); assert_eq!(r["path"], json!(p)); @@ -175,13 +177,14 @@ fn layout_saveas_writes_the_layout_and_the_named_objects_it_uses() { fn typed_layout_saveas_asks_for_the_layout_and_the_template_file() { hooks(); let mut s = Session::new(); + let dir = TempDir::new("templates"); s.cmdline("LAYOUT").unwrap(); s.cmdline("sa").unwrap(); assert_eq!(s.current_prompt().unwrap().display(), "Enter layout to save to template :"); s.cmdline("Layout2").unwrap(); assert_eq!(s.current_prompt().unwrap().display(), "Enter template file name :"); // No extension: the template is a .dwt. - let p = path("typed"); + let p = dir.path_str("typed"); s.cmdline(&p).unwrap(); assert!(s.current_prompt().is_none()); let saved = format!("{p}.dwt"); @@ -189,11 +192,11 @@ fn typed_layout_saveas_asks_for_the_layout_and_the_template_file() { assert_eq!(layout_names(&written("typed.dwt")), ["Layout2"]); // The JSON form of LAYOUT, other file types, a missing path and an unknown layout. - let dxf = path("sheet1.dxf"); + let dxf = dir.path_str("sheet1.dxf"); let r = s.execute("layout", &json!({ "option": "saveas", "name": "layout1", "path": dxf })).unwrap(); assert_eq!(r["name"], json!("Layout1")); assert_eq!(layout_names(&written("sheet1.dxf")), ["Layout1"]); - assert!(s.execute("layout.saveas", &json!({ "path": path("sheet.png") })).is_err()); + assert!(s.execute("layout.saveas", &json!({ "path": dir.path_str("sheet.png") })).is_err()); assert!(s.execute("layout.saveas", &json!({})).is_err()); - assert!(s.execute("layout.saveas", &json!({ "name": "Nope", "path": path("nope.dwt") })).is_err()); + assert!(s.execute("layout.saveas", &json!({ "name": "Nope", "path": dir.path_str("nope.dwt") })).is_err()); } diff --git a/crates/engine/tests/xref.rs b/crates/engine/tests/xref.rs index d53e37886..c67c627b2 100644 --- a/crates/engine/tests/xref.rs +++ b/crates/engine/tests/xref.rs @@ -2,7 +2,7 @@ //! loading with `xref|name` symbols, saving only the reference, reopening, Reload/Unload/Detach/ //! Path, Bind and XBIND, overlays, missing files, circular and deeply nested references. -use std::path::{Path, PathBuf}; +use std::path::Path; use std::sync::Arc; use cadcraft_engine::Session; @@ -12,6 +12,11 @@ use cadcraft_engine::doc::geom::Vec3; use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, Insert, Layer, Line, Linetype, MAX_BLOCK_DEPTH, XrefStatus}; use serde_json::json; +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + fn hooks() { set_io(IoHooks { read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), @@ -20,12 +25,9 @@ fn hooks() { }); } -/// A fresh folder for one test. -fn folder(tag: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("cadcraft-xref-{}-{tag}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir +/// A fresh folder for one test, removed when the test ends. +fn folder(tag: &str) -> TempDir { + TempDir::new(&format!("xref-{tag}")) } fn save(d: &Drawing, path: &Path) { diff --git a/crates/ui-egui/src/capture/tests.rs b/crates/ui-egui/src/capture/tests.rs index 6e70aea7b..b85961c44 100644 --- a/crates/ui-egui/src/capture/tests.rs +++ b/crates/ui-egui/src/capture/tests.rs @@ -168,6 +168,7 @@ fn focus_change_cancels_an_unissued_capture() { /// Two requests issue from one settled frame; each reply carries its own token and a distinct, readable file with a PNG signature. #[test] fn issued_callbacks_reply_once_with_matching_tokens_and_distinct_pathless_files() { + let _shots = crate::control::lock_pathless_shots(); let ctx = egui::Context::default(); let mut app = app(); set_geometry(&mut app, &ctx, egui::vec2(800.0, 600.0)); @@ -190,7 +191,6 @@ fn issued_callbacks_reply_once_with_matching_tokens_and_distinct_pathless_files( assert_ne!(a, b, "one file per request"); for path in [&a, &b] { assert!(std::fs::read(path).is_ok_and(|bytes| bytes.starts_with(b"\x89PNG\r\n\x1a\n")), "{path}"); - let _ = std::fs::remove_file(path); } assert!(app.shots.is_empty()); } @@ -342,6 +342,7 @@ fn raw_geometry_uses_screen_rect_when_inner_rect_is_absent() { /// not issue, and the settled second pass must issue exactly once. #[test] fn a_discarded_pass_does_not_issue_and_the_settled_pass_does_once() { + let _shots = crate::control::lock_pathless_shots(); let ctx = egui::Context::default(); let mut app = app(); let (rx, _) = admit_one(&mut app, &ctx); @@ -365,13 +366,15 @@ fn a_discarded_pass_does_not_issue_and_the_settled_pass_does_once() { assert_eq!(app.ui_frames, 1, "one settled frame, not one per pass"); complete(callbacks, [800, 600]); drain(&mut app, &ctx); - assert_eq!(rx.recv().expect("a reply")["ok"], true); + let reply = rx.recv().expect("a reply"); + assert_eq!(reply["ok"], true, "{reply}"); } /// Issuance re-bases the expected image on the settled pass, so the saved interface zoom /// (applied by egui at the start of a later pass) cannot leave a stale admission estimate. #[test] fn issuance_uses_the_settled_interface_scale_not_the_admission_estimate() { + let _shots = crate::control::lock_pathless_shots(); let ctx = egui::Context::default(); let mut app = app(); app.options.interface_scale = 2.0; @@ -387,8 +390,6 @@ fn issuance_uses_the_settled_interface_scale_not_the_admission_estimate() { drain(&mut app, &ctx); let reply = rx.recv().expect("a reply"); assert_eq!(reply["ok"], true, "{reply}"); - let path = reply["result"]["path"].as_str().expect("a file").to_string(); - let _ = std::fs::remove_file(path); } /// A→B→A: a switch that returns to the same drawing still invalidates the queued request. @@ -447,6 +448,7 @@ fn a_settled_window_does_not_keep_changing_the_surface_epoch() { /// A window resized while the request is still settling is issued against the new size. #[test] fn a_resize_while_settling_is_absorbed_at_issue() { + let _shots = crate::control::lock_pathless_shots(); let ctx = egui::Context::default(); let mut app = app(); let (rx, _) = admit_one(&mut app, &ctx); @@ -464,6 +466,4 @@ fn a_resize_while_settling_is_absorbed_at_issue() { drain(&mut app, &ctx); let reply = rx.recv().expect("a reply"); assert_eq!(reply["ok"], true, "{reply}"); - let path = reply["result"]["path"].as_str().expect("a file").to_string(); - let _ = std::fs::remove_file(path); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 2dc1f898a..7330681db 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -619,6 +619,35 @@ fn is_private_shot_dir(meta: &std::fs::Metadata) -> bool { } } +/// Pathless screenshots share one directory per process. Tests that write them hold this guard, +/// so no other test writes while it is cleaned up. Dropping it, even while a failed test unwinds, +/// removes every screenshot file in the directory and then the directory itself. +#[cfg(test)] +pub(crate) struct PathlessShots { + _lock: std::sync::MutexGuard<'static, ()>, +} + +#[cfg(test)] +pub(crate) fn lock_pathless_shots() -> PathlessShots { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + PathlessShots { _lock: LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } +} + +#[cfg(test)] +impl Drop for PathlessShots { + fn drop(&mut self) { + let Ok(dir) = private_shot_dir() else { return }; + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten() { + if entry.file_name().to_string_lossy().starts_with("cadcraft-shot-") { + let _ = std::fs::remove_file(entry.path()); + } + } + } + let _ = std::fs::remove_dir(&dir); + } +} + /// Save a pathless screenshot into the private per-process directory: re-validate or recreate it as an owner-only real directory (0700 on Unix; plain create elsewhere), then create up to 64 exclusive files (0600 on Unix) and write a PNG. fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Result { use std::io::Write as _; @@ -641,8 +670,13 @@ fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Resu let path = dir.join(format!("cadcraft-shot-{token}-{}.png", next_pathless_nonce())); match create_private_file(&path) { Ok(mut file) => { - img.write_to(&mut file, image::ImageFormat::Png).map_err(std::io::Error::other)?; - file.flush()?; + let written = img.write_to(&mut file, image::ImageFormat::Png).map_err(std::io::Error::other).and_then(|()| file.flush()); + if let Err(e) = written { + // The reply carries no path on failure, so nobody else could remove the partial file. + drop(file); + let _ = std::fs::remove_file(&path); + return Err(e); + } return Ok(path); } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, @@ -735,6 +769,7 @@ mod tests { /// Two pathless saves with the same token produce distinct, decodable PNGs; on Unix the files are 0600 and their directory 0700. #[test] fn pathless_screenshots_are_unique_private_png_files() { + let _shots = lock_pathless_shots(); let img = egui::ColorImage::filled([4, 3], egui::Color32::RED); let first = save_screenshot(&img, None, 1); let second = save_screenshot(&img, None, 1); @@ -759,9 +794,6 @@ mod tests { let dir_mode = std::fs::metadata(dir).expect("directory metadata").permissions().mode() & 0o777; assert_eq!(dir_mode, 0o700, "the screenshot directory is owner-only"); } - for path in [&a, &b] { - let _ = std::fs::remove_file(path); - } } /// `create_new` refuses a pre-existing symlink with `AlreadyExists` and leaves the link target unchanged. diff --git a/crates/ui-egui/tests/recent_files.rs b/crates/ui-egui/tests/recent_files.rs index 946a6792a..34d460255 100644 --- a/crates/ui-egui/tests/recent_files.rs +++ b/crates/ui-egui/tests/recent_files.rs @@ -9,17 +9,18 @@ use cadcraft_ui_egui::{CadApp, Services}; use egui::{Rect, Shape, vec2}; use egui_kittest::Harness; -/// Two drawing files on disk (the reader below accepts anything, so their contents don't matter). -fn drawings(test: &str) -> (String, String) { +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +/// Two drawing files on disk (the reader below accepts anything, so their contents don't matter), +/// in a folder that is removed when the returned guard is dropped. +fn drawings(test: &str) -> (TempDir, String, String) { set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(Vec::new()), plot: None }); - let dir = std::env::temp_dir().join(format!("cadcraft-recent-{test}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = |name: &str| { - let p = dir.join(name); - std::fs::write(&p, b"0\nEOF\n").unwrap(); - p.to_string_lossy().to_string() - }; - (path("plan.dxf"), path("section.dwg")) + let dir = TempDir::new(&format!("recent-{test}")); + let (plan, section) = (dir.file("plan.dxf", b"0\nEOF\n"), dir.file("section.dwg", b"0\nEOF\n")); + (dir, plan, section) } /// Wait for the drawings being read in the background to be added (or reported). @@ -49,7 +50,7 @@ fn open_recent(app: &CadApp) -> Vec<(String, String)> { #[test] fn opened_drawings_are_listed_newest_first_and_survive_a_restart() { - let (plan, section) = drawings("menu"); + let (_dir, plan, section) = drawings("menu"); let mut app = CadApp::new(Session::empty(), Services::default()); assert!(app.ui.recent_files.is_empty()); @@ -99,7 +100,7 @@ fn texts(shape: &Shape, out: &mut Vec<(String, Rect)>) { #[test] fn start_page_lists_recent_files_and_opens_one_on_click() { - let (plan, section) = drawings("start"); + let (_dir, plan, section) = drawings("start"); let mut app = CadApp::new(Session::empty(), Services::default()); app.ui.recent_files = vec![section.clone(), plan.clone()]; let mut h = Harness::builder().with_size(vec2(1200.0, 760.0)).build_ui_state( diff --git a/crates/ui-egui/tests/support/temp_dir.rs b/crates/ui-egui/tests/support/temp_dir.rs new file mode 100644 index 000000000..e1f16b8c1 --- /dev/null +++ b/crates/ui-egui/tests/support/temp_dir.rs @@ -0,0 +1,46 @@ +//! A test's own folder in the system temp directory, removed when the test ends, even when an +//! assertion fails. Shared by the integration tests through `#[path]`. +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// `cadcraft---`: the process id keeps parallel test binaries apart and the counter +/// keeps the tests of one binary apart, so no two tests ever share (or delete) one folder. +pub struct TempDir(PathBuf); + +impl TempDir { + pub fn new(tag: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("cadcraft-{tag}-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create the test's temp folder"); + Self(dir) + } + + /// Write `contents` to `name` in the folder; returns the file's path as text. + pub fn file(&self, name: &str, contents: impl AsRef<[u8]>) -> String { + let p = self.0.join(name); + std::fs::write(&p, contents).expect("write a test file"); + p.to_string_lossy().into_owned() + } + + /// The path of `name` in the folder as text, without creating it. + pub fn path_str(&self, name: &str) -> String { + self.0.join(name).to_string_lossy().into_owned() + } +} + +impl std::ops::Deref for TempDir { + type Target = Path; + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} diff --git a/crates/ui-egui/tests/xref_palette.rs b/crates/ui-egui/tests/xref_palette.rs index 2f242b277..f950427c4 100644 --- a/crates/ui-egui/tests/xref_palette.rs +++ b/crates/ui-egui/tests/xref_palette.rs @@ -11,6 +11,11 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + /// Test drawings: any file holds one line on layer Walls. fn read(_bytes: &[u8], _name: &str) -> Result { let mut d = Drawing::new_metric(); @@ -21,14 +26,6 @@ fn read(_bytes: &[u8], _name: &str) -> Result { Ok(d) } -fn site_file() -> String { - let dir = std::env::temp_dir().join(format!("cadcraft-xref-palette-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let p = dir.join("site.dxf"); - std::fs::write(&p, "site").unwrap(); - p.to_string_lossy().into_owned() -} - fn status(app: &CadApp) -> Option { app.session.doc().ok()?.block("site").map(|b| b.xref_status) } @@ -37,7 +34,8 @@ fn status(app: &CadApp) -> Option { fn xref_opens_the_palette_and_its_buttons_manage_the_xref() { set_io(IoHooks { read, write: |_, _| Err("no writer in this test".into()), plot: None }); let mut app = CadApp::new(Session::default(), Services::default()); - app.run("xattach", json!({ "path": site_file(), "at": [10, 10] })).unwrap(); + let dir = TempDir::new("xref-palette"); + app.run("xattach", json!({ "path": dir.file("site.dxf", "site"), "at": [10, 10] })).unwrap(); assert_eq!(status(&app), Some(XrefStatus::Loaded)); // Typed (by its alias) it opens the palette instead of listing. assert!(app.cmdline("XR").is_none()); From b9b7b3d439d0ff889475116a1a145b3f2e65f9c8 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:21:58 +0100 Subject: [PATCH 185/900] Refuse invalid count in JSON copy instead of clamping it (#2294) Found while testing crates/engine/src/cmd/modify/transform.rs:69 (run_copy) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd/modify/transform.rs | 5 ++++- crates/engine/tests/it/copy_count.rs | 24 +++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 crates/engine/tests/it/copy_count.rs diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 5474dde16..5a86d9e07 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -66,7 +66,10 @@ pub(super) fn run_move(s: &mut Session, p: &Value) -> Result { pub(super) fn run_copy(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let d = delta_of("copy", p)?; - let n = p.get("count").and_then(Value::as_u64).unwrap_or(1).clamp(1, 10_000); + let n = match p.get("count") { + None => 1, + Some(v) => v.as_u64().filter(|n| (1..=10_000).contains(n)).ok_or_else(|| bad("copy", "`count` must be an integer from 1 to 10000"))?, + }; let mut out = Vec::new(); for k in 1..=n { out.extend(transform_entities(s, &hs, &Mat3::translate(d * k as f64), true)?.into_iter().map(|h| h.hex())); diff --git a/crates/engine/tests/it/copy_count.rs b/crates/engine/tests/it/copy_count.rs new file mode 100644 index 000000000..64deab8f0 --- /dev/null +++ b/crates/engine/tests/it/copy_count.rs @@ -0,0 +1,24 @@ +//! JSON COPY refuses a `count` that is not an integer from 1 to 10000 instead of clamping it. + +use cadcraft_engine::Session; +use serde_json::{Value, json}; + +fn entities(s: &Session) -> usize { + s.doc().map(|d| d.model.iter().count()).unwrap_or(0) +} + +#[test] +fn invalid_copy_count_is_refused() { + let mut s = Session::new(); + let r = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let h = r["handles"][0].clone(); + let before = entities(&s); + let bad: [Value; 7] = [json!(0), json!(-3), json!(2.5), json!("abc"), json!(null), json!(10001), json!(50000)]; + for c in bad { + let r = s.execute("copy", &json!({"handles": [h], "delta": [0, 5], "count": c})); + assert!(r.is_err(), "count {c} should be refused"); + assert_eq!(entities(&s), before, "count {c} changed the drawing"); + } + s.execute("copy", &json!({"handles": [h], "delta": [0, 5], "count": 3})).unwrap(); + assert_eq!(entities(&s), before + 3); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 4a2a829a7..51cec4590 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -21,6 +21,7 @@ mod burst; mod compare_export; mod constraint_geometry; mod constraint_infer; +mod copy_count; mod count; mod dash_block; mod data_extraction; From 303bc97f9aa9dfb541548ba99f2a1cadf09f3d34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20Mittelst=C3=A4dt?= <62167861+TheGalitube@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:22:01 +0100 Subject: [PATCH 186/900] Count DXF group codes correctly when enforcing limits (#2408) Found while testing crates/dxf/src/lib.rs:185 Co-authored-by: GPT-6-Luna --- crates/dxf/src/lib.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 4e888bdc0..b9e394766 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -181,8 +181,20 @@ 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); + // Count nonblank group-code/value pairs, stopping at EOF just as the parser does. + let mut lines = bytes.split(|&b| b == b'\n'); + let mut tags = 0; + while let Some(code) = lines.next() { + let code = code.trim_ascii(); + if code.is_empty() { + continue; + } + let Some(value) = lines.next() else { break }; + tags += 1; + if code == b"0" && value.trim_ascii() == b"EOF" { + break; + } + } if tags > max_tags { return Err(DxfError::TooLarge { tags, limit: max_tags }); } @@ -581,6 +593,12 @@ mod tests { } } + #[test] + fn blank_lines_do_not_consume_group_code_limit() { + let tags = parse_with_limit(b"0\nEOF\n\n\n", 1).expect("one group code should fit a limit of one"); + assert_eq!(tags, vec![Tag::s(0, "EOF")]); + } + #[test] fn ascii_roundtrip() { let tags = vec![ From 1013b482a81067f7d9f6e1e4247070ba99b8b37b Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 12:26:09 +1100 Subject: [PATCH 187/900] DXF: SAT-text note only for DXF output, from the host drawing, without xref contents (#2334) The DWG bridge writes R2000 text for the DWG writer, which keeps SAT-text solids: the skip is now keyed on the DXF's declared version, not the DWG target. The save note reads the version and count from the host drawing while the Block Editor is open, and leaves out xref blocks (path or xref| name), which the DXF writer empties anyway; the xref name rule is shared with the writer. --- crates/doc/src/foreign.rs | 10 ++++++- crates/engine/src/cmd/file.rs | 10 ++++--- crates/engine/tests/save_reports_not_saved.rs | 27 +++++++++++++++++++ crates/io/src/dxf_write/sections.rs | 4 ++- crates/io/src/dxf_xref.rs | 2 +- crates/io/tests/it/acis_data_store.rs | 27 +++++++++++++++++++ 6 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 3b6aa8ef9..60000c6dd 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -109,7 +109,9 @@ pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collectio pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap { let stored = d.foreign.data_store_entities(); let mut out = BTreeMap::new(); - let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)); + // The writer saves xrefs as references: their blocks (and `xref|` ones) hold nothing in the file. + let own_blocks = d.blocks.values().filter(|b| b.xref_path.is_none() && !xref_dependent(&b.name)); + let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(own_blocks.map(|b| &b.entities)); for e in stores.flat_map(|s| s.iter()) { if let crate::EntityKind::Unknown(u) = &e.kind && sat_text_acis(u, e.handle, &stored) @@ -120,3 +122,9 @@ pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap { } out } + +/// Whether a symbol name belongs to an attached xref (`xref|name`): the DXF writer leaves such +/// symbols out, and the contents of xref blocks too ([`Block::xref_path`](crate::Block::xref_path)). +pub fn xref_dependent(name: &str) -> bool { + name.contains('|') +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 5b012bb4e..5d89a196e 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -490,8 +490,11 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result { /// The version a drawing is saved in at `path` when none is asked for: its `$ACADVER` (2018 by /// default), and for DWG at least 2004 (the io layer's rule: R2000 DWG has no true colours). fn drawing_version(s: &Session, path: &str) -> Version { - let v = - s.doc().ok().and_then(|d| d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)).unwrap_or_default(); + let v = s + .state() + .ok() + .and_then(|st| st.drawing().header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).and_then(Version::for_acadver)) + .unwrap_or_default(); if is_dxf(path) { v } else { v.max(Version::R2004) } } @@ -585,7 +588,8 @@ fn is_dxf_file(path: impl AsRef) -> bool { /// Say on the command line which solid modeler entities a DXF of 2013 or later left out because /// they hold SAT-text ACIS data, which such files keep in a data store instead (#2334). fn report_sat_text_dropped(s: &mut Session, r: &mut Value) { - let lost = s.doc().map(cadcraft_doc::foreign::sat_text_dropped).unwrap_or_default(); + // The drawing a file holds: the host while the Block Editor is open. + let lost = s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default(); if lost.is_empty() { return; } diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index f231f8ace..839c2489b 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -112,3 +112,30 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() { let _ = std::fs::remove_file(&path); assert!(r.get("notSaved").is_none() && s.log.len() == n); } + +/// In the Block Editor the file still holds the host drawing: its solids and version decide the +/// note, not the edited block's (#2334). +#[test] +fn the_note_counts_the_host_drawing_while_a_block_is_edited() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + set_write_as(|_, _, _: &SaveAs| Ok(b"x".to_vec())); + let mut d = Drawing::new_imperial(); + let sat = EntityKind::Unknown(Unknown { + dxf_type: "REGION".into(), + tags: vec![ + RawTag { code: 8, value: "0".into() }, + RawTag { code: 1, value: "400 1 1 0".into() }, + RawTag { code: 3, value: "End-of-ACIS-data".into() }, + ], + }); + d.add(&Space::Model, Common::default(), sat).unwrap(); + d.blocks.insert("Door".into(), std::sync::Arc::new(Block::new("Door"))); + let mut s = Session::empty(); + s.open_drawing(d, "region.dxf", None); + s.execute("bedit", &json!({ "name": "Door" })).unwrap(); + + let path = std::env::temp_dir().join(format!("cadcraft-sat-edit-{}.dxf", std::process::id())); + let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2018 })).unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(r["notSaved"], json!({ "REGION": 1 })); +} diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 90214b401..815f4eb32 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1115,7 +1115,9 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec= Version::R2013); + // Only a DXF declares the version it is written for: the DWG bridge writes R2000 text for the + // DWG writer, which keeps SAT-text solids (#2334). + crate::dxf_raw::finish(&mut w.t, d, version >= Version::R2013); crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013); add_class_instance_counts(&mut w.t); mark_xrefs(&mut w.t, d); diff --git a/crates/io/src/dxf_xref.rs b/crates/io/src/dxf_xref.rs index f98a044f7..9ea7904cd 100644 --- a/crates/io/src/dxf_xref.rs +++ b/crates/io/src/dxf_xref.rs @@ -13,7 +13,7 @@ use cadcraft_doc::Drawing; /// Whether a symbol name belongs to an attached xref (`xref|name`). pub(crate) fn dependent(name: &str) -> bool { - name.contains('|') + cadcraft_doc::foreign::xref_dependent(name) } /// The drawing as it is saved: xref blocks emptied, xref-dependent symbols other than layers and diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index 36c947892..308b532d9 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -129,3 +129,30 @@ fn sat_text_solids_are_left_out_of_dxf_2013_and_later() { let stored = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap(); assert!(cadcraft_doc::foreign::sat_text_dropped(&stored).is_empty()); } + +/// A DWG keeps SAT-text solids at any version (its writer handles them), and a DXF's note leaves +/// out the contents of xref blocks, which the DXF doesn't hold anyway (#2334). +#[test] +fn sat_text_solids_stay_in_dwg_2018_and_xref_contents_are_not_counted() { + let sat = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n\ + 0\nREGION\n5\n2B\n100\nAcDbEntity\n8\n0\n100\nAcDbModelerGeometry\n70\n1\n1\n400 1 1 0\n3\nEnd-of-ACIS-data\n\ + 0\nLINE\n5\n2D\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nENDSEC\n0\nEOF\n"; + let d = cadcraft_io::read_dxf(sat.as_bytes()).unwrap(); + let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2018), binary: false }; + let dwg = cadcraft_io::write_with(&d, "x.dwg", &opts).unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + let unknown = |d: &cadcraft_doc::Drawing| d.model.iter().filter(|e| matches!(&e.kind, EntityKind::Unknown(u) if u.dxf_type == "REGION")).count(); + assert_eq!(unknown(&back), 1, "the DWG 2018 keeps the region"); + + // Xref blocks (and `xref|` ones) hold no entities in the file: not reported as left out. + let mut x = d.clone(); + let region = d.model.iter().find(|e| matches!(&e.kind, EntityKind::Unknown(_))).cloned().unwrap(); + let mut host = cadcraft_doc::Block::new("REF"); + host.xref_path = Some("other.dwg".into()); + host.entities.push((*region).clone()); + x.blocks.insert("REF".into(), std::sync::Arc::new(host)); + let mut dep = cadcraft_doc::Block::new("REF|PART"); + dep.entities.push((*region).clone()); + x.blocks.insert("REF|PART".into(), std::sync::Arc::new(dep)); + assert_eq!(cadcraft_doc::foreign::sat_text_dropped(&x), [("REGION".to_string(), 1)].into(), "only the model-space region"); +} From 3243271d4eea800a02cf532b202d833429dc631c Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:31:09 +0100 Subject: [PATCH 188/900] Reject zero distance in JSON offset command (#2190) Found while testing crates/engine/src/cmd/modify.rs:791 (run_offset) Co-authored-by: Claude Haiku 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/modify/offset.rs | 3 +++ crates/engine/src/tests.rs | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/crates/engine/src/cmd/modify/offset.rs b/crates/engine/src/cmd/modify/offset.rs index 01ca46c04..20e6ba58e 100644 --- a/crates/engine/src/cmd/modify/offset.rs +++ b/crates/engine/src/cmd/modify/offset.rs @@ -197,6 +197,9 @@ fn join_point(a: &Segment, b: &Segment) -> Option { pub(super) fn run_offset(s: &mut Session, p: &Value) -> Result { let h = targets(s, p)?.first().copied().ok_or_else(|| bad("offset", "`handle` is required"))?; let dist = f64_req("offset", p, "distance")?; + if dist == 0.0 { + return Err(bad("offset", "Requires a positive distance.")); + } let side = point_req("offset", p, "side")?; let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| bad("offset", "no such object"))?; let k = offset_kind(&e.kind, dist.abs(), side).ok_or_else(|| bad("offset", "cannot offset that object"))?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b06641fbb..be6246824 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -344,6 +344,15 @@ fn fillet_two_lines() { assert!(g.iter().any(|p| p.near(Vec2::new(2.0, 0.0), 1e-9))); } +#[test] +fn offset_zero_distance_is_rejected() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let r = s.execute("offset", &json!({"handle": "100", "distance": 0, "side": [1, 1]})); + assert!(r.is_err(), "offset distance 0 made a coincident copy: {r:?}"); + assert_eq!(s.doc().unwrap().model.len(), 1); +} + #[test] fn offset_circle_and_polyline() { let mut s = Session::new(); From 0d9e62bc9aa55356f65310417fd80602f2b4db7e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:31:13 +0100 Subject: [PATCH 189/900] Stop DIMTMOVE 2 text taking the DIMTAD 1 clearance twice (#2302) Fixes #2222 Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/render/src/dim/linear.rs | 16 ++++++++++------ crates/render/src/dim/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/render/src/dim/linear.rs b/crates/render/src/dim/linear.rs index 40b684832..8127aef8f 100644 --- a/crates/render/src/dim/linear.rs +++ b/crates/render/src/dim/linear.rs @@ -150,11 +150,13 @@ fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { }; state.side_out = if (config.dimension.defpt.xy() - state.p1).dot(state.n) >= 0.0 { state.n } else { -state.n }; state.text_axis = Vec2::from_angle(state.angle); - let off_along = |axis: Vec2| { - let glyph_extent = state.text_width * state.text_axis.dot(axis).abs() / 2.0 - + state.text_height * state.text_axis.perp().dot(axis).abs() * if st.text_above == 1 { 0.6 } else { 0.5 }; - config.gap + glyph_extent + let clearance = |axis: Vec2, across: f64| { + config.gap + + state.text_width * state.text_axis.dot(axis).abs() / 2.0 + + state.text_height * state.text_axis.perp().dot(axis).abs() * across }; + // Empirical #2004 match: 0.595× height with SHX and 0.601× with TrueType. + let off_along = |axis: Vec2| clearance(axis, if st.text_above == 1 { 0.6 } else { 0.5 }); let above = if state.angle.abs() < 1e-12 && state.n.y.abs() > 1e-9 { if state.n.y > 0.0 { state.n } else { -state.n } } else if state.angle.abs() < 1e-12 { @@ -181,11 +183,13 @@ fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { + outward * (config.gap + state.text_height / 2.0); } else if state.moved { let mid = state.f1.mid(state.f2); - let lift = off_along(state.side_out) + 2.0 * config.arrow_size.max(config.tick_size); + // Half the text height either way, whatever DIMTAD says (#2222). + let clear = clearance(state.side_out, 0.5); + let lift = clear + 2.0 * config.arrow_size.max(config.tick_size); state.text_mid = if st.text_move == 1 { mid + state.side_out * lift + state.u * state.half_extent } else { - mid + state.side_out * (lift + off_along(state.side_out)) + mid + state.side_out * (lift + clear) }; } else if !config.dimension.user_text_pos { state.text_mid = state.along_center + state.offset; diff --git a/crates/render/src/dim/tests.rs b/crates/render/src/dim/tests.rs index fd439097c..fe3b3c74e 100644 --- a/crates/render/src/dim/tests.rs +++ b/crates/render/src/dim/tests.rs @@ -233,6 +233,29 @@ fn text_that_does_not_fit_follows_dimtmove_2() { assert!(g.lines_of(LineRole::Dim).flatten().all(|p| p.x <= 0.5 + 1e-9 && p.y >= 5.0 - 1e-9), "no leader, no line out to the text"); } +#[test] +fn dimtmove_2_text_clearance_matches_autocad() { + // #2222: the 0.10 dimension of #1998 in the #2004 1:50 style. AutoCAD 2026 recomputes the + // moved text at about 0.358 from the dimension line (0.658214, 0.05). + let st = st_with(|s| { + s.scale = 50.0; + s.text_height = 0.0025; + s.text_gap = 0.0008; + s.arrow_size = 0.0015; + s.text_above = 1; + s.text_inside_horizontal = false; + s.text_outside_horizontal = false; + s.decimals = 2; + s.text_move = 2; + }); + let d = lin((0.0, 0.0), (0.0, 0.10), (0.30, 0.0), std::f64::consts::FRAC_PI_2); + let g = dimension_geometry(&d, &st, 50.0); + assert!(g.text_pos.dist(Vec2::new(0.658214, 0.05)) < 0.005, "vertical: {:?}", g.text_pos); + let d = lin((0.0, 0.0), (0.10, 0.0), (0.0, -0.30), 0.0); + let g = dimension_geometry(&d, &st, 50.0); + assert!(g.text_pos.dist(Vec2::new(0.05, -0.658214)) < 0.005, "horizontal: {:?}", g.text_pos); +} + #[test] fn text_that_does_not_fit_follows_dimtmove_1() { // Moved off the line with a leader from the middle of the dimension line. From dcbcb6ab32fc13a043a58d3e0d020029b7aa7d17 Mon Sep 17 00:00:00 2001 From: Jonas <80707953+jonascloud@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:31:17 +0100 Subject: [PATCH 190/900] fix: keep WIPEOUT closure coherent across grips and outlines (#2284) * fix: keep WIPEOUT closure coherent across grips and outlines Treat WIPEOUT as a closed polygon with an optional exact terminal closure marker, not as an open polyline. Centralize logical vertices, explicit outlines and closure-preserving vertex edits in the document type. Reuse this contract in grips, geometric primitives, rendering and DXF export without changing the stored schema or writer closure convention. Add six-version DXF ASCII/binary and DWG regressions for implicit/explicit closure, both windings, all corners, API/interactive edits, undo/redo and repeated saves. Keep open/closed polylines and their coincident endpoints distinct. Cover multiple hot grips, hostile inputs and equivalent mask/frame output. Validation: cargo xtask ci, all seven stages passed (2571 tests passed, one pre-existing skip). Two unrelated network tests failed transiently in earlier runs; each passed in isolation and the complete final run passed without exclusions. Direct and reopened grip edits produce byte-identical CLI PNG output. Fixes #2256; related test-only matrix PR #2237 and tracker #2238 B3. * fix(doc): keep coincident WIPEOUT endpoints separately editable When an edit makes the endpoints of an implicit boundary coincide, add a separate closing marker rather than reclassifying the edited corner as that marker. Retain the logical vertex count and allow either coincident corner to move independently afterwards. The document regression fails before the fix. Add API/interactive coverage for both endpoint directions and both closure forms, undo/redo, and subsequent separate edits across all six DXF/DWG versions including binary DXF and save-after-edit. Update the documented editing contract. Validation: cargo xtask ci passed all seven stages; 2573 tests passed, one pre-existing skip. Addresses the coincident-endpoint review on PR #2284; related #2256. --------- Co-authored-by: cloudj Co-authored-by: Brandon Thomas --- crates/doc/src/entity.rs | 12 +- crates/doc/src/entity/fill.rs | 5 - crates/doc/src/entity/wipeout.rs | 162 +++++++++++++++++ crates/engine/src/grips.rs | 2 +- crates/engine/src/grips/tests.rs | 15 ++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/wipeout_grips.rs | 227 ++++++++++++++++++++++++ crates/io/src/dxf_write/entity.rs | 9 +- crates/render/src/draw.rs | 6 +- crates/render/tests/it/wipeout_mask.rs | 37 ++++ docs/file-format-parity.md | 2 +- docs/ui-parity.md | 5 +- 12 files changed, 455 insertions(+), 28 deletions(-) create mode 100644 crates/doc/src/entity/wipeout.rs create mode 100644 crates/engine/tests/it/wipeout_grips.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 089904109..d13b82722 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -44,14 +44,16 @@ mod dim; mod fill; mod layout; mod text; +mod wipeout; pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal}; pub use common::{Common, Handle, Lineweight, RawTag, Transparency}; pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyline3d, RayLine, Solid}; pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader}; -pub use fill::{Gradient, Hatch, HatchLoop, Wipeout}; +pub use fill::{Gradient, Hatch, HatchLoop}; pub use layout::{Image, Table, TableCell, Viewport}; pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign}; +pub use wipeout::Wipeout; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Unknown { pub dxf_type: String, @@ -226,11 +228,7 @@ impl EntityKind { h.loops.iter().flat_map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.segments()).map(Prim::Seg).collect() } EntityKind::Wipeout(w) => { - let mut pts = w.boundary.clone(); - if let Some(f) = pts.first().copied() { - pts.push(f); - } - pts.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect() + w.closed_boundary().windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect() } EntityKind::Viewport(v) => { let c = v.center.xy(); @@ -535,7 +533,7 @@ impl EntityKind { Bounds2::new(c - h, c + h).corners().to_vec() } EntityKind::Image(i) => vec![i.insert.xy()], - EntityKind::Wipeout(w) => w.boundary.clone(), + EntityKind::Wipeout(w) => w.vertices().to_vec(), EntityKind::Table(t) => vec![t.insert.xy()], EntityKind::Tolerance(t) => vec![t.insert.xy()], EntityKind::Unknown(_) => Vec::new(), diff --git a/crates/doc/src/entity/fill.rs b/crates/doc/src/entity/fill.rs index 6790b0a7c..cff172a71 100644 --- a/crates/doc/src/entity/fill.rs +++ b/crates/doc/src/entity/fill.rs @@ -54,8 +54,3 @@ pub struct Gradient { #[serde(default)] pub centered: bool, } - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Wipeout { - pub boundary: Vec, -} diff --git a/crates/doc/src/entity/wipeout.rs b/crates/doc/src/entity/wipeout.rs new file mode 100644 index 000000000..c79e93275 --- /dev/null +++ b/crates/doc/src/entity/wipeout.rs @@ -0,0 +1,162 @@ +//! WIPEOUT is always a closed masking polygon, unlike a polyline with an open/closed flag. +//! One exact terminal copy of the first point is a closure marker, not an editable corner. +//! Preserve logical corners when editing, adding a separate marker if the endpoints meet. +//! Grips, edits and explicit outlines share this rule; other duplicates are not simplified. + +use std::borrow::Cow; + +use cadcraft_geom::Vec2; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Wipeout { + /// Ordered boundary, implicitly closed or ending in a repeated first point. + pub boundary: Vec, +} + +impl Wipeout { + /// Editable vertices, excluding one exactly repeated closing point, without changing storage. + pub fn vertices(&self) -> &[Vec2] { + match self.boundary.split_last() { + Some((last, vertices)) if vertices.first() == Some(last) => vertices, + _ => &self.boundary, + } + } + + /// An explicitly closed outline for geometry, rendering and export. Already closed or + /// empty/single-point boundaries are borrowed; otherwise one closing point is appended. + pub fn closed_boundary(&self) -> Cow<'_, [Vec2]> { + if self.vertices().len() < self.boundary.len() || self.boundary.len() < 2 { + Cow::Borrowed(&self.boundary) + } else { + let mut points = self.boundary.clone(); + points.extend(self.boundary.first()); + Cow::Owned(points) + } + } + + /// Move an editable vertex, carrying an existing closing marker with vertex zero. If an + /// implicit boundary's endpoints meet, add a marker so both corners remain addressable. + /// Invalid indices/non-finite points leave the boundary unchanged. + pub fn set_vertex(&mut self, index: usize, to: Vec2) -> Option<()> { + let count = self.vertices().len(); + if index >= count || !to.is_finite() { + return None; + } + let explicit = count < self.boundary.len(); + *self.boundary.get_mut(index)? = to; + if explicit + && index == 0 + && let Some(last) = self.boundary.last_mut() + { + *last = to; + } + if !explicit && self.vertices().len() < count { + // The moved endpoint is a logical corner, not the newly implied closing marker. + if let Some(first) = self.boundary.first().copied() { + self.boundary.push(first); + } + } + Some(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::EntityKind; + + #[test] + fn vertices_and_grips_exclude_only_the_exact_closing_point() { + let (a, b, c) = (Vec2::ZERO, Vec2::new(7.0, 1.0), Vec2::new(3.0, 7.0)); + let near_a = Vec2::new(1e-13, 0.0); + for (boundary, expected) in [ + (vec![], vec![]), + (vec![a], vec![a]), + (vec![a, a], vec![a]), + (vec![a, b, c], vec![a, b, c]), + (vec![a, b, c, a], vec![a, b, c]), + (vec![a, b, a, c, a], vec![a, b, a, c]), + (vec![a, b, c, a, a], vec![a, b, c, a]), + (vec![a, b, c, near_a], vec![a, b, c, near_a]), + ] { + let wipeout = Wipeout { boundary: boundary.clone() }; + assert_eq!(wipeout.vertices(), expected); + assert_eq!(EntityKind::Wipeout(wipeout.clone()).grips(), expected); + assert_eq!(wipeout.boundary, boundary); + } + } + + #[test] + fn explicit_outline_is_stable_and_does_not_add_zero_length_closing_edges() { + let points = vec![Vec2::ZERO, Vec2::new(7.0, 1.0), Vec2::new(3.0, 7.0)]; + let implicit = Wipeout { boundary: points.clone() }; + let mut expected = points.clone(); + expected.push(points[0]); + assert!(matches!(implicit.closed_boundary(), Cow::Owned(_))); + assert_eq!(implicit.closed_boundary().as_ref(), expected); + assert_eq!(implicit.boundary, points); + let explicit = Wipeout { boundary: expected.clone() }; + assert!(matches!(explicit.closed_boundary(), Cow::Borrowed(_))); + assert_eq!(explicit.closed_boundary().as_ref(), expected); + let a = EntityKind::Wipeout(implicit).prims(); + let b = EntityKind::Wipeout(explicit).prims(); + assert_eq!(a, b); + assert_eq!(a.len(), 3); + for boundary in [vec![], vec![Vec2::ZERO]] { + let wipeout = Wipeout { boundary: boundary.clone() }; + assert!(matches!(wipeout.closed_boundary(), Cow::Borrowed(_))); + assert_eq!(wipeout.closed_boundary().as_ref(), boundary); + assert!(EntityKind::Wipeout(wipeout).prims().is_empty()); + } + } + + #[test] + fn moving_endpoints_together_keeps_both_corners_editable() { + let points = [Vec2::ZERO, Vec2::new(8.0, 0.0), Vec2::new(8.0, 6.0), Vec2::new(0.0, 6.0)]; + for explicit in [false, true] { + for index in [0, 3] { + let other = 3 - index; + let mut boundary = points.to_vec(); + if explicit { + boundary.push(points[0]); + } + let mut wipeout = Wipeout { boundary }; + let mut expected = points; + expected[index] = points[other]; + for _ in 0..2 { + assert_eq!(wipeout.set_vertex(index, points[other]), Some(())); + assert_eq!(wipeout.vertices(), expected); + assert_eq!(wipeout.boundary.len(), 5, "one separate closing marker, no growth"); + } + expected[other] = Vec2::new(-2.0, 4.0); + assert_eq!(wipeout.set_vertex(other, expected[other]), Some(())); + assert_eq!(wipeout.vertices(), expected); + assert_eq!(wipeout.boundary.len(), 5); + assert_eq!(wipeout.boundary.first(), wipeout.boundary.last()); + } + } + } + + #[test] + fn editing_keeps_the_closure_but_not_other_coincident_vertices_attached() { + let (a, b, c, to) = (Vec2::ZERO, Vec2::new(7.0, 1.0), Vec2::new(3.0, 7.0), Vec2::new(2.0, 3.0)); + for explicit in [false, true] { + let mut boundary = vec![a, b, a, c]; + if explicit { + boundary.push(a); + } + let mut wipeout = Wipeout { boundary }; + assert_eq!(wipeout.set_vertex(0, to), Some(())); + let mut expected = vec![to, b, a, c]; + if explicit { + expected.push(to); + } + assert_eq!(wipeout.boundary, expected); + for (index, point) in [(4, a), (usize::MAX, a), (0, Vec2::new(f64::NAN, 0.0)), (0, Vec2::new(0.0, f64::INFINITY))] { + assert_eq!(wipeout.set_vertex(index, point), None); + assert_eq!(wipeout.boundary, expected); + } + } + } +} diff --git a/crates/engine/src/grips.rs b/crates/engine/src/grips.rs index a3b8921aa..8c58e30b5 100644 --- a/crates/engine/src/grips.rs +++ b/crates/engine/src/grips.rs @@ -239,7 +239,7 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option *w.boundary.get_mut(index)? = to, + EntityKind::Wipeout(w) => w.set_vertex(index, to)?, EntityKind::Unknown(_) => return None, } Some(k) diff --git a/crates/engine/src/grips/tests.rs b/crates/engine/src/grips/tests.rs index 971937704..2fc4502b6 100644 --- a/crates/engine/src/grips/tests.rs +++ b/crates/engine/src/grips/tests.rs @@ -169,6 +169,21 @@ fn other_entity_grips() { assert!(matches!(kind(&s, pt), EntityKind::Point(p) if near(p.p.xy(), 2.0, 2.0))); } +#[test] +fn wipeout_grips_reject_the_closing_marker_and_hostile_input() { + let kind = EntityKind::Wipeout(cadcraft_doc::Wipeout { boundary: vec![v(0.0, 0.0), v(7.0, 1.0), v(3.0, 7.0), v(0.0, 0.0)] }); + for (index, to) in [(3, v(2.0, 2.0)), (usize::MAX, v(2.0, 2.0)), (0, v(f64::NAN, 0.0)), (0, v(0.0, f64::INFINITY))] { + assert!(stretch_grip(&kind, index, to).is_none()); + } + for boundary in [vec![], vec![v(0.0, 0.0)], vec![v(0.0, 0.0), v(0.0, 0.0)]] { + let kind = EntityKind::Wipeout(cadcraft_doc::Wipeout { boundary }); + for index in [0, 1, usize::MAX] { + let result = stretch_grip(&kind, index, v(2.0, 2.0)); + assert_eq!(result.is_some(), index < kind.grips().len()); + } + } +} + #[test] fn grip_modes() { let mut s = Session::new(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 51cec4590..8e20e6fa8 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -144,6 +144,7 @@ mod undo_layout_tab; mod viewport_clip; mod vplayer_prompts; mod vports; +mod wipeout_grips; mod xdata_follows_entity; mod zoom_keywords; mod zoom_viewport; diff --git a/crates/engine/tests/it/wipeout_grips.rs b/crates/engine/tests/it/wipeout_grips.rs new file mode 100644 index 000000000..e34620089 --- /dev/null +++ b/crates/engine/tests/it/wipeout_grips.rs @@ -0,0 +1,227 @@ +//! WIPEOUT's optional repeated closing point is not a second editable corner (#2256). +//! Authored contours keep their grips and edit results through DXF/DWG saves, both via the +//! command API and the interactive grip machine, without changing the file's explicit closure. + +use cadcraft_doc::{Drawing, EntityKind, Handle, LwPolyline, Space}; +use cadcraft_engine::{ + Input, Session, + grips::{GripMode, stretch_grip}, +}; +use cadcraft_geom::{PolyVertex, Vec2}; +use cadcraft_io::{SaveOptions, Version}; +use serde_json::json; + +fn fixture(explicit: bool, reversed: bool) -> (Drawing, Handle, Vec) { + let mut points = vec![Vec2::new(1.0, 2.0), Vec2::new(7.0, 3.0), Vec2::new(4.0, 9.0)]; + if reversed { + points.reverse(); + } + let mut input = points.clone(); + if explicit { + input.push(points[0]); + } + let mut session = Session::new(); + let input: Vec<_> = input.iter().map(|p| [p.x, p.y]).collect(); + let reply = session.execute("wipeout", &json!({"points": input})).unwrap(); + let handle = Handle::parse_hex(reply["handle"].as_str().unwrap()).unwrap(); + (session.doc().unwrap().clone(), handle, points) +} + +fn points_equal(actual: &[Vec2], expected: &[Vec2]) { + assert_eq!(actual.len(), expected.len(), "{actual:?} != {expected:?}"); + for (a, b) in actual.iter().zip(expected) { + assert!(a.near(*b, 1e-12), "{actual:?} != {expected:?}"); + } +} + +fn assert_boundary(drawing: &Drawing, handle: Handle, points: &[Vec2], explicit: bool) { + let EntityKind::Wipeout(w) = &drawing.entity(handle).unwrap().kind else { panic!("WIPEOUT lost") }; + let mut expected = points.to_vec(); + if explicit { + expected.push(points[0]); + } + points_equal(&w.boundary, &expected); +} + +fn move_grip(session: &mut Session, handle: Handle, index: usize, to: Vec2, interactive: bool) { + session.set_selection(vec![handle]); + if interactive { + session.start_grip_edit(&[(handle, index)]).unwrap(); + session.input(Input::Point(to)).unwrap(); + assert!(!session.prompting()); + } else { + session.grip_edit(handle, index, to, GripMode::Stretch).unwrap(); + } +} + +fn edit(drawing: Drawing, handle: Handle, points: &[Vec2], explicit: bool, index: usize, interactive: bool) -> Drawing { + let mut session = Session::new(); + session.open_drawing(drawing, "wipeout", None); + points_equal(&session.grips_of(handle).unwrap(), points); + let to = points[index] + Vec2::new(2.0, 1.0); + let mut expected = points.to_vec(); + expected[index] = to; + move_grip(&mut session, handle, index, to, interactive); + assert_boundary(session.doc().unwrap(), handle, &expected, explicit); + points_equal(&session.grips_of(handle).unwrap(), &expected); + session.execute("undo", &json!({})).unwrap(); + assert_boundary(session.doc().unwrap(), handle, points, explicit); + session.execute("redo", &json!({})).unwrap(); + assert_boundary(session.doc().unwrap(), handle, &expected, explicit); + session.doc().unwrap().clone() +} + +fn check(format: &str, interactive: bool) { + for explicit in [false, true] { + for reversed in [false, true] { + let (drawing, handle, points) = fixture(explicit, reversed); + for index in 0..points.len() { + edit(drawing.clone(), handle, &points, explicit, index, interactive); + } + for version in Version::ALL { + for binary in [false, true].into_iter().filter(|binary| !*binary || format == "wipeout.dxf") { + let options = SaveOptions { version: Some(version), binary }; + let mut current = drawing.clone(); + for _pass in 0..2 { + let bytes = cadcraft_io::write_with(¤t, format, &options).unwrap(); + current = cadcraft_io::read(&bytes, format).unwrap(); + assert!(current.read_notes.is_empty() && current.skipped_records.is_empty()); + assert_boundary(¤t, handle, &points, true); + for index in 0..points.len() { + let edited = edit(current.clone(), handle, &points, true, index, interactive); + let mut expected = points.clone(); + expected[index] += Vec2::new(2.0, 1.0); + let bytes = cadcraft_io::write_with(&edited, format, &options).unwrap(); + let back = cadcraft_io::read(&bytes, format).unwrap(); + assert_boundary(&back, handle, &expected, true); + } + } + } + } + } + } +} + +#[test] +fn dxf_api_grips_survive_roundtrip() { + check("wipeout.dxf", false); +} + +#[test] +fn dxf_interactive_grips_survive_roundtrip() { + check("wipeout.dxf", true); +} + +#[test] +fn dwg_api_grips_survive_roundtrip() { + check("wipeout.dwg", false); +} + +#[test] +fn dwg_interactive_grips_survive_roundtrip() { + check("wipeout.dwg", true); +} + +#[test] +fn polyline_closedness_is_not_inferred_from_coincident_endpoints() { + for closed in [false, true] { + for repeated in [false, true] { + let mut points = vec![Vec2::ZERO, Vec2::new(7.0, 1.0), Vec2::new(3.0, 7.0)]; + if repeated { + points.push(points[0]); + } + let polyline = LwPolyline { + vertices: points.iter().copied().map(PolyVertex::new).collect(), + closed, + const_width: 0.0, + elevation: 0.0, + plinegen: false, + }; + let kind = EntityKind::LwPolyline(polyline); + let segments = if repeated || closed { 3 } else { 2 }; + assert_eq!(kind.prims().len(), segments); + assert_eq!(kind.grips().len(), points.len() + segments); + let to = Vec2::new(2.0, 3.0); + let EntityKind::LwPolyline(edited) = stretch_grip(&kind, 0, to).unwrap() else { panic!("polyline") }; + assert_eq!(edited.closed, closed); + let mut expected = points.clone(); + expected[0] = to; + assert_eq!(edited.vertices.iter().map(|v| v.p).collect::>(), expected); + + // WIPEOUT conversion requires the closed flag, even with coincident endpoints. + let mut session = Session::new(); + let handle = session.doc_mut().unwrap().add(&Space::Model, Default::default(), kind).unwrap(); + let result = session.execute("wipeout", &json!({"handle": handle.hex()})); + assert_eq!(result.is_ok(), closed); + if let Ok(result) = result { + let wipeout = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap(); + assert_boundary(session.doc().unwrap(), wipeout, &points[..3], repeated); + points_equal(&session.grips_of(wipeout).unwrap(), &points[..3]); + } else { + assert_eq!(session.doc().unwrap().model.len(), 1); + } + } + } +} + +#[test] +fn coincident_endpoints_remain_separately_editable_after_save() { + let original = [Vec2::ZERO, Vec2::new(8.0, 0.0), Vec2::new(8.0, 6.0), Vec2::new(0.0, 6.0)]; + for explicit in [false, true] { + for interactive in [false, true] { + for index in [0, 3] { + let other = 3 - index; + let mut input: Vec<_> = original.iter().map(|p| [p.x, p.y]).collect(); + if explicit { + input.push(input[0]); + } + let mut session = Session::new(); + let reply = session.execute("wipeout", &json!({"points": input})).unwrap(); + let handle = Handle::parse_hex(reply["handle"].as_str().unwrap()).unwrap(); + let mut coincident = original; + coincident[index] = original[other]; + move_grip(&mut session, handle, index, coincident[index], interactive); + points_equal(&session.grips_of(handle).unwrap(), &coincident); + assert_boundary(session.doc().unwrap(), handle, &coincident, true); + session.undo().unwrap(); + assert_boundary(session.doc().unwrap(), handle, &original, explicit); + session.execute("redo", &json!({})).unwrap(); + points_equal(&session.grips_of(handle).unwrap(), &coincident); + let collapsed = session.doc().unwrap().clone(); + for version in Version::ALL { + for (format, binary) in [("wipeout.dxf", false), ("wipeout.dxf", true), ("wipeout.dwg", false)] { + let options = SaveOptions { version: Some(version), binary }; + let bytes = cadcraft_io::write_with(&collapsed, format, &options).unwrap(); + let back = cadcraft_io::read(&bytes, format).unwrap(); + session.open_drawing(back, "coincident corners", None); + points_equal(&session.grips_of(handle).unwrap(), &coincident); + assert_boundary(session.doc().unwrap(), handle, &coincident, true); + let mut separated = coincident; + separated[other] = Vec2::new(-2.0, 4.0); + move_grip(&mut session, handle, other, separated[other], interactive); + points_equal(&session.grips_of(handle).unwrap(), &separated); + assert_boundary(session.doc().unwrap(), handle, &separated, true); + let bytes = cadcraft_io::write_with(session.doc().unwrap(), format, &options).unwrap(); + let back = cadcraft_io::read(&bytes, format).unwrap(); + assert_boundary(&back, handle, &separated, true); + } + } + } + } + } +} + +#[test] +fn multiple_hot_grips_keep_the_closing_point_attached() { + let (drawing, handle, mut points) = fixture(true, false); + let mut session = Session::new(); + session.open_drawing(drawing, "wipeout", None); + session.set_selection(vec![handle]); + session.start_grip_edit(&[(handle, 0), (handle, 1)]).unwrap(); + let delta = Vec2::new(2.0, 1.0); + session.input(Input::Point(points[0] + delta)).unwrap(); + points[0] += delta; + points[1] += delta; + assert_boundary(session.doc().unwrap(), handle, &points, true); + points_equal(&session.grips_of(handle).unwrap(), &points); +} diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index cd41cdf91..9c2f12896 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -665,14 +665,9 @@ fn write_wipeout_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: w.i(282, 50); w.i(283, 0); w.i(71, 2); - let mut pts = wo.boundary.clone(); - if let (Some(first), Some(last)) = (pts.first().copied(), pts.last().copied()) - && first != last - { - pts.push(first); - } + let pts = wo.closed_boundary(); w.i(91, pts.len() as i64); - for q in pts { + for q in pts.iter() { w.p2(14, Vec2::new((q.x - o.x) / sx - 0.5, 0.5 - (q.y - o.y) / sy)); } } diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 04e2651c5..cf37e28f7 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -294,11 +294,7 @@ fn draw_wipeout(b: &mut Builder, ctx: &Ctx, w: &cadcraft_doc::Wipeout, rgb: Ink, _ => true, }; if frame { - let mut pts = w.boundary.clone(); - if let Some(f) = pts.first().copied() { - pts.push(f); - } - b.polyline(ctx, rgb, lw, &pts); + b.polyline(ctx, rgb, lw, &w.closed_boundary()); } } diff --git a/crates/render/tests/it/wipeout_mask.rs b/crates/render/tests/it/wipeout_mask.rs index 508b052b6..6c9531988 100644 --- a/crates/render/tests/it/wipeout_mask.rs +++ b/crates/render/tests/it/wipeout_mask.rs @@ -59,6 +59,43 @@ fn wipeout_hides_what_is_drawn_before_it() { assert!(inside > 0); } +#[test] +fn implicit_and_explicit_closure_draw_the_same_mask_and_frame() { + for reversed in [false, true] { + let mut implicit = drawing(false); + let handle = implicit.model.iter().find(|e| matches!(e.kind, EntityKind::Wipeout(_))).unwrap().handle; + if reversed { + implicit.model.modify(handle, |e| { + let EntityKind::Wipeout(w) = &mut e.kind else { panic!("wipeout") }; + w.boundary.reverse(); + }); + } + let mut explicit = implicit.clone(); + explicit.model.modify(handle, |e| { + let EntityKind::Wipeout(w) = &mut e.kind else { panic!("wipeout") }; + w.boundary.push(w.boundary[0]); + }); + for frame in [0, 1, 2] { + implicit.header.set_i64("WIPEOUTFRAME", frame); + explicit.header.set_i64("WIPEOUTFRAME", frame); + for plot in [false, true] { + let draw = if plot { build_plot } else { build }; + let a = draw(&implicit, &Space::Model, &Options::default()); + let b = draw(&explicit, &Space::Model, &Options::default()); + assert_eq!(a.prims, b.prims); + assert_eq!(a.verts, b.verts); + assert_eq!(a.tris, b.tris); + for primitive in b.prims.iter().filter(|p| p.handle == handle && p.kind == Kind::Polyline) { + let points = b.points(primitive); + assert_eq!(points.len(), 5, "four corners and exactly one closing point"); + assert_eq!(points.first(), points.last()); + } + assert_eq!(dark_pixels(&a), dark_pixels(&b)); + } + } + } +} + #[test] fn wipeoutframe_controls_the_frame() { // Polylines in the list: the line, plus the frame when it is drawn. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 2bfea4a51..291c9b202 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -87,7 +87,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | ACAD_TABLE | yes | 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) | | +| WIPEOUT | yes | yes (#147, fixes #79) | Implicit or explicit closure in memory; explicit closing point on save. Same logical grips and edit results before/after DXF/DWG round trips (#2256). | | 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); a proxy entity's class number (group 91) is renumbered to its class's place in the written CLASSES (#1812); **dropped by DWG save** (acadrust) | only their layer follows edits | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6bf0c20f8..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-26 · **Change:** minor (browser panel layout storage) · **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 @@ -111,7 +111,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Feature | AutoCAD | CADCraft | |---|---|---| -| Stretch grips per object type | yes | lines (midpoint moves), arcs (start/mid/end), ellipses (axes), polylines (vertices; segment midpoints move or reshape the bulge), dimensions (text and definition points), MLEADER, viewport, wipeout, spline (`grips.rs:79-270`) | +| Stretch grips per object type | yes | lines (midpoint moves), arcs (start/mid/end), ellipses (axes), polylines (vertices; segment midpoints move or reshape the bulge), dimensions (text and definition points), MLEADER, viewport, wipeout (one grip per logical corner, including coincident corners; an explicit closing marker follows the first vertex), spline (`grips.rs`) | | Text/MText grips | position, width, column grips | move the whole object | | Hot-grip modes with Space/Enter cycling | Stretch, Move, Rotate, Scale, Mirror | yes (`canvas.rs:58-67`) | | Hot-grip options: Base point, Copy, Undo, Reference, eXit | yes | **advertised in the prompt but not parsed**; the engine's JSON grip commands accept `copy`, the UI never passes it | @@ -204,6 +204,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | WIPEOUT grips treat implicit and explicit closure alike; moving the first vertex carries the closing marker, and moving endpoints together keeps both corners editable. Open/closed polyline flags and coincident polyline vertices remain independent (#2256) | | 2026-10-26 | minor | Browser host stores bounded, validated panel layout separately from drawing state; malformed or unsupported records retain defaults. Native workspace storage is unchanged. | | 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 | From d15de754069bac149f2fe199310299752ebbcd0f Mon Sep 17 00:00:00 2001 From: Books Date: Fri, 30 Oct 2026 12:31:22 +1100 Subject: [PATCH 191/900] Dimensions: report the measurement as soon as one is created (#2421) (#2438) * Dimensions: fill in the measurement when one is created (#2421) A dimension made in the session kept measurement 0.0 until it was saved and reopened. add_dim now sets it with the geometry call the DXF/DWG writer uses for group 42. Block names are still assigned at save time. Test: a_new_dimension_reports_its_measurement. * Parity checklist: regenerated after merging main * Dimensions: a jogged radius dimension stores its radius as the measurement (#2421) draw_jogged_radius set the text but not DimGeometry.measurement, so DIMJOGGED dimensions kept measurement 0 (and the DXF/DWG group 42 was 0). It now sets the radius. Test: jogged_radius asserts the stored measurement. * Parity checklist: regenerated after merging main * Dimensions: fill in a new dimension's text position when it is created (#2421) A dimension made in the session kept text_mid (0,0) until it was saved and reopened. add_dim now sets it from the same dimension_geometry result as the measurement, the position the writer puts in group 11, unless the user placed the text. Test: a_new_dimension_reports_its_text_position. --------- Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/annotate/common.rs | 13 ++++++++++++ crates/engine/tests/it/dim_commands.rs | 27 ++++++++++++++++++++++++ crates/render/src/dim/variants.rs | 1 + docs/parity-checklist.md | 1 + 4 files changed, 42 insertions(+) diff --git a/crates/engine/src/cmd/annotate/common.rs b/crates/engine/src/cmd/annotate/common.rs index 2267f16bf..419723288 100644 --- a/crates/engine/src/cmd/annotate/common.rs +++ b/crates/engine/src/cmd/annotate/common.rs @@ -48,6 +48,19 @@ pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result { { dm.assoc = crate::assoc::reassociate(s.doc()?, &s.space(), dm); } + // The measurement is what the DXF/DWG writer computes from the geometry (group 42); filling it + // in now means queries show it before the drawing is saved and reopened (#2421). + if let EntityKind::Dimension(dm) = &mut k + && let Ok(d) = s.doc() + { + let style = d.dim_style(&dm.style).cloned().unwrap_or_default(); + let g = cadcraft_render::dimension_geometry(dm, &style, d.header.f64("DIMSCALE", 1.0)); + dm.measurement = g.measurement; + // The text position the writer puts in group 11 when the user has not placed the text. + if !dm.user_text_pos { + dm.text_mid = g.text_pos.to3(0.0); + } + } let h = s.add_entity(k)?; s.last_dim = Some(h); Ok(h) diff --git a/crates/engine/tests/it/dim_commands.rs b/crates/engine/tests/it/dim_commands.rs index 8e67b1039..3c5b5c90a 100644 --- a/crates/engine/tests/it/dim_commands.rs +++ b/crates/engine/tests/it/dim_commands.rs @@ -99,6 +99,7 @@ fn jogged_radius() { let (dm, g) = dim_of(&s, &h); let j = dm.marks.jogged.clone().unwrap(); assert_eq!(g.value, "R50.0000", "the true radius"); + assert!((dm.measurement - 50.0).abs() < 1e-9, "the stored measurement is the radius, got {} (#2421)", dm.measurement); assert!(j.center.xy().dist(Vec2::new(20.0, -10.0)) < 1e-9); // The line runs from the arrowhead on the circle to the override, with a 45° jog (DIMJOGANG). let tip = Vec2::new(1.0, 1.0).normalized() * 50.0; @@ -257,3 +258,29 @@ fn marks_follow_move_and_rotate_and_hostile_values_do_not_panic() { .unwrap(); let _ = dim_of(&s, &h); } + +/// A dimension made in the session reports its measurement at once, not 0.0 until it is saved +/// and reopened (#2421). +#[test] +fn a_new_dimension_reports_its_measurement() { + let mut s = Session::new(); + let measurement = |s: &Session, h: &str| dim_of(s, h).0.measurement; + let horizontal = handle(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [100, 0], "at": [50, 20] })).unwrap()); + assert!((measurement(&s, &horizontal) - 100.0).abs() < 1e-9, "{}", measurement(&s, &horizontal)); + let vertical = handle(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [0, 37.5], "at": [-10, 20] })).unwrap()); + assert!((measurement(&s, &vertical) - 37.5).abs() < 1e-9, "{}", measurement(&s, &vertical)); +} + +/// A new dimension's text position is known at once, as it is after save and reopen (#2421). +#[test] +fn a_new_dimension_reports_its_text_position() { + let mut s = Session::new(); + let horizontal = handle(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [100, 0], "at": [50, 20] })).unwrap()); + let vertical = handle(&s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [0, 37.5], "at": [-20, 18] })).unwrap()); + for h in [&horizontal, &vertical] { + let (dm, g) = dim_of(&s, h); + assert!(dm.text_mid.xy().dist(g.text_pos) < 1e-9, "stored {:?}, drawn at {:?}", dm.text_mid, g.text_pos); + assert!(dm.text_mid.xy().dist(Vec2::ZERO) > 1.0, "still at the origin: {:?}", dm.text_mid); + } + assert!((dim_of(&s, &horizontal).0.text_mid.x - 50.0).abs() < 1e-9); +} diff --git a/crates/render/src/dim/variants.rs b/crates/render/src/dim/variants.rs index 240b5e88d..948483a54 100644 --- a/crates/render/src/dim/variants.rs +++ b/crates/render/src/dim/variants.rs @@ -27,6 +27,7 @@ pub(super) fn draw_jogged_radius(config: &DimConfig<'_>, g: &mut DimGeometry, te if !r.is_finite() { break 'jogged; } + g.measurement = r; let (tw, _) = measure(&g.mtext); let u = (tip - center).normalized(); let u = if u == Vec2::ZERO || !u.is_finite() { Vec2::X } else { u }; diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index ee0358f9e..d0bd6f967 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,5 +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. 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 42667d1332ce9e9922771b8599caee796106190c Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Fri, 30 Oct 2026 08:31:26 +0700 Subject: [PATCH 192/900] ELLIPSE from axis endpoints matches what AutoCAD stores (#2197) * ELLIPSE from axis endpoints matches what AutoCAD stores Typed ELLIPSE input was checked against AutoCAD 2024 black-box (synthetic input in accoreconsole, read back with entget); three rules differed: - The major axis pointed at the second axis endpoint; AutoCAD points it at the first. A full ellipse looks the same, but an elliptical arc's angles are measured from that axis, so the arc was drawn on the opposite side of the center, and the stored major vector, start point and quadrant order all differed. - A point at "Specify distance to other axis" gave its distance from the first axis; AutoCAD takes its distance from the center (the rubber band), then swaps the axes when it is the longer one. - The end-angle prompt had no Included angle option, so `_I` was rejected and the next number became an absolute end angle. AutoCAD adds the included angle (default 180) to the start angle. The JSON form (ellipse.axis / ellipse.arc with p1, p2, p3) follows the same rules. The regression test pins ten AutoCAD-measured cases, among them survey (VN-2000) coordinates, a near-millimetre ellipse and both Included angle cases. Co-Authored-By: Claude Opus 5.5 * docs: geometry parity says which part was measured against AutoCAD The "How this was measured" section still said no numeric comparison against AutoCAD had been run, next to the new ELLIPSE revision row that reports one. It now names the 11 measured ELLIPSE cases and the test that pins them, and keeps the rest of the document marked as read from the source. Pointed out in review. Co-Authored-By: Claude Opus 5.5 * ellipse: drop the import the axis-endpoint change left unused --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/draw/ellipse.rs | 47 +++++++++-- crates/engine/src/cmd/draw2.rs | 2 +- crates/engine/src/cmd/draw2/ellipse.rs | 11 ++- crates/engine/src/cmd/draw2/tests.rs | 112 +++++++++++++++++++++++++ docs/geometry-parity.md | 14 ++-- 5 files changed, 165 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/draw/ellipse.rs b/crates/engine/src/cmd/draw/ellipse.rs index c1e7967d9..b1cd56927 100644 --- a/crates/engine/src/cmd/draw/ellipse.rs +++ b/crates/engine/src/cmd/draw/ellipse.rs @@ -34,19 +34,24 @@ pub(super) struct EllipseM { /// The `Parameter` option: arc start/end values are ellipse parameters, not true angles. param: bool, start: Option, + /// The `Included angle` option: the next value is the arc's angle from its start angle. + included: bool, /// The Isocircle option (isometric snap style) in progress. iso: Option, } impl EllipseM { fn axis(&self) -> Option<(Vec2, Vec2)> { - // (center, major vector) + // (center, major vector): towards the first axis endpoint, as AutoCAD stores it. match (self.center_mode, self.pts.as_slice()) { (true, [c, e, ..]) => Some((*c, *e - *c)), - (false, [a, b, ..]) => Some((a.mid(*b), *b - a.mid(*b))), + (false, [a, b, ..]) => Some((a.mid(*b), *a - a.mid(*b))), _ => None, } } + /// The other half axis reaches as far as `other` is from the center (AutoCAD measures the + /// picked point's distance from the center, not from the first axis). Longer than the + /// first half axis, it becomes the major axis: the first axis turned 90° counterclockwise. fn build(&self, other: Vec2) -> Option { let (c, m) = self.axis()?; let ml = m.len(); @@ -54,7 +59,7 @@ impl EllipseM { return None; } let u = m / ml; - let minor = ((other - c).dot(u.perp())).abs(); + let minor = (other - c).len(); let (major, ratio) = if minor > ml { (u.perp() * minor, ml / minor) } else { (m, minor / ml) }; (ratio > 1e-9).then_some(Ellipse::full(c, major, ratio.min(1.0))) } @@ -88,13 +93,16 @@ impl Interactive for EllipseM { } fn prompt(&self, s: &Session) -> Prompt { if let Some(e) = &self.ellipse { - let msg = match (self.start.is_none(), self.param) { - (true, false) => "Specify start angle", - (false, false) => "Specify end angle", - (true, true) => "Specify start parameter", - (false, true) => "Specify end parameter", + if self.included { + return Prompt::new("Specify included angle for arc", Accept::POINT_OR_NUMBER).default("180").base(e.center); + } + let (msg, kw): (&str, &[&str]) = match (self.start.is_none(), self.param) { + (true, false) => ("Specify start angle", &["Parameter"]), + (false, false) => ("Specify end angle", &["Parameter", "Included angle"]), + (true, true) => ("Specify start parameter", &["Angle"]), + (false, true) => ("Specify end parameter", &["Angle"]), }; - return Prompt::new(msg, Accept::POINT_OR_NUMBER).kw(if self.param { &["Angle"] } else { &["Parameter"] }).base(e.center); + return Prompt::new(msg, Accept::POINT_OR_NUMBER).kw(kw).base(e.center); } if let Some(iso) = &self.iso { return iso.prompt(); @@ -112,11 +120,32 @@ impl Interactive for EllipseM { fn input(&mut self, s: &mut Session, i: Input) -> Result { if let Some(e) = self.ellipse { let ge = Ellipse { start: 0.0, end: cadcraft_geom::TAU, ..e }; + if self.included { + let incl = match i { + Input::Point(p) => (p - e.center).angle(), + Input::Text(t) => s.angle_settings().amount(&t).ok_or_else(|| crate::EngineError::Other("Requires an angle.".into()))?, + Input::Enter => std::f64::consts::PI, + _ => return Ok(Step::Continue), + }; + // A true angle added to the start angle (AutoCAD: start 214.659°, included + // 232.716° ends the arc at 87.375° from the major axis). + let st = self.start.unwrap_or(0.0); + let end = ge.param_of(e.center + Vec2::from_angle((ge.at_param(st) - e.center).angle() + incl)); + s.add_entity(EntityKind::Ellipse(cadcraft_doc::Ellipse { + center: v3(e.center), + major: v3(e.major), + ratio: e.ratio, + start: st, + end, + }))?; + return Ok(Step::Done); + } let ang = match i { Input::Keyword(k) => { match k.as_str() { "Parameter" => self.param = true, "Angle" => self.param = false, + "Included angle" if self.start.is_some() && !self.param => self.included = true, _ => {} } return Ok(Step::Continue); diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index b37ebbc68..003edf2a8 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -105,7 +105,7 @@ pub fn specs() -> Vec { .interactive(|_| Ok(Box::new(TanCircleM::new(false)))), CommandSpec::new("ellipse.axis", "Axis, End", run_ellipse_axis) .menu(&["Draw", "Ellipse", "Axis, End"]) - .params("{p1, p2, distance} | {p1, p2, p3} (axis endpoints, then half the other axis)") + .params("{p1, p2, distance} | {p1, p2, p3} (axis endpoints, then half the other axis: a distance, or a point that far from the center)") .interactive(|_| Ok(super::draw::ellipse_machine(false, false))), CommandSpec::new("ellipse.arc", "Elliptical Arc", run_ellipse_arc) .menu(&["Draw", "Ellipse", "Arc"]) diff --git a/crates/engine/src/cmd/draw2/ellipse.rs b/crates/engine/src/cmd/draw2/ellipse.rs index e699eac58..430effa6b 100644 --- a/crates/engine/src/cmd/draw2/ellipse.rs +++ b/crates/engine/src/cmd/draw2/ellipse.rs @@ -1,10 +1,11 @@ -use super::{Ellipse, EntityKind, Line, Result, Session, TAU, Value, Vec2, added, bad, f64_req, point_param, point_req, v3}; +use super::{Ellipse, EntityKind, Result, Session, TAU, Value, Vec2, added, bad, f64_req, point_param, point_req, v3}; // ---------------- ellipse entries ---------------- fn ellipse_from_axis(p1: Vec2, p2: Vec2, half: f64) -> Option { let c = p1.mid(p2); - let m = p2 - c; + // The major axis points at the first endpoint, as AutoCAD stores it. + let m = p1 - c; let ml = m.len(); let half = half.abs(); if ml < 1e-12 || half < 1e-12 || !half.is_finite() { @@ -17,10 +18,8 @@ fn axis_ellipse_params(cmd: &str, p: &Value) -> Result { let p1 = point_req(cmd, p, "p1")?; let p2 = point_req(cmd, p, "p2")?; let half = match point_param(p, "p3") { - Some(p3) => { - let ax = Line::new(p1, p2); - ax.project(p3).dist(p3) - } + // As at the prompt: the point's distance from the center, not from the first axis. + Some(p3) => p3.dist(p1.mid(p2)), None => f64_req(cmd, p, "distance")?, }; ellipse_from_axis(p1, p2, half).ok_or_else(|| bad(cmd, "degenerate ellipse")) diff --git a/crates/engine/src/cmd/draw2/tests.rs b/crates/engine/src/cmd/draw2/tests.rs index b5585e381..8eedd3772 100644 --- a/crates/engine/src/cmd/draw2/tests.rs +++ b/crates/engine/src/cmd/draw2/tests.rs @@ -270,6 +270,118 @@ fn ellipse_arc_typed_angles_are_true_angles() { } } +/// Typed ELLIPSE input against what AutoCAD 2024 stores for the same input (black-box: synthetic +/// input in accoreconsole, read back with `entget`). The major axis points at the first axis +/// endpoint; a point at the distance prompt gives its distance from the center; an other axis +/// longer than the first becomes the major axis, the first turned 90° counterclockwise; the +/// Included angle is added to the start angle. +#[test] +fn ellipse_axis_endpoints_match_autocad() { + type Case = (&'static str, [f64; 2], [f64; 2], f64, Option<[f64; 2]>); + // (input after ELLIPSE, center, major axis, ratio, arc start/end parameters) + let cases: [Case; 10] = [ + // The other axis (27.02) is longer than the first half axis (26.42). + ( + "16.459468652708743,28.120073391143574 -5.034438825478263,-20.14843889196848 27.021868057769268", + [5.712514913615239, 3.985817249587547], + [-24.6850622596004, 10.99222700689644], + 0.9776866627982613, + None, + ), + ( + "33.45015752893423,-27.997665254733153 1.0902141405158297,-9.876490849047837 _R 36.361957504949", + [17.27018583472502, -18.93707805189049], + [16.1799716942092, -9.060587202842658], + 0.8052876303433125, + None, + ), + ( + "0.5161247992610992,0.27380397971284964 0.49874786589184156,0.23294359917255586 0.0026647279687818256", + [0.5074363325764704, 0.2533737894427027], + [0.00868846668462886, 0.02043019027014691], + 0.1200276615332929, + None, + ), + // Arcs: the angles are taken from the major axis, so a reversed axis draws the arc + // on the opposite side of the center. + ( + "_A 612354.66928411,2398796.595432055 612364.9910379789,2398751.70959102 3.5361631006792016 259.40675054209663 162.0895061623204", + [612359.8301610444, 2398774.152511537], + [-5.160876934416592, 22.44292051764205], + 0.1535548572193783, + Some([4.683678586016272, 2.014340486820176]), + ), + ( + "_A -32.49789607178266,25.826299666765127 16.360636510348964,-6.670894598441254 9.326202777586586 _P 235.35128996877393 341.0349294763654", + [-8.068629780716847, 9.577702534161936], + [-24.42926629106581, 16.24859713260318], + 0.317871961092373, + Some([4.107654908771007, 5.952182383669234]), + ), + ( + "_A _C 15.895131938563559,-16.135236520373613 1.9672122380661037,-18.61293795336168 14.456880177932417 214.65903577683966 _I 232.7163597705933", + [15.89513193856356, -16.13523652037361], + [2.53204749973717, -14.23341561039267], + 0.9785367111972643, + Some([3.756694588158375, 1.5259701966906878]), + ), + ( + "_A _C 1.8822645373261935,-7.920292708078534 28.89115893105938,-23.280023918605742 38.7551404612689 136.20071263173944 _I 129.90755425686075", + [1.882264537326193, -7.920292708078534], + [19.15838502833398, 33.68853210335513], + 0.8017236937148501, + Some([2.267136066480607, 4.657903136501946]), + ), + // The other axis given by a point. + ( + "-16.377480557612035,55.44699770062272 -15.579405511585826,-24.406726331471475 -4.27081078679767,42.69814401696656", + [-15.97844303459893, 15.52013568457562], + [-0.3990375230131046, 39.92686201604709], + 0.7411292927991227, + None, + ), + ( + "8.137326847228081,16.045209411091605 -2.4500932561568627,22.585405165312338 -2.4956573993017335,12.374292543621266", + [2.843616795535609, 19.31530728820197], + [4.602217644463162, 7.450176331143755], + 0.7105482899194384, + None, + ), + ( + "_C 15.418189586495892,-18.741133769301225 43.29367724019212,5.337090633133826 12.043993630141971,-7.0535727363182446", + [15.41818958649589, -18.74113376930122], + [27.87548765369622, 24.07822440243505], + 0.3302549104883693, + None, + ), + ]; + use std::f64::consts::{PI, TAU}; + let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0); + let same_angle = |a: f64, b: f64| { + let d = (a - b).rem_euclid(TAU); + d < 1e-9 || TAU - d < 1e-9 + }; + for (input, center, major, ratio, arc) in cases { + let mut s = Session::new(); + s.cmdline(&format!("ellipse {input}")).unwrap(); + assert!(s.running.is_none(), "{input}: {}", s.prompt_text()); + let EntityKind::Ellipse(e) = last(&s) else { panic!("{input}: no ellipse") }; + assert!(same(e.center.x, center[0]) && same(e.center.y, center[1]), "{input}: center {:?}", e.center); + assert!(same(e.major.x, major[0]) && same(e.major.y, major[1]), "{input}: major {:?}", e.major); + assert!(same(e.ratio, ratio), "{input}: ratio {}", e.ratio); + let [start, end] = arc.unwrap_or([0.0, TAU]); + assert!(same_angle(e.start, start) && same_angle(e.end, end), "{input}: {} {}", e.start, e.end); + } + // Enter takes the default included angle, 180°: half the ellipse. + let mut s = Session::new(); + s.cmdline("ellipse _A 10,0 -10,0 5 30 _I").unwrap(); + assert!(s.prompt_text().contains("included angle"), "{}", s.prompt_text()); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let EntityKind::Ellipse(e) = last(&s) else { panic!("no ellipse") }; + assert!(same_angle(e.end, e.start + PI), "{} {}", e.start, e.end); +} + // ---------------- DIVIDE / MEASURE ---------------- #[test] diff --git a/docs/geometry-parity.md b/docs/geometry-parity.md index 3809c637f..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-10-26 · **Change:** minor (PEDIT Multiple at the command line) · **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 @@ -18,10 +18,13 @@ drawings behave differently from mid-sized ones. 3D geometry doesn't exist. Rema ## How this was measured -Read from the source on 2026-10-10 (main at bd2412f), with file:line evidence in the tables. No -numeric comparison against AutoCAD has been run yet: the plan is a set of synthetic drawings whose -exact answers are known analytically, measured in both apps black-box (LIST, ID, AREA results) -and in CADCraft headless. Until then the percentages are judgements. +Read from the source on 2026-10-10 (main at bd2412f), with file:line evidence in the tables. The +one numeric comparison against AutoCAD so far is ELLIPSE from axis endpoints (2026-10-26): 11 +typed inputs measured black-box in AutoCAD 2024 (accoreconsole, read back with `entget`) and +pinned by `ellipse_axis_endpoints_match_autocad`. Everything else is still to be measured: the +plan is a set of synthetic drawings whose exact answers are known analytically, measured in both +apps black-box (LIST, ID, AREA results) and in CADCraft headless. Until then the percentages are +judgements. Weights (how much AutoCAD users lean on each area in 2D drafting): numeric robustness 15%, curve representation 10%, intersections 15%, offsets 15%, trim/extend/fillet/chamfer/break/join @@ -157,6 +160,7 @@ Total ≈ 90–140 h; items 1–6 parallelise across two or three agents. | Date | Change | Summary | |---|---|---| +| 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) | | 2026-10-14 | trivial | JOIN Close: a single arc becomes its circle, a single elliptical arc its full ellipse (#1175) | From 912558635e40d252c95c2dcc0b429c49b9bd1e1d Mon Sep 17 00:00:00 2001 From: Books Date: Fri, 30 Oct 2026 12:31:29 +1100 Subject: [PATCH 193/900] DWG: keep block draw-order sort handles through the DXF bridge (#2410) (#2439) * DWG: keep block draw-order sort handles through the DXF bridge (#2410) acadrust's DXF writer renumbers SORTENTSTABLE sort handles past every entity handle, so an entity left out of a table (sorted by its own handle) drew below every listed one. The table now carries its codes verbatim before writing. Tests in io/tests/it/sortents.rs; the bridge test fails without the fix. * Parity checklist: regenerated after merging main * DXF: a block/space sort handle of 0 draws last (#2439) A SORTENTSTABLE sort handle of 0 means the entity is drawn after every other (ezdxf reorder.py, which notes AutoCAD defines it). apply_sortents sorted it first; key it after all nonzero handles. Test: a_zero_sort_handle_draws_last (DXF and DWG bridge). * Parity checklist: regenerated after merging main * Draw order: test two block entities left out of a SORTENTSTABLE (#2439) Each unlisted entity must sort by its own handle, landing between the listed ones. A single fallback key for all of them would put them side by side. Checked in a DXF and across the DWG bridge; test-only. --------- Co-authored-by: Brandon Thomas --- crates/dwg/src/lib.rs | 22 +++++++ crates/io/src/dxf_read/document.rs | 6 +- crates/io/tests/it/sortents.rs | 93 ++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+), 1 deletion(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 8abb696b5..7e4a88fee 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -107,6 +107,7 @@ mod native { current_style_names(&mut doc); table_merges(&mut doc); table_style_rows(&mut doc, false); + keep_sort_handles(&mut doc); let orphans = drop_orphaned_dgn_components(&mut doc); if orphans > 0 { let (s, were) = if orphans == 1 { ("", "was") } else { ("s", "were") }; @@ -265,6 +266,27 @@ mod native { } } + /// Draw-order tables (SORTENTSTABLE) keep the sort handles the file gave them. acadrust's DXF + /// writer renumbers them past every entity handle, but an entity left out of a table sorts by + /// its own handle, so after renumbering it would draw below every listed entity (#2410). Giving + /// the table its codes verbatim makes the writer emit them unchanged. + fn keep_sort_handles(doc: &mut acadrust::CadDocument) { + use acadrust::objects::ObjectType; + let version = doc.version; + for o in doc.objects.values_mut() { + let ObjectType::SortEntitiesTable(t) = o else { continue }; + let hex = |h: acadrust::types::Handle| format!("{:X}", h.value()); + let mut codes = + vec![(5, hex(t.handle)), (330, hex(t.owner_handle)), (100, "AcDbSortentsTable".to_string()), (330, hex(t.block_owner_handle))]; + for e in t.entries() { + codes.push((331, hex(e.entity_handle))); + codes.push((5, hex(e.sort_handle))); + } + t.raw_dxf_codes = Some(codes); + t.raw_dxf_version = Some(version); + } + } + /// Table styles' title and header suppression between the two places acadrust 0.6.3 keeps /// it. 2010+ (AC1024+) DWG stores it only in the style's flags (title 1, header 2), while /// acadrust's DXF reader and writer use the `title_suppressed`/`header_suppressed` fields diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 2e16afbf3..02ea0f532 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -311,7 +311,11 @@ pub(super) fn apply_sortents( for (owner, map) in tables { let Some(name) = brs.get(owner) else { continue }; let up = name.to_ascii_uppercase(); - let key = |e: &Entity| map.get(&e.handle).copied().unwrap_or(e.handle.0); + // A sort handle of 0 draws last (ezdxf `reorder`, which notes AutoCAD defines it, undocumented). + let key = |e: &Entity| { + let k = map.get(&e.handle).copied().unwrap_or(e.handle.0); + (k == 0, k) + }; if up == "*MODEL_SPACE" { d.model.sort_by_key(key); } else if up.starts_with("*PAPER_SPACE") { diff --git a/crates/io/tests/it/sortents.rs b/crates/io/tests/it/sortents.rs index 0be17e910..35b3e0dab 100644 --- a/crates/io/tests/it/sortents.rs +++ b/crates/io/tests/it/sortents.rs @@ -46,3 +46,96 @@ fn broken_sortentstables_are_ignored() { assert_eq!(order(&d), ["A1", "A2", "A3"], "{table:?}"); } } + +/// A block whose SORTENTSTABLE leaves out the circle (it sorts by its own handle) draws the +/// wipeout, the circle, then the two lines (#2410). +fn block_dxf() -> String { + block_dxf_with("331\n25B\n5\n25D\n331\n25D\n5\n25E\n331\n25E\n5\n25B\n") +} + +fn block_dxf_with(entries: &str) -> String { + let rec = |h: &str, n: &str| format!("0\nBLOCK_RECORD\n5\n{h}\n2\n{n}\n"); + let mut s = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nBLOCK_RECORD\n"); + s.push_str(&rec("1F", "*Model_Space")); + s.push_str(&rec("2A", "MASKED_B")); + s.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n5\n2B\n330\n2A\n8\n0\n2\nMASKED_B\n70\n0\n10\n0\n20\n0\n30\n0\n"); + let ent = |kind: &str, h: &str, body: &str| format!("0\n{kind}\n5\n{h}\n330\n2A\n8\n0\n{body}"); + s.push_str(&ent("LINE", "25B", "10\n0\n20\n0\n30\n0\n11\n10\n21\n0\n31\n0\n")); + s.push_str(&ent("CIRCLE", "25C", "10\n5\n20\n5\n30\n0\n40\n2\n")); + s.push_str(&ent("LINE", "25D", "10\n5\n20\n-5\n30\n0\n11\n5\n21\n5\n31\n0\n")); + s.push_str(&ent( + "WIPEOUT", + "25E", + "10\n0\n20\n0\n30\n0\n11\n1\n21\n0\n31\n0\n12\n0\n22\n1\n32\n0\n14\n-0.5\n24\n-0.5\n14\n9.5\n24\n-0.5\n14\n9.5\n24\n9.5\n14\n-0.5\n24\n9.5\n", + )); + s.push_str("0\nENDBLK\n5\n2C\n330\n2A\n8\n0\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n"); + s.push_str("0\nSORTENTSTABLE\n5\nB0\n330\nB1\n100\nAcDbSortentsTable\n330\n2A\n"); + s.push_str(entries); + s.push_str("0\nENDSEC\n0\nEOF\n"); + s +} + +fn block_kinds(d: &Drawing) -> Vec<&'static str> { + let b = d.block("MASKED_B").unwrap(); + b.entities + .iter() + .map(|e| match &e.kind { + EntityKind::Wipeout(_) => "wipeout", + EntityKind::Circle(_) => "circle", + EntityKind::Line(l) if l.b.y == l.a.y => "hline", + EntityKind::Line(_) => "vline", + _ => "other", + }) + .collect() +} + +#[test] +fn a_block_entity_left_out_of_the_table_sorts_by_its_own_handle() { + let d = cadcraft_io::read_dxf(block_dxf().as_bytes()).unwrap(); + assert_eq!(block_kinds(&d), ["wipeout", "circle", "hline", "vline"]); +} + +#[test] +fn the_block_draw_order_survives_dxf_and_dwg() { + let d = cadcraft_io::read_dxf(block_dxf().as_bytes()).unwrap(); + let dxf = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(block_kinds(&dxf), ["wipeout", "circle", "hline", "vline"], "DXF"); + let dwg = cadcraft_io::read(&cadcraft_io::write(&d, "t.dwg").unwrap(), "t.dwg").unwrap(); + assert_eq!(block_kinds(&dwg), ["wipeout", "circle", "hline", "vline"], "DWG"); +} + +/// The table itself (not CADCraft's reordered records) goes through the DWG bridge (#2410). +#[test] +fn a_partial_block_table_survives_the_dwg_bridge() { + let dwg = cadcraft_dwg::dxf_to_dwg(block_dxf().as_bytes()).unwrap(); + let dxf = cadcraft_dwg::dwg_to_dxf(&dwg).unwrap(); + let d = cadcraft_io::read_dxf(&dxf).unwrap(); + assert_eq!(block_kinds(&d), ["wipeout", "circle", "hline", "vline"]); +} + +/// A sort handle of 0 draws the entity last, in a DXF and across the DWG bridge (#2439). +#[test] +fn a_zero_sort_handle_draws_last() { + // The horizontal line is keyed 0 (last); the vertical line 25E; the wipeout 25B; the circle its own 25C. + let dxf = block_dxf_with("331\n25B\n5\n0\n331\n25D\n5\n25E\n331\n25E\n5\n25B\n"); + let want = ["wipeout", "circle", "vline", "hline"]; + assert_eq!(block_kinds(&cadcraft_io::read_dxf(dxf.as_bytes()).unwrap()), want, "DXF"); + let dwg = cadcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap(); + let back = cadcraft_io::read_dxf(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + assert_eq!(block_kinds(&back), want, "DWG"); +} + +/// Two entities left out of the table each sort by their own handle, so they land between the +/// listed ones (a single fallback key for every unlisted entity would put them side by side) +/// in a DXF and across the DWG bridge (#2439). +#[test] +fn two_unlisted_block_entities_each_sort_by_their_own_handle() { + // Listed: the horizontal line 25B and the vertical line 25D, each under its own handle. + // Unlisted: the circle 25C and the wipeout 25E. + let dxf = block_dxf_with("331\n25B\n5\n25B\n331\n25D\n5\n25D\n"); + let want = ["hline", "circle", "vline", "wipeout"]; + assert_eq!(block_kinds(&cadcraft_io::read_dxf(dxf.as_bytes()).unwrap()), want, "DXF"); + let dwg = cadcraft_dwg::dxf_to_dwg(dxf.as_bytes()).unwrap(); + let back = cadcraft_io::read_dxf(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + assert_eq!(block_kinds(&back), want, "DWG"); +} From 9b4c1fb840b3bd6720e09a38e2a4ff89196a5185 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Fri, 30 Oct 2026 02:31:33 +0100 Subject: [PATCH 194/900] Reject negative or non-finite JSON chamfer distances (#2406) Found while testing crates/engine/src/cmd/modify/fillet.rs:120-121 (run_chamfer) and 53-54 (fillet_lines) Co-authored-by: Claude Haiku 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/modify/fillet.rs | 6 +++++- crates/engine/src/tests.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/modify/fillet.rs b/crates/engine/src/cmd/modify/fillet.rs index 963de2607..2a75b22e7 100644 --- a/crates/engine/src/cmd/modify/fillet.rs +++ b/crates/engine/src/cmd/modify/fillet.rs @@ -118,7 +118,11 @@ pub(super) fn run_chamfer(s: &mut Session, p: &Value) -> Result { } (None, None) => { let d1 = f64_or(p, "d1", s.doc()?.header.f64("CHAMFERA", 0.0)); - ChamferCut::Dist(d1, f64_or(p, "d2", d1)) + let d2 = f64_or(p, "d2", d1); + if !(d1.is_finite() && d1 >= 0.0 && d2.is_finite() && d2 >= 0.0) { + return Err(bad("chamfer", "`d1` and `d2` must be >= 0")); + } + ChamferCut::Dist(d1, d2) } _ => return Err(bad("chamfer", "`length` (>= 0) and `angle` (degrees, 0 to 180) go together")), }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index be6246824..427bfe8d4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1454,6 +1454,18 @@ fn hostile_variable_like_input_never_panics() { assert!(setvar_prompt_open(&s)); } +#[test] +fn chamfer_rejects_negative_distances() { + let mut s = Session::new(); + let h1 = s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let h2 = s.execute("line", &json!({"points": [[0, 0], [0, 10]]})).unwrap(); + let before = format!("{:?}", s.doc().unwrap().model.iter().map(|e| e.kind.clone()).collect::>()); + let r = s.execute("chamfer", &json!({"h1": h1["handles"][0], "h2": h2["handles"][0], "p1": [5, 0], "p2": [0, 5], "d1": -3, "d2": 2})); + assert!(r.is_err(), "negative chamfer distance accepted: {r:?}"); + let after = format!("{:?}", s.doc().unwrap().model.iter().map(|e| e.kind.clone()).collect::>()); + assert_eq!(before, after); +} + #[test] fn array_counts_reject_invalid_values() { let mut s = Session::new(); From f883454d7dd4e1016a100fed90968e6825953d9d Mon Sep 17 00:00:00 2001 From: Books Date: Fri, 30 Oct 2026 12:37:44 +1100 Subject: [PATCH 195/900] DWG: post-read fix-ups run under catch_unwind; merge work is bounded (#1934) (#2402) * DWG: post-read fix-ups run under catch_unwind; merge work is bounded (#1934) table_merges and the other fix-ups on the acadrust document ran outside the panic guard, and each merge range could visit rows x cols cells with no total limit. They now run in one guarded post_process, and table_merges stops at MAX_MERGE_CELLS cells in all. Tests: merge_work_is_bounded_by_the_cell_budget, a_panic_in_post_processing_is_an_error. * Parity checklist: regenerated after merging main * DWG: test that the read and convert guards catch a panic through the public API (#2402) The existing test only exercised guarded() itself. A test-only hook now makes post_process or convert panic on entry, and tests go through dwg_to_dxf and dxf_to_dwg: both fail if their guard is removed. convert()'s fix-ups, which run on the third-party reader's document, are now under guarded() too, with their own error. * Parity checklist: regenerated after merging main * DWG: build the panic-test helpers only on native targets, like the tests that use them (#2402) PanicIn and MINIMAL_DXF referenced the native-only PANIC_IN, so the dwg tests did not compile for wasm32 (cargo check -p cadcraft-dwg --tests --target wasm32-unknown-unknown). --------- Co-authored-by: Brandon Thomas --- crates/dwg/src/lib.rs | 153 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 140 insertions(+), 13 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 7e4a88fee..f7bf13dd6 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -104,11 +104,7 @@ mod native { } let mut notes = read_notes(&outcome.stats); let mut doc = outcome.document; - current_style_names(&mut doc); - table_merges(&mut doc); - table_style_rows(&mut doc, false); - keep_sort_handles(&mut doc); - let orphans = drop_orphaned_dgn_components(&mut doc); + 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") }; notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out")); @@ -238,6 +234,33 @@ mod native { /// cells already carry merges are left alone. Each range's first cell gets the span; the /// cells it covers are marked merged with no span of their own, as CADCraft's DXF writer does. fn table_merges(doc: &mut acadrust::CadDocument) { + table_merges_within(doc, MAX_MERGE_CELLS); + } + + /// The most table cells [`table_merges`] visits in one document: each range is capped, but + /// can cover rows × cols cells, so the total is bounded too. + const MAX_MERGE_CELLS: usize = 1 << 24; + + /// The fix-ups made to a document after the DWG read, returning how many orphaned DGN + /// components were dropped. The document comes from a third-party reader and is hostile. + fn post_process(doc: &mut acadrust::CadDocument) -> usize { + super::fail_in_test("post_process"); + current_style_names(doc); + table_merges(doc); + table_style_rows(doc, false); + keep_sort_handles(doc); + drop_orphaned_dgn_components(doc) + } + + /// Runs `f`, turning a panic into an error (the reader and writer are guarded the same way). + fn guarded(f: impl FnOnce() -> R + std::panic::UnwindSafe) -> Result { + std::panic::catch_unwind(f).map_err(|_| ()) + } + + /// [`table_merges`] visiting at most `budget` cells in all; a range that would pass it is + /// left unmerged. Returns the cells visited. + fn table_merges_within(doc: &mut acadrust::CadDocument, budget: usize) -> usize { + let mut left = budget; for e in doc.entities_mut() { let acadrust::entities::EntityType::Table(t) = e else { continue }; if t.merged_ranges.is_empty() || t.rows.iter().flat_map(|r| &r.cells).any(|c| c.merge_width > 1 || c.merge_height > 1) { @@ -253,6 +276,11 @@ mod native { if r.top_row > bottom || r.left_col > right || rows == 0 || cols == 0 || (r.top_row, r.left_col) == (bottom, right) { continue; } + let area = (bottom - r.top_row + 1).saturating_mul(right - r.left_col + 1); + if area > left { + continue; + } + left -= area; let span = |n: usize| i32::try_from(n + 1).unwrap_or(i32::MAX); for (ri, row) in t.rows.iter_mut().enumerate().take(bottom + 1).skip(r.top_row) { for (ci, cell) in row.cells.iter_mut().enumerate().take(right + 1).skip(r.left_col) { @@ -264,6 +292,7 @@ mod native { } } } + budget - left } /// Draw-order tables (SORTENTSTABLE) keep the sort handles the file gave them. acadrust's DXF @@ -569,14 +598,19 @@ mod native { None if doc.version < MIN_DWG_VERSION => doc.version = MIN_DWG_VERSION, None => {} } - other_layout_owners(&mut doc); - table_style_rows(&mut doc, true); - dimension_flags(&mut doc); - drop_unwritable(&mut doc); - current_dimstyle(&mut doc); - add_variable_dictionary(&mut doc); - current_text_style(&mut doc); - current_layer(&mut doc); + // 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"); + other_layout_owners(&mut doc); + table_style_rows(&mut doc, true); + dimension_flags(&mut doc); + drop_unwritable(&mut doc); + current_dimstyle(&mut doc); + add_variable_dictionary(&mut doc); + current_text_style(&mut doc); + current_layer(&mut doc); + })) + .map_err(|_| "the DXF to DWG conversion failed on this file".to_string())?; std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DwgWriter::write_to_vec(&doc))) .map_err(|_| "the DWG writer failed on this drawing".to_string())? .map_err(|e| format!("DWG write: {e}")) @@ -673,11 +707,60 @@ mod native { } } } + + #[cfg(test)] + mod post_tests { + use super::*; + use acadrust::entities::{CellRange, EntityType, Table}; + + fn doc_with_table(rows: usize, cols: usize, ranges: usize) -> acadrust::CadDocument { + let mut t = Table::new(acadrust::types::Vector3::new(0.0, 0.0, 0.0), rows, cols); + t.merged_ranges = (0..ranges).map(|_| CellRange::new(0, 0, rows - 1, cols - 1)).collect(); + let mut doc = acadrust::CadDocument::new(); + assert!(doc.add_entity(EntityType::Table(Box::new(t))).is_ok()); + doc + } + + /// Overlapping whole-table ranges can't make the merge pass visit more than its budget (#1934). + #[test] + fn merge_work_is_bounded_by_the_cell_budget() { + let mut doc = doc_with_table(10, 10, 50); + assert_eq!(table_merges_within(&mut doc, 250), 200, "two whole-table ranges fit, the rest are skipped"); + let mut doc = doc_with_table(10, 10, 1); + assert_eq!(table_merges_within(&mut doc, usize::MAX), 100); + } + + /// A panic in the post-read fix-ups is an error, not a crash (#1934). + #[test] + fn a_panic_in_post_processing_is_an_error() { + #[allow(clippy::panic)] + let r = guarded(AssertUnwindSafe(|| -> usize { panic!("boom") })); + assert!(r.is_err()); + assert_eq!(guarded(|| 3), Ok(3)); + } + } } #[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}; +// Test-only: the stage ("post_process" or "convert") whose guard the current test checks. The +// stage then panics on entry, so a test through the public API shows whether it is guarded. +#[cfg(all(test, not(target_arch = "wasm32")))] +thread_local! { + static PANIC_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Panics when a test asked for `stage` to fail (see [`PANIC_IN`]); does nothing otherwise. +#[cfg(not(target_arch = "wasm32"))] +#[allow(clippy::panic)] +fn fail_in_test(_stage: &str) { + #[cfg(test)] + if PANIC_IN.with(|p| p.get()) == Some(_stage) { + panic!("test-forced panic in {_stage}"); + } +} + /// The error for a DWG version CADCraft can't write. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] fn unsupported(version: &str) -> String { @@ -710,6 +793,50 @@ pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result, String> { mod tests { use super::*; + /// The DXF of an empty drawing, enough for the bridge to make a small DWG. + #[cfg(not(target_arch = "wasm32"))] + const MINIMAL_DXF: &str = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nEOF\n"; + + /// Makes `stage` panic on the current thread until dropped. + #[cfg(not(target_arch = "wasm32"))] + struct PanicIn; + + #[cfg(not(target_arch = "wasm32"))] + impl PanicIn { + fn at(stage: &'static str) -> Self { + PANIC_IN.with(|p| p.set(Some(stage))); + Self + } + } + + #[cfg(not(target_arch = "wasm32"))] + impl Drop for PanicIn { + fn drop(&mut self) { + PANIC_IN.with(|p| p.set(None)); + } + } + + /// The public read reports a panic in the post-read fix-ups as an error: this fails if the + /// `guarded` call around `post_process` is taken out (#2402). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn reading_a_dwg_survives_a_panic_in_post_processing() { + let dwg = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap(); + assert!(dwg_to_dxf(&dwg).is_ok(), "the DWG reads without the forced panic"); + let _panic = PanicIn::at("post_process"); + let err = dwg_to_dxf(&dwg).unwrap_err(); + assert!(err.contains("the DWG post-processing failed on this file"), "{err}"); + } + + /// The DXF to DWG conversion reports a panic in its fix-ups as an error, not a crash (#2402). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn converting_to_dwg_survives_a_panic_in_the_fix_ups() { + let _panic = PanicIn::at("convert"); + let err = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap_err(); + assert!(err.contains("the DXF to DWG conversion failed on this file"), "{err}"); + } + #[test] fn detects_magic() { assert!(is_dwg(b"AC1032\0\0\0\0")); From 2d2be155dd97212ecc3bb81dec0fe31bcb15d123 Mon Sep 17 00:00:00 2001 From: smacdmac101 <152641296+smacdmac101@users.noreply.github.com> Date: Thu, 29 Oct 2026 21:38:15 -0400 Subject: [PATCH 196/900] fix(engine): refresh attribute baselines after value changes (#2214) * xtask: the test suite and clippy pass on Windows Two Windows-only failures stopped `cargo xtask ci` before it got going on a Windows checkout (CI runs the gate on Linux only, so neither showed): - parity::tests::civil_dates built a SystemTime 115,740,740 days after the epoch (year 318857). Windows' SystemTime ends in the year 30828, so the addition panicked ("overflow when adding duration to `SystemTime`"). That case now checks `civil_from_days` on the day count, which is what it was about, on every platform. - stats.rs imported `walk` for a test that only exists on Unix, so the import was unused on Windows and `clippy -D warnings` refused it. The Unix test calls `super::walk`, as its neighbour calls `super::walk_inner`. Checked on Windows 11 x64: `cargo test --workspace` and `cargo clippy --workspace --all-targets -- -D warnings` both pass. Co-Authored-By: Claude Opus 5.5 * fix(engine): refresh attribute baselines after value changes CC-046: invalidate the derived XY baseline for changed justified attribute values, including small changes inside the writer's imported-font tolerance. Preserve no-op placement, alignment anchors and Aligned/Fit endpoints. Regression reproduced on current upstream; all three focused tests pass. Full cargo xtask ci passed all seven stages on Windows (2558 passing test executions, zero failures, one ignored). Release Trunk web build passed. Browser interaction verification is pending user dismissal of a Windows Security prompt; do not treat the build as a runtime pass. Windows validation prerequisite: original upstream PR #2198 commit a2dd814. Independent of editor/ribbon changes; reverting restores only this setter, its regression tests and corresponding file-format parity record. * fix(io): preserve insertion elevation when refreshing text baselines CC-046 review follow-up to PR #2214 comment 4377706777. Regression reproduced insertion Z 9 becoming 7. Preserve group 10 Z; test DXF independent elevations and document the DWG bridge shared elevation. Full cargo xtask ci passes all seven gates. This separate commit is reversible; reverting it restores elevation loss during baseline recomputation. Existing browser UI verification predates this writer correction. * test(engine): cover global attribute no-ops and two-point exports CC-046 review 5653054817: verify equal-value global JSON and scripted -ATTEDIT preserve imported placement, and Aligned/Fit DXF save/reopen retain both placement points and justification. Validation: cargo xtask ci passed all seven gates on this branch; git diff --check passed. Test-only follow-up, no application change. Depends on CC-046 and unchanged Windows prerequisite #2198. Revert this commit independently to remove only these assertions. Runtime evidence remains separately recorded for the production commits. --------- Co-authored-by: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/attedit.rs | 22 +- .../tests/it/attribute_value_baseline.rs | 203 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/io/src/dxf_write/common.rs | 3 +- docs/file-format-parity.md | 5 +- 5 files changed, 228 insertions(+), 6 deletions(-) create mode 100644 crates/engine/tests/it/attribute_value_baseline.rs diff --git a/crates/engine/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index ad123f0b3..be59474c5 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -3,7 +3,7 @@ //! time or by replacing a string in all of them. Attribute tags match in any case, as in AutoCAD. use cadcraft_doc::color::Color; -use cadcraft_doc::{AttribProps, Common, EntityKind, Handle}; +use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign}; use serde_json::{Map, Value, json}; use crate::cmd::curves::KW; @@ -67,7 +67,7 @@ fn run(s: &mut Session, p: &Value) -> Result { if let EntityKind::Insert(i) = &mut e.kind { for a in &mut i.attribs { if let Some(v) = value_for(&vals, &a.tag) { - a.text.value = v; + set_value(&mut a.text, v); n += 1; } } @@ -130,13 +130,29 @@ fn edit(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&str) -> Option && let Some(a) = ins.attribs.get_mut(k) && let Some(v) = f(&a.text.value).filter(|v| *v != a.text.value) { - a.text.value = v; + set_value(&mut a.text, v); changed = true; } })?; Ok(changed) } +/// Refresh the derived baseline after a value change, even one within the writer's +/// imported-font tolerance. Equal XY points request recomputation on export; retain +/// both elevations and the independent endpoints used by Aligned/Fit text. +fn set_value(text: &mut Text, value: String) { + if text.value == value { + return; + } + text.value = value; + if !matches!((text.halign, text.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)) + && let Some(anchor) = text.align_pt + { + text.insert.x = anchor.x; + text.insert.y = anchor.y; + } +} + /// Change the properties set on attribute `k` of block reference `h`. fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut AttribProps)) -> Result<()> { s.doc_mut()?.modify_entity(h, |e| { diff --git a/crates/engine/tests/it/attribute_value_baseline.rs b/crates/engine/tests/it/attribute_value_baseline.rs new file mode 100644 index 000000000..8f7523e0b --- /dev/null +++ b/crates/engine/tests/it/attribute_value_baseline.rs @@ -0,0 +1,203 @@ +//! Small value changes must not export an imported justified attribute's old baseline. +use cadcraft_doc::{Attrib, Drawing, EntityKind, HAlign, Handle, Text, VAlign}; +use cadcraft_engine::{Input, Session}; +use cadcraft_geom::Vec3; +use serde_json::json; + +const BEFORE: &str = "POWER ADAPTER"; +const AFTER: &str = "POWER ADAPTER."; + +fn fixture() -> (Session, Handle, Handle) { + let mut s = Session::new(); + for (tag, value, y) in [("T", BEFORE, 15), ("U", "ADPT-01", 0)] { + s.execute("attdef", &json!({"tag":tag,"default":value,"at":[0,y],"height":3})).unwrap(); + } + s.execute("line", &json!({"points":[[0,-5],[40,-5]]})).unwrap(); + let handles: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name":"Equipment","handles":handles,"base":[0,0],"keep":"delete"})).unwrap(); + let a = s.execute("insert", &json!({"name":"Equipment","at":[100,200],"scale":2,"rotation":30})).unwrap(); + let b = s.execute("insert", &json!({"name":"Equipment","at":[300,200],"attribs":{"T":"Other"}})).unwrap(); + let a = Handle::parse_hex(a["handle"].as_str().unwrap()).unwrap(); + let b = Handle::parse_hex(b["handle"].as_str().unwrap()).unwrap(); + // Set existing document fields directly: this regression does not require Text Options. + s.doc_mut() + .unwrap() + .modify_entity(a, |e| { + let EntityKind::Insert(i) = &mut e.kind else { panic!("insert") }; + let t = &mut i.attribs[0].text; + t.insert.z = 7.0; + t.align_pt = Some(t.insert); + t.halign = HAlign::Center; + t.valign = VAlign::Top; + }) + .unwrap(); + let imported = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let mut s = Session::empty(); + s.open_drawing(imported, "Imported", None); + (s, a, b) +} + +fn attributes(d: &Drawing, h: Handle) -> Vec { + let EntityKind::Insert(i) = &d.entity(h).unwrap().kind else { panic!("insert") }; + i.attribs.clone() +} + +fn baseline(d: &Drawing, t: &Text) -> cadcraft_geom::Vec2 { + let style = d.text_style(&t.style).unwrap(); + let (h, v) = cadcraft_render::text_align(t.halign, t.valign); + cadcraft_fonts::baseline_start( + &cadcraft_fonts::TextFont::resolve(&style.font), + &t.value, + &cadcraft_fonts::TextParams { + insert: t.insert.xy(), + align_pt: t.align_pt.map(|p| p.xy()), + height: t.height, + rotation: t.rotation, + width_factor: t.width_factor, + oblique: t.oblique, + h, + v, + backwards: style.backwards, + upside_down: style.upside_down, + }, + ) +} + +#[test] +fn all_attribute_value_paths_refresh_small_justified_export_changes() { + for path in ["json", "interactive", "global-json", "global-interactive"] { + let (mut s, a, b) = fixture(); + let before = attributes(s.doc().unwrap(), a); + let other = attributes(s.doc().unwrap(), b); + let definition = s.doc().unwrap().block("Equipment").unwrap().clone(); + match path { + "json" => { + s.execute("attedit", &json!({"handle":a.hex(),"values":{"t":AFTER}})).unwrap(); + } + "interactive" => { + s.start("attedit").unwrap(); + s.input(Input::Pick(vec![a])).unwrap(); + s.input(Input::Text(AFTER.into())).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none()); + } + "global-json" => { + s.execute("-attedit", &json!({"handles":[a.hex()],"tag":"T","find":"ADAPTER","replace":"ADAPTER."})).unwrap(); + } + "global-interactive" => { + s.script("-attedit\nn\nn\nEquipment\nT\n\nADAPTER\nADAPTER.\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + } + _ => panic!("path"), + } + let edited = attributes(s.doc().unwrap(), a); + assert_eq!(edited[0].text.value, AFTER, "{path}"); + assert_eq!(edited[0].text.align_pt, before[0].text.align_pt); + assert_eq!(edited[0].text.insert.z, 7.0); + assert_eq!(edited[1], before[1]); + assert_eq!(attributes(s.doc().unwrap(), b), other); + assert_eq!(s.doc().unwrap().block("Equipment").unwrap(), &definition); + let expected = baseline(s.doc().unwrap(), &edited[0].text); + assert!(expected.dist(before[0].text.insert.xy()) > 0.01, "fixture must change width"); + for name in ["edited.dxf", "edited.dwg"] { + let reopened = cadcraft_io::read(&cadcraft_io::write(s.doc().unwrap(), name).unwrap(), name).unwrap(); + let restored = attributes(&reopened, a); + assert!( + restored[0].text.insert.xy().dist(expected) < 1e-8, + "{path} {name}: stale {:?}, expected {expected:?}", + restored[0].text.insert.xy() + ); + assert_eq!(restored[0].text.align_pt, before[0].text.align_pt); + assert_eq!(restored[0].text.value, AFTER); + assert_eq!(restored[0].text.insert.z, 7.0); + } + s.undo().unwrap(); + assert_eq!(attributes(s.doc().unwrap(), a), before, "{path} undo"); + s.redo().unwrap(); + assert_eq!(attributes(s.doc().unwrap(), a), edited, "{path} redo"); + } +} + +#[test] +fn equal_attribute_values_preserve_an_imported_font_baseline() { + let (mut s, a, _) = fixture(); + // A small imported-font offset must survive a no-op edit (writer tolerance is deliberate). + s.doc_mut() + .unwrap() + .modify_entity(a, |e| { + let EntityKind::Insert(i) = &mut e.kind else { panic!("insert") }; + i.attribs[0].text.insert.x += 0.1; + }) + .unwrap(); + let before = attributes(s.doc().unwrap(), a); + s.execute("attedit", &json!({"handle":a.hex(),"values":{"T":BEFORE}})).unwrap(); + assert_eq!(attributes(s.doc().unwrap(), a), before); + s.start("attedit").unwrap(); + s.input(Input::Pick(vec![a])).unwrap(); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + assert_eq!(attributes(s.doc().unwrap(), a), before); + s.execute("-attedit", &json!({"handles":[a.hex()],"tag":"T","find":"ADAPTER","replace":"ADAPTER"})).unwrap(); + assert_eq!(attributes(s.doc().unwrap(), a), before, "global JSON no-op"); + s.script("-attedit\nn\nn\nEquipment\nT\n\nADAPTER\nADAPTER\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(attributes(s.doc().unwrap(), a), before, "global interactive no-op"); +} + +/// Recomputing a justified baseline must not replace its independent insertion elevation. +#[test] +fn value_edits_preserve_distinct_insertion_and_alignment_elevations_on_export() { + let (mut s, a, _) = fixture(); + s.doc_mut() + .unwrap() + .modify_entity(a, |e| { + let EntityKind::Insert(i) = &mut e.kind else { panic!("insert") }; + i.attribs[0].text.insert.z = 9.0; + }) + .unwrap(); + let anchor = attributes(s.doc().unwrap(), a)[0].text.align_pt; + s.execute("attedit", &json!({"handle":a.hex(),"values":{"T":AFTER}})).unwrap(); + for name in ["elevations.dxf", "elevations.dwg"] { + let reopened = cadcraft_io::read(&cadcraft_io::write(s.doc().unwrap(), name).unwrap(), name).unwrap(); + let restored = attributes(&reopened, a); + assert_eq!(restored[0].text.insert.z, 9.0, "{name}: insertion elevation"); + assert_eq!(restored[0].text.align_pt.map(|p| p.xy()), anchor.map(|p| p.xy()), "{name}: alignment XY"); + if name.ends_with(".dxf") { + assert_eq!(restored[0].text.align_pt, anchor, "DXF retains independent alignment elevation"); + } else { + // The DWG bridge uses one text elevation for both points. + assert_eq!(restored[0].text.align_pt.unwrap().z, 9.0); + } + } +} + +#[test] +fn value_edits_preserve_left_baseline_and_two_point_placements() { + for horizontal in [HAlign::Left, HAlign::Aligned, HAlign::Fit] { + let (mut s, a, _) = fixture(); + s.doc_mut() + .unwrap() + .modify_entity(a, |e| { + let EntityKind::Insert(i) = &mut e.kind else { panic!("insert") }; + let t = &mut i.attribs[0].text; + t.halign = horizontal; + t.valign = VAlign::Baseline; + t.insert = Vec3::new(10.0, 20.0, 7.0); + t.align_pt = (horizontal != HAlign::Left).then_some(Vec3::new(40.0, 30.0, 9.0)); + }) + .unwrap(); + let before = attributes(s.doc().unwrap(), a); + s.execute("attedit", &json!({"handle":a.hex(),"values":{"T":AFTER}})).unwrap(); + let mut expected = before; + expected[0].text.value = AFTER.into(); + assert_eq!(attributes(s.doc().unwrap(), a), expected); + if horizontal != HAlign::Left { + let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let restored = attributes(&reopened, a); + assert_eq!(restored[0].text.insert, expected[0].text.insert); + assert_eq!(restored[0].text.align_pt, expected[0].text.align_pt); + assert_eq!(restored[0].text.halign, horizontal); + assert_eq!(restored[0].text.value, AFTER); + } + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 8e20e6fa8..ed88a2316 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -10,6 +10,7 @@ mod attedit_prompts; mod attrib_modes; mod attrib_props; mod attribute_tools; +mod attribute_value_baseline; mod block_description; mod block_keep; mod block_redefine; diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index bf8fad449..6ba3ce8ef 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -237,7 +237,8 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 { upside_down: ts.upside_down, }; let q = cadcraft_fonts::baseline_start(&cadcraft_fonts::TextFont::resolve(&ts.font), &t.value, &p); - if q.is_finite() { Vec3::new(q.x, q.y, a.z) } else { t.insert } + // Justification recalculates the baseline in XY; group 10 keeps its own elevation. + if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert } } pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 291c9b202..d2af85803 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LAYOUT SAveas writes a layout as a DWT template) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (attribute value edits refresh exported baselines) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -75,7 +75,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137) | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); changed attribute values refresh justified baselines, including small width changes | ATTDEF prompt kept (#137); unchanged values retain imported-font placement | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written for every associated kind — linear/aligned, angular, radial/diametric, ordinate and arc length — and read back without CADCraft's xdata (#1651) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-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-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) | From 7546277128b82ce3c89f0fdf6a663bbea2ad6bc4 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 29 Oct 2026 21:39:34 -0400 Subject: [PATCH 197/900] fmt: rustfmt the DIMTMOVE 2 clearance port (#2302) Co-Authored-By: Claude Opus 5.5 --- crates/render/src/dim/linear.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/crates/render/src/dim/linear.rs b/crates/render/src/dim/linear.rs index 8127aef8f..da1b2a746 100644 --- a/crates/render/src/dim/linear.rs +++ b/crates/render/src/dim/linear.rs @@ -151,9 +151,7 @@ fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { state.side_out = if (config.dimension.defpt.xy() - state.p1).dot(state.n) >= 0.0 { state.n } else { -state.n }; state.text_axis = Vec2::from_angle(state.angle); let clearance = |axis: Vec2, across: f64| { - config.gap - + state.text_width * state.text_axis.dot(axis).abs() / 2.0 - + state.text_height * state.text_axis.perp().dot(axis).abs() * across + config.gap + state.text_width * state.text_axis.dot(axis).abs() / 2.0 + state.text_height * state.text_axis.perp().dot(axis).abs() * across }; // Empirical #2004 match: 0.595× height with SHX and 0.601× with TrueType. let off_along = |axis: Vec2| clearance(axis, if st.text_above == 1 { 0.6 } else { 0.5 }); @@ -186,11 +184,8 @@ fn position_linear_text(config: &DimConfig<'_>, state: &mut LinearDimState) { // Half the text height either way, whatever DIMTAD says (#2222). let clear = clearance(state.side_out, 0.5); let lift = clear + 2.0 * config.arrow_size.max(config.tick_size); - state.text_mid = if st.text_move == 1 { - mid + state.side_out * lift + state.u * state.half_extent - } else { - mid + state.side_out * (lift + clear) - }; + state.text_mid = + if st.text_move == 1 { mid + state.side_out * lift + state.u * state.half_extent } else { mid + state.side_out * (lift + clear) }; } else if !config.dimension.user_text_pos { state.text_mid = state.along_center + state.offset; } From fc8270d8c52acd6dba69e221b889193b1a497739 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 12:47:03 +1100 Subject: [PATCH 198/900] 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 b3158b56a8a2024681b33ad1a7655cc94bf82484 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 29 Oct 2026 22:14:18 -0400 Subject: [PATCH 199/900] CI: workflows only call craft-common-actions at @main (#2473) AGENTS.md (and CLAUDE.md where present) gets a CI workflows section: workflows only call craft-common-actions at @main, with no other jobs; feature and fix PRs don't touch CI and link or open a craft-common-actions issue (a PR only for a small fix that is safe for every app and does not increase CI time); legacy jobs aren't added to and move only as their own task, staying until a shared workflow runs them. windows-arm64.yml moves from its SHA pin to @main. The pinned revision is on craft-common-actions main and the workflow (and the actions it calls) is identical there, so nothing changes in behaviour. --- .github/workflows/windows-arm64.yml | 4 ++-- AGENTS.md | 5 +++++ CLAUDE.md | 5 +++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/workflows/windows-arm64.yml b/.github/workflows/windows-arm64.yml index a671ff2f2..167839e9e 100644 --- a/.github/workflows/windows-arm64.yml +++ b/.github/workflows/windows-arm64.yml @@ -25,8 +25,8 @@ permissions: jobs: windows-arm64: - # Immutable supporting workflow revision until the new install contract lands upstream. - uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f + # 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/windows-arm64.yml@main with: app-name: cadcraft app-dir: CADCraft diff --git a/AGENTS.md b/AGENTS.md index e436894b2..e3d7418d7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,3 +66,8 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr GitHub profiles). Never hand-edit `contributors.json`. - Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also re-verifies who wrote each `people.toml` entry; `--check` only verifies). + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/CLAUDE.md b/CLAUDE.md index 33e6a2121..8e4a1fdfa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,3 +47,8 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr ## Roadmap `ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. It follows craftrules' `standards/progress-docs.md`: the assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the affected rows and the docs' status lines and revision history. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. From adc18768095b88dda9c22da9bfb1a129d602beec Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 13:15:13 +1100 Subject: [PATCH 200/900] 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 201/900] 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 f8b09e92e55e869a0c5199f9f447e487fde0aeda Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 29 Oct 2026 22:22:29 -0400 Subject: [PATCH 202/900] deps: bump tar, zip, roxmltree, rustls-webpki and symphonia to their latest versions (#2475) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `zip`: 9.1.1 → 9.1.3 Lockfile only. --- Cargo.lock | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 34cfc44cc..1159481f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -268,7 +268,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.59.0", "wl-clipboard-rs", "x11rb", ] @@ -1642,7 +1642,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3434,7 +3434,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4029,7 +4029,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4086,7 +4086,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4561,10 +4561,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5470,7 +5470,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6114,9 +6114,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.1" +version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "518b847fd864440c379748ad684c449f293af68978a485a4ff16f7c901c1f7c4" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ "crc32fast", "flate2", From 7f590216eb5bca3adb6ef4f1500bc89c71445f74 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 13:34:46 +1100 Subject: [PATCH 203/900] 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 204/900] 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 205/900] 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 206/900] 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 86d010eaac0d458a528d91705c0a2118f80fa528 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 14:59:16 +1100 Subject: [PATCH 207/900] DXF: SAT text is groups 1 and 3 of the modeler subclass; only ASM_Data records keep geometry (#2334) sat_text_acis now looks for groups 1 and 3 inside AcDbModelerGeometry only (all groups when a file has no subclass markers), and the data store counts an entity as stored only when its ACDSRECORD holds ASM_Data. The writer and the reader share one record splitter (data_store_records). --- crates/doc/src/foreign.rs | 46 ++++++++++++++++++++++++--- crates/io/src/dxf_raw.rs | 6 +--- crates/io/tests/it/acis_data_store.rs | 29 +++++++++++++++++ 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 60000c6dd..133c525e2 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -89,9 +89,17 @@ impl Foreign { && self.data_store.is_empty() } - /// The entities the data store has records for (their 320 handles). + /// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity + /// (320) that holds its `ASM_Data`. A 320 without one doesn't keep an entity's geometry. pub fn data_store_entities(&self) -> std::collections::BTreeSet { - self.data_store.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim())).collect() + let mut out = std::collections::BTreeSet::new(); + for rec in data_store_records(&self.data_store) { + let is_record = rec.first().is_some_and(|t| t.value.trim().eq_ignore_ascii_case("ACDSRECORD")); + if is_record && rec.iter().any(|t| t.code == 2 && t.value.trim().eq_ignore_ascii_case("ASM_Data")) { + out.extend(rec.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim()))); + } + } + out } } @@ -99,9 +107,7 @@ impl Foreign { /// (groups 1 and 3), which DXF 2013 and later no longer has: those files keep it in the data /// store section, so an entity with SAT text and no record there can't be written to one (#2334). pub fn sat_text_acis(u: &crate::Unknown, handle: Handle, stored: &std::collections::BTreeSet) -> bool { - ["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) - && !stored.contains(&handle) - && u.tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 1 || r.code == 3) + ["3DSOLID", "REGION", "BODY"].iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) && !stored.contains(&handle) && has_sat_text(&u.tags) } /// The entities a DXF of 2013 or later leaves out because they hold SAT-text ACIS data @@ -128,3 +134,33 @@ pub fn sat_text_dropped(d: &crate::Drawing) -> BTreeMap { pub fn xref_dependent(name: &str) -> bool { name.contains('|') } + +/// The records of a data store section's groups: each starts at a `0` group and runs to the next +/// (the section's own groups before the first record are not part of one). +pub fn data_store_records(tags: &[RawTag]) -> Vec<&[RawTag]> { + let mut out = Vec::new(); + let mut start = tags.iter().position(|t| t.code == 0).unwrap_or(tags.len()); + while start < tags.len() { + let end = tags.iter().skip(start + 1).position(|t| t.code == 0).map_or(tags.len(), |k| start + 1 + k); + out.push(tags.get(start..end).unwrap_or(&[])); + start = end; + } + out +} + +/// Whether an entity's groups hold SAT text: groups 1 and 3 inside its `AcDbModelerGeometry` +/// subclass. A file of a version before the subclass markers has no `100` groups: all of its +/// groups (before the extended data) are the entity's. +fn has_sat_text(tags: &[RawTag]) -> bool { + let own = tags.iter().take_while(|r| r.code < 1000); + let marked = tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 100); + let mut in_modeler = !marked; + for r in own { + if r.code == 100 { + in_modeler = r.value.trim().eq_ignore_ascii_case("AcDbModelerGeometry"); + } else if in_modeler && (r.code == 1 || r.code == 3) { + return true; + } + } + false +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 5a2aa398c..7856a24b8 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -601,17 +601,13 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { let first = ds.iter().position(|t| t.code == 0).unwrap_or(ds.len()); out.extend(ds.iter().take(first).map(tag)); let mut records = 0usize; - let mut i = first; - while i < ds.len() { - let end = ds.iter().skip(i + 1).position(|t| t.code == 0).map_or(ds.len(), |k| i + 1 + k); - let rec = ds.get(i..end).unwrap_or(&[]); + for rec in cadcraft_doc::foreign::data_store_records(ds) { let is_record = rec.first().is_some_and(|t| t.value.trim().eq_ignore_ascii_case("ACDSRECORD")); let owner = rec.iter().find(|t| t.code == 320).map(|t| norm(&t.value)); if !is_record || owner.as_ref().is_some_and(|h| written.contains(h)) { records += usize::from(is_record); out.extend(rec.iter().map(tag)); } - i = end; } if records == 0 { return; diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index 308b532d9..4f8f455b4 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -156,3 +156,32 @@ fn sat_text_solids_stay_in_dwg_2018_and_xref_contents_are_not_counted() { x.blocks.insert("REF|PART".into(), std::sync::Arc::new(dep)); assert_eq!(cadcraft_doc::foreign::sat_text_dropped(&x), [("REGION".to_string(), 1)].into(), "only the model-space region"); } + +/// Only groups 1 and 3 of the modeler geometry subclass are SAT text, and only a record holding +/// the entity's ASM_Data keeps its geometry in the data store (#2334). +#[test] +fn sat_text_is_told_by_its_subclass_and_a_geometry_record() { + use cadcraft_doc::foreign::{Foreign, sat_text_acis}; + use cadcraft_doc::{Handle, RawTag, Unknown}; + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let solid = |tags: Vec| Unknown { dxf_type: "3DSOLID".into(), tags }; + let none = std::collections::BTreeSet::new(); + let h = Handle(0x2B); + // A stray 1 or 3 outside AcDbModelerGeometry is not SAT text. + let stray = + solid(vec![tag(100, "AcDbEntity"), tag(1, "name"), tag(100, "AcDbModelerGeometry"), tag(70, "1"), tag(100, "AcDb3dSolid"), tag(3, "x")]); + assert!(!sat_text_acis(&stray, h, &none)); + let real = solid(vec![tag(100, "AcDbEntity"), tag(100, "AcDbModelerGeometry"), tag(70, "1"), tag(1, "400 1 1 0"), tag(100, "AcDb3dSolid")]); + assert!(sat_text_acis(&real, h, &none)); + // Without subclass markers (an old file) the groups are the entity's own. + assert!(sat_text_acis(&solid(vec![tag(8, "0"), tag(1, "400 1 1 0")]), h, &none)); + + // A 320 in the data store without an ASM_Data record doesn't keep the geometry. + let store = |asm: bool| { + let mut t = vec![tag(0, "ACDSRECORD"), tag(90, "1"), tag(320, "2B")]; + t.push(tag(2, if asm { "ASM_Data" } else { "Other" })); + Foreign { data_store: t, ..Foreign::default() } + }; + assert!(store(true).data_store_entities().contains(&h)); + assert!(store(false).data_store_entities().is_empty()); +} From 28428b0cc381ed7c59b94d52e9c866a4da8e6695 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 15:27:25 +1100 Subject: [PATCH 208/900] 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 d6de2db6dbf5ae39ae9f78a54c0e0cd481d67239 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 30 Oct 2026 01:28:46 -0400 Subject: [PATCH 209/900] Update prompt shows the app icon and accent color instead of a letter (#2479) UPDATE_APP (native builds; craft-update is a native-only dependency) carries our 128 px icon and accent (#3ea6e8, its colour in ArtCraft Launcher). The updater, the self-update helper and craft-update's startup prompt all get them through crate::UPDATE_APP; the prompt draws the icon, the accent and "by ArtCraft" (craft-update's default developer). craft-update is pinned to storytold/craft-libs main at 1065653e7 (#434). Clippy fixes for Rust 1.99 in untouched code (same logic): - crates/constraints/src/auto.rs - crates/engine/src/audit.rs - crates/engine/src/cmd/inquiry.rs - crates/engine/src/mtext_edit.rs - crates/geom/src/nurbs.rs - crates/io/src/dxf_raw.rs - crates/io/src/dxf_read/document.rs - crates/render/src/text.rs - crates/ui-egui/src/cmdline.rs - xtask/src/layers.rs --- Cargo.lock | 3 ++- Cargo.toml | 3 ++- apps/cadcraft/src/main.rs | 2 +- crates/constraints/src/auto.rs | 12 ++++-------- crates/engine/src/audit.rs | 16 ++++++---------- crates/engine/src/cmd/inquiry.rs | 14 +++++--------- crates/engine/src/mtext_edit.rs | 8 +++----- crates/geom/src/nurbs.rs | 2 +- crates/io/src/dxf_raw.rs | 6 ++---- crates/io/src/dxf_read/document.rs | 12 +++++------- crates/render/src/text.rs | 2 +- crates/ui-egui/src/cmdline.rs | 12 +++++------- crates/ui-egui/src/lib.rs | 9 +++++++++ crates/ui-egui/src/updates_ui.rs | 3 +-- xtask/src/layers.rs | 6 ++---- 15 files changed, 49 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1159481f5..fd4345fb1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1191,13 +1191,14 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +source = "git+https://github.com/storytold/craft-libs?rev=1065653e75854e9c17e1ff563acdd344c1b185f0#1065653e75854e9c17e1ff563acdd344c1b185f0" dependencies = [ "chrono", "dunce", "egui", "flate2", "getrandom 0.3.4", + "image", "log", "plist", "semver", diff --git a/Cargo.toml b/Cargo.toml index 1d4d7c530..220f29403 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,7 +65,8 @@ eframe = { version = "0.37", default-features = false } egui-wgpu = "0.37" # Monotonic time on native and web (performance.now on wasm). web-time = "1.1" -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] } +# craft-update with storytold/craft-libs#434: the update prompt shows the app's icon, accent and developer. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1065653e75854e9c17e1ff563acdd344c1b185f0", features = ["egui"] } rfd = "0.17" arboard = { version = "3.6", default-features = false } diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 19546d6ce..4d7bdc39b 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -218,7 +218,7 @@ fn main() -> eframe::Result { let logger = logging::install(); // The update helper relaunches this binary after a self-update; it runs and exits here. #[cfg(not(target_arch = "wasm32"))] - if let Some(done) = craft_update::self_update::finish(&craft_update::suite::CADCRAFT, &std::env::args_os().skip(1).collect::>()) { + if let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { if let Err(e) = done { eprintln!("CADCraft update helper failed: {e}"); std::process::exit(1); diff --git a/crates/constraints/src/auto.rs b/crates/constraints/src/auto.rs index fe7764205..211be6b93 100644 --- a/crates/constraints/src/auto.rs +++ b/crates/constraints/src/auto.rs @@ -52,15 +52,11 @@ fn collect(d: &Drawing, handles: &[Handle]) -> Geo { g.curves.push((GeomRef::whole(h), ga.center, a.radius)); } } - EntityKind::Circle(c) => { - if c.center.is_finite() && c.radius.is_finite() { - g.curves.push((GeomRef::whole(h), c.center.xy(), c.radius)); - } + EntityKind::Circle(c) if c.center.is_finite() && c.radius.is_finite() => { + g.curves.push((GeomRef::whole(h), c.center.xy(), c.radius)); } - EntityKind::Point(p) => { - if p.p.is_finite() { - g.points.push((GeomRef::whole(h), p.p.xy())); - } + EntityKind::Point(p) if p.p.is_finite() => { + g.points.push((GeomRef::whole(h), p.p.xy())); } EntityKind::LwPolyline(p) => { let n = p.vertices.len(); diff --git a/crates/engine/src/audit.rs b/crates/engine/src/audit.rs index f78de7efe..c055bff25 100644 --- a/crates/engine/src/audit.rs +++ b/crates/engine/src/audit.rs @@ -460,17 +460,13 @@ fn references(d: &mut Drawing, out: &mut Vec) { m.style = "Standard".into(); } } - EntityKind::Table(t) => { - if !has_name(&d.table_styles, &t.style, |s| &s.name) { - note("table style", &t.style); - t.style = "Standard".into(); - } + EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => { + note("table style", &t.style); + t.style = "Standard".into(); } - EntityKind::Leader(l) => { - if !ok_dim(d, &l.style) { - note("dimension style", &l.style); - l.style = "Standard".into(); - } + EntityKind::Leader(l) if !ok_dim(d, &l.style) => { + note("dimension style", &l.style); + l.style = "Standard".into(); } EntityKind::Dimension(dim) => { if !ok_dim(d, &dim.style) { diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index c7f59a0cf..0fa342e23 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -840,11 +840,9 @@ impl Interactive for DistM { let model = model_points(&self.sources); s.echo(format!("Distance = {}", fmt_d(s, path_len(model.as_deref().unwrap_or(pts), &self.bulges)))); } - Input::Keyword(k) if k == "Undo" => { - if pts.len() > 1 { - self.arcs.undo(pts, &mut self.bulges); - self.sources.pop(); - } + Input::Keyword(k) if k == "Undo" && pts.len() > 1 => { + self.arcs.undo(pts, &mut self.bulges); + self.sources.pop(); } Input::Keyword(k) if k == "Length" => self.length = true, Input::Keyword(k) if k == "Total" => return self.total(s, false), @@ -852,10 +850,8 @@ impl Interactive for DistM { self.arcs.close(pts, &mut self.bulges)?; return self.total(s, true); } - Input::Keyword(k) => { - if !self.arcs.keyword(&k, pts) { - s.echo(format!("{k}: not available yet")); - } + Input::Keyword(k) if !self.arcs.keyword(&k, pts) => { + s.echo(format!("{k}: not available yet")); } Input::Enter => return self.total(s, false), _ => {} diff --git a/crates/engine/src/mtext_edit.rs b/crates/engine/src/mtext_edit.rs index 30da0b897..97ecede6f 100644 --- a/crates/engine/src/mtext_edit.rs +++ b/crates/engine/src/mtext_edit.rs @@ -136,11 +136,9 @@ impl Formatted { i += 2; match code { None => {} - Some('P') => { - if f.paras.len() < MAX_PARAS { - f.push_char('\n', &cur); - f.paras.push(props.clone()); - } + Some('P') if f.paras.len() < MAX_PARAS => { + f.push_char('\n', &cur); + f.paras.push(props.clone()); } Some(c @ ('\\' | '{' | '}')) => f.push_char(c, &cur), Some('L') => cur.underline = true, diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 5268203b1..104ba8d3c 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -487,7 +487,7 @@ impl Spline { /// Arc length between parameters `a` and `b` (adaptive Gauss–Legendre over each knot span). pub fn length_between(&self, a: f64, b: f64) -> f64 { - if !self.is_valid() || !(a.is_finite() && b.is_finite()) { + if !(self.is_valid() && a.is_finite() && b.is_finite()) { return 0.0; } let (lo, hi) = self.domain(); diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 0154b01d3..9b755f80f 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -135,10 +135,8 @@ fn head(tags: &[Tag]) -> Head { h.has_reactors |= group.as_deref() == Some("ACAD_REACTORS"); } (_, Some("ACAD_REACTORS")) => h.reactors.push(norm(&t.str())), - (_, Some("ACAD_XDICTIONARY")) => { - if h.xdict.is_none() { - h.xdict = Some(norm(&t.str())); - } + (_, Some("ACAD_XDICTIONARY")) if h.xdict.is_none() => { + h.xdict = Some(norm(&t.str())); } (_, Some(_)) => {} (5 | 105, None) if h.handle.is_none() => h.handle = Some(norm(&t.str())), diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 02ea0f532..d732f4450 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -35,13 +35,11 @@ pub(super) fn parse_entities( extra = more; kindent = Some((c, k)); } - "INSERT" => { - if t.i(66) == Some(1) { - let ins_layer = kindent.as_ref().map(|(c, _)| c.layer.clone()).unwrap_or_default(); - let attribs = insert_attribs(recs, &mut i, &ins_layer); - if let Some((_, EntityKind::Insert(ins))) = kindent.as_mut() { - ins.attribs = attribs; - } + "INSERT" if t.i(66) == Some(1) => { + let ins_layer = kindent.as_ref().map(|(c, _)| c.layer.clone()).unwrap_or_default(); + let attribs = insert_attribs(recs, &mut i, &ins_layer); + if let Some((_, EntityKind::Insert(ins))) = kindent.as_mut() { + ins.attribs = attribs; } } // A VERTEX or ATTRIB with no POLYLINE or INSERT before it; a stray SEQEND holds nothing. diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 1f80d7af4..8e692facd 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -77,7 +77,7 @@ pub(super) fn mesh(g: &TextGlyph, xf: Mat3, pixel: f64) -> Arc { let contours = ttf::glyph_contours(&g.face, g.gid); let points = contours.iter().map(Vec::len).try_fold(0usize, usize::checked_add); // Font data is untrusted; don't hand unbounded or invalid paths to the tessellator. - if !points.is_some_and(|n| n <= MAX_POINTS) || contours.iter().flatten().any(|p| !p.is_finite() || p.x.abs().max(p.y.abs()) > 1.0e6) { + if points.is_none_or(|n| n > MAX_POINTS) || contours.iter().flatten().any(|p| !p.is_finite() || p.x.abs().max(p.y.abs()) > 1.0e6) { return Arc::new(Mesh { contours: Arc::default(), triangles: Vec::new() }); } let contours = match detail { diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index d78561551..9d8bd9821 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -379,13 +379,11 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { app.cmd.buffer.pop(); } } - Key::ArrowUp if !modifiers.any() => { - if !app.cmd.history.is_empty() { - let n = app.cmd.history.len(); - let pos = app.cmd.history_pos.map(|p| p.saturating_sub(1)).unwrap_or(n - 1); - app.cmd.history_pos = Some(pos); - app.cmd.buffer = app.cmd.history.get(pos).cloned().unwrap_or_default(); - } + Key::ArrowUp if !modifiers.any() && !app.cmd.history.is_empty() => { + let n = app.cmd.history.len(); + let pos = app.cmd.history_pos.map(|p| p.saturating_sub(1)).unwrap_or(n - 1); + app.cmd.history_pos = Some(pos); + app.cmd.buffer = app.cmd.history.get(pos).cloned().unwrap_or_default(); } Key::ArrowDown if !modifiers.any() => { if !options_key(app, 1) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 22e325cbe..311dd4cbf 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,6 +8,15 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +/// CADCraft as craft-update knows it, with its 128 px icon and accent colour: the update +/// prompt shows both, and an AppImage's menu entry gets the icon. +#[cfg(not(target_arch = "wasm32"))] +pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { + icon_png: Some(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.cadcraft.png")), + accent: Some([0x3e, 0xa6, 0xe8]), + ..craft_update::suite::CADCRAFT +}; + pub mod aliasdlg; pub mod animation; pub mod autosave; diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 1bd05c6f8..ffc625767 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -2,7 +2,6 @@ //! Updates… (desktop only; the web build is always the latest). The flow itself is //! `craft_update::updater::Updater`. -use craft_update::suite::CADCRAFT; use craft_update::updater::{Action, Status, Updater}; use crate::CadApp; @@ -21,7 +20,7 @@ pub struct Runtime { impl Default for Runtime { fn default() -> Self { - Self { updater: Updater::new(&CADCRAFT, VERSION), enabled: false, check_requested: false } + Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false } } } diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index aab245784..c23825d11 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -167,10 +167,8 @@ pub fn check(crates: &[Crate]) -> Vec { match classify(&d.name) { // Unregistered deps are reported on their own entry. None => {} - Some(Class::Testkit) => { - if d.kind != DepKind::Dev { - out.push(Violation::TestkitAsNormalDep { krate: c.name.clone() }); - } + Some(Class::Testkit) if d.kind != DepKind::Dev => { + out.push(Violation::TestkitAsNormalDep { krate: c.name.clone() }); } Some(dc) => { let to = dc.layer().unwrap_or(u8::MAX); From f536bf406f01541006c81deec47ec842acc83158 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 30 Oct 2026 02:35:23 -0400 Subject: [PATCH 210/900] UPD.1: honor pretend versions and restore dev-testkit checks (#2486) --- Cargo.lock | 2 +- Cargo.toml | 4 ++-- contributors/people.toml | 3 +++ xtask/src/layers.rs | 2 ++ 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fd4345fb1..51693203d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1191,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1065653e75854e9c17e1ff563acdd344c1b185f0#1065653e75854e9c17e1ff563acdd344c1b185f0" +source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116" dependencies = [ "chrono", "dunce", diff --git a/Cargo.toml b/Cargo.toml index 220f29403..da6bca3b4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,8 +65,8 @@ eframe = { version = "0.37", default-features = false } egui-wgpu = "0.37" # Monotonic time on native and web (performance.now on wasm). web-time = "1.1" -# craft-update with storytold/craft-libs#434: the update prompt shows the app's icon, accent and developer. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1065653e75854e9c17e1ff563acdd344c1b185f0", features = ["egui"] } +# craft-update: app-specific pretend versions apply to startup and manual checks. +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] } rfd = "0.17" arboard = { version = "3.6", default-features = false } diff --git a/contributors/people.toml b/contributors/people.toml index 101a329ac..28564415e 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -96,3 +96,6 @@ real_name = "Doan Huynh Huu Khuong" display_name = "Doan Huynh Huu Khuong" sync_github_name = false + +[people.dylanmtaylor] +sync_github_name = true diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index c23825d11..d8db1c526 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -170,6 +170,8 @@ pub fn check(crates: &[Crate]) -> Vec { Some(Class::Testkit) if d.kind != DepKind::Dev => { out.push(Violation::TestkitAsNormalDep { krate: c.name.clone() }); } + // Test support is allowed as a dev-dependency, regardless of its layer. + Some(Class::Testkit) => {} Some(dc) => { let to = dc.layer().unwrap_or(u8::MAX); if to >= layer && !(to == layer && intra_layer_allowed(&c.name, &d.name)) { From 590b97a3211743a780de5996f7e2dadb1918879d Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 18:42:24 +1100 Subject: [PATCH 211/900] Save note: QSAVE reports by the version it writes, not a `version` it ignores (#2334) QSAVE takes no version and writes the drawing's own, but the SAT-text note read a `version` passed to it, so `qsave {version: 2010}` on a 2018 drawing skipped the note while still leaving the solids out. Only SAVEAS's requested version now picks the reporting branch. Test: saving_sat_text_solids_as_dxf_2013_reports_them (qsave case fails without the fix). --- crates/engine/src/cmd/file.rs | 10 ++++++---- crates/engine/tests/save_reports_not_saved.rs | 5 +++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 28c8d66be..e91bbd9da 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -613,10 +613,11 @@ fn report_not_saved(s: &mut Session, r: &mut Value, lost: &std::collections::BTr } /// Save, then report the entities the file couldn't keep (nothing is dropped silently). -fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> Result) -> Result { +fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> Result, asked: Option) -> Result { // What the file will hold depends on the version it is saved as (the data store from 2013). + // QSAVE takes no `version` and keeps the drawing's own; SAVEAS writes the one asked for. let path = str_param(p, "path").map(str::to_string).or_else(|| s.state().ok().and_then(|st| st.path.clone())).unwrap_or_default(); - let version = save_options("save", p).ok().and_then(|o| o.version).unwrap_or_else(|| drawing_version(s, &path)); + let version = asked.unwrap_or_else(|| drawing_version(s, &path)); let lost = s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default(); let mut r = run(s, p)?; if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) { @@ -628,11 +629,12 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R } fn run_qsave_reporting(s: &mut Session, p: &Value) -> Result { - save_reporting(s, p, run_save) + save_reporting(s, p, run_save, None) } fn run_saveas_reporting(s: &mut Session, p: &Value) -> Result { - save_reporting(s, p, run_saveas) + let asked = save_options("saveas", p)?.version; + save_reporting(s, p, run_saveas, asked) } const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 839c2489b..5472254a1 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -107,6 +107,11 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() { assert_eq!(r["notSaved"], json!({ "REGION": 1 })); assert!(s.log.iter().any(|l| l.contains("Not saved in the DXF file") && l.contains("1 REGION")), "{:?}", s.log); + // QSAVE takes no version: a `version` passed to it doesn't change what it writes (the + // drawing's own 2018), so the note still comes. + let r = s.execute("qsave", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap(); + assert_eq!(r["notSaved"], json!({ "REGION": 1 })); + let n = s.log.len(); let r = s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": 2010 })).unwrap(); let _ = std::fs::remove_file(&path); From 7baa9703818416d132e88e0978c8de83a75ef648 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 19:18:41 +1100 Subject: [PATCH 212/900] Save note: a data store record stores its first entity; a DWG keeps SAT-text solids (#2334) The writer keeps an ACDSRECORD by its first 320 only, so data_store_entities now credits that handle alone (one shared rule, data_store_owner). The DWG writer converts a solid's SAT text itself at any version, so not_saved_as no longer lists solids that hold SAT text as left out of a DWG. --- crates/doc/src/foreign.rs | 10 ++++++++-- crates/engine/src/cmd/file.rs | 6 +++++- crates/engine/tests/save_reports_not_saved.rs | 15 +++++++++++++++ crates/io/src/dxf_raw.rs | 2 +- crates/io/tests/it/acis_data_store.rs | 11 +++++++++++ 5 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 133c525e2..dbae3ab49 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -96,7 +96,7 @@ impl Foreign { for rec in data_store_records(&self.data_store) { let is_record = rec.first().is_some_and(|t| t.value.trim().eq_ignore_ascii_case("ACDSRECORD")); if is_record && rec.iter().any(|t| t.code == 2 && t.value.trim().eq_ignore_ascii_case("ASM_Data")) { - out.extend(rec.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim()))); + out.extend(data_store_owner(rec).and_then(|t| Handle::parse_hex(t.value.trim()))); } } out @@ -151,7 +151,7 @@ pub fn data_store_records(tags: &[RawTag]) -> Vec<&[RawTag]> { /// Whether an entity's groups hold SAT text: groups 1 and 3 inside its `AcDbModelerGeometry` /// subclass. A file of a version before the subclass markers has no `100` groups: all of its /// groups (before the extended data) are the entity's. -fn has_sat_text(tags: &[RawTag]) -> bool { +pub fn has_sat_text(tags: &[RawTag]) -> bool { let own = tags.iter().take_while(|r| r.code < 1000); let marked = tags.iter().take_while(|r| r.code < 1000).any(|r| r.code == 100); let mut in_modeler = !marked; @@ -164,3 +164,9 @@ fn has_sat_text(tags: &[RawTag]) -> bool { } false } + +/// The group naming the entity a data store record belongs to: its first `320`. A record is kept +/// or dropped by this handle alone, in the writer and wherever the store is read. +pub fn data_store_owner(record: &[RawTag]) -> Option<&RawTag> { + record.iter().find(|t| t.code == 320) +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e91bbd9da..0bccbfb4f 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -550,7 +550,11 @@ 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) { + // A DWG writer converts SAT text to its own form at any version, and from 2013 a data + // store record keeps the geometry too: neither loses the solid. + if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) + && (stored.contains(&e.handle) || cadcraft_doc::foreign::has_sat_text(&u.tags)) + { 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 5472254a1..d50b1a503 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -144,3 +144,18 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() { let _ = std::fs::remove_file(&path); assert_eq!(r["notSaved"], json!({ "REGION": 1 })); } + +/// A DWG writer converts a solid's SAT text itself (at any version), so a DWG save doesn't list +/// solids that hold it as left out; ones with neither SAT text nor a data store record are (#2334). +#[test] +fn a_dwg_keeps_solids_that_hold_sat_text() { + use cadcraft_engine::cmd::file::{Version, not_saved_as}; + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let solid = |tags: Vec| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags }); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 1 1 0")])).unwrap(); + d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap(); + for v in [Version::R2010, Version::R2018] { + assert_eq!(not_saved_as(&d, v), [("3DSOLID".to_string(), 1)].into_iter().collect(), "{v:?}"); + } +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 7856a24b8..9efb5b07d 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -603,7 +603,7 @@ pub(crate) fn data_store(tags: &mut Vec, d: &Drawing, modern: bool) { let mut records = 0usize; for rec in cadcraft_doc::foreign::data_store_records(ds) { let is_record = rec.first().is_some_and(|t| t.value.trim().eq_ignore_ascii_case("ACDSRECORD")); - let owner = rec.iter().find(|t| t.code == 320).map(|t| norm(&t.value)); + let owner = cadcraft_doc::foreign::data_store_owner(rec).map(|t| norm(&t.value)); if !is_record || owner.as_ref().is_some_and(|h| written.contains(h)) { records += usize::from(is_record); out.extend(rec.iter().map(tag)); diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index 4f8f455b4..5bb4bc8ee 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -185,3 +185,14 @@ fn sat_text_is_told_by_its_subclass_and_a_geometry_record() { assert!(store(true).data_store_entities().contains(&h)); assert!(store(false).data_store_entities().is_empty()); } + +/// The writer keeps a data store record by its first 320 only, so only that entity counts as +/// stored (#2334). +#[test] +fn a_data_store_record_stores_only_its_first_entity() { + use cadcraft_doc::foreign::Foreign; + use cadcraft_doc::{Handle, RawTag}; + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let store = Foreign { data_store: vec![tag(0, "ACDSRECORD"), tag(320, "2B"), tag(320, "2C"), tag(2, "ASM_Data")], ..Foreign::default() }; + assert_eq!(store.data_store_entities(), [Handle(0x2B)].into()); +} From e65132c77ac293602eac3f314caf4cdf43f6d4f1 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Fri, 30 Oct 2026 19:43:43 +1100 Subject: [PATCH 213/900] -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 214/900] 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 1e96a3d50c2e955da294a0d2dbf2bdb53c40d9f5 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:13:10 -0300 Subject: [PATCH 215/900] DXF: never let a trail byte 0x5C start an escape MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In Shift-JIS, Big5 and GBK a double-byte character's trail byte can be 0x5C, the backslash (表 95 5C, ソ 83 5C, 許 B3 5C, 乗 81 5C). Written as its bytes right before U+ or M+, the file holds a backslash byte followed by U+, an escape for a reader that looks for escapes before it decodes the code page. CADCraft decodes first, so it read back right, but such a character there is now written as a \U+XXXX escape and the file reads the same either way. Elsewhere it stays as its bytes. ANSI_949 has no such trail byte. Suggested by austin62jake on #1693. --- crates/dxf/src/lib.rs | 23 ++++++++++++++++++++--- crates/dxf/tests/code_page_write.rs | 22 ++++++++++++++++++++++ docs/file-format-parity.md | 2 +- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index ec350adaa..7f40c8f32 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -547,18 +547,21 @@ pub fn is_binary(bytes: &[u8]) -> bool { /// its bytes, and every other one `\U+XXXX` (a surrogate pair of escapes above U+FFFF). Without /// a code page the result is ASCII, so it is valid in any code page. In every form a backslash /// that would start a `\U+` or `\M+` sequence is written as `\U+005C`, so the reader gives back -/// the literal text (#2050). +/// the literal text (#2050). So is a double-byte character whose trail byte is 0x5C (`\`) in that +/// place, such as Shift-JIS `表` or Big5 `許`: CADCraft decodes the code page before it looks for +/// escapes, but a reader that looks first would take that byte and the `U+` after it for one. fn push_string(s: &str, strings: Strings, out: &mut Vec) { let chars: Vec = s.chars().collect(); + let escape_at = |j: usize| matches!(chars.get(j), Some('U' | 'M')) && chars.get(j + 1) == Some(&'+'); for (i, &c) in chars.iter().enumerate() { match (c, strings) { ('\r' | '\n', _) => out.push(b' '), - ('\\', _) if matches!(chars.get(i + 1), Some('U' | 'M')) && chars.get(i + 2) == Some(&'+') => { + ('\\', _) if escape_at(i + 1) => { out.extend_from_slice(b"\\U+005C"); } (c, Strings::Utf8) => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()), (c, _) if c.is_ascii() => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()), - (c, Strings::Escaped(Some(d))) if codepage::encode_char(c, d, out) => {} + (c, Strings::Escaped(Some(d))) if code_page_bytes(c, d, escape_at(i + 1), out) => {} (c, Strings::Escaped(_)) => { let mut units = [0u16; 2]; for u in c.encode_utf16(&mut units) { @@ -569,6 +572,20 @@ fn push_string(s: &str, strings: Strings, out: &mut Vec) { } } +/// `c` in the code page `d`, if it has it, unless it is a double-byte character whose trail byte +/// is 0x5C and an escape's `U+` or `M+` follows (`before_escape`): see [`push_string`]. +fn code_page_bytes(c: char, d: codepage::Decoder, before_escape: bool, out: &mut Vec) -> bool { + let start = out.len(); + if !codepage::encode_char(c, d, out) { + return false; + } + if before_escape && out.len() - start > 1 && out.last() == Some(&b'\\') { + out.truncate(start); + return false; + } + true +} + /// A section: `0 SECTION / 2 NAME ... 0 ENDSEC`. #[derive(Clone, Debug, Default)] pub struct Section { diff --git a/crates/dxf/tests/code_page_write.rs b/crates/dxf/tests/code_page_write.rs index 466a2b2a6..75d647c08 100644 --- a/crates/dxf/tests/code_page_write.rs +++ b/crates/dxf/tests/code_page_write.rs @@ -92,3 +92,25 @@ fn literal_escapes_survive_code_page_text() { } } } + +/// Double-byte code pages whose trail byte can be 0x5C (`\\`): Shift-JIS `表` (95 5C) and `ソ` +/// (83 5C), Big5 `許` (B3 5C), GBK `乗` (81 5C). Right before `U+` or `M+`, such a character is +/// written as an escape, so even a reader that looks for escapes before it decodes the code page +/// reads it right. Elsewhere it stays as its bytes. Both forms read back as written. +#[test] +fn a_trail_byte_backslash_never_starts_an_escape() { + let cases: [(&str, &str, &[u8], &[u8]); 4] = [ + ("ANSI_932", "表U+0041 表示", b"\\U+8868U+0041 \x95\x5C\x8E\xA6", b"\x95\x5CU+"), + ("ANSI_932", "ソM+1A2B", b"\\U+30BDM+1A2B", b"\x83\x5CM+"), + ("ANSI_950", "許U+0041", b"\\U+8A31U+0041", b"\xB3\x5CU+"), + ("ANSI_936", "乗U+0041", b"\\U+4E57U+0041", b"\x81\x5CU+"), + ]; + for (cp, text, written, never) in cases { + let tags = file(cp, text); + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + assert!(contains(&bytes, written), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); + assert!(!contains(&bytes, never), "{cp} {what}: a trail byte starts an escape"); + assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); + } + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d919cf6ba..eda4a0872 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -66,7 +66,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | R12 binary | read, write | **no** (binary parser expects R13+ 2-byte group codes) | no | | R13–R2018, ASCII | read, write each of 2000/2004/2007/2010/2013/2018 | yes, one reader for all versions | yes, each of 2000–2018 (#421): R2000 structure (later versions add only optional groups) with that `$ACADVER`; UTF-8 text from 2007; no CLASS instance counts (91) | | R13–R2018, binary | read, write | yes | yes, each of 2000–2018 (SAVEAS `binary`; a binary file stays binary on QSAVE) | -| Code pages (`$DWGCODEPAGE`, ANSI_932/936/949/950/125x) | yes | yes (#505): ASCII and binary DXF before 2007 decode from their code page (ANSI_874/932/936/949/950/1250–1258, DOS437/850/852/866, ISO 8859, Macintosh); a file that is valid UTF-8 reads as UTF-8; Johab and other DOS code pages read as ANSI_1252 (`dxf/src/codepage.rs`) | before 2007 writes text in the declared code page (the one read from the file, else `ANSI_1252`), characters outside it as `\U+` escapes; an unknown code page, or ASCII DXF whose code page bytes would also read as UTF-8, gives pure ASCII with escapes (#169) | +| Code pages (`$DWGCODEPAGE`, ANSI_932/936/949/950/125x) | yes | yes (#505): ASCII and binary DXF before 2007 decode from their code page (ANSI_874/932/936/949/950/1250–1258, DOS437/850/852/866, ISO 8859, Macintosh); a file that is valid UTF-8 reads as UTF-8; Johab and other DOS code pages read as ANSI_1252 (`dxf/src/codepage.rs`) | before 2007 writes text in the declared code page (the one read from the file, else `ANSI_1252`), characters outside it as `\U+` escapes; an unknown code page, or ASCII DXF whose code page bytes would also read as UTF-8, gives pure ASCII with escapes (#169); a double-byte character whose trail byte is `\` (Shift-JIS, Big5, GBK) is escaped where `U+` or `M+` follows it | | `\U+`/`\M+` escapes | yes | yes (`\M+` since #505; Johab `\M+4` stays literal) | `\U+` yes | ### DXF content: read and write by object type 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 216/900] 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 217/900] 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 9d4b3bb091e2bcd83acb84c4757f43e67509d7f7 Mon Sep 17 00:00:00 2001 From: wovadi <350371346+wovadi@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:05:02 +0100 Subject: [PATCH 218/900] Raster images are drawn on screen and in PNG output (#1756) An IMAGE whose file exists was drawn as a frame with two diagonals. Now its pixels are loaded when a drawing opens and drawn on screen and in PNG output, with rotation, clip boundary, fade and object transparency. A file that can't be read keeps the crossed-out frame and reports a message. Ported from the raster commit of #1029 onto the split render and canvas modules. New here: large images are drawn from a pyramid of levels cut into tiles uploaded as they come into view, instead of one texture with pixels skipped, so a large scan stays sharp zoomed in and doesn't shimmer zoomed out. Limits are listed in docs/gaps.md (FF10): PDF and SVG output write only the frame, and on screen images lie under all other objects. Co-Authored-By: Chanthawat Kiriyadee Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 2 +- apps/cadcraft-cli/src/lib.rs | 1 + apps/cadcraft-web/src/main.rs | 1 + apps/cadcraft/src/main.rs | 1 + crates/doc/src/entity/layout.rs | 5 +- crates/doc/src/lib.rs | 5 + crates/doc/src/raster.rs | 93 ++++ crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/blocks/xref.rs | 6 + crates/engine/src/cmd/exchange.rs | 8 +- crates/engine/src/cmd/file.rs | 16 + crates/engine/src/cmd/image.rs | 349 +++++++++++++ crates/engine/tests/image_attach.rs | 376 ++++++++++++++ crates/engine/tests/image_decoder_panic.rs | 55 ++ crates/io/Cargo.toml | 1 + crates/io/src/lib.rs | 2 + crates/io/src/pdf.rs | 2 + crates/io/src/raster.rs | 79 +++ crates/io/src/svg.rs | 2 + crates/io/tests/raster_decode.rs | 172 +++++++ crates/io/tests/raster_foreign_files.rs | 222 +++++++++ crates/render/src/display.rs | 52 ++ crates/render/src/draw.rs | 12 +- crates/render/src/lib.rs | 58 ++- crates/render/src/raster.rs | 98 +++- crates/render/src/viewports.rs | 26 +- crates/render/tests/raster_image.rs | 338 +++++++++++++ crates/ui-egui/src/canvas.rs | 1 + crates/ui-egui/src/canvas/draw.rs | 5 + crates/ui-egui/src/canvas/images.rs | 554 +++++++++++++++++++++ crates/ui-egui/src/canvas/viewport.rs | 3 + crates/ui-egui/src/gpu.rs | 9 + crates/ui-egui/src/i18n/uk.tsv | 2 + docs/file-format-parity.md | 7 +- docs/gaps.md | 5 +- 36 files changed, 2554 insertions(+), 17 deletions(-) create mode 100644 crates/doc/src/raster.rs create mode 100644 crates/engine/src/cmd/image.rs create mode 100644 crates/engine/tests/image_attach.rs create mode 100644 crates/engine/tests/image_decoder_panic.rs create mode 100644 crates/io/src/raster.rs create mode 100644 crates/io/tests/raster_decode.rs create mode 100644 crates/io/tests/raster_foreign_files.rs create mode 100644 crates/render/tests/raster_image.rs create mode 100644 crates/ui-egui/src/canvas/images.rs diff --git a/Cargo.lock b/Cargo.lock index 51693203d..edcfbec50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -752,6 +752,7 @@ dependencies = [ "cadcraft-geom", "cadcraft-render", "craft-pdf", + "image", "miniz_oxide 0.9.1", "quick-xml 0.42.0", "serde", diff --git a/Cargo.toml b/Cargo.toml index da6bca3b4..cab8c4d2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,7 +51,7 @@ skrifa = "0.48" # so the graph has both) and the Unicode Bidirectional Algorithm for right-to-left drawing text. harfrust = "0.14" unicode-bidi = "0.3.18" -image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "bmp", "tiff"] } encoding_rs = "0.8.35" # XML for the SVG reader (streaming parser, no entity expansion beyond the five predefined ones) quick-xml = "0.42" diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index c858417e2..1db550695 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -43,6 +43,7 @@ fn install_io() { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); + cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string())); cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index a25782d6e..30d9c55f5 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -119,6 +119,7 @@ mod web { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); + cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string())); cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 4d7bdc39b..b9efa2e00 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -145,6 +145,7 @@ pub fn install_io() { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); + cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string())); cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); diff --git a/crates/doc/src/entity/layout.rs b/crates/doc/src/entity/layout.rs index be1b9584d..4568c24ac 100644 --- a/crates/doc/src/entity/layout.rs +++ b/crates/doc/src/entity/layout.rs @@ -59,8 +59,9 @@ pub struct Image { /// The image definition's name (its key in the drawing's image dictionary). #[serde(default, skip_serializing_if = "String::is_empty")] pub name: String, - /// Clip boundary in pixel coordinates (origin at the top-left corner of the image, y down): - /// two opposite corners of a rectangle, or a polygon's vertices. Empty: the whole image. + /// Clip boundary in pixel coordinates (y down, counted from pixel centres: the centre of the + /// top-left pixel is the origin, so the whole image is -0.5 to size - 0.5): two opposite + /// corners of a rectangle, or a polygon's vertices. Empty: the whole image. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub clip: Vec, /// The clip boundary is applied. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d970a6a56..4c6febbe4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -16,6 +16,7 @@ mod header; pub mod library; mod plotstyle; mod plotter; +mod raster; mod refedit; mod store; mod tables; @@ -33,6 +34,7 @@ pub use gdt::*; pub use header::{HVal, Header}; pub use plotstyle::*; pub use plotter::*; +pub use raster::{Raster, Rasters}; pub use refedit::{RefEdit, WorkItem}; pub use store::EntityStore; pub use tables::*; @@ -132,6 +134,8 @@ pub struct Drawing { /// Records of the file this drawing was read from that the reader could not place (a damaged /// file), counted by the section they came from. Never written to a file. pub skipped_records: BTreeMap, + /// The pixels of the raster images that are loaded (IMAGE). Never written to a file. + pub rasters: Rasters, } impl Default for Drawing { @@ -191,6 +195,7 @@ impl Drawing { read_notes: Vec::new(), refedit: None, skipped_records: BTreeMap::new(), + rasters: Rasters::default(), } } diff --git a/crates/doc/src/raster.rs b/crates/doc/src/raster.rs new file mode 100644 index 000000000..1eb721997 --- /dev/null +++ b/crates/doc/src/raster.rs @@ -0,0 +1,93 @@ +//! Decoded raster image pixels (IMAGE entities). The drawing keeps them for the session only: +//! they are loaded from the image files after a drawing opens and are never written to a file. + +use std::collections::BTreeMap; +use std::sync::Arc; + +/// The pixels of a raster image: 8-bit RGBA, not premultiplied, rows from the top. +#[derive(Clone, PartialEq)] +pub struct Raster { + width: u32, + height: u32, + rgba: Vec, + opaque: bool, +} + +impl Raster { + /// `None` unless both sides are at least one pixel and `rgba` holds exactly four bytes per pixel. + pub fn new(width: u32, height: u32, rgba: Vec) -> Option { + let pixels = usize::try_from(width).ok()?.checked_mul(usize::try_from(height).ok()?)?; + if pixels == 0 || rgba.len() != pixels.checked_mul(4)? { + return None; + } + let opaque = rgba.as_chunks::<4>().0.iter().all(|[_, _, _, alpha]| *alpha == u8::MAX); + Some(Raster { width, height, rgba, opaque }) + } + pub fn width(&self) -> u32 { + self.width + } + pub fn height(&self) -> u32 { + self.height + } + /// Four bytes per pixel (red, green, blue, alpha), `width * height` pixels. + pub fn rgba(&self) -> &[u8] { + &self.rgba + } + /// No pixel is transparent. + pub fn opaque(&self) -> bool { + self.opaque + } + /// The pixel in column `x` of row `y` (from the top): red, green, blue, alpha. + pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> { + if x >= self.width || y >= self.height { + return None; + } + let (x, y, width) = (usize::try_from(x).ok()?, usize::try_from(y).ok()?, usize::try_from(self.width).ok()?); + let pixels = self.rgba.as_chunks::<4>().0; + pixels.get(y.checked_mul(width)?.checked_add(x)?).copied() + } +} + +impl std::fmt::Debug for Raster { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Raster({}x{})", self.width, self.height) + } +} + +/// The loaded pixels of a drawing's raster images, by image file path ([`crate::Image::path`]). +/// Session data: two drawings are equal whatever images they have loaded, and copying a drawing +/// (undo) shares the pixels. +#[derive(Clone, Default)] +pub struct Rasters(Arc>>); + +impl Rasters { + pub fn get(&self, path: &str) -> Option<&Arc> { + self.0.get(path) + } + pub fn insert(&mut self, path: &str, raster: Arc) { + Arc::make_mut(&mut self.0).insert(path.to_string(), raster); + } + pub fn remove(&mut self, path: &str) { + if self.0.contains_key(path) { + Arc::make_mut(&mut self.0).remove(path); + } + } + pub fn len(&self) -> usize { + self.0.len() + } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl PartialEq for Rasters { + fn eq(&self, _: &Rasters) -> bool { + true + } +} + +impl std::fmt::Debug for Rasters { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Rasters({})", self.0.len()) + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 172e416d1..f3df20305 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -18,6 +18,7 @@ mod gripcmds; mod griphot; pub(crate) mod groups; pub(crate) mod hatch; +mod image; mod inquiry; mod layer; mod layout; @@ -198,6 +199,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(layer::specs()); v.extend(layout::specs()); v.extend(exchange::specs()); + v.extend(image::specs()); v.extend(props::specs()); v.extend(inquiry::specs()); v.extend(settings::specs()); diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index b87e73795..df0e3513a 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -67,6 +67,12 @@ pub(crate) fn after_open(s: &mut Session, i: usize) { echo_all(s, &out); } +/// The file a reference saved as `path` in a drawing at `host` is read from, if there is one +/// (xrefs and raster images look in the same places). +pub(crate) fn find_file(path: &str, host: Option<&str>) -> Option { + load::find(path, host.map(std::path::Path::new), false).ok() +} + /// The open drawing's path (xref paths are relative to its folder). fn host(s: &Session) -> Option { s.state().ok().and_then(|st| st.path.clone()) diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index e28de89fc..ac29b1aba 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -55,11 +55,11 @@ pub fn specs() -> Vec { .alias(&["printpdf", "pdfb"]) .params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (ISO A-series, either orientation) they match") .noundo(), - CommandSpec::new("attach", "Attach", |_, _| { - Err(EngineError::Other("ATTACH is not available yet: raster images and PDF/DWF/DGN underlays can't be shown yet".into())) + CommandSpec::new("attach", "Attach", |s, p| match str_param(p, "path").map(extension) { + Some(e) if super::image::is_image_ext(&e) => super::image::run_imageattach(s, p), + _ => Err(EngineError::Other("ATTACH is not available yet for this file: only raster images (PNG, JPEG, BMP, TIFF; see IMAGEATTACH) can be attached, PDF/DWF/DGN underlays can't be shown yet".into())), }) - .params("not available yet") - .noundo(), + .params("{path: image file, …} as IMAGEATTACH; other file types are not available yet"), CommandSpec::new("share", "Share", |_, _| { Err(EngineError::Other("SHARE is not available yet: there is no online service to share through; EXPORT or PUBLISH the drawing and send the file".into())) }) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 7c26a71f9..26aea531d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -70,6 +70,19 @@ pub fn entity_codec() -> Option<&'static EntityCodec> { /// COMPARE (drawing comparison). pub mod compare; +/// Decode a raster image file (PNG, JPEG, BMP, TIFF) to pixels: installed by the app with the +/// image reader, a lower layer. +pub type ImageHook = fn(&[u8]) -> std::result::Result; + +static IMAGE: OnceLock = OnceLock::new(); + +pub fn set_image_decoder(h: ImageHook) { + let _ = IMAGE.set(h); +} +pub fn image_decoder() -> Option { + IMAGE.get().copied() +} + /// Hand finished file bytes to the user where there is no file system (the browser: a download). /// Arguments: file name, MIME type, bytes. `Ok` only once the delivery was actually started. pub type DeliverHook = fn(&str, &str, &[u8]) -> std::result::Result<(), String>; @@ -301,6 +314,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result { let ReadFile { drawing, binary_dxf, name, path } = f; let i = add_read(s, drawing, binary_dxf, &name, path); super::blocks::xref::after_open(s, i); + super::image::after_open(s, i); Ok(opened(s, i, true)) } @@ -353,6 +367,7 @@ fn run_open(s: &mut Session, p: &Value) -> Result { 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()))?; super::blocks::xref::after_open(s, i); + super::image::after_open(s, i); return Ok(opened(s, i, true)); } #[cfg(target_arch = "wasm32")] @@ -363,6 +378,7 @@ fn run_open(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").unwrap_or("Drawing.dxf"); let i = open_bytes(s, &bytes, name, None)?; super::blocks::xref::after_open(s, i); + super::image::after_open(s, i); Ok(opened(s, i, false)) } diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs new file mode 100644 index 000000000..240664891 --- /dev/null +++ b/crates/engine/src/cmd/image.rs @@ -0,0 +1,349 @@ +//! Raster images (IMAGEATTACH, IMAGE). An IMAGE entity names its file; the pixels are decoded +//! when the drawing opens or the image is attached and kept with the open drawing +//! ([`Drawing::rasters`]), never in the file. An image whose file can't be found or read stays in +//! the drawing as a crossed-out frame. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + +use cadcraft_doc::{Drawing, EntityKind, Image, Raster}; +use cadcraft_geom::Vec2; +use serde_json::{Value, json}; + +use super::file::base64_decode; +use super::{CommandSpec, bad, f64_or, point_param, str_param}; +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; +/// 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. +const MAX_LOADERS: usize = 4; +/// Longest image path taken from a caller. +const MAX_PATH: usize = 4096; + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("imageattach", "Raster Image Reference...", run_imageattach).alias(&["iat"]).params( + "{path: PNG/JPEG/BMP/TIFF file (saved as given; a relative path is relative to this drawing's folder), data?: base64 file contents \ + (instead of reading `path`), at?: [x,y] lower-left corner (default 0,0), scale?: number (default 1: the image is one drawing unit \ + wide), width?: width in drawing units (instead of `scale`), rotation? (degrees), name? (default: the file name)} → {name, handle, \ + path, pixels: [w, h], size: [w, h]}", + ), + CommandSpec::new("image", "Raster Images", run_image) + .alias(&["im"]) + .params("{} → {images: [{name, path, foundAt, status: Loaded|Not Found|Not loaded, references, pixels?: [w, h]}]}") + .noundo(), + ] +} + +/// Whether `ext` (lower case, no dot) is an image file type IMAGEATTACH reads. +pub(crate) fn is_image_ext(ext: &str) -> bool { + matches!(ext, "png" | "jpg" | "jpeg" | "bmp" | "tif" | "tiff") +} + +/// Every IMAGE entity of `d`: in model space, on the layouts and in the blocks. +fn images(d: &Drawing) -> impl Iterator { + let model = std::iter::once(&d.model); + let layouts = d.layouts.iter().map(|l| &l.entities); + let blocks = d.blocks.values().map(|b| &b.entities); + model.chain(layouts).chain(blocks).flat_map(|store| store.iter()).filter_map(|e| match &e.kind { + EntityKind::Image(i) => Some(i), + _ => None, + }) +} + +/// The image files `d` names, each once, in the order they are first used. +fn paths(d: &Drawing) -> Vec { + let mut seen = BTreeSet::new(); + let mut paths = Vec::new(); + for i in images(d) { + if !i.path.trim().is_empty() && seen.insert(i.path.as_str()) { + paths.push(i.path.clone()); + } + } + paths +} + +/// The contents of the image file saved as `path` in a drawing at `host`. +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 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)); + } + std::fs::read(&file).map_err(|e| e.to_string()) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, host); + Err("files are not available on the web".into()) + } +} + +/// Decode an image file. A decoder that panics on a damaged file fails this image only: the +/// drawing it belongs to must still open. +fn decode(bytes: &[u8]) -> std::result::Result { + let hook = super::file::image_decoder().ok_or("image files can't be read in this build")?; + match std::panic::catch_unwind(|| hook(bytes)) { + Ok(r) => r, + Err(_) => Err("the file is damaged and can't be read".into()), + } +} + +fn bytes_of(r: &Raster) -> u64 { + u64::try_from(r.rgba().len()).unwrap_or(u64::MAX) +} + +/// Load the images of drawing `i`, just opened. Those that can't be loaded are reported and +/// stay crossed-out frames; opening never fails over an image. +pub(crate) fn after_open(s: &mut Session, i: usize) { + let Some(st) = s.docs.get_mut(i) else { return }; + let paths = paths(&st.doc); + if paths.is_empty() { + return; + } + let mut rasters = st.doc.rasters.clone(); + let notes = load_missing(&paths, st.path.as_deref(), &mut rasters); + if !rasters.is_empty() { + // Loading pixels is not a change to the drawing. A drawing counts as unchanged while + // it is the very one that was saved, so the saved one follows. + let unchanged = Arc::ptr_eq(&st.doc, &st.saved); + Arc::make_mut(&mut st.doc).rasters = rasters; + if unchanged { + st.saved = st.doc.clone(); + } + } + for n in notes { + s.echo(n); + } +} + +/// Read and decode into `rasters` the files of `paths` that are not in it yet, for a drawing at +/// `host`. Returns one message per file that could not be loaded. +fn load_missing(paths: &[String], host: Option<&str>, rasters: &mut cadcraft_doc::Rasters) -> Vec { + let mut notes = Vec::new(); + let mut missing: Vec<&str> = paths.iter().map(String::as_str).filter(|p| rasters.get(p).is_none()).collect(); + if missing.len() > MAX_IMAGE_FILES { + missing.truncate(MAX_IMAGE_FILES); + notes.push(format!("Images: only the first {MAX_IMAGE_FILES} image files are loaded")); + } + let decoded = decode_files(&missing, host); + // Kept in the order the drawing uses them, up to the memory limit. + let mut kept_bytes = 0u64; + for (path, result) in missing.iter().zip(decoded) { + match result { + Ok(r) => { + kept_bytes = kept_bytes.saturating_add(bytes_of(&r)); + if kept_bytes > MAX_LOADED_BYTES { + notes.push(over_limit(path)); + break; + } + rasters.insert(path, Arc::new(r)); + } + Err(e) => notes.push(format!("Image {path}: {e}")), + } + } + notes +} + +fn over_limit(path: &str) -> String { + format!("Image {path}: not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20) +} + +/// Read and decode the image files `paths` of a drawing at `host`, a few at a time (decoding is +/// what opening a drawing with large images waits for). The results are in the order of `paths`. +fn decode_files(paths: &[&str], host: Option<&str>) -> Vec> { + // Decoded bytes so far, shared by the loaders: past the limit no further file is started. + let decoded_bytes = AtomicU64::new(0); + let load = |path: &str| -> std::result::Result { + if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES { + return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20)); + } + let r = read_file(path, host).and_then(|bytes| decode(&bytes))?; + decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed); + Ok(r) + }; + let mut results: Vec>> = paths.iter().map(|_| None).collect(); + let loaders = loader_count(paths.len()); + if loaders > 1 { + // Each loader takes the next file nobody has started. + let next = AtomicUsize::new(0); + 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 + }; + let finished: Vec<_> = std::thread::scope(|scope| { + let started: Vec<_> = (0..loaders).filter_map(|_| std::thread::Builder::new().spawn_scoped(scope, work).ok()).collect(); + started.into_iter().filter_map(|loader| loader.join().ok()).flatten().collect() + }); + for (index, result) in finished { + if let Some(slot) = results.get_mut(index) { + *slot = Some(result); + } + } + } + // One loader, or files a loader that could not start or finish left behind. + results.into_iter().zip(paths).map(|(result, path)| result.unwrap_or_else(|| load(path))).collect() +} + +/// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large +/// image needs several hundred megabytes while it is decoded) and no more than there are files. +fn loader_count(files: usize) -> usize { + #[cfg(not(target_arch = "wasm32"))] + let processors = std::thread::available_parallelism().map(std::num::NonZero::get).unwrap_or(1); + #[cfg(target_arch = "wasm32")] + let processors = 1; + processors.min(MAX_LOADERS).min(files) +} + +/// The file name without folders and extension (either separator). +fn stem(path: &str) -> String { + let file = path.rsplit(['/', '\\']).next().unwrap_or(path); + match file.rsplit_once('.') { + Some((stem, _)) if !stem.is_empty() => stem.to_string(), + _ => file.to_string(), + } +} + +/// The definition name for a new image of `path`: the name that file already has in `d`, else +/// `wanted`, numbered (`wanted_2`, `wanted_3`, …) when another file has taken it. +fn def_name(d: &Drawing, path: &str, wanted: &str) -> String { + if let Some(i) = images(d).find(|i| i.path == path && !i.name.is_empty()) { + return i.name.clone(); + } + // The names other files have, compared without regard to case. + let taken: BTreeSet = images(d).filter(|i| i.path != path).map(|i| i.name.to_ascii_lowercase()).collect(); + let free = |name: &str| !taken.contains(&name.to_ascii_lowercase()); + if free(wanted) { + return wanted.to_string(); + } + // One of these is free: there are more candidates than names taken. + let candidates = 2..taken.len().saturating_add(3); + candidates.map(|n| format!("{wanted}_{n}")).find(|name| free(name)).unwrap_or_else(|| wanted.to_string()) +} + +const ID: &str = "imageattach"; + +pub(crate) fn run_imageattach(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(ID, "`path` is required"))?.to_string(); + if path.len() > MAX_PATH { + return Err(bad(ID, "`path` is too long")); + } + let place = placement(p)?; + let raster = pixels(s, p, &path)?; + let (w, h) = (f64::from(raster.width()), f64::from(raster.height())); + // One pixel in drawing units, along the image's bottom edge (`u`) and its left edge (`v`). + let pixel = place.width / w; + let u = Vec2::from_angle(place.rotation) * pixel; + let v = u.perp(); + if !(pixel.is_normal() && (pixel * h).is_normal() && u.x.is_finite() && u.y.is_finite()) { + return Err(bad(ID, "the image would be too small or too large to draw")); + } + let wanted = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| stem(&path)); + let name = def_name(s.doc()?, &path, &wanted); + let image = Image { + insert: place.at.to3(0.0), + u: u.to3(0.0), + v: v.to3(0.0), + size: Vec2::new(w, h), + path: path.clone(), + name: name.clone(), + ..Image::default() + }; + s.doc_mut()?.rasters.insert(&path, raster); + let handle = s.add_entity(EntityKind::Image(image))?; + Ok(json!({ "name": name, "handle": handle.hex(), "path": path, "pixels": [w, h], "size": [place.width, pixel * h] })) +} + +/// Where and how large IMAGEATTACH puts the image. +struct Placement { + /// The lower-left corner. + at: Vec2, + /// Radians, counter-clockwise. + rotation: f64, + /// The image's width in drawing units. + width: f64, +} + +/// `at`, `rotation` and the width (`width`, else `scale`: an image is one unit wide at scale 1). +fn placement(p: &Value) -> Result { + let at = point_param(p, "at").unwrap_or(Vec2::ZERO); + if !(at.x.is_finite() && at.y.is_finite()) { + return Err(bad(ID, "`at` must be a point")); + } + let width = match p.get("width") { + Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?, + None => f64_or(p, "scale", 1.0), + }; + if !(width.is_finite() && width > 0.0) { + return Err(bad(ID, "`scale` and `width` must be greater than zero")); + } + Ok(Placement { at, rotation: f64_or(p, "rotation", 0.0).to_radians(), width }) +} + +/// The pixels of the image at `path`: decoded from `data` when the caller hands the file over, +/// else the ones already loaded for that path, else read from the file. +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"))?; + base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))? + } + None => { + if let Some(loaded) = s.doc()?.rasters.get(path) { + return Ok(loaded.clone()); + } + let host = s.state()?.path.clone(); + read_file(path, host.as_deref()).map_err(|e| bad(ID, format!("{path}: {e}")))? + } + }; + Ok(Arc::new(decode(&bytes).map_err(|e| bad(ID, format!("{path}: {e}")))?)) +} + +fn run_image(s: &mut Session, _p: &Value) -> Result { + let host = s.state()?.path.clone(); + let d = s.doc()?; + // Per file: its definition name and how many images show it. + let mut uses: BTreeMap<&str, (&str, usize)> = BTreeMap::new(); + for i in images(d) { + uses.entry(i.path.as_str()).or_insert((i.name.as_str(), 0)).1 += 1; + } + let rows: Vec = paths(d) + .iter() + .map(|path| { + let (name, references) = uses.get(path.as_str()).copied().unwrap_or_default(); + let mut row = describe(d, path, host.as_deref()); + row["name"] = json!(name); + row["references"] = json!(references); + row + }) + .collect(); + Ok(json!({ "images": rows })) +} + +/// The state of image file `path` of drawing `d` (saved at `host`): where it is and whether its +/// pixels are loaded. +fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value { + let loaded = d.rasters.get(path); + let found_at = super::blocks::xref::find_file(path, host).map(|f| f.to_string_lossy().into_owned()); + let status = match (loaded, &found_at) { + (Some(_), _) => "Loaded", + (None, None) => "Not Found", + // The file is there but could not be read as an image. + (None, Some(_)) => "Not loaded", + }; + json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) }) +} diff --git a/crates/engine/tests/image_attach.rs b/crates/engine/tests/image_attach.rs new file mode 100644 index 000000000..864d968a5 --- /dev/null +++ b/crates/engine/tests/image_attach.rs @@ -0,0 +1,376 @@ +//! Raster images (#956): IMAGEATTACH from a file and from handed-over bytes, the pixels loaded +//! again when the drawing is reopened, a missing file left as a frame, and bad input refused. + +use std::path::{Path, PathBuf}; + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, base64_encode, set_image_decoder, set_io}; +use cadcraft_engine::doc::{Drawing, EntityKind, Image, Raster}; +use serde_json::{Value, json}; + +fn hooks() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string())); +} + +/// A fresh folder for one test. +fn folder(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("cadcraft-image-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A PNG file of 4 x 2 pixels. +fn png() -> Vec { + let px: Vec = (0..8u8).flat_map(|i| [i * 30, 255 - i * 30, 7, 255]).collect(); + cadcraft_io::raster::encode_png(&Raster::new(4, 2, px).unwrap()).unwrap() +} + +fn images(s: &Session) -> Vec { + let d = s.doc().unwrap(); + d.model.iter().filter_map(|e| if let EntityKind::Image(i) = &e.kind { Some(i.clone()) } else { None }).collect() +} + +fn open(s: &mut Session, path: &Path) { + s.execute("open", &json!({ "path": path.to_string_lossy() })).unwrap(); +} + +fn listed(s: &mut Session) -> Value { + s.execute("image", &json!({})).unwrap()["images"].clone() +} + +#[test] +fn attach_from_bytes_places_the_image() { + hooks(); + let mut s = Session::new(); + let r = s.execute("imageattach", &json!({ "path": "maps/site.png", "data": base64_encode(&png()), "at": [10, 20], "width": 100 })).unwrap(); + assert_eq!((r["name"].as_str(), r["pixels"].clone(), r["size"].clone()), (Some("site"), json!([4.0, 2.0]), json!([100.0, 50.0]))); + let i = images(&s).pop().unwrap(); + assert_eq!((i.insert.x, i.insert.y, i.u.x, i.u.y, i.v.x, i.v.y), (10.0, 20.0, 25.0, 0.0, 0.0, 25.0)); + assert_eq!((i.size.x, i.size.y, i.path.as_str(), i.name.as_str()), (4.0, 2.0, "maps/site.png", "site")); + assert_eq!(s.doc().unwrap().rasters.get("maps/site.png").map(|r| (r.width(), r.height())), Some((4, 2))); + let l = listed(&mut s); + assert_eq!((l[0]["status"].as_str(), l[0]["references"].as_u64(), l[0]["pixels"].clone()), (Some("Loaded"), Some(1), json!([4, 2]))); + + // A second reference to the same file shares the definition and the pixels; another file + // with the same file name gets its own name. + s.execute("imageattach", &json!({ "path": "maps/site.png", "at": [200, 0], "rotation": 90, "scale": 8 })).unwrap(); + let r = s.execute("attach", &json!({ "path": "other/site.png", "data": base64_encode(&png()) })).unwrap(); + assert_eq!(r["name"], "site_2"); + let all = images(&s); + assert_eq!(all.len(), 3); + assert_eq!(all[1].name, "site"); + assert!((all[1].u.x).abs() < 1e-12 && (all[1].u.y - 2.0).abs() < 1e-12 && (all[1].v.x + 2.0).abs() < 1e-12, "{:?}", all[1]); + assert_eq!(listed(&mut s)[0]["references"], 2); + + // Undo takes the reference away; the drawing draws with its pixels. + s.execute("undo", &json!({})).unwrap(); + assert_eq!(images(&s).len(), 2); + let list = cadcraft_engine::render::build(s.doc().unwrap(), &cadcraft_engine::doc::Space::Model, &cadcraft_engine::render::Options::default()); + assert_eq!(list.images.len(), 2); +} + +#[test] +fn a_file_is_found_next_to_the_drawing_and_loaded_again_on_open() { + hooks(); + let dir = folder("file"); + std::fs::write(dir.join("map.png"), png()).unwrap(); + let host = dir.join("host.dxf"); + std::fs::write(&host, cadcraft_io::write(&Drawing::new_metric(), "host.dxf").unwrap()).unwrap(); + let mut s = Session::new(); + open(&mut s, &host); + let r = s.execute("imageattach", &json!({ "path": "map.png" })).unwrap(); + assert_eq!(r["size"], json!([1.0, 0.5]), "one drawing unit wide by default"); + s.execute("qsave", &json!({})).unwrap(); + + // Reopened: the pixels come back from the file. + let mut s = Session::new(); + open(&mut s, &host); + assert_eq!(images(&s).len(), 1); + assert!(s.doc().unwrap().rasters.get("map.png").is_some()); + assert!(!s.state().unwrap().is_dirty(), "loading images is not a change"); + let l = listed(&mut s); + assert_eq!(l[0]["status"], "Loaded"); + assert!(l[0]["foundAt"].as_str().is_some_and(|f| f.ends_with("map.png"))); + + // The file gone: the drawing still opens, says so, and keeps the reference. + std::fs::remove_file(dir.join("map.png")).unwrap(); + let mut s = Session::new(); + open(&mut s, &host); + assert_eq!(images(&s).len(), 1); + assert!(s.doc().unwrap().rasters.get("map.png").is_none()); + assert!(s.log.iter().any(|l| l.contains("map.png") && l.contains("file not found")), "{:?}", s.log); + assert_eq!(listed(&mut s)[0]["status"], "Not Found"); + + // A file that is not an image is reported the same way. + std::fs::write(dir.join("map.png"), b"not an image").unwrap(); + let mut s = Session::new(); + open(&mut s, &host); + assert!(s.doc().unwrap().rasters.get("map.png").is_none()); + assert!(s.log.iter().any(|l| l.contains("map.png")), "{:?}", s.log); + assert_eq!(listed(&mut s)[0]["status"], "Not loaded"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn bad_input_is_refused_and_changes_nothing() { + hooks(); + let mut s = Session::new(); + let data = base64_encode(&png()); + for p in [ + json!({}), + json!({ "path": " " }), + json!({ "path": "nowhere/missing.png" }), + json!({ "path": "a.png", "data": "***" }), + json!({ "path": "a.png", "data": 5 }), + json!({ "path": "a.png", "data": base64_encode(b"plain text") }), + json!({ "path": "a.png", "data": data, "scale": 0 }), + json!({ "path": "a.png", "data": data, "width": -3 }), + json!({ "path": "a.png", "data": data, "width": "wide" }), + json!({ "path": "a.png", "data": data, "width": 1e-320 }), + json!({ "path": "x".repeat(5000), "data": data }), + ] { + assert!(s.execute("imageattach", &p).is_err(), "{p}"); + } + assert!(images(&s).is_empty()); + assert!(s.execute("attach", &json!({ "path": "plan.pdf" })).unwrap_err().to_string().contains("not available yet")); + assert_eq!(listed(&mut s), json!([])); +} + +#[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, + // and the image must still point at its own pixels. + hooks(); + let mut s = Session::new(); + for i in 0..700 { + s.execute("line", &json!({ "points": [[i, 0], [i, 1]] })).unwrap(); + } + s.execute("imageattach", &json!({ "path": "a.png", "data": base64_encode(&png()), "at": [0, 5], "width": 4 })).unwrap(); + for i in 0..700 { + s.execute("line", &json!({ "points": [[i, 2], [i, 3]] })).unwrap(); + } + s.execute("imageattach", &json!({ "path": "b.png", "data": base64_encode(&png()), "at": [10, 5], "width": 8 })).unwrap(); + let list = cadcraft_engine::render::build(s.doc().unwrap(), &cadcraft_engine::doc::Space::Model, &cadcraft_engine::render::Options::default()); + let widths: Vec = list + .prims + .iter() + .filter_map(|p| match p.kind { + cadcraft_engine::render::Kind::Image { index } => list.images.get(index as usize).map(|i| i.right.x * 4.0), + _ => None, + }) + .collect(); + assert_eq!(widths, [4.0, 8.0]); +} + +fn drawn_images(s: &Session) -> usize { + cadcraft_engine::render::build(s.doc().unwrap(), &cadcraft_engine::doc::Space::Model, &cadcraft_engine::render::Options::default()).images.len() +} + +#[test] +fn editing_commands_work_on_images_and_undo_keeps_the_pixels() { + hooks(); + let mut s = Session::new(); + let r = s.execute("imageattach", &json!({ "path": "a.png", "data": base64_encode(&png()), "at": [10, 0], "width": 4 })).unwrap(); + let h = r["handle"].as_str().unwrap().to_string(); + + // Move, then a quarter turn about the origin: the corner and both axes follow. + s.execute("move", &json!({ "handles": [h], "delta": [0, 5] })).unwrap(); + s.execute("rotate", &json!({ "handles": [h], "base": [0, 0], "angle": 90 })).unwrap(); + let i = images(&s).pop().unwrap(); + let close = |a: f64, b: f64| (a - b).abs() < 1e-9; + assert!(close(i.insert.x, -5.0) && close(i.insert.y, 10.0), "{i:?}"); + assert!(close(i.u.x, 0.0) && close(i.u.y, 1.0) && close(i.v.x, -1.0) && close(i.v.y, 0.0), "{i:?}"); + assert_eq!(drawn_images(&s), 1); + + // A copy is a second reference to the same file. + s.execute("copy", &json!({ "handles": [h], "delta": [20, 0] })).unwrap(); + assert_eq!((images(&s).len(), drawn_images(&s)), (2, 2)); + assert_eq!(listed(&mut s)[0]["references"], 2); + assert_eq!(listed(&mut s).as_array().map(Vec::len), Some(1)); + + // Scaled about its corner: twice the size, still the same pixels. + s.execute("scale", &json!({ "handles": [h], "base": [-5, 10], "factor": 2 })).unwrap(); + let i = images(&s).into_iter().find(|i| close(i.insert.x, -5.0)).unwrap(); + assert!(close(i.u.y, 2.0) && close(i.size.x, 4.0), "{i:?}"); + + // Erased, then brought back by undo, with its picture; redo erases again. + s.execute("erase", &json!({ "handles": [h] })).unwrap(); + assert_eq!((images(&s).len(), drawn_images(&s)), (1, 1)); + s.execute("undo", &json!({})).unwrap(); + assert_eq!((images(&s).len(), drawn_images(&s)), (2, 2)); + s.execute("redo", &json!({})).unwrap(); + assert_eq!(images(&s).len(), 1); + + // Everything undone: no image, and nothing left to draw. + for _ in 0..10 { + let _ = s.execute("undo", &json!({})); + } + assert!(images(&s).is_empty()); + assert_eq!(drawn_images(&s), 0); + assert_eq!(listed(&mut s), json!([])); +} + +#[test] +fn the_alias_and_the_command_line_reach_the_command() { + hooks(); + assert_eq!(cadcraft_engine::cmd::resolve_alias("IAT"), "imageattach"); + assert_eq!(cadcraft_engine::cmd::resolve_alias("im"), "image"); + let spec = |id: &str| cadcraft_engine::cmd::command_specs().iter().find(|c| c.id == id).unwrap(); + assert!(!spec("imageattach").params.is_empty() && !spec("image").params.is_empty()); + // Typed without a file it has nothing to attach: an error, not a crash or a stuck prompt. + let mut s = Session::new(); + let _ = s.cmdline("imageattach"); + let _ = s.cmdline(""); + s.cancel(); + assert!(s.running.is_none() && images(&s).is_empty()); +} + +#[test] +fn images_in_blocks_and_layouts_are_loaded_on_open() { + use cadcraft_engine::doc::geom::{Vec2, Vec3}; + use cadcraft_engine::doc::{Block, Common, Entity, Space}; + hooks(); + let dir = folder("spaces"); + std::fs::create_dir_all(dir.join("maps")).unwrap(); + std::fs::write(dir.join("maps").join("a.png"), png()).unwrap(); + std::fs::write(dir.join("b.png"), png()).unwrap(); + let image = |path: &str, name: &str| { + EntityKind::Image(Image { + u: Vec3::new(1.0, 0.0, 0.0), + v: Vec3::new(0.0, 1.0, 0.0), + size: Vec2::new(4.0, 2.0), + path: path.into(), + name: name.into(), + ..Image::default() + }) + }; + let mut d = Drawing::new_metric(); + // The same file in model space, in a block and on a layout; another only on the layout, + // saved with a folder that no longer exists (found by its name next to the drawing); and + // one that is nowhere. + d.add(&Space::Model, Common::default(), image("maps/a.png", "a")).unwrap(); + let mut blk = Block::new("MAP"); + let bh = d.new_handle(); + blk.entities.push(Entity::new(bh, image("maps/a.png", "a"))); + d.blocks.insert("MAP".into(), std::sync::Arc::new(blk)); + let layout = Space::Paper("Layout1".into()); + d.add(&layout, Common::default(), image("maps/a.png", "a")).unwrap(); + d.add(&layout, Common::default(), image("C:\\old\\place\\b.png", "b")).unwrap(); + d.add(&layout, Common::default(), image("gone.png", "gone")).unwrap(); + let host = dir.join("host.dxf"); + std::fs::write(&host, cadcraft_io::write(&d, "host.dxf").unwrap()).unwrap(); + + let mut s = Session::new(); + open(&mut s, &host); + let doc = s.doc().unwrap(); + assert_eq!(doc.rasters.len(), 2, "each file once"); + assert!(doc.rasters.get("maps/a.png").is_some() && doc.rasters.get("C:\\old\\place\\b.png").is_some()); + assert!(!s.state().unwrap().is_dirty()); + assert_eq!(s.log.iter().filter(|l| l.starts_with("Image ")).count(), 1, "{:?}", s.log); + let l = listed(&mut s); + let row = |name: &str| l.as_array().unwrap().iter().find(|r| r["name"] == name).cloned().unwrap(); + assert_eq!((row("a")["status"].clone(), row("a")["references"].clone()), (json!("Loaded"), json!(3))); + assert_eq!(row("b")["status"], "Loaded"); + assert_eq!(row("gone")["status"], "Not Found"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_drawing_opened_from_bytes_gets_its_pixels_handed_over() { + // The web app's way: no file system, the drawing arrives as bytes and so do the images. + use cadcraft_engine::doc::geom::{Vec2, Vec3}; + use cadcraft_engine::doc::{Common, Space}; + hooks(); + let mut d = Drawing::new_metric(); + let i = Image { + u: Vec3::new(1.0, 0.0, 0.0), + v: Vec3::new(0.0, 1.0, 0.0), + size: Vec2::new(4.0, 2.0), + path: "no-such-folder/web.png".into(), + name: "web".into(), + ..Image::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + let dxf = cadcraft_io::write(&d, "plan.dxf").unwrap(); + + let mut s = Session::new(); + s.execute("open", &json!({ "data": base64_encode(&dxf), "name": "plan.dxf" })).unwrap(); + assert_eq!(images(&s).len(), 1, "opened with its image reference"); + assert!(s.doc().unwrap().rasters.is_empty()); + assert!(s.log.iter().any(|l| l.contains("web.png")), "{:?}", s.log); + assert_eq!(listed(&mut s)[0]["status"], "Not Found"); + assert_eq!(drawn_images(&s), 0); + + // The same file handed over as bytes: the reference that was there draws too. + s.execute("imageattach", &json!({ "path": "no-such-folder/web.png", "data": base64_encode(&png()), "at": [10, 0] })).unwrap(); + assert_eq!((images(&s).len(), drawn_images(&s)), (2, 2)); + let l = listed(&mut s); + assert_eq!((l[0]["status"].clone(), l[0]["references"].clone(), l[0]["name"].clone()), (json!("Loaded"), json!(2), json!("web"))); + + // Saved and read back: the references are kept, the pixels are not in the file. + let bytes = cadcraft_io::write(s.doc().unwrap(), "plan.dxf").unwrap(); + let back = cadcraft_io::read(&bytes, "plan.dxf").unwrap(); + assert!(back.rasters.is_empty()); + assert_eq!(back.model.iter().filter(|e| matches!(e.kind, EntityKind::Image(_))).count(), 2); +} + +#[test] +fn many_files_are_loaded_together_and_reported_in_order() { + // More files than loaders, with missing and unreadable ones among them: each good file is + // loaded, each bad one reported once, in the order the drawing uses them. + use cadcraft_engine::doc::geom::{Vec2, Vec3}; + use cadcraft_engine::doc::{Common, Space}; + hooks(); + let dir = folder("many"); + let mut d = Drawing::new_metric(); + let mut expected_notes = Vec::new(); + for n in 0..60u32 { + let name = format!("tile{n:02}.png"); + match n % 10 { + 3 => expected_notes.push(format!("Image {name}: file not found")), + 7 => { + std::fs::write(dir.join(&name), b"not an image").unwrap(); + expected_notes.push(format!("Image {name}: ")); + } + _ => { + // A different width per file, so a mix-up would show. + let px = vec![200u8; (n as usize + 1) * 4]; + std::fs::write(dir.join(&name), cadcraft_io::raster::encode_png(&Raster::new(n + 1, 1, px).unwrap()).unwrap()).unwrap(); + } + } + let i = Image { + insert: Vec3::new(f64::from(n) * 3.0, 0.0, 0.0), + u: Vec3::new(1.0, 0.0, 0.0), + v: Vec3::new(0.0, 1.0, 0.0), + size: Vec2::new(f64::from(n + 1), 1.0), + path: name.clone(), + name: format!("tile{n:02}"), + ..Image::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + } + let host = dir.join("host.dxf"); + std::fs::write(&host, cadcraft_io::write(&d, "host.dxf").unwrap()).unwrap(); + + for _ in 0..3 { + let mut s = Session::new(); + open(&mut s, &host); + let doc = s.doc().unwrap(); + assert_eq!(doc.rasters.len(), 48); + for n in 0..60u32 { + let loaded = doc.rasters.get(&format!("tile{n:02}.png")).map(|r| r.width()); + assert_eq!(loaded, if matches!(n % 10, 3 | 7) { None } else { Some(n + 1) }, "tile {n}"); + } + let notes: Vec<&String> = s.log.iter().filter(|l| l.starts_with("Image ")).collect(); + assert_eq!(notes.len(), expected_notes.len(), "{notes:?}"); + assert!(notes.iter().zip(&expected_notes).all(|(got, want)| got.starts_with(want.as_str())), "{notes:?}"); + assert!(!s.state().unwrap().is_dirty()); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/image_decoder_panic.rs b/crates/engine/tests/image_decoder_panic.rs new file mode 100644 index 000000000..42e74253e --- /dev/null +++ b/crates/engine/tests/image_decoder_panic.rs @@ -0,0 +1,55 @@ +//! A raster image decoder that panics on a damaged file fails that image only (#956): the +//! drawing it belongs to still opens, and IMAGEATTACH reports an error. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, base64_encode, set_image_decoder, set_io}; +use cadcraft_engine::doc::geom::{Vec2, Vec3}; +use cadcraft_engine::doc::{Common, Drawing, EntityKind, Image, Line, Space}; +use serde_json::json; + +fn hooks() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + set_image_decoder(|_| panic!("decoder bug")); +} + +#[test] +fn a_panicking_decoder_fails_the_image_not_the_drawing() { + hooks(); + let dir = std::env::temp_dir().join(format!("cadcraft-image-panic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("map.png"), b"anything").unwrap(); + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 5.0, 0.0) })).unwrap(); + let i = Image { + u: Vec3::new(1.0, 0.0, 0.0), + v: Vec3::new(0.0, 1.0, 0.0), + size: Vec2::new(4.0, 2.0), + path: "map.png".into(), + name: "map".into(), + ..Image::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + let host = dir.join("host.dxf"); + std::fs::write(&host, cadcraft_io::write(&d, "host.dxf").unwrap()).unwrap(); + + let mut s = Session::new(); + s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap(); + let doc = s.doc().unwrap(); + assert_eq!(doc.model.len(), 2, "the drawing opened with everything in it"); + assert!(doc.rasters.is_empty()); + assert!(s.log.iter().any(|l| l.contains("map.png") && l.contains("damaged")), "{:?}", s.log); + + let before = s.doc().unwrap().model.len(); + let e = s.execute("imageattach", &json!({ "path": "other.png", "data": base64_encode(b"bytes") })).unwrap_err().to_string(); + assert!(e.contains("damaged"), "{e}"); + assert_eq!(s.doc().unwrap().model.len(), before); + // The session still works. + s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap(); + assert_eq!(s.doc().unwrap().model.len(), before + 1); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 2e8b3cc80..f719bbade 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -22,6 +22,7 @@ serde = { workspace = true } miniz_oxide = "0.9" craft-pdf = { workspace = true, features = ["write"] } quick-xml = { workspace = true } +image = { workspace = true } [dev-dependencies] # Reads CADCraft's DWG output as written (tests only; the same version as cadcraft-dwg's). diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 8cad3f24f..f2898ac25 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -14,6 +14,8 @@ mod dxf_write; mod dxf_xref; pub mod pdf; pub mod plotter; +/// Raster image files (PNG, JPEG, BMP, TIFF) decoded to pixels. +pub mod raster; pub mod svg; mod svg_read; diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 3f35233a8..d242112bb 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -844,6 +844,8 @@ fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts: } } Kind::Point => point(s, &mut batch, &p.map, raw, m), + // Raster images are not written to PDF yet: their frame is. + Kind::Image { .. } => {} } } flush(s, &mut batch); diff --git a/crates/io/src/raster.rs b/crates/io/src/raster.rs new file mode 100644 index 000000000..3e09ef9c9 --- /dev/null +++ b/crates/io/src/raster.rs @@ -0,0 +1,79 @@ +//! Raster image files decoded to pixels (IMAGEATTACH): PNG, JPEG, BMP and TIFF, the format taken +//! from the content. Files are hostile input: the size is read from the header and checked +//! before any pixel is decoded. + +use std::io::Cursor; + +use cadcraft_doc::Raster; + +use crate::{IoError, Result}; + +/// Largest image file read (bytes). +pub const MAX_IMAGE_BYTES: usize = 256 << 20; +/// Most pixels decoded per image (four bytes each in memory). +pub const MAX_IMAGE_PIXELS: u64 = 128_000_000; + +fn bad(e: impl std::fmt::Display) -> IoError { + IoError::Format(format!("image: {e}")) +} + +/// A reader over an image file, once it is small enough and of a format we read. +fn reader(bytes: &[u8]) -> Result>> { + if bytes.len() > MAX_IMAGE_BYTES { + return Err(bad(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20))); + } + // The format comes from the file's first bytes, not from its name. + let file = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(bad)?; + if file.format().is_none() { + return Err(bad("not a PNG, JPEG, BMP or TIFF file")); + } + Ok(file) +} + +/// The width and height in pixels of the image in `bytes`, read from its header. +pub fn probe(bytes: &[u8]) -> Result<(u32, u32)> { + let (width, height) = reader(bytes)?.into_dimensions().map_err(bad)?; + if width == 0 || height == 0 { + return Err(bad("the image is empty")); + } + if u64::from(width).saturating_mul(u64::from(height)) > MAX_IMAGE_PIXELS { + return Err(bad(format!("{width} x {height} pixels is more than {} megapixels", MAX_IMAGE_PIXELS / 1_000_000))); + } + Ok((width, height)) +} + +/// Decode the image in `bytes`. +pub fn decode(bytes: &[u8]) -> Result { + // The size is checked first, from the header alone. + let (width, height) = probe(bytes)?; + let mut file = reader(bytes)?; + file.limits(decode_limits(width, height)); + let pixels = file.decode().map_err(bad)?.into_rgba8(); + Raster::new(pixels.width(), pixels.height(), pixels.into_raw()).ok_or_else(|| bad("the image is empty")) +} + +/// What the decoder may allocate for an image of this size: the pixels themselves (up to 16 +/// bytes each before they become 8-bit RGBA) and its own working buffers. +fn decode_limits(width: u32, height: u32) -> image::Limits { + let pixels = u64::from(width).saturating_mul(u64::from(height)); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(width); + limits.max_image_height = Some(height); + limits.max_alloc = Some(pixels.saturating_mul(16).saturating_add(64 << 20)); + limits +} + +/// `raster` as a PNG file. +pub fn encode_png(raster: &Raster) -> Result> { + let mut out = Cursor::new(Vec::new()); + image::write_buffer_with_format( + &mut out, + raster.rgba(), + raster.width(), + raster.height(), + image::ExtendedColorType::Rgba8, + image::ImageFormat::Png, + ) + .map_err(bad)?; + Ok(out.into_inner()) +} diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index b5ace3bcf..2312c9d5f 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -96,6 +96,8 @@ pub fn export_list(list: &cadcraft_render::DisplayList, window: Option) } s.push_str(r#""/>"#); } + // Raster images are not written to SVG yet: their frame is. + Kind::Image { .. } => {} Kind::Point => { if let Some(q) = pts.first() { let _ = write!(s, r#""#, tx(q.x), ty(q.y), stroke); diff --git a/crates/io/tests/raster_decode.rs b/crates/io/tests/raster_decode.rs new file mode 100644 index 000000000..51a6130b7 --- /dev/null +++ b/crates/io/tests/raster_decode.rs @@ -0,0 +1,172 @@ +//! Raster image files decoded to pixels (IMAGEATTACH): round trip through PNG, and hostile files +//! (truncated, random, absurd sizes) refused without a panic. + +use cadcraft_doc::Raster; +use cadcraft_io::raster::{MAX_IMAGE_PIXELS, decode, encode_png, probe}; + +/// A 3 x 2 image with a different colour per pixel, one of them half transparent. +fn sample() -> Raster { + let px: [[u8; 4]; 6] = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 0, 255], [0, 255, 255, 128], [10, 20, 30, 255]]; + Raster::new(3, 2, px.concat()).unwrap() +} + +#[test] +fn png_round_trips_pixel_for_pixel() { + let r = sample(); + let png = encode_png(&r).unwrap(); + assert_eq!(probe(&png).unwrap(), (3, 2)); + let back = decode(&png).unwrap(); + assert_eq!(back, r); + assert!(!back.opaque()); + assert_eq!(back.pixel(1, 1), Some([0, 255, 255, 128])); + assert_eq!(back.pixel(3, 0), None); +} + +#[test] +fn hostile_image_does_not_panic() { + let png = encode_png(&sample()).unwrap(); + // Empty, random, not an image, and every truncation of a real file. + for bytes in [&b""[..], &[0u8; 64], b"0\nSECTION\n2\nHEADER\n", &[0xff; 4096]] { + assert!(decode(bytes).is_err()); + assert!(probe(bytes).is_err()); + } + for n in 0..png.len() { + let _ = probe(&png[..n]); + let _ = decode(&png[..n]); + } + assert!(decode(&png[..png.len() / 2]).is_err()); + // Every byte flipped in turn: an error or an image, never a panic. + for i in 0..png.len() { + let mut b = png.clone(); + b[i] ^= 0xff; + let _ = decode(&b); + } +} + +#[test] +fn an_absurd_declared_size_is_refused_before_decoding() { + // A PNG declaring 60000 x 60000 pixels (3.6 gigapixels) with no pixel data. + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = b"IHDR".to_vec(); + ihdr.extend(60000u32.to_be_bytes()); + ihdr.extend(60000u32.to_be_bytes()); + ihdr.extend([8, 6, 0, 0, 0]); + for chunk in [&ihdr[..], b"IDAT", b"IEND"] { + png.extend(u32::try_from(chunk.len() - 4).unwrap().to_be_bytes()); + png.extend(chunk); + png.extend(crc32(chunk).to_be_bytes()); + } + assert!(u64::from(60000u32) * 60000 > MAX_IMAGE_PIXELS); + let e = decode(&png).unwrap_err().to_string(); + assert!(e.contains("megapixels"), "{e}"); +} + +fn crc32(data: &[u8]) -> u32 { + let mut c = !0u32; + for b in data { + c ^= u32::from(*b); + for _ in 0..8 { + c = if c & 1 != 0 { 0xedb8_8320 ^ (c >> 1) } else { c >> 1 }; + } + } + !c +} + +#[test] +fn raster_new_checks_the_buffer() { + assert!(Raster::new(0, 4, Vec::new()).is_none()); + assert!(Raster::new(2, 2, vec![0; 15]).is_none()); + assert!(Raster::new(u32::MAX, u32::MAX, vec![0; 16]).is_none()); + assert!(Raster::new(2, 2, vec![255; 16]).unwrap().opaque()); +} + +/// `r` written in `format` by the image library. +fn encoded(r: &Raster, format: image::ImageFormat, color: image::ExtendedColorType, bytes: &[u8]) -> Vec { + let mut out = std::io::Cursor::new(Vec::new()); + image::write_buffer_with_format(&mut out, bytes, r.width(), r.height(), color, format).unwrap(); + out.into_inner() +} + +#[test] +fn bmp_tiff_and_jpeg_files_are_read() { + // Opaque colours in 8 x 8 blocks (JPEG works in blocks of that size). + let (w, h) = (16u32, 8u32); + let rgb: Vec = (0..h).flat_map(|_| (0..w).flat_map(|x| if x < 8 { [200u8, 30, 30] } else { [30, 30, 200] })).collect(); + let rgba: Vec = rgb.chunks(3).flat_map(|p| [p[0], p[1], p[2], 255]).collect(); + let r = Raster::new(w, h, rgba).unwrap(); + + for format in [image::ImageFormat::Bmp, image::ImageFormat::Tiff] { + let file = encoded(&r, format, image::ExtendedColorType::Rgb8, &rgb); + assert_eq!(probe(&file).unwrap(), (w, h), "{format:?}"); + let back = decode(&file).unwrap(); + assert_eq!(back, r, "{format:?} keeps every pixel"); + assert!(back.opaque()); + } + + // JPEG loses a little: the colours are close, the size exact. + let file = encoded(&r, image::ImageFormat::Jpeg, image::ExtendedColorType::Rgb8, &rgb); + let back = decode(&file).unwrap(); + assert_eq!((back.width(), back.height()), (w, h)); + for (x, want) in [(2, [200u8, 30, 30]), (13, [30, 30, 200])] { + let got = back.pixel(x, 4).unwrap(); + assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 12) && got[3] == 255, "{got:?} at {x}"); + } + + // Grey and grey-with-alpha files become RGBA. + let grey = Raster::new(2, 1, vec![0, 0, 0, 255, 255, 255, 255, 255]).unwrap(); + assert_eq!(decode(&encoded(&grey, image::ImageFormat::Png, image::ExtendedColorType::L8, &[0, 255])).unwrap(), grey); + let grey_alpha = Raster::new(2, 1, vec![9, 9, 9, 0, 255, 255, 255, 128]).unwrap(); + assert_eq!(decode(&encoded(&grey_alpha, image::ImageFormat::Png, image::ExtendedColorType::La8, &[9, 0, 255, 128])).unwrap(), grey_alpha); +} + +#[test] +fn damaged_files_of_every_format_do_not_panic() { + let (w, h) = (16u32, 8u32); + let rgb = vec![120u8; (w * h * 3) as usize]; + let r = Raster::new(w, h, vec![255; (w * h * 4) as usize]).unwrap(); + for format in [image::ImageFormat::Bmp, image::ImageFormat::Tiff, image::ImageFormat::Jpeg] { + let file = encoded(&r, format, image::ExtendedColorType::Rgb8, &rgb); + for n in 0..file.len() { + let _ = probe(&file[..n]); + let _ = decode(&file[..n]); + } + for i in 0..file.len() { + let mut b = file.clone(); + b[i] ^= 0xff; + let _ = decode(&b); + b[i] = 0; + let _ = decode(&b); + } + } +} + +#[test] +fn the_pixels_never_reach_the_drawing_file() { + use cadcraft_doc::{Common, Drawing, EntityKind, Image, Space}; + use cadcraft_geom::{Vec2, Vec3}; + let mut d = Drawing::new_metric(); + let i = Image { + insert: Vec3::new(3.0, 4.0, 0.0), + u: Vec3::new(0.5, 0.0, 0.0), + v: Vec3::new(0.0, 0.5, 0.0), + size: Vec2::new(3.0, 2.0), + path: "maps/site.png".into(), + name: "site".into(), + ..Image::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Image(i.clone())).unwrap(); + d.rasters.insert("maps/site.png", std::sync::Arc::new(sample())); + let text = cadcraft_io::write_dxf(&d); + assert!(text.contains("maps/site.png")); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + assert!(back.rasters.is_empty(), "a drawing just read has no pixels"); + let got: Vec<&Image> = back.model.iter().filter_map(|e| if let EntityKind::Image(i) = &e.kind { Some(i) } else { None }).collect(); + // An unclipped image is written with the boundary of the whole image, switched off. + let i = Image { clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(2.5, 1.5)], ..i }; + assert_eq!(got, [&i]); + // Loaded pixels don't make two drawings differ. + let mut bare = d.clone(); + bare.rasters.remove("maps/site.png"); + assert!(bare.rasters.is_empty() && d.rasters.len() == 1); + assert_eq!(bare, d); +} diff --git a/crates/io/tests/raster_foreign_files.rs b/crates/io/tests/raster_foreign_files.rs new file mode 100644 index 000000000..bf7c7ace7 --- /dev/null +++ b/crates/io/tests/raster_foreign_files.rs @@ -0,0 +1,222 @@ +//! Raster image files CADCraft did not write itself (#956): files made by another program, and +//! files laid out by hand from the formats' public descriptions, so reading is not only checked +//! against the library that also does the writing. +//! +//! The four embedded files hold our own synthetic picture (16 x 8 pixels: the left half +//! (200, 30, 30), the right half (30, 30, 200)), converted from a hand-built PNG with the macOS +//! command `sips` (`-s format jpeg|tiff|bmp|png`, colour profile removed). They contain nothing +//! but those pixels and the encoder's headers. + +use cadcraft_doc::Raster; +use cadcraft_io::raster::{decode, probe}; + +/// JPEG, baseline, quality 90, with JFIF and Exif headers. +const SIPS_JPEG: &str = "ffd8ffe000104a46494600010100004800480000ffe1004c4578696600004d4d002a00000008000187690004000000010000001a000000000003a001 \ + 000300000001ffff0000a00200040000000100000010a0030004000000010000000800000000ffed003850686f746f73686f7020332e30003842494d \ + 04040000000000003842494d0425000000000010d41d8cd98f00b204e9800998ecf8427effc00011080008001003012200021101031101ffc4001f00 \ + 00010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d0102030004110512213141 \ + 0613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758 \ + 595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8 \ + c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f01000301010101010101010100000000000001020304050607 \ + 08090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272 \ + d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a8283848586 \ + 8788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3 \ + f4f5f6f7f8f9faffdb004300020202020202030202030503030305060505050506080606060606080a0808080808080a0a0a0a0a0a0a0a0c0c0c0c0c \ + 0c0e0e0e0e0e0f0f0f0f0f0f0f0f0f0fffdb00430102030304040407040407100b090b10101010101010101010101010101010101010101010101010 \ + 10101010101010101010101010101010101010101010101010ffdd00040001ffda000c03010002110311003f00f90ebe7fafa02be7fafdc7e8f3ff00 \ + 331ffb87ff00b79fd1de3aff00cc07fdbfff00b69fffd9"; +/// TIFF, big-endian, LZW compressed. +const SIPS_TIFF_LZW: &str = "4d4d002a000000680002a00200040000000100000010a0030004000000010000000800000000803203c1e004160d0784424ac00554261d0f814121f1 \ + 38342e1b148a44631148b46e271a8f43a3b2184c82490791c9e0d2695002532d964aa5f2a98c9e672780800000100100000300000001001000000101 \ + 0003000000010008000001020003000000030000012e010300030000000100050000010600030000000100020000010a000300000001000100000111 \ + 00040000000100000026011200030000000100010000011500030000000100030000011600030000000100080000011700040000000100000041011c \ + 00030000000100010000012800030000000100020000013d000300000001000200000153000300000003000001348769000400000001000000080000 \ + 0000000800080008000100010001"; +/// TIFF, big-endian, not compressed. +const SIPS_TIFF_PLAIN: &str = "4d4d002a000001a60002a00200040000000100000010a0030004000000010000000800000000c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8 \ + 1e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e \ + 1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e \ + 1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec8 \ + 1e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8 \ + 1e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e \ + 1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e \ + 1ec8000f0100000300000001001000000101000300000001000800000102000300000003000002600103000300000001000100000106000300000001 \ + 00020000010a000300000001000100000111000400000001000000260112000300000001000100000115000300000001000300000116000300000001 \ + 00080000011700040000000100000180011c000300000001000100000128000300000001000200000153000300000003000002668769000400000001 \ + 0000000800000000000800080008000100010001"; +/// BMP, 24 bits, rows stored top-down (negative height). +const SIPS_BMP: &str = "424db601000000000000360000002800000010000000f8ffffff010018000000000080010000000000000000000000000000000000001e1ec81e1ec8 \ + 1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8 \ + 1e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1e \ + c81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1e \ + c81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec8 \ + 1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8 \ + 1e1ec81e1ec8c81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1e1e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec81e1ec8c81e1ec81e1e \ + c81e1ec81e1ec81e1ec81e1ec81e1ec81e1e"; +/// PNG as that program writes it (its own chunks and compression). +const SIPS_PNG: &str = "89504e470d0a1a0a0000000d49484452000000100000000808020000007f14e8c00000000467414d410000b18f0bfc6105000000206348524d00007a \ + 26000080840000fa00000080e8000075300000ea6000003a98000017709cba513c00000038655849664d4d002a000000080001876900040000000100 \ + 00001a000000000002a00200040000000100000010a0030004000000010000000800000000470d8f8b000001c869545874584d4c3a636f6d2e61646f \ + 62652e786d7000000000003c783a786d706d65746120786d6c6e733a783d2261646f62653a6e733a6d6574612f2220783a786d70746b3d22584d5020 \ + 436f726520362e302e30223e0a2020203c7264663a52444620786d6c6e733a7264663d22687474703a2f2f7777772e77332e6f72672f313939392f30 \ + 322f32322d7264662d73796e7461782d6e7323223e0a2020202020203c7264663a4465736372697074696f6e207264663a61626f75743d22220a2020 \ + 20202020202020202020786d6c6e733a657869663d22687474703a2f2f6e732e61646f62652e636f6d2f657869662f312e302f223e0a202020202020 \ + 2020203c657869663a436f6c6f7253706163653e313c2f657869663a436f6c6f7253706163653e0a2020202020202020203c657869663a506978656c \ + 5844696d656e73696f6e3e31363c2f657869663a506978656c5844696d656e73696f6e3e0a2020202020202020203c657869663a506978656c594469 \ + 6d656e73696f6e3e383c2f657869663a506978656c5944696d656e73696f6e3e0a2020202020203c2f7264663a4465736372697074696f6e3e0a2020 \ + 203c2f7264663a5244463e0a3c2f783a786d706d6574613e0ae6ba92b400000021494441541819633c2127c7800d8431acc226ccc08455148fe0a806 \ + 3c8103970200086302148ee3f7130000000049454e44ae426082"; + +fn bytes(hex: &str) -> Vec { + let digits: Vec = hex.bytes().filter(u8::is_ascii_hexdigit).collect(); + digits.chunks(2).map(|p| u8::from_str_radix(std::str::from_utf8(p).unwrap(), 16).unwrap()).collect() +} + +const LEFT: [u8; 3] = [200, 30, 30]; +const RIGHT: [u8; 3] = [30, 30, 200]; + +/// The picture is the two-colour 16 x 8 one, each colour within `tolerance`. +#[track_caller] +fn is_the_picture(r: &Raster, tolerance: u8, what: &str) { + assert_eq!((r.width(), r.height()), (16, 8), "{what}"); + assert!(r.opaque(), "{what}"); + for y in 0..8 { + for x in 0..16 { + // A lossy file blends the columns around the colour change (JPEG stores colour at + // half resolution). + if tolerance > 3 && (6..=9).contains(&x) { + continue; + } + let want = if x < 8 { LEFT } else { RIGHT }; + let got = r.pixel(x, y).unwrap(); + assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= tolerance), "{what}: {got:?} at {x},{y}, wanted {want:?}"); + } + } +} + +#[test] +fn files_written_by_another_program_are_read() { + for (hex, tolerance, what) in [ + (SIPS_PNG, 3, "PNG"), + (SIPS_BMP, 3, "top-down BMP"), + (SIPS_TIFF_LZW, 3, "LZW TIFF"), + (SIPS_TIFF_PLAIN, 3, "plain TIFF"), + (SIPS_JPEG, 14, "JPEG"), + ] { + let file = bytes(hex); + assert_eq!(probe(&file).unwrap(), (16, 8), "{what}"); + is_the_picture(&decode(&file).unwrap(), tolerance, what); + // Cut short or damaged, they are refused or read: never a panic. + for n in 0..file.len() { + let _ = decode(&file[..n]); + } + for i in 0..file.len() { + let mut b = file.clone(); + b[i] ^= 0x55; + let _ = decode(&b); + } + } +} + +/// An uncompressed RGB TIFF of one strip, laid out by hand: header, pixels, then the directory. +fn tiff_by_hand(big_endian: bool, w: u32, h: u32, rgb: &[u8]) -> Vec { + let u16b = |v: u16| if big_endian { v.to_be_bytes() } else { v.to_le_bytes() }; + let u32b = |v: u32| if big_endian { v.to_be_bytes() } else { v.to_le_bytes() }; + let mut f: Vec = if big_endian { b"MM".to_vec() } else { b"II".to_vec() }; + f.extend(u16b(42)); + let pixels_at = 8u32; + let bits_at = pixels_at + rgb.len() as u32; + let dir_at = bits_at + 6; + f.extend(u32b(dir_at)); + f.extend(rgb); + for _ in 0..3 { + f.extend(u16b(8)); + } + // (tag, type: 3 short / 4 long, count, value) + let entries: [(u16, u16, u32, u32); 10] = [ + (256, 4, 1, w), + (257, 4, 1, h), + (258, 3, 3, bits_at), + (259, 3, 1, 1), + (262, 3, 1, 2), + (273, 4, 1, pixels_at), + (277, 3, 1, 3), + (278, 4, 1, h), + (279, 4, 1, rgb.len() as u32), + (284, 3, 1, 1), + ]; + f.extend(u16b(entries.len() as u16)); + for (tag, kind, count, value) in entries { + f.extend(u16b(tag)); + f.extend(u16b(kind)); + f.extend(u32b(count)); + // A single short sits in the first two bytes of the value field. + if kind == 3 && count == 1 { + f.extend(u16b(value as u16)); + f.extend([0, 0]); + } else { + f.extend(u32b(value)); + } + } + f.extend(u32b(0)); + f +} + +/// A 24-bit BMP laid out by hand: rows bottom-up, blue-green-red, each padded to four bytes. +fn bmp_by_hand(w: u32, h: u32, rgb: &[u8]) -> Vec { + let row = (w as usize * 3).div_ceil(4) * 4; + let size = 54 + row * h as usize; + let mut f = b"BM".to_vec(); + f.extend((size as u32).to_le_bytes()); + f.extend([0; 4]); + f.extend(54u32.to_le_bytes()); + f.extend(40u32.to_le_bytes()); + f.extend((w as i32).to_le_bytes()); + f.extend((h as i32).to_le_bytes()); + f.extend(1u16.to_le_bytes()); + f.extend(24u16.to_le_bytes()); + f.extend([0; 24]); + for y in (0..h as usize).rev() { + let line = &rgb[y * w as usize * 3..(y + 1) * w as usize * 3]; + for p in line.chunks(3) { + f.extend([p[2], p[1], p[0]]); + } + f.extend(std::iter::repeat_n(0, row - w as usize * 3)); + } + f +} + +#[test] +fn files_laid_out_by_hand_are_read_pixel_for_pixel() { + // 3 x 2: an odd width, so BMP rows are padded; every pixel different. + let rgb: Vec = (0..18u8).map(|i| i * 13 + 5).collect(); + let rgba: Vec = rgb.chunks(3).flat_map(|p| [p[0], p[1], p[2], 255]).collect(); + let want = Raster::new(3, 2, rgba).unwrap(); + for (file, what) in [ + (tiff_by_hand(false, 3, 2, &rgb), "little-endian TIFF"), + (tiff_by_hand(true, 3, 2, &rgb), "big-endian TIFF"), + (bmp_by_hand(3, 2, &rgb), "bottom-up BMP"), + ] { + assert_eq!(probe(&file).unwrap(), (3, 2), "{what}"); + assert_eq!(decode(&file).unwrap(), want, "{what}"); + } +} + +#[test] +fn hand_made_files_that_lie_about_their_size_are_refused() { + let rgb = [9u8; 18]; + // More pixels declared than the file holds. + for file in [tiff_by_hand(false, 300, 200, &rgb), tiff_by_hand(true, 3, 2000, &rgb), bmp_by_hand(3, 2, &rgb)[..60].to_vec()] { + assert!(decode(&file).is_err()); + } + // Sizes past the limit, before any pixel is read. + for file in [tiff_by_hand(false, 60_000, 60_000, &rgb), tiff_by_hand(true, u32::MAX, u32::MAX, &rgb)] { + assert!(decode(&file).is_err()); + } + let mut bmp = bmp_by_hand(3, 2, &rgb); + bmp[18..22].copy_from_slice(&60_000i32.to_le_bytes()); + bmp[22..26].copy_from_slice(&60_000i32.to_le_bytes()); + assert!(decode(&bmp).is_err()); + // A zero-sized image. + assert!(decode(&tiff_by_hand(false, 0, 0, &[])).is_err()); +} diff --git a/crates/render/src/display.rs b/crates/render/src/display.rs index e6ba6b7e9..5fa663974 100644 --- a/crates/render/src/display.rs +++ b/crates/render/src/display.rs @@ -22,6 +22,51 @@ pub enum Kind { Point, /// An infinite line or ray: `verts[start]` = base, `verts[start+1]` = unit direction. Infinite { ray: bool }, + /// A raster image, [`DisplayList::images`]`[index]`; `verts[start..start+4]` are its corners + /// (top left, top right, bottom right, bottom left of the pixel grid). + Image { index: u32 }, +} + +/// A raster image placed in the world. +#[derive(Clone, Debug, PartialEq)] +pub struct DImage { + pub raster: std::sync::Arc, + /// Where the top-left corner of the top-left pixel is. + pub origin: Vec2, + /// One pixel to the right and one pixel down, in world units. + pub right: Vec2, + pub down: Vec2, + /// Closed outlines the image is cut to (all of them: its own clip boundary, then the + /// viewports it is seen through). Empty: the whole image. + pub clips: Vec>, + /// Fade towards the background, percent (0..=100). + pub fade: u8, +} + +impl DImage { + /// The world position of pixel-grid point (`x`, `y`), `y` down from the top. + pub fn at(&self, x: f64, y: f64) -> Vec2 { + self.origin + self.right * x + self.down * y + } + /// The pixel-grid point at world position `q` (the inverse of [`DImage::at`]); `None` for an + /// image squashed to a line or a point. + pub fn pixel_of(&self, q: Vec2) -> Option { + let det = self.right.x * self.down.y - self.right.y * self.down.x; + if !(det.is_finite() && det.abs() > 0.0) { + return None; + } + let d = q - self.origin; + Some(Vec2::new((d.x * self.down.y - d.y * self.down.x) / det, (self.right.x * d.y - self.right.y * d.x) / det)) + } + /// How opaque the image is drawn, 0..=1: the object's opacity `alpha` (0..=255) less the fade. + pub fn opacity(&self, alpha: u8) -> f32 { + f32::from(alpha) / 255.0 * (1.0 - f32::from(self.fade.min(100)) / 100.0) + } + /// The corners: top left, top right, bottom right, bottom left. + pub fn corners(&self) -> [Vec2; 4] { + let (w, h) = (f64::from(self.raster.width()), f64::from(self.raster.height())); + [self.at(0.0, 0.0), self.at(w, 0.0), self.at(w, h), self.at(0.0, h)] + } } #[derive(Clone, Copy, Debug, PartialEq)] @@ -46,6 +91,8 @@ pub struct DisplayList { pub prims: Vec, pub verts: Vec, pub tris: Vec, + /// The raster images drawn by [`Kind::Image`] primitives. + pub images: Vec, /// Plots ([`build_plot`]): for each primitive, the index in [`Drawing::layers`] of the layer /// it is drawn on (block contents on layer 0: the block reference's; [`NO_LAYER`] when the /// layer isn't in the table), for PDF layers. Empty for other lists. @@ -131,14 +178,19 @@ impl DisplayList { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) { let (verts, tris, prims) = (dst.verts.len() as u32, dst.tris.len() as u32, dst.prims.len() as u32); + let images = dst.images.len() as u32; // Pens are parallel to the primitives, with missing entries meaning "use object". if !src.pens.is_empty() { dst.pens.resize(dst.prims.len(), Pen::default()); } dst.prims.extend(src.prims.into_iter().map(|mut p| { p.start += if matches!(p.kind, Kind::Tris | Kind::Mask) { tris } else { verts }; + if let Kind::Image { index } = &mut p.kind { + *index = index.saturating_add(images); + } p })); + dst.images.extend(src.images); dst.verts.extend(src.verts); dst.tris.extend(src.tris); dst.prim_layers.extend(src.prim_layers); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index cf37e28f7..d6ecede7c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -186,9 +186,17 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { let o = i.insert.xy(); let u = i.u.xy() * i.size.x; let v = i.v.xy() * i.size.y; + // Display flag 1: show the image. Without pixels (file not found, not loaded yet, + // hidden) the rectangle is crossed out. + let raster = if i.display & 1 != 0 { ctx.d.rasters.get(&i.path) } else { None }; + if let Some(r) = raster { + b.image(ctx, rgb, i, r); + } b.polyline(ctx, rgb, lw, &[o, o + u, o + u + v, o + v, o]); - b.polyline(ctx, rgb, lw, &[o, o + u + v]); - b.polyline(ctx, rgb, lw, &[o + u, o + v]); + if raster.is_none() { + b.polyline(ctx, rgb, lw, &[o, o + u + v]); + b.polyline(ctx, rgb, lw, &[o + u, o + v]); + } } EntityKind::Table(t) => table(b, ctx, t, rgb, lw), EntityKind::Tolerance(t) => tolerance::draw(b, ctx, e, t, lw, tol), diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6fa236e4c..0e34ee68a 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -186,6 +186,45 @@ impl Builder<'_> { len: pts.len() as u32, }); } + /// The pixels of image `i` over its rectangle, cut to its clip boundary. + fn image(&mut self, ctx: &Ctx, color: Ink, i: &cadcraft_doc::Image, raster: &std::sync::Arc) { + // Where the entity puts its picture: the top-left corner, and one of its pixels to the + // right and down. + let top_left = ctx.xf.apply(i.insert.xy() + i.v.xy() * i.size.y); + let right = ctx.xf.apply_vec(i.u.xy()); + let down = ctx.xf.apply_vec(i.v.xy() * -1.0); + let clip = image_clip(i, |q| top_left + right * q.x + down * q.y); + // The file found can have another pixel count than the entity records: its pixels are + // stretched over the same rectangle. + let img = DImage { + raster: raster.clone(), + origin: top_left, + right: right * (i.size.x / f64::from(raster.width())), + down: down * (i.size.y / f64::from(raster.height())), + clips: clip.into_iter().collect(), + fade: i.fade.min(100), + }; + let corners = img.corners(); + if !corners.iter().all(|q| q.x.is_finite() && q.y.is_finite()) { + return; + } + let (Ok(index), Ok(start)) = (u32::try_from(self.list.images.len()), u32::try_from(self.list.verts.len())) else { return }; + for q in corners { + self.list.bounds.add(q); + self.list.verts.push(q); + } + self.list.images.push(img); + self.list.prims.push(DPrim { + handle: ctx.top, + color: color.rgb, + aci7: color.aci7, + lw: 0.0, + transparency: self.transparency, + kind: Kind::Image { index }, + start, + len: 4, + }); + } fn tris(&mut self, ctx: &Ctx, color: Ink, tris: &[Vec2]) { self.tris_at(ctx, color, tris, ctx.xf); } @@ -298,6 +337,23 @@ impl Builder<'_> { } } +/// The clip boundary of image `i` as a closed outline, or `None` when the whole image shows. +/// `place` gives the position of a point of the entity's pixel grid (x right, y down from the +/// top-left corner of the image). +fn image_clip(i: &cadcraft_doc::Image, place: impl Fn(Vec2) -> Vec2) -> Option> { + if !i.clipping { + return None; + } + // Boundaries count from pixel centres: the top-left corner of the image is (-0.5, -0.5). + let at = |q: Vec2| place(Vec2::new(q.x + 0.5, q.y + 0.5)); + match i.clip.as_slice() { + // Two opposite corners of a rectangle. + [a, b] => Some(vec![at(*a), at(Vec2::new(b.x, a.y)), at(*b), at(Vec2::new(a.x, b.y))]), + polygon if polygon.len() >= 3 => Some(polygon.iter().map(|q| at(*q)).collect()), + _ => None, + } +} + mod table; pub use table::{MAX_LAYOUT_CELLS, TableFill, TableGeom, TableLine, TableText, table_covered, table_geometry, table_style_of}; @@ -311,7 +367,7 @@ mod text_entity; mod viewports; pub use dim_draw::{dim_text, dimension_in}; -pub use display::{DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha}; +pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha}; pub use pipeline::{Options, build, build_entities, build_plot}; use props::{default_lineweight, resolve_common}; use text_entity::text_style; diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 72ac821d0..761191dce 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -4,7 +4,7 @@ use cadcraft_color::Rgb; use cadcraft_geom::{Bounds2, Vec2}; use tiny_skia::{FillRule, LineCap, LineJoin, Paint, PathBuilder, Pixmap, Stroke, Transform}; -use crate::{DisplayList, Kind}; +use crate::{DImage, DisplayList, Kind}; /// A 2D view: world point at the image centre and pixels per drawing unit. #[derive(Clone, Copy, Debug, PartialEq)] @@ -147,6 +147,13 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option { + if let Some(img) = list.images.get(index as usize) + && Bounds2::from_points(pts.iter().copied()).intersects(&vis) + { + image(&mut pm, img, view, p.alpha(), o.antialias); + } + } Kind::Infinite { ray } => { let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) else { continue }; let far = (vis.width() + vis.height()) * 2.0 + base.dist(vis.center()); @@ -222,6 +229,95 @@ impl Hairlines { } } +/// Draw `img` with the object opacity `alpha`, cut to its clip outlines. +fn image(pm: &mut Pixmap, img: &DImage, view: &View, alpha: u8, antialias: bool) { + let r = &img.raster; + let Some(to_screen) = grid_to_screen(img, view) else { return }; + let Ok(mask) = clip_mask(pm, img, view, antialias) else { return }; + // tiny-skia wants premultiplied pixels; opaque ones already are. + let owned; + let pixels = if r.opaque() { + tiny_skia::PixmapRef::from_bytes(r.rgba(), r.width(), r.height()) + } else { + owned = premultiplied(r); + owned.as_ref().map(Pixmap::as_ref) + }; + let Some(pixels) = pixels else { return }; + let paint = Paint { + shader: tiny_skia::Pattern::new( + pixels, + tiny_skia::SpreadMode::Pad, + tiny_skia::FilterQuality::Bilinear, + img.opacity(alpha), + Transform::identity(), + ), + anti_alias: antialias, + ..Paint::default() + }; + // The picture's own rectangle in its pixel grid, carried to the screen by `to_screen`. + // Filled as a path: tiny-skia's anti-aliased `fill_rect` trips a debug assertion on narrow + // rects (see the points above), which a one-pixel image drawn at its own size would be. + if let Some(rect) = tiny_skia::Rect::from_xywh(0.0, 0.0, r.width() as f32, r.height() as f32) { + pm.fill_path(&PathBuilder::from_rect(rect), &paint, FillRule::Winding, to_screen, mask.as_ref()); + } +} + +/// The transform from `img`'s pixel grid (x right, y down) to screen pixels; `None` when the +/// image has no area on screen or lies out of number range. +fn grid_to_screen(img: &DImage, view: &View) -> Option { + let s = view.scale; + let (x, y) = view.to_screen(img.origin); + // Screen y runs down, world y up. + let ts = Transform::from_row((img.right.x * s) as f32, (-img.right.y * s) as f32, (img.down.x * s) as f32, (-img.down.y * s) as f32, x, y); + (ts.is_finite() && ts.invert().is_some()).then_some(ts) +} + +/// The image has a clip outline without area: nothing of it shows. +struct Hidden; + +/// The part of the picture `img`'s clip outlines leave visible: `None` for all of it. +fn clip_mask(pm: &Pixmap, img: &DImage, view: &View, antialias: bool) -> Result, Hidden> { + let mut mask: Option = None; + for outline in &img.clips { + let path = outline_path(outline, view).ok_or(Hidden)?; + match &mut mask { + // The first outline starts the mask; each further one narrows it. + None => { + let mut m = tiny_skia::Mask::new(pm.width(), pm.height()).ok_or(Hidden)?; + m.fill_path(&path, FillRule::EvenOdd, antialias, Transform::identity()); + mask = Some(m); + } + Some(m) => m.intersect_path(&path, FillRule::EvenOdd, antialias, Transform::identity()), + } + } + Ok(mask) +} + +/// A closed world-space outline as a screen path. +fn outline_path(outline: &[Vec2], view: &View) -> Option { + let mut pb = PathBuilder::new(); + for (i, q) in outline.iter().enumerate() { + let (x, y) = view.to_screen(*q); + if i == 0 { + pb.move_to(x, y); + } else { + pb.line_to(x, y); + } + } + pb.close(); + pb.finish() +} + +/// The pixels of `r` with each colour multiplied by its alpha. +fn premultiplied(r: &cadcraft_doc::Raster) -> Option { + let mut data = Vec::with_capacity(r.rgba().len()); + for [red, green, blue, a] in r.rgba().as_chunks::<4>().0 { + let m = |c: &u8| ((u16::from(*c) * u16::from(*a) + 127) / 255) as u8; + data.extend_from_slice(&[m(red), m(green), m(blue), *a]); + } + Pixmap::from_vec(data, tiny_skia::IntSize::from_wh(r.width(), r.height())?) +} + /// Render and encode as PNG. pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option> { render(list, view, o)?.encode_png().ok() diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 6f1e57517..f4d4e7d98 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::{DPrim, DisplayList, Kind, PlotText, VIEWPORT_CONTENT}; +use super::display::{DImage, DPrim, DisplayList, Kind, PlotText, VIEWPORT_CONTENT}; use super::draw::entity; #[cfg(not(target_arch = "wasm32"))] use super::pipeline::PARALLEL_CHUNK; @@ -228,6 +228,11 @@ fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { push_raw(dst, p, Kind::Point, &[*q]); } } + (Kind::Image { index }, _) => { + if let Some(img) = src.images.get(index as usize) { + push_clipped_image(dst, p, img, pts, clip); + } + } (Kind::Infinite { ray }, Clip::Rect(rect)) => { if let (Some(base), Some(dir)) = (pts.first(), pts.get(1)) && let Some((a, c)) = clip::clip_infinite(*base, *dir, ray, rect) @@ -246,6 +251,25 @@ fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { } } +/// Append image `img` (primitive `p`, corners `corners`) to `dst`, to be cut to `clip` when it +/// is drawn: the picture is not cut here, the outline is added to those it carries. +fn push_clipped_image(dst: &mut DisplayList, p: &DPrim, img: &DImage, corners: &[Vec2], clip: &Clip) { + let outline = match clip { + Clip::Rect(rect) => { + if !Bounds2::from_points(corners.iter().copied()).intersects(rect) { + return; + } + vec![rect.min, Vec2::new(rect.max.x, rect.min.y), rect.max, Vec2::new(rect.min.x, rect.max.y)] + } + Clip::Poly(c) => c.polygon().to_vec(), + }; + let Ok(index) = u32::try_from(dst.images.len()) else { return }; + let mut img = img.clone(); + img.clips.push(outline); + dst.images.push(img); + push_raw(dst, p, Kind::Image { index }, corners); +} + fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2]) { let min = match kind { Kind::Polyline => 2, diff --git a/crates/render/tests/raster_image.rs b/crates/render/tests/raster_image.rs new file mode 100644 index 000000000..8cc2d09e8 --- /dev/null +++ b/crates/render/tests/raster_image.rs @@ -0,0 +1,338 @@ +//! Raster images (IMAGE): the pixels are drawn over the image's rectangle, rotated with it and +//! cut to its clip boundary; an image without loaded pixels is a crossed-out frame. + +use std::sync::Arc; + +use cadcraft_color::Rgb; +use cadcraft_doc::{Block, Common, Drawing, Entity, EntityKind, Handle, Image, Insert, Line, Raster, Space, Transparency, Viewport}; +use cadcraft_geom::{Vec2, Vec3}; +use cadcraft_render::raster::{RasterOptions, View, render}; +use cadcraft_render::{Kind, Options, build}; + +const RED: [u8; 4] = [255, 0, 0, 255]; +const GREEN: [u8; 4] = [0, 255, 0, 255]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; +const WHITE: [u8; 4] = [255, 255, 255, 255]; +const BG: Rgb = Rgb(33, 40, 48); + +/// Two by two pixels: red and green on top, blue and white below. +fn pixels() -> Arc { + Arc::new(Raster::new(2, 2, [RED, GREEN, BLUE, WHITE].concat()).unwrap()) +} + +/// A 10 x 10 unit image of `map.png` with its lower-left corner at the origin. +fn image() -> Image { + Image { + insert: Vec3::ZERO, + u: Vec3::new(5.0, 0.0, 0.0), + v: Vec3::new(0.0, 5.0, 0.0), + size: Vec2::new(2.0, 2.0), + path: "map.png".into(), + ..Image::default() + } +} + +fn drawing(i: Image, loaded: bool) -> Drawing { + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + if loaded { + d.rasters.insert("map.png", pixels()); + } + d +} + +/// The colour at the centre of each quarter of the 10 x 10 square: top left, top right, bottom +/// left, bottom right. +fn quarters(d: &Drawing) -> [[u8; 4]; 4] { + let list = build(d, &Space::Model, &Options::default()); + let view = View { center: Vec2::new(5.0, 5.0), scale: 10.0, width: 100, height: 100 }; + let pm = render(&list, &view, &RasterOptions { antialias: false, ..Default::default() }).unwrap(); + [(25, 25), (75, 25), (25, 75), (75, 75)].map(|(x, y)| { + let c = pm.pixel(x, y).unwrap(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) +} + +fn bg() -> [u8; 4] { + [BG.0, BG.1, BG.2, 255] +} + +/// The quarters show `want` (the filter blends a little of the neighbouring pixel in). +#[track_caller] +fn shows(got: [[u8; 4]; 4], want: [[u8; 4]; 4]) { + let near = got.iter().flatten().zip(want.iter().flatten()).all(|(a, b)| a.abs_diff(*b) <= 6); + assert!(near, "{got:?} is not {want:?}"); +} + +#[test] +fn the_pixels_are_drawn_over_the_rectangle() { + let d = drawing(image(), true); + shows(quarters(&d), [RED, GREEN, BLUE, WHITE]); + let list = build(&d, &Space::Model, &Options::default()); + assert_eq!(list.images.len(), 1); + let p = list.prims.iter().find(|p| matches!(p.kind, Kind::Image { .. })).unwrap(); + assert_eq!(list.points(p), [Vec2::new(0.0, 10.0), Vec2::new(10.0, 10.0), Vec2::new(10.0, 0.0), Vec2::new(0.0, 0.0)]); + assert_eq!(list.prims.iter().filter(|p| p.kind == Kind::Polyline).count(), 1, "the frame, not crossed out"); +} + +#[test] +fn an_image_without_pixels_is_a_crossed_out_frame() { + for d in [drawing(image(), false), drawing(Image { display: 6, ..image() }, true)] { + let list = build(&d, &Space::Model, &Options::default()); + assert!(list.images.is_empty()); + assert_eq!(list.prims.iter().filter(|p| p.kind == Kind::Polyline).count(), 3, "frame and two diagonals"); + } +} + +#[test] +fn the_image_turns_with_its_axes() { + // Turned a quarter turn counter-clockwise about its lower-left corner, then moved back over + // the square: the image's top edge is now the square's left edge. + let i = Image { insert: Vec3::new(10.0, 0.0, 0.0), u: Vec3::new(0.0, 5.0, 0.0), v: Vec3::new(-5.0, 0.0, 0.0), ..image() }; + shows(quarters(&drawing(i, true)), [GREEN, WHITE, RED, BLUE]); +} + +#[test] +fn the_clip_boundary_cuts_the_image() { + // The left pixel column only (pixel coordinates from pixel centres, y down from the top). + let i = Image { clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(0.5, 1.5)], clipping: true, ..image() }; + shows(quarters(&drawing(i, true)), [RED, bg(), BLUE, bg()]); + // A triangle over the top-left half. + let i = Image { clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(1.5, -0.5), Vec2::new(-0.5, 1.5)], clipping: true, ..image() }; + let q = quarters(&drawing(i, true)); + shows([q[0], q[3], q[0], q[3]], [RED, bg(), RED, bg()]); + // The boundary is kept but switched off. + let i = Image { clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(0.5, 1.5)], clipping: false, ..image() }; + shows(quarters(&drawing(i, true)), [RED, GREEN, BLUE, WHITE]); + // The boundary a file holds for an unclipped image is the whole image. + let i = Image { clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(1.5, 1.5)], clipping: true, ..image() }; + shows(quarters(&drawing(i, true)), [RED, GREEN, BLUE, WHITE]); +} + +#[test] +fn a_file_of_another_size_fills_the_same_rectangle() { + // The entity says 4 x 4 pixels of 2.5 units; the file found has 2 x 2. + let i = Image { u: Vec3::new(2.5, 0.0, 0.0), v: Vec3::new(0.0, 2.5, 0.0), size: Vec2::new(4.0, 4.0), ..image() }; + shows(quarters(&drawing(i, true)), [RED, GREEN, BLUE, WHITE]); +} + +#[test] +fn fade_and_degenerate_images_do_not_panic() { + let faded = quarters(&drawing(Image { fade: 100, ..image() }, true)); + assert_eq!(faded[0], bg(), "fully faded shows the background"); + for i in [ + Image { u: Vec3::ZERO, ..image() }, + Image { u: Vec3::new(f64::NAN, 0.0, 0.0), ..image() }, + Image { size: Vec2::new(0.0, -1.0), ..image() }, + Image { insert: Vec3::new(1e308, 1e308, 0.0), u: Vec3::new(1e308, 0.0, 0.0), ..image() }, + Image { clip: vec![Vec2::new(f64::INFINITY, 0.0), Vec2::new(1.0, f64::NAN)], clipping: true, ..image() }, + ] { + let _ = quarters(&drawing(i, true)); + } +} + +#[test] +fn a_one_pixel_image_at_its_own_size_does_not_panic() { + // One pixel drawn one screen pixel wide, at whole and at half pixel positions, with and + // without smoothing (tiny-skia asserts on narrow anti-aliased rectangles). + for x in [0.0, 0.25, 0.5] { + let mut d = Drawing::new_imperial(); + let i = Image { + insert: Vec3::new(x, x, 0.0), + u: Vec3::new(1.0, 0.0, 0.0), + v: Vec3::new(0.0, 1.0, 0.0), + size: Vec2::new(1.0, 1.0), + path: "dot.png".into(), + ..Image::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + d.rasters.insert("dot.png", Arc::new(Raster::new(1, 1, RED.to_vec()).unwrap())); + let list = build(&d, &Space::Model, &Options::default()); + for antialias in [true, false] { + let view = View { center: Vec2::new(8.0, 8.0), scale: 1.0, width: 16, height: 16 }; + assert!(render(&list, &view, &RasterOptions { antialias, ..Default::default() }).is_some()); + } + } +} + +/// The colour of one pixel of the 100 x 100 picture of the 10 x 10 square. +fn pixel_at(d: &Drawing, opts: &Options, x: u32, y: u32) -> [u8; 4] { + let list = build(d, &Space::Model, opts); + let view = View { center: Vec2::new(5.0, 5.0), scale: 10.0, width: 100, height: 100 }; + let c = render(&list, &view, &RasterOptions { antialias: false, ..Default::default() }).unwrap().pixel(x, y).unwrap(); + [c.red(), c.green(), c.blue(), c.alpha()] +} + +#[track_caller] +fn near(got: [u8; 4], want: [u8; 4]) { + assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 6), "{got:?} is not {want:?}"); +} + +#[test] +fn the_image_primitive_belongs_to_its_entity_and_widens_the_bounds() { + let mut d = Drawing::new_imperial(); + let i = Image { insert: Vec3::new(100.0, 200.0, 0.0), ..image() }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + d.rasters.insert("map.png", pixels()); + let list = build(&d, &Space::Model, &Options::default()); + let p = list.prims.iter().find(|p| matches!(p.kind, Kind::Image { .. })).unwrap(); + assert_eq!(p.handle, h, "picking and highlighting find the entity"); + assert_eq!((list.bounds.min, list.bounds.max), (Vec2::new(100.0, 200.0), Vec2::new(110.0, 210.0))); + let img = &list.images[0]; + assert_eq!((img.origin, img.right, img.down), (Vec2::new(100.0, 210.0), Vec2::new(5.0, 0.0), Vec2::new(0.0, -5.0))); + assert_eq!(img.at(2.0, 2.0), Vec2::new(110.0, 200.0)); +} + +#[test] +fn draw_order_is_kept_in_pictures() { + // A white line across the top half (y = 7.5, picture row 25). + let line = || EntityKind::Line(Line { a: Vec3::new(0.0, 7.5, 0.0), b: Vec3::new(10.0, 7.5, 0.0) }); + let build_with = |image_last: bool| { + let mut d = Drawing::new_imperial(); + let order = if image_last { [line(), EntityKind::Image(image())] } else { [EntityKind::Image(image()), line()] }; + for k in order { + d.add(&Space::Model, Common::default(), k).unwrap(); + } + d.rasters.insert("map.png", pixels()); + d + }; + near(pixel_at(&build_with(true), &Options::default(), 25, 25), RED); + near(pixel_at(&build_with(false), &Options::default(), 25, 25), WHITE); +} + +#[test] +fn an_image_in_a_block_follows_the_block_reference() { + let mut d = Drawing::new_imperial(); + let mut blk = Block::new("MAP"); + // A 2 x 2 unit image in the block. + let small = Image { u: Vec3::new(1.0, 0.0, 0.0), v: Vec3::new(0.0, 1.0, 0.0), ..image() }; + blk.entities.push(Entity::new(Handle(900), EntityKind::Image(small))); + d.blocks.insert("MAP".into(), Arc::new(blk)); + // Inserted five times larger at the origin: the same 10 x 10 square. + let ins = Insert { + block: "MAP".into(), + insert: Vec3::ZERO, + scale: Vec3::new(5.0, 5.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(ins.clone())).unwrap(); + d.rasters.insert("map.png", pixels()); + shows(quarters(&d), [RED, GREEN, BLUE, WHITE]); + let list = build(&d, &Space::Model, &Options::default()); + assert_eq!(list.prims.iter().find(|p| matches!(p.kind, Kind::Image { .. })).map(|p| p.handle), Some(h), "selected with its block reference"); + + // A quarter turn about the origin, moved back over the square. + let mut d2 = d.clone(); + let turned = Insert { insert: Vec3::new(10.0, 0.0, 0.0), rotation: std::f64::consts::FRAC_PI_2, ..ins }; + d2.model = Default::default(); + d2.add(&Space::Model, Common::default(), EntityKind::Insert(turned)).unwrap(); + shows(quarters(&d2), [GREEN, WHITE, RED, BLUE]); +} + +#[test] +fn a_layout_viewport_cuts_the_image_to_its_outline() { + let mut d = Drawing::new_metric(); + d.add( + &Space::Model, + Common::default(), + EntityKind::Image(Image { clip: vec![Vec2::new(-0.5, -0.5), Vec2::new(1.5, 0.5)], clipping: true, ..image() }), + ) + .unwrap(); + d.rasters.insert("map.png", pixels()); + // 90 x 100 paper units at 10:1, looking at the middle of the image: model x 0.5..9.5. + let vp = Viewport { + center: Vec3::new(60.0, 60.0, 0.0), + width: 90.0, + height: 100.0, + view_center: Vec2::new(5.0, 5.0), + view_height: 10.0, + id: 2, + locked: false, + frozen_layers: Vec::new(), + layer_colors: Vec::new(), + clip: None, + on: true, + }; + d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); + let list = build(&d, &Space::Paper("Layout1".into()), &Options::default()); + assert_eq!(list.images.len(), 1); + let img = &list.images[0]; + // In paper units: ten times larger, the image's top-left corner at (10, 110). + assert_eq!((img.origin, img.right, img.down), (Vec2::new(10.0, 110.0), Vec2::new(50.0, 0.0), Vec2::new(0.0, -50.0))); + assert_eq!(img.clips.len(), 2, "its own boundary, then the viewport"); + assert_eq!(img.clips[0], [Vec2::new(10.0, 110.0), Vec2::new(110.0, 110.0), Vec2::new(110.0, 60.0), Vec2::new(10.0, 60.0)], "the top pixel row"); + assert_eq!(img.clips[1], [Vec2::new(15.0, 10.0), Vec2::new(105.0, 10.0), Vec2::new(105.0, 110.0), Vec2::new(15.0, 110.0)]); + let p = list.prims.iter().find(|p| matches!(p.kind, Kind::Image { index: 0 })).unwrap(); + assert_eq!(list.points(p).len(), 4); + + // Drawn: inside the viewport and the image's top row there is the picture; outside the + // viewport, or in the clipped-away bottom row, there is none. + let view = View { center: Vec2::new(60.0, 60.0), scale: 1.0, width: 120, height: 120 }; + let pm = render(&list, &view, &RasterOptions { antialias: false, ..Default::default() }).unwrap(); + let px = |x: u32, y: u32| { + let c = pm.pixel(x, y).unwrap(); + [c.red(), c.green(), c.blue(), c.alpha()] + }; + // (Sampled at pixel centres: an enlarged picture is smoothed between them.) + near(px(35, 35), RED); + near(px(85, 35), GREEN); + near(px(12, 35), bg()); + near(px(107, 35), bg()); + near(px(35, 85), bg()); + near(px(85, 85), bg()); + + // A viewport looking elsewhere shows nothing of it. + let mut away = d.clone(); + let Some(l) = away.layouts.iter_mut().find(|l| l.name == "Layout1") else { panic!("no Layout1") }; + l.entities = Default::default(); + let far = Viewport { + view_center: Vec2::new(500.0, 500.0), + ..match &d.layouts.iter().find(|l| l.name == "Layout1").unwrap().entities.iter().last().unwrap().kind { + EntityKind::Viewport(v) => v.clone(), + _ => panic!("not a viewport"), + } + }; + away.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(far)).unwrap(); + assert!(build(&away, &Space::Paper("Layout1".into()), &Options::default()).images.is_empty()); +} + +#[test] +fn object_transparency_and_pixel_alpha_blend_with_what_is_under() { + // Half transparent as an object. + let mut d = Drawing::new_imperial(); + let c = Common { transparency: Transparency::Percent(50), ..Default::default() }; + d.add(&Space::Model, c, EntityKind::Image(image())).unwrap(); + d.rasters.insert("map.png", pixels()); + let half = |c: u8, b: u8| ((u16::from(c) + u16::from(b)) / 2) as u8; + let mixed = [half(255, BG.0), half(0, BG.1), half(0, BG.2), 255]; + near(pixel_at(&d, &Options { transparency: true, ..Options::default() }, 25, 25), mixed); + near(pixel_at(&d, &Options::default(), 25, 25), RED); + + // Half transparent pixels in the file. + let mut d = drawing(image(), false); + d.rasters.insert("map.png", Arc::new(Raster::new(2, 2, [[255, 0, 0, 128], GREEN, BLUE, [0, 0, 0, 0]].concat()).unwrap())); + let q = quarters(&d); + near(q[0], mixed); + near(q[1], GREEN); + near(q[3], bg()); + + // Half faded. + let d = drawing(Image { fade: 50, ..image() }, true); + near(quarters(&d)[0], mixed); +} + +#[test] +fn two_references_share_one_set_of_pixels() { + let mut d = drawing(image(), true); + d.add(&Space::Model, Common::default(), EntityKind::Image(Image { insert: Vec3::new(20.0, 0.0, 0.0), ..image() })).unwrap(); + let list = build(&d, &Space::Model, &Options::default()); + assert_eq!(list.images.len(), 2); + assert!(Arc::ptr_eq(&list.images[0].raster, &list.images[1].raster)); + let kinds: Vec = list.prims.iter().map(|p| p.kind).filter(|k| matches!(k, Kind::Image { .. })).collect(); + assert_eq!(kinds, [Kind::Image { index: 0 }, Kind::Image { index: 1 }]); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fcc464be3..5e121688b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1154,4 +1154,5 @@ mod blockedit; mod compare; /// Background rebuilds of the display list for a new view. +mod images; mod rebuild; diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index 9ca1d9314..1e46926e8 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -22,6 +22,7 @@ fn clip_infinite(xf: &Xf, base: Vec2, dir: Vec2, ray: bool) -> Option<[Pos2; 2]> /// Draw a display list. pub(crate) fn draw_list(p: &egui::Painter, xf: &Xf, list: &DisplayList, bg: Rgb, lwdisplay: bool) { let vis = xf.world_bounds(); + super::images::draw(p, xf, list); let mut shapes: Vec = Vec::with_capacity(list.prims.len()); let px = 1.0 / xf.scale; for prim in &list.prims { @@ -79,6 +80,8 @@ pub(crate) fn draw_list(p: &egui::Painter, xf: &Xf, list: &DisplayList, bg: Rgb, shapes.push(Shape::line_segment(seg, Stroke::new(1.0, col))); } } + // Drawn first, under the lines (`images::draw`). + Kind::Image { .. } => {} } } p.extend(shapes); @@ -228,6 +231,7 @@ pub(super) fn draw_list_gpu(c: &mut CanvasState, p: &egui::Painter, xf: &Xf, bg: c.mesh_origin = origin; c.mesh_ms = crate::now_ms() - t0; } + super::images::draw(p, xf, list); let center = xf.rect.center(); p.add(egui_wgpu::Callback::new_paint_callback( xf.rect, @@ -317,6 +321,7 @@ pub(crate) fn draw_highlight(p: &egui::Painter, xf: &Xf, list: &DisplayList, pri line(outline.iter().map(|q| xf.to_screen(*q)).collect(), &mut shapes); } } + Kind::Image { .. } => line(pts.iter().chain(pts.first()).map(|q| xf.to_screen(*q)).collect(), &mut shapes), } } if !fill.is_empty() { diff --git a/crates/ui-egui/src/canvas/images.rs b/crates/ui-egui/src/canvas/images.rs new file mode 100644 index 000000000..4818c079d --- /dev/null +++ b/crates/ui-egui/src/canvas/images.rs @@ -0,0 +1,554 @@ +//! Raster images on the canvas. Each image is a pyramid of levels, each half the size of the one +//! before, cut into tiles that are uploaded as egui textures when first seen. The level drawn is +//! the smallest that still has a pixel for every screen pixel, so a large scan stays sharp zoomed +//! in, doesn't shimmer zoomed out, and only what is on screen takes texture memory. Images are +//! drawn as meshes under the drawing's lines (the drawing itself goes through the GPU callback, +//! so images are not yet interleaved with it in draw order). + +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::sync::{Arc, Mutex, Weak}; + +use cadcraft_doc::Raster; +use cadcraft_geom::{Bounds2, Vec2}; +use cadcraft_render::{DImage, DisplayList, Kind}; +use egui::{Color32, Mesh, Rect, Shape, TextureHandle, TextureOptions, epaint::Vertex, pos2}; + +use super::Xf; + +/// The longest tile side uploaded, whatever the device allows. +const MAX_TILE_SIDE: usize = 2048; +/// Above this many uploaded texels per image, tiles not drawn this frame are let go. +const MAX_UPLOADED_TEXELS: usize = 64_000_000; +/// The pyramid stops once a level's longer side is at most this. +const SMALLEST_LEVEL: usize = 256; + +/// One level of an image's pyramid. +struct Level { + width: usize, + height: usize, + /// Its pixels; empty for the first level, which is the raster's own. + rgba: Vec, + /// Tiles uploaded so far, by column and row. + tiles: HashMap<(usize, usize), TextureHandle>, +} + +/// The pyramid of one image; it goes when its pixels do. +struct Pyramid { + pixels: Weak, + levels: Vec, +} + +/// Pyramids by the address of the pixels they were made from, kept between frames. Behind a +/// mutex of its own: uploading a texture takes the context's lock, which `Context::data_mut` holds. +#[derive(Clone, Default)] +struct Textures(Arc>>); + +/// `rgba` (`width` x `height`) at half the size, each pixel the average of up to four. +fn halved(rgba: &[u8], width: usize, height: usize) -> Option<(Vec, usize, usize)> { + let (w, h) = (width.div_ceil(2), height.div_ceil(2)); + let mut out = Vec::with_capacity(w.checked_mul(h)?.checked_mul(4)?); + let pixel = |x: usize, y: usize| rgba.get(y.checked_mul(width)?.checked_add(x)?.checked_mul(4)?..)?.first_chunk::<4>(); + for y in 0..h { + let (y0, y1) = (y * 2, (y * 2 + 1).min(height - 1)); + for x in 0..w { + let (x0, x1) = (x * 2, (x * 2 + 1).min(width - 1)); + let (a, b, c, d) = (pixel(x0, y0)?, pixel(x1, y0)?, pixel(x0, y1)?, pixel(x1, y1)?); + for i in 0..4 { + let sum = u16::from(a[i]) + u16::from(b[i]) + u16::from(c[i]) + u16::from(d[i]); + out.push(((sum + 2) / 4) as u8); + } + } + } + Some((out, w, h)) +} + +/// The level to draw at `px_per_unit` device pixels per world unit: the smallest with at least one +/// pixel per device pixel. Level `n` is `2^n` raster pixels to its pixel. +fn level_for(img: &DImage, px_per_unit: f64) -> usize { + let per_device_pixel = 1.0 / (img.right.len().min(img.down.len()) * px_per_unit); + if !(per_device_pixel.is_finite() && per_device_pixel > 1.0) { + return 0; + } + per_device_pixel.log2().floor() as usize +} + +impl Pyramid { + fn new(raster: &Arc) -> Option { + let (width, height) = (usize::try_from(raster.width()).ok()?, usize::try_from(raster.height()).ok()?); + Some(Pyramid { pixels: Arc::downgrade(raster), levels: vec![Level { width, height, rgba: Vec::new(), tiles: HashMap::new() }] }) + } + + /// Make the levels up to `wanted` (fewer for a small image); the index of the last one to use. + fn reach(&mut self, raster: &Raster, wanted: usize) -> usize { + while self.levels.len() <= wanted { + let Some(last) = self.levels.last() else { return 0 }; + if last.width.max(last.height) <= SMALLEST_LEVEL { + break; + } + let rgba = if last.rgba.is_empty() { raster.rgba() } else { &last.rgba }; + let Some((rgba, width, height)) = halved(rgba, last.width, last.height) else { break }; + self.levels.push(Level { width, height, rgba, tiles: HashMap::new() }); + } + wanted.min(self.levels.len().saturating_sub(1)) + } + + fn texels(&self) -> usize { + let tile = |t: &TextureHandle| t.size()[0].saturating_mul(t.size()[1]); + self.levels.iter().flat_map(|l| l.tiles.values()).map(tile).sum() + } +} + +/// The texture of tile (`col`, `row`), `side` pixels on a side at most, of level `l`. +fn tile(ctx: &egui::Context, l: &mut Level, raster: &Raster, side: usize, col: usize, row: usize) -> Option { + if let Some(t) = l.tiles.get(&(col, row)) { + return Some(t.clone()); + } + let rgba = if l.rgba.is_empty() { raster.rgba() } else { &l.rgba }; + let (x, y) = (col.checked_mul(side)?, row.checked_mul(side)?); + let (w, h) = (side.min(l.width.checked_sub(x)?), side.min(l.height.checked_sub(y)?)); + let mut bytes = Vec::with_capacity(w.checked_mul(h)?.checked_mul(4)?); + for r in y..y + h { + let start = r.checked_mul(l.width)?.checked_add(x)?.checked_mul(4)?; + bytes.extend_from_slice(rgba.get(start..start.checked_add(w.checked_mul(4)?)?)?); + } + let name = format!("raster-{:x}-{}x{}-{col}-{row}", std::ptr::from_ref(raster) as usize, l.width, l.height); + let image = egui::ColorImage::from_rgba_unmultiplied([w, h], &bytes); + let texture = ctx.load_texture(name, image, TextureOptions::LINEAR); + l.tiles.insert((col, row), texture.clone()); + Some(texture) +} + +/// `poly` cut to the rectangle `min`..`max` (Sutherland-Hodgman; keeps the order of its points). +fn clip_to_rect(poly: &[Vec2], min: Vec2, max: Vec2) -> Vec { + let mut out = poly.to_vec(); + // Inside is `v * sign >= limit`, for each side in turn. + for (x_axis, sign, limit) in [(true, 1.0, min.x), (true, -1.0, -max.x), (false, 1.0, min.y), (false, -1.0, -max.y)] { + let dist = |q: Vec2| (if x_axis { q.x } else { q.y }) * sign - limit; + let input = std::mem::take(&mut out); + let mut prev = input.last().copied(); + for cur in input { + if let Some(p) = prev { + let (dp, dc) = (dist(p), dist(cur)); + if (dp < 0.0) != (dc < 0.0) { + out.push(p + (cur - p) * (dp / (dp - dc))); + } + } + if dist(cur) >= 0.0 { + out.push(cur); + } + prev = Some(cur); + } + } + out +} + +/// `outline` as a rectangle when it is one with sides along the axes. +fn axis_rect(outline: &[Vec2]) -> Option { + if outline.len() != 4 { + return None; + } + let bounds = Bounds2::from_points(outline.iter().copied()); + // Four points are such a rectangle when each lies on a corner of their bounding box. + let close = (bounds.width() + bounds.height()) * 1e-9; + let on_either = |v: f64, low: f64, high: f64| (v - low).abs() <= close || (v - high).abs() <= close; + let on_a_corner = |q: &Vec2| on_either(q.x, bounds.min.x, bounds.max.x) && on_either(q.y, bounds.min.y, bounds.max.y); + outline.iter().all(on_a_corner).then_some(bounds) +} + +/// Draw the images of `list`. +pub(super) fn draw(p: &egui::Painter, xf: &Xf, list: &DisplayList) { + if list.images.is_empty() { + return; + } + let vis = xf.world_bounds(); + for prim in &list.prims { + if let Kind::Image { index } = prim.kind + && let Some(img) = list.images.get(index as usize) + && Bounds2::from_points(img.corners()).intersects(&vis) + { + draw_one(p, xf, img, prim.alpha()); + } + } +} + +/// Draw one image as textured meshes, one per tile on screen: its rectangle, or the outline it is +/// clipped to. +fn draw_one(p: &egui::Painter, xf: &Xf, img: &DImage, alpha: u8) { + let ctx = p.ctx(); + let raster = &img.raster; + let cut = cut(img, xf, p.clip_rect()); + if !cut.rect.is_positive() { + return; + } + // Where in the raster the triangles are. + let Some(tris) = triangles(img, cut.outline).iter().map(|q| img.pixel_of(*q)).collect::>>() else { return }; + let color = Color32::from_white_alpha((img.opacity(alpha) * 255.0) as u8); + let textures = ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("cadcraft-raster-textures")).clone()); + let Ok(mut pyramids) = textures.0.lock() else { return }; + // Pyramids whose pixels are gone (drawing closed, image undone) go too. + pyramids.retain(|_, pyramid| pyramid.pixels.strong_count() > 0); + let key = Arc::as_ptr(raster) as usize; + let pyramid = match pyramids.entry(key) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => { + let Some(new) = Pyramid::new(raster) else { return }; + e.insert(new) + } + }; + let index = pyramid.reach(raster, level_for(img, xf.scale * f64::from(ctx.pixels_per_point()))); + let Some(level) = pyramid.levels.get_mut(index) else { return }; + let side = ctx.input(|i| i.max_texture_side).clamp(1, MAX_TILE_SIDE); + // Raster pixels per pixel of this level (not quite 2^index for an odd size). + let (kx, ky) = (f64::from(raster.width()) / level.width as f64, f64::from(raster.height()) / level.height as f64); + let mut drawn = Vec::new(); + for row in 0..level.height.div_ceil(side) { + for col in 0..level.width.div_ceil(side) { + let (tw, th) = (side.min(level.width - col * side), side.min(level.height - row * side)); + let min = Vec2::new((col * side) as f64 * kx, (row * side) as f64 * ky); + let max = Vec2::new(((col * side + tw) as f64) * kx, ((row * side + th) as f64) * ky); + let corners = [img.at(min.x, min.y), img.at(max.x, min.y), img.at(max.x, max.y), img.at(min.x, max.y)]; + let on_screen = Rect::from_points(&corners.map(|q| xf.to_screen(q))); + if !on_screen.intersects(cut.rect) { + continue; + } + let mut mesh = Mesh::default(); + for t in tris.as_chunks::<3>().0 { + let piece = clip_to_rect(t, min, max); + // A fan over the piece, each triangle laid out in turn. + for pair in piece.get(1..).unwrap_or(&[]).windows(2) { + for q in [piece.first(), pair.first(), pair.last()].into_iter().flatten() { + let at = img.at(q.x, q.y); + let uv = + pos2(((q.x - min.x) / (max.x - min.x)).clamp(0.0, 1.0) as f32, ((q.y - min.y) / (max.y - min.y)).clamp(0.0, 1.0) as f32); + mesh.indices.push(mesh.vertices.len() as u32); + mesh.vertices.push(Vertex { pos: xf.to_screen(at), uv, color }); + } + } + } + if mesh.indices.is_empty() { + continue; + } + let Some(texture) = tile(ctx, level, raster, side, col, row) else { continue }; + mesh.texture_id = texture.id(); + p.with_clip_rect(cut.rect).add(Shape::mesh(mesh)); + drawn.push((col, row)); + } + } + if pyramid.texels() > MAX_UPLOADED_TEXELS { + for (i, l) in pyramid.levels.iter_mut().enumerate() { + l.tiles.retain(|at, _| i == index && drawn.contains(at)); + } + } +} + +/// How an image's clip outlines are applied on the canvas, which can clip a painter to a +/// rectangle but has no general clip. +struct Cut<'a> { + /// The screen rectangle the painter is clipped to: the canvas, narrowed by every outline + /// that is a rectangle along the axes (viewports, an upright image's own boundary). + rect: Rect, + /// The first outline of another shape, which the mesh itself is cut to. Further ones are + /// not applied on screen. + outline: Option<&'a [Vec2]>, +} + +fn cut<'a>(img: &'a DImage, xf: &Xf, canvas: Rect) -> Cut<'a> { + let mut cut = Cut { rect: canvas, outline: None }; + for outline in &img.clips { + match axis_rect(outline) { + Some(b) => cut.rect = cut.rect.intersect(Rect::from_two_pos(xf.to_screen(b.min), xf.to_screen(b.max))), + None if cut.outline.is_none() => cut.outline = Some(outline), + None => {} + } + } + cut +} + +/// World points, three per triangle, covering what is drawn of `img`: the area inside +/// `outline`, or the whole rectangle. +fn triangles(img: &DImage, outline: Option<&[Vec2]>) -> Vec { + match outline { + Some(o) => { + let mut t = cadcraft_render::triangulate_evenodd(&[o.to_vec()]); + t.truncate(t.len() - t.len() % 3); + t + } + None => { + let [a, b, c, d] = img.corners(); + vec![a, b, c, a, c, d] + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_doc::{Common, Drawing, EntityKind, Image, Space}; + use cadcraft_geom::Vec3; + use cadcraft_render::{Options, build}; + use egui::epaint::ClippedShape; + + fn v(x: f64, y: f64) -> Vec2 { + Vec2::new(x, y) + } + + /// `w` x `h` pixels, each with its column in red and its row in green. + fn raster(w: u32, h: u32) -> Arc { + let px: Vec = (0..h).flat_map(|y| (0..w).flat_map(move |x| [x as u8, y as u8, 0, 255])).collect(); + Arc::new(Raster::new(w, h, px).unwrap()) + } + + /// A drawing with a 10 x 10 unit image of 2 x 2 pixels at the origin, changed by `f`. + fn list(f: impl FnOnce(&mut Image)) -> DisplayList { + let mut i = Image { u: Vec3::new(5.0, 0.0, 0.0), v: Vec3::new(0.0, 5.0, 0.0), size: v(2.0, 2.0), path: "a.png".into(), ..Image::default() }; + f(&mut i); + let mut d = Drawing::new_imperial(); + d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + d.rasters.insert("a.png", raster(2, 2)); + build(&d, &Space::Model, &Options::default()) + } + + /// A 100 x 100 point canvas showing the 10 x 10 square, and what `draw` painted on it. + fn painted(list: &DisplayList) -> (egui::Context, Vec) { + let ctx = egui::Context::default(); + let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); + let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0 }; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + draw(&painter, &xf, list); + }); + // No renderer takes the uploads in a test. + out.textures_delta.clear(); + let shapes = std::mem::take(&mut out.shapes); + (ctx, shapes) + } + + fn meshes(shapes: &[ClippedShape]) -> Vec<(Rect, &Mesh)> { + shapes.iter().filter_map(|s| if let Shape::Mesh(m) = &s.shape { Some((s.clip_rect, &**m)) } else { None }).collect() + } + + #[test] + fn a_rectangle_along_the_axes_is_recognised() { + assert!(axis_rect(&[v(0.0, 0.0), v(4.0, 0.0), v(4.0, 2.0), v(0.0, 2.0)]).is_some()); + assert!(axis_rect(&[v(4.0, 2.0), v(0.0, 2.0), v(0.0, 0.0), v(4.0, 0.0)]).is_some()); + assert!(axis_rect(&[v(0.0, 0.0), v(4.0, 1.0), v(4.0, 2.0), v(0.0, 2.0)]).is_none(), "a slanted side"); + assert!(axis_rect(&[v(0.0, 0.0), v(4.0, 0.0), v(0.0, 2.0)]).is_none(), "a triangle"); + assert!(axis_rect(&[]).is_none()); + assert!(axis_rect(&[v(f64::NAN, 0.0), v(1.0, 0.0), v(1.0, 1.0), v(0.0, 1.0)]).is_none()); + } + + #[test] + fn each_level_is_half_the_size_and_averages_its_pixels() { + let r = raster(4, 3); + let (half, w, h) = halved(r.rgba(), 4, 3).unwrap(); + assert_eq!((w, h), (2, 2)); + assert_eq!(half.len(), 16); + // Columns 0 and 1 of rows 0 and 1: red 0.5 rounds up, green likewise. + assert_eq!(&half[..4], &[1, 1, 0, 255]); + // The odd last row counts twice in the bottom-right pixel: columns 2 and 3 of row 2. + assert_eq!(&half[12..16], &[3, 2, 0, 255]); + } + + #[test] + fn the_level_follows_the_zoom() { + let img = |px: f64| DImage { raster: raster(1, 1), origin: v(0.0, 0.0), right: v(px, 0.0), down: v(0.0, -px), clips: Vec::new(), fade: 0 }; + // One raster pixel to a screen pixel or larger: all of them. + assert_eq!(level_for(&img(1.0), 1.0), 0); + assert_eq!(level_for(&img(1.0), 5.0), 0); + // Eight raster pixels to a screen pixel. + assert_eq!(level_for(&img(1.0), 0.125), 3); + assert_eq!(level_for(&img(1.0), 0.2), 2); + // Squashed flat: never a number that means anything. + assert_eq!(level_for(&img(0.0), 1.0), 0); + } + + #[test] + fn clipping_keeps_the_points_inside_and_cuts_the_rest() { + let tri = [v(0.0, 0.0), v(10.0, 0.0), v(0.0, 10.0)]; + assert_eq!(clip_to_rect(&tri, v(-1.0, -1.0), v(11.0, 11.0)), tri, "all inside, in order"); + assert!(clip_to_rect(&tri, v(20.0, 20.0), v(30.0, 30.0)).is_empty()); + let cut = clip_to_rect(&tri, v(0.0, 0.0), v(5.0, 10.0)); + assert_eq!(cut.len(), 4); + assert!(cut.iter().all(|q| q.x <= 5.0)); + } + + #[test] + fn an_image_larger_than_a_tile_is_cut_into_tiles_that_meet() { + let side = 4096; + let d = { + let mut d = Drawing::new_imperial(); + let i = Image { + u: Vec3::new(1.0, 0.0, 0.0), + v: Vec3::new(0.0, 1.0, 0.0), + size: v(side as f64, 1.0), + path: "a.png".into(), + ..Image::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap(); + d.rasters.insert("a.png", Arc::new(Raster::new(side, 1, vec![255; side as usize * 4]).unwrap())); + d + }; + let l = build(&d, &Space::Model, &Options::default()); + let ctx = egui::Context::default(); + let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(8192.0, 100.0)); + let xf = Xf { rect, center: v(side as f64 / 2.0, 0.5), scale: 2.0 }; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), max_texture_side: Some(1 << 14), ..Default::default() }, |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + draw(&painter, &xf, &l); + }); + out.textures_delta.clear(); + let m = meshes(&out.shapes); + assert_eq!(m.len(), 2, "two tiles of {MAX_TILE_SIDE} pixels"); + let edge = |m: &Mesh, right: bool| { + m.vertices.iter().map(|q| q.pos.x).fold(if right { f32::MIN } else { f32::MAX }, if right { f32::max } else { f32::min }) + }; + assert_eq!(edge(m[0].1, true), edge(m[1].1, false), "no gap between them"); + assert_ne!(m[0].1.texture_id, m[1].1.texture_id); + } + + #[test] + fn an_image_is_one_textured_rectangle() { + let l = list(|_| {}); + let (_ctx, shapes) = painted(&l); + let m = meshes(&shapes); + assert_eq!(m.len(), 1); + let (_, mesh) = m[0]; + assert_ne!(mesh.texture_id, egui::TextureId::default()); + assert_eq!(mesh.indices, [0, 1, 2, 3, 4, 5], "two triangles"); + // On screen and in the texture: top left, top right, bottom right, then top left, bottom + // right, bottom left of the picture. + let (tl, tr, br, bl) = (pos2(0.0, 0.0), pos2(100.0, 0.0), pos2(100.0, 100.0), pos2(0.0, 100.0)); + let uv = |p: egui::Pos2| pos2(p.x / 100.0, p.y / 100.0); + let got: Vec<(egui::Pos2, egui::Pos2)> = mesh.vertices.iter().map(|v| (v.pos, v.uv)).collect(); + assert_eq!(got, [tl, tr, br, tl, br, bl].map(|p| (p, uv(p)))); + assert!(mesh.vertices.iter().all(|v| v.color == Color32::WHITE)); + } + + #[test] + fn fade_dims_the_image_and_nothing_is_drawn_when_fully_faded_or_out_of_view() { + let (_c, shapes) = painted(&list(|i| i.fade = 50)); + assert_eq!(meshes(&shapes)[0].1.vertices[0].color, Color32::from_white_alpha(127)); + // Far from the view: skipped. + let (_c, shapes) = painted(&list(|i| i.insert = Vec3::new(1000.0, 1000.0, 0.0))); + assert!(meshes(&shapes).is_empty()); + // No images at all. + let (_c, shapes) = painted(&DisplayList::default()); + assert!(shapes.is_empty()); + } + + #[test] + fn an_upright_clip_boundary_clips_the_painter_and_another_shapes_the_mesh() { + // The left pixel column: a rectangle along the axes. + let (_c, shapes) = painted(&list(|i| { + i.clip = vec![v(-0.5, -0.5), v(0.5, 1.5)]; + i.clipping = true; + })); + let m = meshes(&shapes); + assert_eq!(m.len(), 1); + assert_eq!(m[0].0, Rect::from_min_max(pos2(0.0, 0.0), pos2(50.0, 100.0))); + assert_eq!(m[0].1.vertices.len(), 6, "the whole rectangle, cut by the clip"); + + // A triangle over the top-left half: the mesh is the triangle, with matching texture points. + let (_c, shapes) = painted(&list(|i| { + i.clip = vec![v(-0.5, -0.5), v(1.5, -0.5), v(-0.5, 1.5)]; + i.clipping = true; + })); + let m = meshes(&shapes); + let mesh = m[0].1; + assert!(mesh.vertices.len() >= 3 && mesh.indices.len().is_multiple_of(3) && mesh.indices.len() == mesh.vertices.len()); + for vert in &mesh.vertices { + assert!((vert.pos.x / 100.0 - vert.uv.x).abs() < 1e-4 && (vert.pos.y / 100.0 - vert.uv.y).abs() < 1e-4, "{vert:?}"); + assert!(vert.pos.x + vert.pos.y <= 100.0 + 1e-3, "inside the triangle: {vert:?}"); + } + } + + #[test] + fn a_tile_is_uploaded_once_and_dropped_with_its_pixels() { + let r = raster(4, 4); + let mut l = list(|_| {}); + // The list's pixels are this test's. + l.images[0].raster = r.clone(); + let ctx = egui::Context::default(); + let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); + let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0 }; + let frame = |list: &DisplayList| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + draw(&painter, &xf, list); + }); + let uploads = out.textures_delta.set.len(); + out.textures_delta.clear(); + uploads + }; + assert!(frame(&l) >= 1, "the first frame also uploads the font atlas"); + assert_eq!(frame(&l), 0, "already uploaded"); + // The pixels gone (drawing closed, image undone): the pyramid goes on the next draw. + let count = |ctx: &egui::Context| { + let t = ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("cadcraft-raster-textures")).clone()); + t.0.lock().unwrap().len() + }; + assert_eq!(count(&ctx), 1); + drop(l); + drop(r); + frame(&list(|_| {})); + assert_eq!(count(&ctx), 1, "only the new image's"); + } + + /// A known limit, kept visible here: on screen images are painted first, so they lie under + /// lines drawn before them. (Pictures and plots keep the draw order; see the renderer's + /// `draw_order_is_kept_in_pictures`.) When the canvas learns to interleave them, this test + /// changes with it. + #[test] + fn on_screen_images_lie_under_the_lines_whatever_the_draw_order() { + use cadcraft_doc::Line; + let line = EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) }); + let image = EntityKind::Image(Image { + u: Vec3::new(5.0, 0.0, 0.0), + v: Vec3::new(0.0, 5.0, 0.0), + size: v(2.0, 2.0), + path: "a.png".into(), + ..Image::default() + }); + for order in [[line.clone(), image.clone()], [image, line]] { + let mut d = Drawing::new_imperial(); + for k in order { + d.add(&Space::Model, Common::default(), k).unwrap(); + } + d.rasters.insert("a.png", raster(2, 2)); + let l = build(&d, &Space::Model, &Options::default()); + let ctx = egui::Context::default(); + let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); + let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0 }; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + crate::canvas::draw_list(&painter, &xf, &l, cadcraft_color::Rgb(0, 0, 0), false); + }); + out.textures_delta.clear(); + let kinds: Vec = out.shapes.iter().map(|s| matches!(s.shape, Shape::Mesh(_))).collect(); + assert!(kinds.len() >= 2, "the image and the lines: {kinds:?}"); + assert_eq!(kinds.iter().position(|m| *m), Some(0), "the image comes first: {kinds:?}"); + assert_eq!(kinds.iter().filter(|m| **m).count(), 1); + } + } + + #[test] + fn degenerate_images_do_not_panic() { + for f in [ + (|i: &mut Image| i.u = Vec3::ZERO) as fn(&mut Image), + |i| i.v = i.u, + |i| i.u = Vec3::new(1e300, 0.0, 0.0), + |i| i.insert = Vec3::new(-1e300, 1e300, 0.0), + |i| { + i.clip = vec![v(0.0, 0.0), v(0.0, 0.0), v(0.0, 0.0)]; + i.clipping = true; + }, + |i| { + i.clip = vec![v(f64::NAN, 0.0), v(1.0, f64::INFINITY), v(-1e300, 1e300)]; + i.clipping = true; + }, + ] { + let _ = painted(&list(f)); + } + } +} diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index c79354b6c..d273af4b6 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -162,6 +162,9 @@ pub(super) fn draw_vp_content(c: &mut VpContent, gpu: bool, p: &egui::Painter, f draw_list(p, xf, &c.list, bg, lwdisplay); return; } + // Images first, under the lines, as in `draw_list_gpu` (`p` clips them to the viewport's + // rectangle; a clipped viewport's outline masks the GPU geometry only). + super::images::draw(p, xf, &c.list); let mut stencil = crate::gpu::Stencil::Off; if let Some(outline) = &f.outline { draw_vp_mask(c, p, outline, xf_paper); diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 30f3b0a85..095c2d192 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -232,6 +232,8 @@ pub fn build_mesh(list: &DisplayList, origin: Vec2, bg: Rgb, lwdisplay: bool) -> } // Drawn on the CPU each frame (clipped to the view). Kind::Infinite { .. } => {} + // Drawn by the canvas as a textured mesh. + Kind::Image { .. } => {} } } m @@ -281,6 +283,13 @@ pub fn build_highlight_mesh(list: &DisplayList, prims: &[usize], origin: Vec2, c } } Kind::Infinite { .. } => {} + Kind::Image { .. } => { + let mut run = 0.0; + for (a, b) in pts.iter().zip(pts.iter().cycle().skip(1)) { + push_instance(&mut m.quads, rel(*a, origin), rel(*b, origin), color, width, run as f32); + run += a.dist(*b); + } + } } } m diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3f2de02df..df13e48c8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -198,6 +198,8 @@ Cylinder Циліндр DWG DWG DWG Reference... Посилання на DWG... + Raster Image Reference... Посилання на растрове зображення... + Raster Images Растрові зображення DXF DXF Dark Темна Data Extraction... Вилучення даних... diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d2af85803..a9f74a6fd 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-28 · **Change:** minor (attribute value edits refresh exported baselines) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (raster images are drawn on screen) · **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 @@ -86,7 +86,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | SOLID, TRACE, 3DFACE | yes | yes | | | ACAD_TABLE | yes | 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) | +| IMAGE | yes, with IMAGEDEF | yes, with IMAGEDEF and IMAGEDEF_REACTOR | the picture is loaded from its file and drawn (#1756); brightness and contrast are kept but not applied (FF10) | | WIPEOUT | yes | yes (#147, fixes #79) | Implicit or explicit closure in memory; explicit closing point on save. Same logical grips and edit results before/after DXF/DWG round trips (#2256). | | 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) | | @@ -112,7 +112,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | DWS standards | open, save, CHECKSTANDARDS | no | 6–10 | | PDF output (PLOT, EXPORTPDF) | multi-sheet, layers, searchable text, hyperlinks | vector PDF with lineweights, real text in embedded TrueType subsets, layers (OCG), several sheets per file and hyperlinks (#567, #571); object transparency as PDF alpha when "Plot transparency" is on (the option isn't saved in DXF/DWG: no public plot layout flag) | 1–2 | | PDF import (PDFIMPORT) and PDF underlays (PDFATTACH) | yes | no | 15–25 | -| Raster images attach (PNG, JPEG, TIFF, BMP …) | yes | IMAGE entity exists, no attach/loading/display path | 6–10 | +| Raster images attach (PNG, JPEG, TIFF, BMP …) | yes | **partial** (#956): IMAGEATTACH (JSON form) reads PNG, JPEG, BMP and TIFF; drawn on screen and in PNG output with rotation, clip boundary and fade; reloaded on open, a missing file stays a crossed-out frame. Not yet: PDF and SVG output of the picture, prompts and dialog, detach/reload/unload, IMAGECLIP, IMAGEADJUST, images stored in the drawing | 14–22 | | PNG / JPEG / BMP / TIFF export | PNGOUT, JPGOUT, BMPOUT, TIFOUT | PNG; SVG too (AutoCAD doesn't export SVG) | 1–2 | | DWF/DWFx export, DWF underlay | yes | no | 10–15 | | DGN import/export/underlay | yes | no (needs a public spec; owner decision) | 25–40 | @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Raster images: the picture is loaded from its file when a drawing opens and drawn on screen and in PNG output (#1756, viewport part; based on #1029) | | 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-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) | diff --git a/docs/gaps.md b/docs/gaps.md index b270525d6..4de1e7c7b 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-28 · **Change:** minor (BEDIT in the Block Editor switches blocks: F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (raster images are drawn on screen: FF10 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 @@ -82,7 +82,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | 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 | | 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 | +| FF10 | PDF import and underlays (PDFATTACH). Raster images (#956): IMAGEATTACH from JSON reads PNG, JPEG, BMP and TIFF, the picture is drawn on screen and in PNG exports and plot previews (rotation, clip boundary, fade), sharp at any zoom whatever its size (a pyramid of levels cut into tiles, uploaded as they come into view), and reloaded when the drawing opens; left: PDF and SVG output write only the frame, no prompts, dialog or menu row, no -IMAGE options (detach, reload, unload, path), IMAGECLIP, IMAGEADJUST or IMAGEFRAME, brightness and contrast not applied, images lie under all other objects on screen whatever their draw order, size not taken from the file's resolution, images can't be stored in the drawing. PDF export has real text in embedded TrueType subsets, PDF layers, several sheets per file and hyperlinks (#567, #571) | Medium | 24–40 | | FF11 | DWF/DWFx, DGN, WMF, EPS, ACIS/STL and other exchange formats | Low-medium | 50–100 | | FF12 | DWG in the web build | Medium | 6–10 | | FF13 | R12 binary DXF, pre-R13 DWG | Low | 10–20 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | Raster images are drawn on screen and in PNG output, large ones in tiles at the level the zoom needs (#1756, viewport part; based on #1029): FF10 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-26 | minor | BEDIT in the Block Editor (typed, Edit Block, or the Edit Block Definition dialog) switches to another block as AutoCAD's does, asking whether to save the changes not saved yet; the JSON form takes `save`: F3 evidence | From 0ae424c77109cea202dec02601650e250d13f718 Mon Sep 17 00:00:00 2001 From: assamaral Date: Fri, 30 Oct 2026 14:33:00 -0300 Subject: [PATCH 219/900] fix(io): derive the column count of a dynamic auto-height MTEXT from its widths An R2018 dynamic auto-height embedded object stores 0 in group 72 even with several columns, and the clamp turned it into one. With 72 at zero the count is now (42 + 45) / (44 + 45), the inverse of the total width the writer emits. Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/dxf_read/mtext_dxf.rs | 10 ++++- crates/io/tests/it/mtext_columns_roundtrip.rs | 38 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_read/mtext_dxf.rs b/crates/io/src/dxf_read/mtext_dxf.rs index e7752f711..df22cbe36 100644 --- a/crates/io/src/dxf_read/mtext_dxf.rs +++ b/crates/io/src/dxf_read/mtext_dxf.rs @@ -118,9 +118,17 @@ fn read_embedded_columns(tags: &[Tag]) -> Option<(MTextColumns, f64)> { // The column height: the entity's own 46 (defined height), else the object's 41 or first 46. let own_46 = own(tags).iter().find(|t| t.code == 46).map(|t| finite(t.f64()).max(0.0)); let defined = [own_46, first(41).map(|t| finite(t.f64())), heights.first().copied()].into_iter().flatten().find(|h| *h > 0.0).unwrap_or(0.0); + // A dynamic auto-height object stores 0 columns in 72: the count follows from the total width + // (42 = n * 44 + (n - 1) * 45). + let [width, gutter, total] = [44, 45, 42].map(|g| first(g).map_or(0.0, |t| finite(t.f64()))); + let count = match first(72).map(Tag::i64) { + Some(n) if n > 0 => n, + Some(_) if width + gutter > 0.0 && total > 0.0 => ((total + gutter) / (width + gutter)).round() as i64, + _ => 1, + }; let c = MTextColumns { kind, - count: u16::try_from(first(72).map(Tag::i64).unwrap_or(1).clamp(1, MAX_COLUMNS as i64)).unwrap_or(1), + count: u16::try_from(count.clamp(1, MAX_COLUMNS as i64)).unwrap_or(1), gutter: first(45).map(|t| finite(t.f64()).max(0.0)).unwrap_or(0.0), height: if manual { heights.iter().copied().fold(0.0, f64::max) } else { defined }, auto_height, diff --git a/crates/io/tests/it/mtext_columns_roundtrip.rs b/crates/io/tests/it/mtext_columns_roundtrip.rs index 3525c8d29..b147f311e 100644 --- a/crates/io/tests/it/mtext_columns_roundtrip.rs +++ b/crates/io/tests/it/mtext_columns_roundtrip.rs @@ -194,3 +194,41 @@ fn r2018_writes_the_embedded_object_and_older_versions_the_legacy_groups() { assert!(!r2000.contains("Embedded Object"), "R2000 has no embedded object"); assert!(r2000.contains(" 75\r\n1\r\n"), "R2000 keeps the legacy column groups"); } + +#[test] +fn dynamic_auto_height_embedded_count_comes_from_the_total_width() { + // A dynamic auto-height object stores no column count (72 = 0): the count is what 42 (total + // width), 44 (column width) and 45 (gutter) hold, 3 * 50 + 2 * 12.5 = 175. + let mut tags = embedded_tags(1, 50.0, 12.5, &[]); + let at = tags.iter().position(|t| t.code == 101).unwrap(); + for t in &mut tags[at..] { + *t = match t.code { + 42 => cadcraft_dxf::Tag::f(42, 175.0), + 71 => cadcraft_dxf::Tag::i(71, 2), + 72 => cadcraft_dxf::Tag::i(72, 0), + 73 => cadcraft_dxf::Tag::i(73, 1), + _ => t.clone(), + }; + } + let (_, t) = mtext_from_groups(&tags); + let c = t.columns.expect("columns"); + assert_eq!((c.kind, c.auto_height, c.count), (MTextColumnType::Dynamic, true, 3)); + assert_eq!(c.gutter, 12.5); +} + +#[test] +fn dynamic_auto_height_count_comes_from_the_widths_when_72_is_zero() { + // A dynamic auto-height object stores 0 in 72; the count is implied by the total width + // (42 = n * 44 + (n - 1) * 45): (175 + 12.5) / (50 + 12.5) = 3. + let mut tags = embedded_tags(0, 50.0, 12.5, &[]); + let mut set = |code: i32, v: cadcraft_dxf::Tag| { + let at = tags.iter().rposition(|t| t.code == code).unwrap(); + tags[at] = v; + }; + set(71, cadcraft_dxf::Tag::i(71, 2)); + set(73, cadcraft_dxf::Tag::i(73, 1)); + set(42, cadcraft_dxf::Tag::f(42, 175.0)); + let (_, t) = mtext_from_groups(&tags); + let c = t.columns.expect("columns"); + assert_eq!((c.kind, c.auto_height, c.count), (MTextColumnType::Dynamic, true, 3)); +} From 53ac71c1fe7342ba0bb07fd10f7e5d8e068dc362 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Fri, 30 Oct 2026 15:30:39 -0400 Subject: [PATCH 220/900] Clear the navigation drag when its button is released after Escape stopped it Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 4 ++ .../ui-egui/tests/it/realtime_nav_release.rs | 44 ++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4d71058c2..ae2768cd0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -704,6 +704,10 @@ fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickCo // The release of a drag that panned or zoomed (Enter can end the command mid-drag) places // nothing in the command it returns to. let nav_release = drag_stopped && std::mem::take(&mut app.canvas.nav_drag); + // A drag Escape stopped early ends with no drag stop: its release still ends it. + if ui.input(|i| i.pointer.primary_released()) { + app.canvas.nav_drag = false; + } let pressed_primary = context.primary_clicked || (point_prompt && drag_stopped && !nav_release); if point_prompt && context.inside && pressed_primary && !context.middle_down && app.cmd.options.is_none() && app.cmd.buffer.is_empty() { let releases: Vec = ui.input(|i| { diff --git a/crates/ui-egui/tests/it/realtime_nav_release.rs b/crates/ui-egui/tests/it/realtime_nav_release.rs index 6305d8401..fceb0ae91 100644 --- a/crates/ui-egui/tests/it/realtime_nav_release.rs +++ b/crates/ui-egui/tests/it/realtime_nav_release.rs @@ -1,11 +1,12 @@ //! A drag that pans in realtime places no point when it is let go, even after Enter ended the -//! transparent PAN mid-drag and handed the prompt back to the drawing command. +//! transparent PAN mid-drag and handed the prompt back to the drawing command; a pan drag that +//! Escape stopped leaves the next drag free to place a point. use cadcraft_engine::Session; use cadcraft_engine::doc::{Drawing, EntityKind, Space}; use cadcraft_engine::geom::Vec2; use cadcraft_ui_egui::{CadApp, Services}; -use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::Harness; use serde_json::json; @@ -75,3 +76,42 @@ fn enter_mid_drag_ends_pan_and_the_release_places_no_point() { h.run_steps(2); assert_eq!(lines(&h), 1); } + +#[test] +fn a_pan_drag_stopped_by_escape_leaves_the_next_drag_placing_a_point() { + let mut h = harness(); + h.state_mut().session.cmdline("PAN").unwrap(); + h.run_steps(1); + assert!(h.state().session.realtime_pan_active()); + let (a, b) = (screen(&h, Vec2::new(40.0, 40.0)), screen(&h, Vec2::new(60.0, 30.0))); + button(&mut h, a, true); + for i in 1..=4 { + h.event(Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))); + h.run_steps(1); + } + for pressed in [true, false] { + h.event(Event::Key { key: Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + button(&mut h, b, false); + h.run_steps(2); + assert!(!h.state().session.realtime_pan_active()); + h.state_mut().start("line"); + h.run_steps(2); + // Screen points near the middle of the canvas, wherever the pan left the drawing. + let first = Pos2::new(700.0, 450.0); + button(&mut h, first, true); + button(&mut h, first, false); + h.run_steps(2); + // The second point is a press, a drag and a release. + let (c, d) = (Pos2::new(760.0, 420.0), Pos2::new(820.0, 400.0)); + button(&mut h, c, true); + for i in 1..=4 { + h.event(Event::PointerMoved(c + (d - c) * (i as f32 / 4.0))); + h.run_steps(1); + } + button(&mut h, d, false); + h.run_steps(2); + assert_eq!(lines(&h), 1, "the drag after an Escape-stopped pan drag placed no point"); +} + From a5c8b1acf61020ccf66d2dd9af7d3d9e04d56870 Mon Sep 17 00:00:00 2001 From: mattlafy Date: Fri, 30 Oct 2026 15:37:22 -0400 Subject: [PATCH 221/900] Format the Escape-drag test Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/realtime_nav_release.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/tests/it/realtime_nav_release.rs b/crates/ui-egui/tests/it/realtime_nav_release.rs index fceb0ae91..359e98fb2 100644 --- a/crates/ui-egui/tests/it/realtime_nav_release.rs +++ b/crates/ui-egui/tests/it/realtime_nav_release.rs @@ -114,4 +114,3 @@ fn a_pan_drag_stopped_by_escape_leaves_the_next_drag_placing_a_point() { h.run_steps(2); assert_eq!(lines(&h), 1, "the drag after an Escape-stopped pan drag placed no point"); } - From 3ba2362ec912e7483e1a30d4320c32107660ba13 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:45:50 +0700 Subject: [PATCH 222/900] LISP: entity names answer prompts that pick one object (#2477) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * LISP: entity names answer prompts that pick one object `command` fed an entity name, alone or as `entsel` returns it (name and point), to the running command as a pick. Prompts that pick a single object with a point (MEASURE, DIVIDE, LENGTHEN, PEDIT, BREAK, TRIM and EXTEND in Standard mode, FILLET, OFFSET, REVCLOUD Object, dimensions…) only take points, so routines got "Invalid input" or nothing at all. At such a prompt the name is now entered as its point, and a pick at exactly that point finds the named object (Session::pick_object), so the point says where on it, as in AutoCAD. A bare name stands at the object's DXF group 10 point, the point AutoCAD picks it at: a line's start, a circle's or an arc's centre, a polyline's first vertex. At an arc's centre MEASURE runs from the arc's end, as AutoCAD does. Co-Authored-By: Claude Opus 5.5 * Keep a named object for its own input and its own space A name given at a prompt picking one object now holds only while that input is taken: a later pick at the same point finds what lies there. A name for an object in another space picks nothing, instead of the object under its point in the current space. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/annotate/common.rs | 2 +- crates/engine/src/cmd/constraints.rs | 6 +- crates/engine/src/cmd/curves.rs | 5 +- crates/engine/src/cmd/draw2/divide.rs | 3 + crates/engine/src/cmd/modify/break_join.rs | 2 +- crates/engine/src/cmd/modify/fillet.rs | 2 +- crates/engine/src/cmd/modify/offset.rs | 2 +- crates/engine/src/cmd/trimextend.rs | 2 +- crates/engine/src/lib.rs | 5 + crates/engine/src/lisp/drawing.rs | 18 +++- crates/engine/src/lisp/tests.rs | 105 +++++++++++++++++++++ crates/engine/src/session/interactive.rs | 1 + crates/engine/src/session/picking.rs | 45 ++++++++- docs/autolisp.md | 5 +- 14 files changed, 185 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/annotate/common.rs b/crates/engine/src/cmd/annotate/common.rs index 419723288..398102797 100644 --- a/crates/engine/src/cmd/annotate/common.rs +++ b/crates/engine/src/cmd/annotate/common.rs @@ -107,7 +107,7 @@ pub(super) fn hex_param(p: &Value, key: &str) -> Option { pub(super) fn pick_at(s: &Session, p: Vec2) -> Option { let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; - crate::select::pick(s.doc().ok()?, &s.space(), p, ap) + s.pick_object(&s.space(), p, ap).ok().flatten() } /// The straight or curved piece of `h` picked at `p`: a line, an arc, or the polyline segment nearest `p`. diff --git a/crates/engine/src/cmd/constraints.rs b/crates/engine/src/cmd/constraints.rs index 5b685dd45..9f21dca6a 100644 --- a/crates/engine/src/cmd/constraints.rs +++ b/crates/engine/src/cmd/constraints.rs @@ -461,7 +461,7 @@ impl Interactive for GcM { } Input::Point(p) => { let space = s.space(); - let Some(h) = crate::select::pick(s.doc()?, &space, p, aperture(s)) else { + let Some(h) = s.pick_object(&space, p, aperture(s))? else { s.echo("*Invalid selection*"); return Ok(Step::Continue); }; @@ -706,11 +706,11 @@ impl Interactive for DcM { Input::Point(p) => { let space = s.space(); let ap = aperture(s); - let d = s.doc()?; - let Some(h) = crate::select::pick(d, &space, p, ap) else { + let Some(h) = s.pick_object(&space, p, ap)? else { s.echo("*Invalid selection*"); return Ok(Step::Continue); }; + let d = s.doc()?; let want = match dc { Dc::Radius | Dc::Diameter => Want::Curve, Dc::Angular if self.refs.is_empty() => { diff --git a/crates/engine/src/cmd/curves.rs b/crates/engine/src/cmd/curves.rs index 2ef2e24f2..ca918834a 100644 --- a/crates/engine/src/cmd/curves.rs +++ b/crates/engine/src/cmd/curves.rs @@ -18,10 +18,9 @@ pub fn pick_aperture(s: &Session) -> f64 { s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5 } -/// The object under `p` in the current space. +/// The object under `p` in the current space (or the one named for `p`: [`Session::pick_object`]). pub fn pick_at(s: &Session, p: Vec2) -> Option { - let space = s.space(); - crate::select::pick(s.doc().ok()?, &space, p, pick_aperture(s)) + s.pick_object(&s.space(), p, pick_aperture(s)).ok().flatten() } pub fn entity(s: &Session, h: Handle) -> Result { diff --git a/crates/engine/src/cmd/draw2/divide.rs b/crates/engine/src/cmd/draw2/divide.rs index 65e7ab06c..4e92f561f 100644 --- a/crates/engine/src/cmd/draw2/divide.rs +++ b/crates/engine/src/cmd/draw2/divide.rs @@ -81,6 +81,9 @@ pub(super) fn run_measure(s: &mut Session, p: &Value) -> Result { if let Some(from) = point_param(p, "from") { let past_half = match curves::entity(s, h)?.kind { EntityKind::Circle(_) => false, + // At an arc's centre, where a bare name given from AutoLISP stands (its DXF group 10 + // point), every point of it is as near: AutoCAD measures from its end. + EntityKind::Arc(a) if from.dist(a.center.xy()) <= a.radius * 1e-9 => true, // A spline by its own parameter: its tessellation drops zero-length pieces, so the // segment count is not the spline's parameter range. EntityKind::Spline(sp) => { diff --git a/crates/engine/src/cmd/modify/break_join.rs b/crates/engine/src/cmd/modify/break_join.rs index c7432e223..74fd482a2 100644 --- a/crates/engine/src/cmd/modify/break_join.rs +++ b/crates/engine/src/cmd/modify/break_join.rs @@ -250,7 +250,7 @@ impl Interactive for BreakM { (None, Input::Point(p)) => { let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; let space = s.space(); - match crate::select::pick(s.doc()?, &space, p, ap) { + match s.pick_object(&space, p, ap)? { Some(h) => { self.obj = Some((h, p)); s.set_selection(vec![h]); diff --git a/crates/engine/src/cmd/modify/fillet.rs b/crates/engine/src/cmd/modify/fillet.rs index 2a75b22e7..b0cb32174 100644 --- a/crates/engine/src/cmd/modify/fillet.rs +++ b/crates/engine/src/cmd/modify/fillet.rs @@ -342,7 +342,7 @@ impl Interactive for FilletM { Input::Point(p) => { 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 { + let Some(h) = s.pick_object(&space, p, ap)? else { s.echo("*Invalid selection*"); return Ok(Step::Continue); }; diff --git a/crates/engine/src/cmd/modify/offset.rs b/crates/engine/src/cmd/modify/offset.rs index 20e6ba58e..17cd15b09 100644 --- a/crates/engine/src/cmd/modify/offset.rs +++ b/crates/engine/src/cmd/modify/offset.rs @@ -445,7 +445,7 @@ impl Interactive for OffsetM { (None, Input::Point(p)) => { let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; let space = s.space(); - match crate::select::pick(s.doc()?, &space, p, ap) { + match s.pick_object(&space, p, ap)? { Some(h) => { self.picked = Some(h); s.set_selection(vec![h]); diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 4640c58ac..ab03d5c31 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -474,7 +474,7 @@ impl Interactive for TrimM { Input::Point(p) => { 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 { + let Some(h) = s.pick_object(&space, p, ap)? else { // A pick in empty space opens a crossing window there. self.stage = Stage::Crossing(Some(p)); return Ok(Step::Continue); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2dea12394..8f84b35d7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -142,6 +142,10 @@ pub struct Session { lisp_last: Option>, /// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks). pub hatch_picks: Option, + /// The object named with a point for the input a prompt picking one object is taking + /// ([`Session::input_object`]): a pick at exactly that point picks that object + /// ([`Session::pick_object`]). + pick_hint: Option<(Handle, Vec2)>, } impl Default for Session { @@ -192,6 +196,7 @@ impl Session { lisp: lisp::LispState::default(), lisp_last: None, hatch_picks: None, + pick_hint: None, } } diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 0042ea434..4db7d0c20 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -64,8 +64,10 @@ fn items(p: &PickSet) -> Vec { /// `(command arg…)`: arguments go to the command line as typed input: a string starts a command /// or answers a prompt ("" is Enter), a number or a point is entered, an entity name or a -/// selection set picks objects, and `pause` waits for the user. A command not finished by the -/// arguments stays active for the next `command` call. No arguments: cancel the active command. +/// selection set picks objects (a name, alone or with a point as `entsel` gives it, also answers +/// a prompt picking one object: [`Session::input_object`]), and `pause` waits for the user. A +/// command not finished by the arguments stays active for the next `command` call. No +/// arguments: cancel the active command. pub fn command(ctx: &mut Ctx<'_>, a: Vec) -> Result { if a.is_empty() { if ctx.s.running.is_some() { @@ -108,14 +110,14 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec) -> Result { } } } - Value::Ename(h) => feed(ctx.s, Input::Pick(vec![*h])), + Value::Ename(h) => named(ctx.s, *h, None), 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]))); } else if let Value::Ename(h) = arg.car() { // An `entsel` result: (ename point). - feed(ctx.s, Input::Pick(vec![h])); + named(ctx.s, h, arg.cdr().car().as_point().map(|p| Vec2::new(p[0], p[1]))); } else { return Err(LispError::bad_arg("command argument", arg)); } @@ -134,6 +136,14 @@ fn feed(s: &mut Session, input: Input) { } } +fn named(s: &mut Session, h: Handle, at: Option) { + if s.running.is_some() + && let Err(e) = s.input_object(h, at) + { + s.echo(e.to_string()); + } +} + // ---------------- system variables ---------------- /// A JSON value as LISP: integers, reals, strings, lists (points). diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 58f421765..ca492e409 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -563,6 +563,111 @@ fn appload_and_load() { assert!(r["error"].as_str().is_some_and(|e| e.contains("bad argument type"))); } +/// `command` gives an entity name, alone or as `entsel` returns it (name and point), to a prompt +/// picking one object: the point picks that object, and a bare name stands at its DXF group 10 +/// point. Each call and its numbers are AutoCAD 2024's (accoreconsole, read back with `entget`); +/// AutoCAD ran TRIM and EXTEND in Standard mode there. +#[test] +fn command_names_objects_at_prompts_picking_one() { + use cadcraft_doc::EntityKind; + let near = |a: [f64; 2], b: [f64; 2]| (0..2).all(|i| (a[i] - b[i]).abs() <= 1e-9 * a[i].abs().max(1.0)); + // The drawing's points, lines and polyline widths after `forms`, each evaluated on its own. + let run = |forms: &[&str]| { + let mut s = session(); + ok(&mut s, "(setvar \"TRIMEXTENDMODE\" 0)"); + for f in forms { + ok(&mut s, f); + } + assert!(s.running.is_none(), "{forms:?}: a command is still running"); + let (mut points, mut lines, mut widths) = (Vec::new(), Vec::new(), Vec::new()); + for e in s.doc().unwrap().model.iter() { + match &e.kind { + EntityKind::Point(p) => points.push([p.p.x, p.p.y]), + EntityKind::Line(l) => lines.push(([l.a.x, l.a.y], [l.b.x, l.b.y])), + EntityKind::LwPolyline(pl) => widths.push(pl.const_width), + _ => {} + } + } + (points, lines, widths) + }; + let has_point = |points: &[[f64; 2]], p: [f64; 2]| points.iter().any(|q| near(*q, p)); + let has_line = |lines: &[([f64; 2], [f64; 2])], a: [f64; 2], b: [f64; 2]| lines.iter().any(|(p, q)| near(*p, a) && near(*q, b)); + let line = |name: &str, a: [f64; 2], b: [f64; 2]| { + format!("(setq {name} (progn (entmake '((0 . \"LINE\") (10 {} {} 0.0) (11 {} {} 0.0))) (entlast)))", a[0], a[1], b[0], b[1]) + }; + + // A circle named alone stands at its centre, where nothing is drawn. + let (points, ..) = run(&[ + "(setq a (progn (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 15.0))) (entlast)))", + "(command \"_.MEASURE\" a 10.275598705220492)", + ]); + assert!(points.len() == 9 && has_point(&points, [14.89599800946832, -1.763304653744166]), "{points:?}"); + // An arc named alone stands at its centre too, as near to either end: MEASURE runs from its + // end (250°), so its points run from 233.4° down to 34.4°, not from 46.6° up. + let (points, ..) = run(&[ + "(setq a (progn (entmake '((0 . \"ARC\") (10 -35000.0 81000.0 0.0) (40 . 1000.0) (50 . 0.5235987755982988) (51 . 4.363323129985824))) (entlast)))", + "(command \"_.MEASURE\" a 289.4960530820059)", + ]); + assert!(points.len() == 13 && has_point(&points, [-35596.04133310627, 80197.0462471419]), "{points:?}"); + assert!(has_point(&points, [-34174.59349504207, 81564.53883973838]), "{points:?}"); + // PEDIT takes a polyline by name. + let (_, _, widths) = run(&[ + "(setq a (progn (entmake '((0 . \"LWPOLYLINE\") (100 . \"AcDbEntity\") (100 . \"AcDbPolyline\") (90 . 3) (70 . 0) (10 0.0 0.0) (10 30.0 0.0) (42 . 0.4) (10 40.0 20.0))) (entlast)))", + "(command \"_.PEDIT\" a \"_W\" 1.25 \"\")", + ]); + assert_eq!(widths, [1.25]); + // `entsel` lists: the point picks the end LENGTHEN moves, BREAK's first point, the piece + // TRIM removes and the end EXTEND moves. + let (_, lines, _) = run(&[ + &line("a", [0.0, 0.0], [-11.745250375031729, -27.60523670660726]), + "(command \"_.LENGTHEN\" \"_DE\" 5.0 (list a '(-10.962233683362948 -25.764887592833446)) \"\")", + ]); + assert!(has_line(&lines, [0.0, 0.0], [-13.70279210420368, -32.2061094910418]), "{lines:?}"); + let (_, lines, _) = run(&[ + &line("a", [0.0, 0.0], [-97.11873949964188, 23.831710765295487]), + "(command \"_.BREAK\" (list a '(-19.77309329359773 4.852067095763353)) '(-77.20177993977879 18.94434070674469))", + ]); + assert!(lines.len() == 2 && has_line(&lines, [0.0, 0.0], [-19.77309329359773, 4.852067095763352]), "{lines:?}"); + assert!(has_line(&lines, [-77.20177993977879, 18.94434070674469], [-97.11873949964188, 23.83171076529548]), "{lines:?}"); + let (_, lines, _) = run(&[ + &line("a", [-38.39479850296135, -32.02872847799295], [38.39479850296135, 32.02872847799295]), + &line("b", [-9.422796057479543, -30.193534825244917], [-15.589739201426854, 9.328216303207391]), + &line("c", [35.428336962443794, 7.710053620262788], [-2.7893410422311042, 19.517216189270982]), + "(command \"_.TRIM\" a b c \"\" (list a '(1.9066151653265737 1.5904878218740615)) \"\")", + ]); + assert!(lines.len() == 4 && has_line(&lines, [-38.39479850296135, -32.02872847799294], [-12.50626762945319, -10.43265926101876]), "{lines:?}"); + assert!(has_line(&lines, [16.31949796010634, 13.61363490476688], [38.39479850296135, 32.02872847799294]), "{lines:?}"); + let (_, lines, _) = run(&[ + &line("a", [0.0, 0.0], [18.819750237318146, -6.7688256739971955]), + &line("b", [17.056820153998288, -35.36317014637398], [58.2221807952743, 8.2878674503852]), + "(command \"_.EXTEND\" a b \"\" (list a '(14.11481267798861 -5.076619255497897)) \"\")", + ]); + assert!(has_line(&lines, [0.0, 0.0], [37.63950047463629, -13.53765134799439]), "{lines:?}"); +} + +#[test] +fn a_named_object_holds_for_its_own_input_in_its_own_space() { + use cadcraft_doc::Space; + let mut s = session(); + ok(&mut s, "(setq a (progn (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 10.0 0.0 0.0))) (entlast)))"); + // BREAK takes A at (5,3), off the line; a later pick there finds nothing. + ok(&mut s, "(command \"_.BREAK\" (list a '(5.0 3.0)))"); + assert!(s.prompt_text().contains("Specify second break point"), "{}", s.prompt_text()); + let model = s.space(); + assert_eq!(s.pick_object(&model, cadcraft_geom::Vec2::new(5.0, 3.0), 0.5).unwrap(), None); + s.cancel(); + // A paper-space copy of A named in model space picks nothing, not A under its start. + let p = { + let d = s.doc_mut().unwrap(); + let e = d.model.iter().next().unwrap(); + let (common, kind) = (e.common.clone(), e.kind.clone()); + d.add(&Space::Paper("Layout1".into()), common, kind).unwrap() + }; + ok(&mut s, &format!("(command \"_.BREAK\" (handent \"{}\"))", p.hex())); + assert!(s.prompt_text().contains("Select object"), "{}", s.prompt_text()); + s.cancel(); +} + #[test] fn appload_reads_a_lsp_path_and_reports_its_commands() { let dir = std::env::temp_dir().join(format!("cadcraft-appload-lisp-{}", std::process::id())); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index e7cb07450..13d944d63 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -9,6 +9,7 @@ impl Session { /// Start a command by name or alias as if typed at the command line. pub fn start(&mut self, name: &str) -> Result<()> { self.last_polar = None; + self.pick_hint = None; let name = name.trim(); let (transparent, name) = match name.strip_prefix('\'') { Some(n) => (true, n), diff --git a/crates/engine/src/session/picking.rs b/crates/engine/src/session/picking.rs index 5646e8569..a9d146571 100644 --- a/crates/engine/src/session/picking.rs +++ b/crates/engine/src/session/picking.rs @@ -1,4 +1,4 @@ -use super::{Bounds2, Handle, Input, PendingWindow, Result, Session, Vec2, cmd, select}; +use super::{Bounds2, Drawing, Entity, Handle, Input, PendingWindow, Result, Session, Space, Vec2, cmd, select}; impl Session { // ---------------- picking without a command ---------------- @@ -125,4 +125,47 @@ impl Session { st.previous_selection = sel.to_vec(); } } + + // ---------------- one object by name ---------------- + + /// Give the running command an object by name, as AutoLISP's `command` does with an entity + /// name or an `entsel` list (name and point). A prompt picking one object with a point + /// (BREAK's "Select object", MEASURE's "Select object to measure"…) takes the point, and a + /// pick there finds that object ([`Session::pick_object`]) wherever it lies. A bare name + /// stands at the object's DXF group 10 point (a line's start, a circle's centre, a + /// polyline's first vertex), the point AutoCAD picks it at. The name holds for that input + /// only: a later pick at the same point finds what lies there. Other prompts take the object + /// as a pick. + pub fn input_object(&mut self, h: Handle, at: Option) -> Result<()> { + let one = self.current_prompt().is_some_and(|p| p.accept.point && !p.accept.select && p.picks_objects()); + let p = if one { at.or_else(|| self.doc().ok().and_then(|d| group_10(d, d.entity(h)?))) } else { None }; + let Some(p) = p.filter(|p| p.is_finite()) else { return self.input(Input::Pick(vec![h])) }; + self.pick_hint = Some((h, p)); + let r = self.input(Input::Point(p)); + self.pick_hint = None; + r + } + + /// The object a prompt picking one object finds at `p` in `space`: the one named for that + /// point ([`Session::input_object`]), which is none when it lies in another space, else the + /// object under `p` within `aperture`. + pub fn pick_object(&self, space: &Space, p: Vec2, aperture: f64) -> Result> { + let d = self.doc()?; + if let Some((h, q)) = self.pick_hint + && q == p + { + return Ok((d.space_of(h).as_ref() == Some(space)).then_some(h)); + } + Ok(select::pick(d, space, p, aperture)) + } +} + +/// An object's DXF group 10 point: the first point of its entity list, or its first grip where +/// entity lists are not built in. +fn group_10(d: &Drawing, e: &Entity) -> Option { + let Some(codec) = cmd::file::entity_codec() else { return e.kind.grips().first().copied() }; + let (_, tags) = (codec.groups)(d, e); + let i = tags.iter().position(|t| t.code == 10)?; + let y = tags.get(i + 1).filter(|t| t.code == 20)?; + Some(Vec2::new(tags[i].value.as_f64(), y.value.as_f64())) } diff --git a/docs/autolisp.md b/docs/autolisp.md index 8dd79129a..91a55c101 100644 --- a/docs/autolisp.md +++ b/docs/autolisp.md @@ -73,8 +73,9 @@ reached", malformed source is a reader error, and every built-in checks its argu - **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` -- **Drawing:** `command` (also `command-s`, `vl-cmdf`) with `pause`, a command left open for the - next call, and `(command)` to cancel; `getvar setvar`; `entget entmake entmod entdel entlast +- **Drawing:** `command` (also `command-s`, `vl-cmdf`) with `pause`, entity names and `entsel` + lists at prompts picking one object (a bare name picks at its DXF group 10 point, as in AutoCAD), + a command left open for the next call, and `(command)` to cancel; `getvar setvar`; `entget entmake entmod entdel entlast entnext entupd handent`; `ssget` (modes X, L, P, I, W, C, F, WP, CP, a point, or the user selecting; filters with wildcards and `-4` operators) `ssadd ssdel sslength ssname ssmemb sssetfirst ssgetfirst`; `tblsearch tblnext` (LAYER, LTYPE, STYLE, BLOCK, DIMSTYLE, APPID) From 6ec6d97ea012c108f6ba0e9d571493a0670f945a Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:45:53 +0700 Subject: [PATCH 223/900] LISP: getvar and setvar take angle variables in radians (#2482) * LISP: getvar and setvar take angle variables in radians CADCraft keeps ANGBASE, SNAPANG, POLARANG, HPANG, CHAMFERD and DIMJOGANG in degrees as far as sysvars::get/set go, which is right for the SETVAR command, but AutoLISP's getvar returned those degrees and setvar took them: (getvar "DIMJOGANG") gave 45.0, and (setvar "ANGBASE" (/ pi 2)) set 1.57 degrees. AutoCAD 2024 gives and takes them in radians from AutoLISP: each set to 30 by SETVAR, or to (/ pi 6) by setvar, reads 0.5235987755982987. The LISP bridge now converts these six; the SETVAR command is unchanged. getangle_is_relative_to_angbase sets ANGBASE in radians accordingly. Co-Authored-By: Claude Opus 5.5 * SETVAR: keep real dimension variables real A dimension variable whose style field is a real (DIMJOGANG, DIMSCALE and the other real DIM* fields) is now stored as a real header value, even when the first value set is a whole number. SETVAR DIMJOGANG 45 followed by (setvar "DIMJOGANG" 0.5) no longer rejects the fractional degrees the radian value gives. Co-Authored-By: Claude Opus 5.5 * SETVAR: store the value the dimension style took A real dimension variable now stores the value its style field took after validation, so any input the style accepts (true for DIMSCALE gives 1) is stored as it was before. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/lisp/drawing.rs | 18 +++++++++++++++- crates/engine/src/lisp/tests.rs | 35 ++++++++++++++++++++++++++++++- crates/engine/src/sysvars.rs | 7 +++++++ docs/autolisp.md | 2 ++ 4 files changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 4db7d0c20..88da7fd85 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -191,10 +191,22 @@ fn to_json_bounded(v: &Value, depth: usize, budget: &mut u64) -> Option bool { + RADIAN_VARS.iter().any(|v| v.eq_ignore_ascii_case(name.trim())) +} + pub fn getvar(ctx: &mut Ctx<'_>, a: Vec) -> Result { arity(&a, 1, 1)?; let name = string(&a[0])?; - Ok(Flow::Value(crate::sysvars::get(ctx.s, &name).map(|v| from_json(&v)).unwrap_or_default())) + Ok(Flow::Value(match crate::sysvars::get(ctx.s, &name) { + Some(serde_json::Value::Number(n)) if in_radians(&name) => Value::Real(n.as_f64().unwrap_or(0.0).to_radians()), + v => v.map(|v| from_json(&v)).unwrap_or_default(), + })) } /// Set a system variable after bounded JSON conversion, reporting invalid or oversized values as LISP errors. @@ -205,6 +217,10 @@ pub fn setvar(ctx: &mut Ctx<'_>, a: Vec) -> Result { let Some(json) = to_json_bounded(&a[1], 0, &mut budget) else { return Err(LispError::new(format!("AutoCAD variable setting rejected: {} value too large", to_text(&a[0], true)))); }; + let json = match json { + serde_json::Value::Number(n) if in_radians(&name) => serde_json::json!(n.as_f64().unwrap_or(0.0).to_degrees()), + other => other, + }; match crate::sysvars::set(ctx.s, &name, &json) { Ok(()) => Ok(Flow::Value(a[1].clone())), Err(_) => Err(LispError::new(format!("AutoCAD variable setting rejected: {} {}", to_text(&a[0], true), to_text(&a[1], true)))), diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index ca492e409..31e78bd15 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -528,7 +528,8 @@ fn interactive_routine_waits_for_the_user() { #[test] fn getangle_is_relative_to_angbase() { let mut s = session(); - s.cmdline("(setvar \"ANGBASE\" 90)").unwrap(); + // AutoLISP sets angle variables in radians: ANGBASE 90 degrees. + s.cmdline("(setvar \"ANGBASE\" (/ pi 2))").unwrap(); // A picked point at 180° in world terms is 90° from ANGBASE. s.cmdline("(setq a (getangle '(0 0)))").unwrap(); s.input(crate::Input::Point(cadcraft_geom::Vec2::new(-1.0, 0.0))).unwrap(); @@ -543,6 +544,38 @@ fn getangle_is_relative_to_angbase() { assert_eq!(to_text(&s.lisp_var("T2"), true), "3.14159"); } +/// `getvar` and `setvar` take angle variables in radians, as AutoCAD 2024's do (each set to 30 by +/// SETVAR, or to `(/ pi 6)` by `setvar`, reads 0.5235987755982987; DIMJOGANG's 45 degrees reads +/// 0.785398), while the SETVAR command keeps degrees. +#[test] +fn getvar_and_setvar_take_angle_variables_in_radians() { + let mut s = session(); + let degrees = |s: &Session, name: &str| crate::sysvars::get(s, name).and_then(|v| v.as_f64()).unwrap(); + // The defaults: polar tracking every 90 degrees, a 45-degree jog. + assert_eq!(ok(&mut s, "(list (equal (getvar \"POLARANG\") (/ pi 2) 1e-12) (equal (getvar \"DIMJOGANG\") (/ pi 4) 1e-12))"), "(T T)"); + // Set from LISP in radians, shown by SETVAR in degrees. + for (name, radians, deg) in + [("SNAPANG", "(/ pi 6)", 30.0), ("CHAMFERD", "0.95993108859688", 55.0), ("ANGBASE", "(/ pi 2)", 90.0), ("POLARANG", "(/ pi 4)", 45.0)] + { + ok(&mut s, &format!("(setvar \"{name}\" {radians})")); + assert!((degrees(&s, name) - deg).abs() < 1e-9, "{name}: {}", degrees(&s, name)); + assert_eq!(ok(&mut s, &format!("(equal (getvar \"{name}\") {radians} 1e-12)")), "T", "{name}"); + } + // Set by the SETVAR command in degrees, read by LISP in radians. + s.cmdline("SETVAR HPANG 45").unwrap(); + assert!((degrees(&s, "HPANG") - 45.0).abs() < 1e-9); + assert_eq!(ok(&mut s, "(equal (getvar \"HPANG\") 0.7853981633974482 1e-12)"), "T"); + // DIMJOGANG set to a whole number of degrees still takes a fraction of one from LISP. + s.cmdline("SETVAR DIMJOGANG 45").unwrap(); + ok(&mut s, "(setvar \"DIMJOGANG\" 0.5)"); + assert!((degrees(&s, "DIMJOGANG") - 0.5_f64.to_degrees()).abs() < 1e-9, "{}", degrees(&s, "DIMJOGANG")); + // It takes the value the dimension style takes: `true` is a DIMSCALE of 1. + crate::sysvars::set(&mut s, "DIMSCALE", &serde_json::json!(true)).unwrap(); + assert_eq!(crate::sysvars::get(&s, "DIMSCALE").and_then(|v| v.as_f64()), Some(1.0)); + // Other variables are as they were. + assert_eq!(ok(&mut s, "(getvar \"ANGDIR\")"), "0"); +} + #[test] fn appload_and_load() { let mut s = session(); diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 945a694bc..5c0f3951c 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -396,6 +396,13 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { if !st.apply_fields(&serde_json::Map::from_iter([((*field).to_string(), v.clone())])).is_empty() { return Err(bad()); } + // A real style field (DIMJOGANG, DIMSCALE...) is a real variable, even set to a + // whole number first, so a later fraction still fits. It takes the value the style + // took. + if let Some(f) = serde_json::to_value(&st).ok().and_then(|j| j.get(*field).filter(|f| f.is_f64()).and_then(|f| f.as_f64())) { + d.header.set_f64(&n, f); + return Ok(()); + } } let val = match v { Value::Number(x) if x.is_i64() => cadcraft_doc::HVal::Int(x.as_i64().unwrap_or(0)), diff --git a/docs/autolisp.md b/docs/autolisp.md index 91a55c101..d89684d00 100644 --- a/docs/autolisp.md +++ b/docs/autolisp.md @@ -82,6 +82,8 @@ reached", malformed source is a reader error, and every built-in checks its argu - **Input:** `initget getpoint getcorner getdist getangle getorient getreal getint getstring getkword entsel nentsel` - **Units:** `rtos angtos distof angtof` +- **Angle variables:** `getvar` and `setvar` give and take ANGBASE, SNAPANG, POLARANG, HPANG, + CHAMFERD and DIMJOGANG in radians, as in AutoCAD; the SETVAR command shows them in degrees. - **No-ops:** `vl-load-com gc redraw`; `ver` Entity lists use the DXF group codes of CADCraft's DXF files: what `entget` returns is what a From 2be869a154e11026fb68e6c3bd1e6e8c44e8a6c0 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:45:57 +0700 Subject: [PATCH 224/900] Units and rtos: round a half away from zero, at 15 significant digits (#2484) Decimal and scientific numbers went through Rust's formatting, which rounds the exact binary value and a half to even: (rtos 1500.5 2 0) gave 1500, (rtos 0.125 2 2) 0.12 and (rtos 1.005 2 2) 1.00. AutoCAD 2024 gives 1501, 0.13 and 1.01: it rounds at 15 significant digits, with a half away from zero, for scientific notation too (2.5 to none is 3E+00). units::fixed does that on the decimal digits; format_distance's decimal and scientific forms and rtos use it. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/lisp/drawing.rs | 2 +- crates/engine/src/units.rs | 94 ++++++++++++++++++++++++++----- 2 files changed, 81 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/lisp/drawing.rs b/crates/engine/src/lisp/drawing.rs index 88da7fd85..238551094 100644 --- a/crates/engine/src/lisp/drawing.rs +++ b/crates/engine/src/lisp/drawing.rs @@ -1055,7 +1055,7 @@ pub fn rtos(ctx: &mut Ctx<'_>, a: Vec) -> Result { } fn decimal(v: f64, prec: usize, dimzin: i64) -> String { - let mut s = format!("{v:.prec$}"); + let mut s = crate::units::fixed(v, prec); if s.starts_with("-0") && s.trim_start_matches(['-', '0', '.']).is_empty() { s = s.trim_start_matches('-').to_string(); } diff --git a/crates/engine/src/units.rs b/crates/engine/src/units.rs index 0a18a0039..3c6f3456e 100644 --- a/crates/engine/src/units.rs +++ b/crates/engine/src/units.rs @@ -68,23 +68,62 @@ pub fn format_distance(v: f64, lunits: i64, luprec: i64) -> String { }; format!("{}{}{}", if neg { "-" } else { "" }, whole, fs) } - _ => format!("{:.*}", prec, v), + _ => fixed(v, prec), } } -/// Scientific notation with a signed exponent of at least two digits (`1.7500E+01`, `1.00E-05`). -fn scientific(v: f64, prec: usize) -> String { - let s = format!("{:.*E}", prec, v); - match s.split_once('E') { - Some((mantissa, exp)) => { - let (sign, digits) = match exp.strip_prefix('-') { - Some(d) => ('-', d), - None => ('+', exp), - }; - format!("{mantissa}E{sign}{digits:0>2}") - } - None => s, +/// `v` with `prec` decimals, rounded as AutoCAD rounds a number it shows (RTOS, LUNITS): at 15 +/// significant digits, with a half rounded away from zero. AutoCAD 2024 gives 1.01 for 1.005 to two +/// places (its binary value is just below 1.005), 3 for 2.5 and -0.13 for -0.125, where Rust's +/// formatting rounds the binary value and a half to even (1.00, 2 and -0.12). +pub fn fixed(v: f64, prec: usize) -> String { + let plain = || format!("{v:.prec$}"); + if !v.is_finite() { + return plain(); } + let sci = format!("{:.14e}", v.abs()); + let Some((mantissa, exp)) = sci.split_once('e') else { return plain() }; + let Ok(exp) = exp.parse::() else { return plain() }; + let sig: Vec = mantissa.bytes().filter(u8::is_ascii_digit).map(|b| b - b'0').collect(); + // Digit `k` of `sig` is worth 10^(exp - k); keep those down to 10^-prec, in units of 10^-prec. + let digit = |k: i64| usize::try_from(k).ok().and_then(|k| sig.get(k)).copied().unwrap_or(0); + let keep = exp + 1 + prec as i64; + let mut units: Vec = (0..keep).map(digit).collect(); + if keep >= 0 && digit(keep) >= 5 { + let mut carry = true; + for d in units.iter_mut().rev() { + if *d == 9 { + *d = 0; + } else { + *d += 1; + carry = false; + break; + } + } + if carry { + units.insert(0, 1); + } + } + let n: String = units.iter().map(|d| char::from(b'0' + d)).collect(); + let n = format!("{:0>width$}", n.trim_start_matches('0'), width = prec + 1); + let (int, frac) = n.split_at(n.len() - prec); + let body = if prec == 0 { int.to_string() } else { format!("{int}.{frac}") }; + if v < 0.0 && n.bytes().any(|b| b != b'0') { format!("-{body}") } else { body } +} + +/// Scientific notation with a signed exponent of at least two digits (`1.7500E+01`, `1.00E-05`), +/// the mantissa rounded as [`fixed`] rounds. +fn scientific(v: f64, prec: usize) -> String { + let s = format!("{:.14e}", v); + let Some((m, e)) = s.split_once('e') else { return s }; + let (Ok(m), Ok(mut e)) = (m.parse::(), e.parse::()) else { return s }; + let mut mantissa = fixed(m, prec); + // 9.99… rounded up to 10: one more power of ten. + if mantissa.trim_start_matches('-').starts_with("10") { + e += 1; + mantissa = fixed(m / 10.0, prec); + } + format!("{mantissa}E{}{:0>2}", if e < 0 { '-' } else { '+' }, e.abs()) } fn gcd(a: i64, b: i64) -> i64 { @@ -435,11 +474,38 @@ mod tests { assert_eq!(format_distance(11.6, 3, 0), "1'-0\""); } + /// RTOS in AutoCAD 2024 (accoreconsole, DIMZIN 0): a half rounds away from zero, at 15 + /// significant digits. + #[test] + fn numbers_round_as_autocad_rounds_them() { + for (v, prec, want) in [ + (1500.5, 0, "1501"), + (2.5, 0, "3"), + (-2.5, 0, "-3"), + (0.125, 2, "0.13"), + (0.5, 0, "1"), + (1.005, 2, "1.01"), + (3.5, 0, "4"), + (0.0625, 3, "0.063"), + (-0.125, 2, "-0.13"), + (1234.5678, 3, "1234.568"), + ] { + assert_eq!(format_distance(v, 2, prec), want, "{v} to {prec}"); + } + assert_eq!(format_distance(2.5, 1, 0), "3E+00"); + assert_eq!(format_distance(0.125, 1, 1), "1.3E-01"); + assert_eq!(format_distance(9.96, 1, 1), "1.0E+01"); + assert_eq!(fixed(-0.004, 2), "0.00"); + assert_eq!(fixed(1e-20, 3), "0.000"); + assert_eq!(fixed(123456789012.0, 1), "123456789012.0"); + } + #[test] fn scientific_exponent_is_signed_and_padded() { assert_eq!(format_distance(17.5, 1, 4), "1.7500E+01"); assert_eq!(format_distance(0.00001, 1, 2), "1.00E-05"); - assert_eq!(format_distance(1234.5, 1, 3), "1.234E+03"); + // 1.2345 is halfway: away from zero, as AutoCAD rounds 2.5 to 3E+00. + assert_eq!(format_distance(1234.5, 1, 3), "1.235E+03"); assert_eq!(format_distance(12345678.0, 1, 3), "1.235E+07"); assert_eq!(format_distance(-17.5, 1, 4), "-1.7500E+01"); assert_eq!(format_distance(0.0, 1, 2), "0.00E+00"); From dda6562a97bb96e60da37278a9b04e79a96246d7 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:46:01 +0700 Subject: [PATCH 225/900] Pick the object drawn last, not the nearest one (#2488) select::pick said it returns the topmost entity within the aperture, but it returned the nearest, using the draw order only to break ties. AutoCAD 2024 picks the object drawn last among those under the pickbox, and DRAWORDER changes which: a circle and a line drawn after it, 0.05 and 0.45 from the pick, give the line. Candidates already come topmost first, so pick_with returns the first within the aperture; pick_all keeps that order for selection cycling. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/select.rs | 50 ++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index d3db01c9b..6c70bee37 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -181,7 +181,9 @@ pub(crate) fn candidates<'a>( } } -/// The topmost entity within `aperture` of `p`. +/// The topmost entity within `aperture` of `p`: the one drawn last (on top in the draw order), not +/// the nearest, as AutoCAD 2024 picks (two objects under the pickbox: the one drawn later is +/// picked, and DRAWORDER changes which). pub fn pick(d: &Drawing, space: &Space, p: Vec2, aperture: f64) -> Option { let ix = spatial::index(d, space); pick_with(d, space, &ix, p, aperture) @@ -189,7 +191,7 @@ pub fn pick(d: &Drawing, space: &Space, p: Vec2, aperture: f64) -> Option>, p: Vec2, aperture: f64) -> Option { let probe = Bounds2::new(p, p).expand(aperture); - let mut best: Option<(f64, Handle)> = None; + // Candidates come topmost first: the first within the aperture is the one. for (e, known) in candidates(d, space, ix, &probe.expand(aperture), true, true)? { if !selectable(d, e) { continue; @@ -198,30 +200,24 @@ pub(crate) fn pick_with(d: &Drawing, space: &Space, ix: &Option Vec { let ix = spatial::index(d, space); let probe = Bounds2::new(p, p).expand(aperture); let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() }; - let mut hits: Vec<(f64, Handle)> = cands + cands .filter(|(e, known)| selectable(d, e) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe))) - .map(|(e, _)| (entity_distance(d, e, p, aperture / 4.0), e.handle)) - .filter(|(dist, _)| *dist <= aperture) - .collect(); - hits.sort_by(|a, b| a.0.total_cmp(&b.0)); - hits.into_iter().map(|(_, h)| h).collect() + .filter(|(e, _)| entity_distance(d, e, p, aperture / 4.0) <= aperture) + .map(|(e, _)| e.handle) + .collect() } /// Whether PREVIEWFILTER keeps `e` from being highlighted under the cursor: bits 1 objects on @@ -486,6 +482,26 @@ mod tests { assert_eq!(fence_hits(EntityKind::XLine(line.clone()), [(0.0, 1.0), (0.0, 5.0)]), 0); assert_eq!(fence_hits(EntityKind::Ray(line), [(5.0, 1.0), (5.0, 5.0)]), 0); } + + /// Two objects under the pickbox: AutoCAD 2024 picks the one drawn last, not the nearer one, + /// and DRAWORDER changes which (`(ssget pt)` in accoreconsole). + #[test] + fn a_pick_takes_the_object_drawn_last() { + let mut d = Drawing::new_metric(); + let circle = d + .add(&Space::Model, Common::default(), EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(50.0, 50.0, 0.0), radius: 10.0 })) + .unwrap(); + let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(40.5, 45.0, 0.0), b: Vec3::new(40.5, 55.0, 0.0) }); + let line = d.add(&Space::Model, Common::default(), line).unwrap(); + // 0.05 from the circle and 0.45 from the line, both inside an aperture of 1. + let p = Vec2::new(40.05, 50.0); + assert_eq!(pick(&d, &Space::Model, p, 1.0), Some(line)); + assert_eq!(pick_all(&d, &Space::Model, p, 1.0), vec![line, circle]); + d.model.send_to_back(line); + assert_eq!(pick(&d, &Space::Model, p, 1.0), Some(circle)); + // Only one within reach: that one, whatever the order. + assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line)); + } } #[cfg(test)] From 16ae23424d4c2e89c075eb653159322559d7b8cb Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:46:05 +0700 Subject: [PATCH 226/900] -INSERT: X, Y and Z presets, XYZ, and the Z factor AutoCAD stores (#2480) * -INSERT: X, Y and Z presets, XYZ, and the Z factor AutoCAD stores The insertion point prompt offers X, Y and Z: the factor for that axis alone, the others 1, and no scale prompts after the point. The X scale prompt offers XYZ, which asks X, Y and Z in turn. A Z factor not asked is the size of the X factor: X -1 with Y as X stored Z -1, where AutoCAD stores +1. Basepoint picks on the block dropped at the cursor, as AutoCAD drops it where it is being dragged (the origin in a script), instead of at its definition position. Each was measured in AutoCAD 2024 from AutoLISP's command and is pinned in insert_options_match_autocad. Co-Authored-By: Claude Opus 5.5 * -INSERT: store the Z factor as AutoCAD does after Scale, Z and XYZ Measured in AutoCAD 2024: Scale -2 gives X and Y -2 and Z 2; a Z preset of -3 gives Z 3; XYZ with X -2 and Enter at Y and Z gives Z 2; a Z typed at XYZ's Z prompt (-4) stays as typed. XYZ followed by a corner, with Corner or a point straight away, still asks for Z, which defaults to the size of the corner's X factor. Co-Authored-By: Claude Opus 5.5 * -INSERT: an axis preset after Scale changes that axis alone Measured in AutoCAD 2024: Scale -3 then X 2 gives 2/-3/3; X 2 then Scale -3 gives -3/-3/3; Scale 2 then Z -5 gives 2/2/5. Scale now sets all three presets, so a later X, Y or Z keeps the other two. Co-Authored-By: Claude Opus 5.5 * -INSERT test: Basepoint with the cursor away from the origin Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks.rs | 121 ++++++++++++++++++++--- crates/engine/tests/it/insert_prompts.rs | 78 ++++++++++++++- 2 files changed, 182 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index ca4cfffec..8cc248685 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -202,13 +202,13 @@ pub(crate) fn insert(s: &mut Session, name: &str, at: Vec2, scale: f64, rotation insert_with(s, name, at, Vec2::new(scale, scale), rotation, None, values) } -/// The block reference INSERT places: X/Y scale factors, and an optional base point (in block +/// The block reference INSERT places: X/Y/Z scale factors, and an optional base point (in block /// coordinates) that lands on `at` instead of the block's own base point. -fn insert_entity(blk: &Block, at: Vec2, scale: Vec2, rotation: f64, base: Option) -> Insert { +fn insert_entity(blk: &Block, at: Vec2, scale: Vec3, rotation: f64, base: Option) -> Insert { let mut ins = Insert { block: blk.name.clone(), insert: v3(at), - scale: Vec3::new(scale.x, scale.y, scale.x), + scale, rotation, attribs: Vec::new(), cols: 1, @@ -223,7 +223,8 @@ fn insert_entity(blk: &Block, at: Vec2, scale: Vec2, rotation: f64, base: Option ins } -/// [`insert`] with separate X/Y scale factors and an optional base point (see [`insert_entity`]). +/// [`insert`] with separate X/Y scale factors (Z as X) and an optional base point (see +/// [`insert_entity`]). pub(crate) fn insert_with( s: &mut Session, name: &str, @@ -232,6 +233,19 @@ pub(crate) fn insert_with( rotation: f64, base: Option, values: &serde_json::Map, +) -> Result { + insert_scaled(s, name, at, Vec3::new(scale.x, scale.y, scale.x), rotation, base, values) +} + +/// [`insert_with`] with a Z scale factor of its own. +fn insert_scaled( + s: &mut Session, + name: &str, + at: Vec2, + scale: Vec3, + rotation: f64, + base: Option, + values: &serde_json::Map, ) -> Result { let blk = s.doc()?.block(name).cloned().ok_or_else(|| EngineError::Other(format!("Block \"{name}\" not found.")))?; let mut ins = insert_entity(&blk, at, scale, rotation, base); @@ -566,15 +580,19 @@ enum InsStage { /// A file whose block already exists: redefine it from the file? Redefine, Point, - /// Basepoint: a new base point, picked on the block shown at its definition position. + /// Basepoint: a new base point, picked on the block dropped where it was (at the cursor). BasePoint, /// Scale preset before the insertion point. PresetScale, + /// X, Y or Z scale preset (0, 1, 2) before the insertion point: that axis alone. + PresetAxis(usize), /// Rotate preset before the insertion point. PresetRotation, XScale, Corner, YScale, + /// XYZ: the Z scale factor, after X and Y. + ZScale, Rotation, Attribs, } @@ -587,6 +605,15 @@ struct InsertM { base: Option, x_scale: Option, scale: Option, + /// The Z scale factor when given (a preset or XYZ); otherwise the X factor's size. AutoCAD + /// keeps a Z factor typed at XYZ's Z prompt as given, and stores the size of any other. + z_scale: Option, + /// X/Y/Z presets given so far. + axes: [Option; 3], + /// XYZ at the X scale prompt: X, Y and Z are asked in turn. + xyz: bool, + /// Where the block was dropped to pick a Basepoint on it. + dropped: Option, rotation: Option, attdefs: Vec<(String, String, String)>, values: serde_json::Map, @@ -610,7 +637,7 @@ impl InsertM { && self.values.len() >= self.attdefs.len() && let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation) { - let h = insert_with(s, &n, a, sc, r, self.base, &self.values)?; + let h = insert_scaled(s, &n, a, self.scale3(sc), r, self.base, &self.values)?; if self.explode { insert_file::explode_insert(s, h)?; } @@ -656,6 +683,23 @@ impl InsertM { } } + /// X/Y scale factors with Z: as given, else the X factor's size (AutoCAD 2024: X -1 with Y + /// as X stores Z +1). + /// X and Y from a corner: XYZ still asks Z, which defaults to the size of X. + fn corner_scale(&mut self, s: &mut Session, sc: Vec2) -> Result { + self.scale = Some(sc); + if self.xyz { + self.x_scale = Some(sc.x); + self.stage = InsStage::ZScale; + return Ok(Step::Continue); + } + self.advance(s) + } + + fn scale3(&self, sc: Vec2) -> Vec3 { + Vec3::new(sc.x, sc.y, self.z_scale.unwrap_or(sc.x.abs())) + } + /// Scale factors from an opposite corner: the X and Y distances from the insertion point. fn corner(a: Vec2, p: Vec2) -> Result { let d = p - a; @@ -686,15 +730,18 @@ impl Interactive for InsertM { let name = self.file.as_ref().map(|f| f.name.clone()).unwrap_or_default(); Prompt::new(format!("Block \"{name}\" already exists. Redefine it?"), super::curves::KW).kw(&["Yes", "No"]).default("N") } - InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "Rotate"]), + InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]), InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT), InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"), + InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"), InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"), + InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at), InsStage::XScale => { - Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at) + Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at) } InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at), InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"), + InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"), InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at), InsStage::Attribs => { let (_, prompt, default) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); @@ -742,14 +789,25 @@ impl Interactive for InsertM { self.at = Some(p); return self.advance(s); } - Input::Keyword(k) if k == "Basepoint" => self.stage = InsStage::BasePoint, + Input::Keyword(k) if k == "Basepoint" => { + // AutoCAD drops the block where it is being dragged, at the cursor (the origin + // in a script: 2024 inserted (15, 5) for base point (612350.678, 2398770.432) + // and insertion point (612365.678, 2398775.432)). + self.dropped = Some(s.cursor); + self.stage = InsStage::BasePoint; + } Input::Keyword(k) if k == "Scale" => self.stage = InsStage::PresetScale, + Input::Keyword(k) if k == "X" => self.stage = InsStage::PresetAxis(0), + Input::Keyword(k) if k == "Y" => self.stage = InsStage::PresetAxis(1), + Input::Keyword(k) if k == "Z" => self.stage = InsStage::PresetAxis(2), Input::Keyword(k) if k == "Rotate" => self.stage = InsStage::PresetRotation, _ => {} }, InsStage::BasePoint => { if let Input::Point(p) = i { - self.base = Some(p); + // From the dropped block to its own coordinates. + let def = s.doc()?.block(self.name.as_deref().unwrap_or_default()).map_or(Vec2::ZERO, |b| b.base.xy()); + self.base = Some(def + (p - self.dropped.unwrap_or(def))); self.stage = InsStage::Point; } } @@ -760,12 +818,30 @@ impl Interactive for InsertM { _ => return Ok(Step::Continue), }; self.scale = Some(Vec2::new(f, f)); + self.z_scale = Some(f.abs()); + // An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3). + self.axes = [Some(f), Some(f), Some(f.abs())]; // Exploded insertion asks its one scale factor after the insertion point. if self.at.is_some() { return self.advance(s); } self.stage = InsStage::Point; } + // One axis preset: the others are 1, and no scale factors are asked after the point. + InsStage::PresetAxis(ax) => { + let f = match i { + Input::Text(t) => nonzero(&t)?, + Input::Enter => 1.0, + _ => return Ok(Step::Continue), + }; + if let Some(a) = self.axes.get_mut(ax) { + *a = Some(f); + } + let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0)); + self.scale = Some(Vec2::new(x, y)); + self.z_scale = Some(z.abs()); + self.stage = InsStage::Point; + } InsStage::PresetRotation => { self.rotation = Some(match i { Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?, @@ -776,9 +852,10 @@ impl Interactive for InsertM { } InsStage::XScale => match i { Input::Keyword(k) if k == "Corner" => self.stage = InsStage::Corner, + Input::Keyword(k) if k == "XYZ" => self.xyz = true, Input::Point(p) => { - self.scale = Some(Self::corner(self.at.unwrap_or_default(), p)?); - return self.advance(s); + let sc = Self::corner(self.at.unwrap_or_default(), p)?; + return self.corner_scale(s, sc); } Input::Text(t) => { self.x_scale = Some(nonzero(&t)?); @@ -792,8 +869,8 @@ impl Interactive for InsertM { }, InsStage::Corner => { if let Input::Point(p) = i { - self.scale = Some(Self::corner(self.at.unwrap_or_default(), p)?); - return self.advance(s); + let sc = Self::corner(self.at.unwrap_or_default(), p)?; + return self.corner_scale(s, sc); } } InsStage::YScale => { @@ -804,6 +881,18 @@ impl Interactive for InsertM { _ => return Ok(Step::Continue), }; self.scale = Some(Vec2::new(x, y)); + if self.xyz { + self.stage = InsStage::ZScale; + return Ok(Step::Continue); + } + return self.advance(s); + } + InsStage::ZScale => { + self.z_scale = Some(match i { + Input::Text(t) => nonzero(&t)?, + Input::Enter => self.x_scale.unwrap_or(1.0).abs(), + _ => return Ok(Step::Continue), + }); return self.advance(s); } InsStage::Rotation => { @@ -832,7 +921,7 @@ impl Interactive for InsertM { let Some(b) = d.block(n) else { return Vec::new() }; // Picking a new base point: the block sits at its definition position. if self.stage == InsStage::BasePoint { - return vec![EntityKind::Insert(insert_entity(b, b.base.xy(), Vec2::new(1.0, 1.0), 0.0, None))]; + return vec![EntityKind::Insert(insert_entity(b, self.dropped.unwrap_or(b.base.xy()), Vec3::new(1.0, 1.0, 1.0), 0.0, None))]; } let at = self.at.unwrap_or(c); let scale = self.scale.unwrap_or_else(|| match (self.stage, self.x_scale) { @@ -841,7 +930,7 @@ impl Interactive for InsertM { _ => Vec2::new(1.0, 1.0), }); let rot = self.rotation.unwrap_or(if self.stage == InsStage::Rotation { at.angle_to(c) } else { 0.0 }); - vec![EntityKind::Insert(insert_entity(b, at, scale, rot, self.base))] + vec![EntityKind::Insert(insert_entity(b, at, self.scale3(scale), rot, self.base))] } } diff --git a/crates/engine/tests/it/insert_prompts.rs b/crates/engine/tests/it/insert_prompts.rs index 89ea729d3..00c5b8e41 100644 --- a/crates/engine/tests/it/insert_prompts.rs +++ b/crates/engine/tests/it/insert_prompts.rs @@ -1,4 +1,4 @@ -//! Command-line INSERT: X/Y scale prompts and the Basepoint/Scale/Rotate options (#245). +//! Command-line INSERT: X/Y/Z scale prompts and the Basepoint/Scale/X/Y/Z/Rotate options (#245). use cadcraft_engine::Session; use cadcraft_engine::doc::EntityKind; @@ -53,3 +53,79 @@ fn script_insert_reads_x_and_y_scale_then_rotation_and_honours_its_options() { s.execute("insert", &json!({ "name": "B1", "at": [0, 80], "scale": [2, 3], "basePoint": [10, 0] })).unwrap(); assert_eq!(inserts(&s).last(), Some(&(-20.0, 80.0, 2.0, 3.0, 0.0))); } + +/// (x, y, x scale, y scale, z scale, rotation in degrees) of the last block reference. +fn last_insert(s: &Session) -> (f64, f64, f64, f64, f64, f64) { + let r = |v: f64| (v * 1e9).round() / 1e9; + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Insert(i) => Some((r(i.insert.x), r(i.insert.y), r(i.scale.x), r(i.scale.y), r(i.scale.z), r(i.rotation.to_degrees()))), + _ => None, + }) + .last() + .unwrap() +} + +/// The options of AutoCAD 2024's -INSERT, each run as AutoLISP's `command` gives it (accoreconsole, +/// the block reference read back with `entget`): X/Y/Z presets set that axis alone and skip the +/// scale prompts, XYZ asks Z too, a Z factor not asked is the X factor's size, and a Basepoint is +/// picked on the block dropped at the cursor (the origin in a script). +#[test] +fn insert_options_match_autocad() { + // A line (0,0)-(10,0) and a circle at (5,5) r 3, around `base`, as block `name`. + let block = |s: &mut Session, name: &str, base: [f64; 2], unit: f64| { + let at = |x: f64, y: f64| [base[0] + x * unit, base[1] + y * unit]; + s.execute("line", &json!({ "points": [at(0.0, 0.0), at(10.0, 0.0)] })).unwrap(); + s.execute("circle", &json!({ "center": at(5.0, 5.0), "radius": 3.0 * unit })).unwrap(); + let hs: Vec = s.doc().unwrap().model.handles().iter().map(|h| h.hex()).collect(); + s.execute("block", &json!({ "name": name, "base": base, "keep": "delete", "handles": hs })).unwrap(); + }; + let cases: [(&str, [f64; 2], f64, &str, (f64, f64, f64, f64, f64, f64)); 17] = [ + // X -1, Y as X: Z +1. + ("B3", [612345.678, 2398765.432], 1.0, "\"B3\" '(612365.678 2398775.432) -1 \"\" 0", (612365.678, 2398775.432, -1.0, -1.0, 1.0, 0.0)), + ("B4", [0.0, 0.0], 1.0, "\"B4\" \"_S\" 2.5 '(20.0 10.0) 45", (20.0, 10.0, 2.5, 2.5, 2.5, 45.0)), + ("B5", [0.0, 0.0], 1.0, "\"B5\" \"_R\" 60 '(20.0 10.0) 2 \"\"", (20.0, 10.0, 2.0, 2.0, 2.0, 60.0)), + // X alone: the next number is the rotation. + ("B6", [0.5, 0.25], 0.001, "\"B6\" \"_X\" 2 '(0.52 0.26) 3", (0.52, 0.26, 2.0, 1.0, 1.0, 3.0)), + ( + "B7", + [612345.678, 2398765.432], + 1.0, + "\"B7\" \"_B\" '(612350.678 2398770.432) '(612365.678 2398775.432) 1 \"\" 0", + (15.0, 5.0, 1.0, 1.0, 1.0, 0.0), + ), + ("B8", [0.0, 0.0], 1.0, "\"B8\" '(20.0 10.0) \"_XYZ\" 2 3 4 0", (20.0, 10.0, 2.0, 3.0, 4.0, 0.0)), + ("B9", [0.0, 0.0], 1.0, "\"B9\" '(20.0 10.0) \"_C\" '(26.0 14.0) 0", (20.0, 10.0, 6.0, 4.0, 6.0, 0.0)), + // Z is stored as a size unless typed at XYZ's Z prompt: Scale -2, XYZ -2 with Enter at Y + // and Z, and a Z preset of -3 all give +; XYZ's -4 stays. + ("C1", [0.0, 0.0], 1.0, "\"C1\" \"_S\" -2 '(20.0 10.0) 0", (20.0, 10.0, -2.0, -2.0, 2.0, 0.0)), + ("C2", [0.0, 0.0], 1.0, "\"C2\" '(20.0 10.0) \"_XYZ\" -2 \"\" \"\" 0", (20.0, 10.0, -2.0, -2.0, 2.0, 0.0)), + ("C5", [0.0, 0.0], 1.0, "\"C5\" \"_Z\" -3 '(20.0 10.0) 0", (20.0, 10.0, 1.0, 1.0, 3.0, 0.0)), + ("C6", [0.0, 0.0], 1.0, "\"C6\" '(20.0 10.0) \"_XYZ\" 2 3 -4 0", (20.0, 10.0, 2.0, 3.0, -4.0, 0.0)), + ("C7", [0.0, 0.0], 1.0, "\"C7\" \"_X\" -2 '(20.0 10.0) 0", (20.0, 10.0, -2.0, 1.0, 1.0, 0.0)), + // Scale and the axis presets in turn: the later one wins for its axes. + ("C8", [0.0, 0.0], 1.0, "\"C8\" \"_S\" -3 \"_X\" 2 '(20.0 10.0) 0", (20.0, 10.0, 2.0, -3.0, 3.0, 0.0)), + ("C9", [0.0, 0.0], 1.0, "\"C9\" \"_X\" 2 \"_S\" -3 '(20.0 10.0) 0", (20.0, 10.0, -3.0, -3.0, 3.0, 0.0)), + ("CA", [0.0, 0.0], 1.0, "\"CA\" \"_S\" 2 \"_Z\" -5 '(20.0 10.0) 0", (20.0, 10.0, 2.0, 2.0, 5.0, 0.0)), + // XYZ then a corner (by Corner or straight away) still asks Z, which defaults to X's size. + ("C3", [0.0, 0.0], 1.0, "\"C3\" '(20.0 10.0) \"_XYZ\" \"_C\" '(26.0 14.0) \"\" 0", (20.0, 10.0, 6.0, 4.0, 6.0, 0.0)), + ("C4", [0.0, 0.0], 1.0, "\"C4\" '(20.0 10.0) \"_XYZ\" '(14.0 14.0) \"\" 0", (20.0, 10.0, -6.0, 4.0, 6.0, 0.0)), + ]; + for (name, base, unit, args, want) in cases { + let mut s = Session::new(); + block(&mut s, name, base, unit); + s.cmdline(&format!("(command \"_.-INSERT\" {args})")).unwrap(); + assert!(s.running.is_none(), "{name}: {}", s.prompt_text()); + assert_eq!(last_insert(&s), want, "{name}"); + } + // Basepoint is picked on the block dropped at the cursor: with the cursor at (100, 50) + // instead of the origin, B7's call inserts 100 and 50 further on. + let mut s = Session::new(); + block(&mut s, "B7", [612345.678, 2398765.432], 1.0); + s.cursor = cadcraft_engine::geom::Vec2::new(100.0, 50.0); + s.cmdline("(command \"_.-INSERT\" \"B7\" \"_B\" '(612350.678 2398770.432) '(612365.678 2398775.432) 1 \"\" 0)").unwrap(); + assert_eq!(last_insert(&s), (115.0, 55.0, 1.0, 1.0, 1.0, 0.0)); +} From 50df1284a3feaabd28302536ba8642e0e80c0324 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:46:08 +0700 Subject: [PATCH 227/900] -HATCH: Properties asks the pattern's scale and angle, and takes Solid (#2481) * -HATCH: Properties asks the pattern's scale and angle, and takes Solid The pattern option asked only for a name, so a script answering it as AutoCAD asks (`_P ANSI31 2 45`) got "Unknown pattern 2" and "Unknown pattern 45" and a hatch at scale 1, angle 0, and `_P _S` reported "Unknown pattern _S". As AutoCAD 2024's -HATCH Properties does, the pattern name is now followed by its scale and then its angle (Enter keeps them), Solid (S, _S or SOLID) sets a solid fill and asks neither, and an unknown name or a refused value is asked again. The sCale and Angle options and the pattern picker are unchanged. Co-Authored-By: Claude Opus 5.5 * -HATCH: ask for the pattern again when a .pat file loads nothing A .pat file that cannot be read, or holds no pattern, now repeats the pattern prompt instead of going on to Scale and Angle with the previous pattern. Co-Authored-By: Claude Opus 5.5 * -HATCH: a pick at a Properties prompt asks again Enter keeps the current pattern, scale or angle; a point or an object (an entity name from LISP) answers none of those prompts, so the prompt comes again instead of going on with the value unchanged. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/hatch.rs | 118 +++++++++++++++++++++++---- crates/engine/tests/lin_pat_files.rs | 15 ++++ 2 files changed, 115 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index df0fef550..ca7defed8 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -550,6 +550,9 @@ struct HatchM { /// Loops by pick (one hatch each when separate). loops: Vec>, asking: Option, + /// The pattern was asked by the Pattern option: its scale and angle follow, as at AutoCAD's + /// -HATCH Properties. + properties: bool, /// "Select objects" mode instead of "Pick internal point"; the next HATCH starts in it again. selecting: bool, } @@ -561,6 +564,7 @@ impl HatchM { settings: HatchSettings::from(s, &Value::Null, gradient), loops: Vec::new(), asking: None, + properties: false, selecting: s.last_used.hatch_select, } } @@ -582,11 +586,13 @@ impl HatchM { h.set_i64("HPORIGINMODE", mode.index()); Ok(()) } - fn answer(&mut self, s: &mut Session, a: HatchAsk, t: &str) -> Result<()> { + /// Take an answer to sub-prompt `a`; false when it was refused. + fn answer(&mut self, s: &mut Session, a: HatchAsk, t: &str) -> Result { match a { HatchAsk::Pattern => { let up = match patfile::typed_file(s, t.trim()) { - Some(n) if n.is_empty() => return Ok(()), + // Nothing loaded from it: the pattern is asked again. + Some(n) if n.is_empty() => return Ok(false), Some(n) => n, None => t.trim().to_ascii_uppercase(), }; @@ -595,20 +601,19 @@ impl HatchM { s.doc_mut()?.header.set_str("HPNAME", &up); } else { s.echo(format!("Unknown pattern {up}. Available: {}", patfile::names().join(", "))); + return Ok(false); } } HatchAsk::Scale => { - if let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) { - self.settings.scale = v; - s.doc_mut()?.header.set_f64("HPSCALE", v); - } + let Some(v) = super::machines::number(t).filter(|v| v.is_finite() && *v > 0.0) else { return Ok(false) }; + self.settings.scale = v; + s.doc_mut()?.header.set_f64("HPSCALE", v); } HatchAsk::Angle => { // Turns the pattern from the X axis (not from ANGBASE), clockwise when ANGDIR is 1. - if let Some(a) = s.angle_settings().rotation(t).filter(|a| a.is_finite()) { - self.settings.angle = a; - s.doc_mut()?.header.set_f64("HPANG", a); - } + let Some(a) = s.angle_settings().rotation(t).filter(|a| a.is_finite()) else { return Ok(false) }; + self.settings.angle = a; + s.doc_mut()?.header.set_f64("HPANG", a); } HatchAsk::Origin => { let mode = match t { @@ -622,7 +627,22 @@ impl HatchM { self.set_origin(s, None, mode)?; } } - Ok(()) + Ok(true) + } + + /// The sub-prompt that follows `a` (`taken`: its answer was taken). The Pattern option goes + /// on, as AutoCAD 2024's -HATCH Properties does, from the pattern name to its scale and then + /// its angle (a solid fill has neither), and asks again for a pattern or a value it refused. + fn after(&self, a: HatchAsk, taken: bool) -> Option { + if !self.properties { + return None; + } + match a { + _ if !taken => Some(a), + HatchAsk::Pattern if self.settings.pattern != "SOLID" => Some(HatchAsk::Scale), + HatchAsk::Scale => Some(HatchAsk::Angle), + _ => None, + } } } @@ -643,9 +663,10 @@ impl Interactive for HatchM { // The sub-prompts offer the current value: Enter keeps it. match self.asking { Some(HatchAsk::Pattern) => { - return Prompt::new("Enter a pattern name", Accept::TEXT) + let p = Prompt::new("Enter a pattern name", Accept::TEXT) .default(self.settings.pattern.clone()) .picker(Picker::HatchPattern(self.settings.pattern.clone())); + return if self.gradient { p } else { p.kw(&["Solid"]) }; } Some(HatchAsk::Scale) => { return Prompt::new("Specify a scale for the hatch pattern", Accept::NUMBER).default(format!("{:.4}", self.settings.scale)); @@ -686,11 +707,19 @@ impl Interactive for HatchM { } fn input(&mut self, s: &mut Session, i: Input) -> Result { if let Some(a) = self.asking.take() { - match &i { - Input::Point(p) if a == HatchAsk::Origin => self.set_origin(s, Some(*p), OriginMode::Current)?, + let taken = match &i { + Input::Point(p) if a == HatchAsk::Origin => { + self.set_origin(s, Some(*p), OriginMode::Current)?; + true + } + Input::Keyword(k) if a == HatchAsk::Pattern && k == "Solid" => self.answer(s, a, "SOLID")?, Input::Text(t) | Input::Keyword(t) => self.answer(s, a, t)?, - _ => {} - } + // Enter keeps the current value; a point or a pick answers none of these prompts. + Input::Enter => true, + _ => false, + }; + self.asking = self.after(a, taken); + self.properties &= self.asking.is_some(); return Ok(Step::Continue); } match i { @@ -723,7 +752,10 @@ impl Interactive for HatchM { "Select objects" => self.set_mode(s, true), "picK internal point" => self.set_mode(s, false), "Undo" => self.loops.clear(), - "Pattern" | "seTtings" => self.asking = Some(HatchAsk::Pattern), + "Pattern" | "seTtings" => { + self.asking = Some(HatchAsk::Pattern); + self.properties = !self.gradient; + } "sCale" => self.asking = Some(HatchAsk::Scale), "Angle" => self.asking = Some(HatchAsk::Angle), "Origin" => self.asking = Some(HatchAsk::Origin), @@ -738,7 +770,7 @@ impl Interactive for HatchM { } // A pattern chosen in the picker while boundaries are picked. Input::Text(t) if !self.gradient => { - self.answer(s, HatchAsk::Pattern, &t)?; + let _ = self.answer(s, HatchAsk::Pattern, &t)?; Ok(Step::Continue) } // Enter ends boundary picking in either mode and creates the hatch. @@ -838,6 +870,9 @@ mod tests { s.input(Input::Keyword("Pattern".into())).unwrap(); assert!(s.current_prompt().unwrap().picker.is_some()); s.input(Input::Text("BRICK".into())).unwrap(); + // Its scale and angle follow; Enter keeps them. + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap(); s.input(Input::Enter).unwrap(); assert_eq!(only_hatch(&s).1.pattern, "BRICK"); @@ -851,6 +886,53 @@ mod tests { assert!(s.current_prompt().unwrap().picker.is_none()); } + /// -HATCH's Properties as AutoCAD 2024 takes them from AutoLISP's `command` (accoreconsole, the + /// hatch read back with `entget`): a pattern name, then its scale and angle (Enter keeps them); + /// Solid (`S`, `_S` or SOLID) asks neither; an unknown name is asked again. + #[test] + fn hatch_properties_ask_pattern_scale_and_angle_as_autocad() { + // (properties given, pattern, solid, scale, angle in degrees) + let cases: [(&str, &str, bool, f64, f64); 7] = [ + ("\"ANSI31\" 2 45 \"_S\" (entlast) \"\"", "ANSI31", false, 2.0, 45.0), + ("\"_S\" \"_S\" (entlast) \"\"", "SOLID", true, 1.0, 0.0), + ("\"ANSI37\" 0.5 30 '(5.0 5.0)", "ANSI37", false, 0.5, 30.0), + ("\"ANSI31\" \"\" \"\" '(5.0 5.0)", "ANSI31", false, 1.0, 0.0), + ("\"S\" '(5.0 5.0)", "SOLID", true, 1.0, 0.0), + ("\"SOLID\" '(5.0 5.0)", "SOLID", true, 1.0, 0.0), + ("\"XYZ\" \"ANSI31\" 1 0 '(5.0 5.0)", "ANSI31", false, 1.0, 0.0), + ]; + for (props, pattern, solid, scale, angle) in cases { + let mut s = Session::new(); + s.execute("circle", &json!({ "center": [20, 15], "radius": 8 })).unwrap(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [40, 30] })).unwrap(); + s.cmdline("(setvar \"HPNAME\" \"ANSI31\")").unwrap(); + s.cmdline("(setvar \"HPSCALE\" 1.0)").unwrap(); + s.cmdline("(setvar \"HPANG\" 0.0)").unwrap(); + s.cmdline(&format!("(command \"_.-HATCH\" \"_P\" {props} \"\")")).unwrap(); + assert!(s.running.is_none(), "{props}: {}", s.prompt_text()); + let h = only_hatch(&s).1; + assert!( + h.pattern == pattern && h.solid == solid && (h.scale - scale).abs() < 1e-12 && (h.angle - angle.to_radians()).abs() < 1e-12, + "{props}: {} {} {} {}", + h.pattern, + h.solid, + h.scale, + h.angle.to_degrees() + ); + } + // An object (an entity name from LISP) answers none of these prompts: each is asked again. + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [40, 30] })).unwrap(); + let h = s.doc().unwrap().model.handles()[0]; + s.cmdline("(command \"_.-HATCH\" \"_P\")").unwrap(); + s.input(crate::Input::Pick(vec![h])).unwrap(); + assert!(s.prompt_text().contains("Enter a pattern name"), "{}", s.prompt_text()); + s.cmdline("ANSI31").unwrap(); + s.input(crate::Input::Pick(vec![h])).unwrap(); + assert!(s.prompt_text().contains("Specify a scale for the hatch pattern"), "{}", s.prompt_text()); + s.cancel(); + } + #[test] fn unknown_pattern_error_and_catalog_name_the_pat_file_route() { let mut s = Session::new(); diff --git a/crates/engine/tests/lin_pat_files.rs b/crates/engine/tests/lin_pat_files.rs index b09b504d4..91f99062e 100644 --- a/crates/engine/tests/lin_pat_files.rs +++ b/crates/engine/tests/lin_pat_files.rs @@ -137,6 +137,9 @@ fn hatch_pattern_prompt_takes_a_pat_file_name() { s.cmdline("hatch").unwrap(); s.cmdline("p").unwrap(); s.cmdline(&path).unwrap(); + // Its scale and angle follow; Enter keeps them. + s.cmdline("").unwrap(); + s.cmdline("").unwrap(); // The pattern named like the file is the one used. s.cmdline("5,5").unwrap(); s.cmdline("").unwrap(); @@ -148,9 +151,21 @@ fn hatch_pattern_prompt_takes_a_pat_file_name() { s.cmdline("hatch").unwrap(); s.cmdline("p").unwrap(); s.cmdline("myother").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("").unwrap(); s.cmdline("5,5").unwrap(); s.cmdline("").unwrap(); assert_eq!(hatches(&s).iter().filter(|h| h.pattern == "MYOTHER").count(), 1); + + // A file with no pattern in it, or none at all, asks for the pattern again. + let empty = dir.file("EMPTY.pat", ";; no patterns\n"); + for file in [empty, dir.path_str("MISSING.pat")] { + s.cmdline("hatch").unwrap(); + s.cmdline("p").unwrap(); + s.cmdline(&file).unwrap(); + assert!(s.prompt_text().contains("Enter a pattern name"), "{file}: {}", s.prompt_text()); + s.cancel(); + } } #[test] From 6350c5b14569288f23bb9bc709efce56c6ed5547 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:46:12 +0700 Subject: [PATCH 228/900] Extents: count layers that are turned off, as AutoCAD does (#2485) * Extents: count layers that are turned off, as AutoCAD does Drawing::extents (ZOOM Extents, EXTMIN/EXTMAX, $EXTMIN/$EXTMAX, Extents plots) left out layers turned off as well as frozen ones. AutoCAD 2024 leaves out only frozen layers: lines from the origin to (10, 10) on layer 0, (100, 0) on a layer turned off and (0, 200) on a frozen one give EXTMAX (100.03, 10.01); inside a block too, and a reference on a frozen layer counts for nothing. Drawing::in_extents keeps a layer turned off, and extent_bounds counts block contents on one. entity_bounds, which the spatial index and selection use, still measures only what is drawn. Co-Authored-By: Claude Opus 5.5 * Extents: leave out attributes on frozen layers An insert's attribute lies on its own layer, else on its definition's, as the renderer draws it. One on a frozen layer no longer stretches the extents; one on a layer turned off still counts, as other objects do. Co-Authored-By: Claude Opus 5.5 * Extents test: build the attribute without an unreachable arm Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/extents.rs | 52 +++++++++++---- crates/doc/src/lib.rs | 14 ++-- crates/doc/src/tests.rs | 131 ++++++++++++++++++++++++++++++++------ 3 files changed, 159 insertions(+), 38 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index d7c7c7a8a..1971acadd 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -36,11 +36,26 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 { /// as when drawing. Dimensional constraints of dynamic blocks (layer `*ADSK_CONSTRAINTS`) and the /// entities a visibility state hides are invisible this way, and they sit far from the block's /// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked. -fn in_block_visible(d: &Drawing, e: &Entity) -> bool { +/// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]). +fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool { // Attribute definitions are not drawn in an insert (its attribs are, see below). - !matches!(e.kind, EntityKind::AttDef(_)) - && e.common.visible - && (e.common.layer == "0" || d.layer(&e.common.layer).is_none_or(crate::Layer::visible)) + !matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts) +} + +/// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which +/// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`. +fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool { + layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) +} + +/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its +/// definition's (layer "0" being the insert's). +fn attrib_layer<'a>(d: &'a Drawing, ins: &crate::Insert, a: &'a crate::Attrib) -> &'a str { + a.props.layer.as_deref().unwrap_or_else(|| { + d.block(&ins.block) + .and_then(|blk| blk.entities.iter().find(|be| matches!(&be.kind, EntityKind::AttDef(ad) if ad.tag.eq_ignore_ascii_case(&a.tag)))) + .map_or("0", |be| be.common.layer.as_str()) + }) } /// A text that draws no glyph (empty, or only blanks and non-breaking spaces) takes no room. @@ -75,16 +90,27 @@ fn mtext_box(t: &crate::MText) -> Bounds2 { Bounds2::from_points(pts) } +/// The box of what `e` draws (block contents on layers turned off left out). pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 { + bounds_of(d, e, depth, false) +} + +/// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer +/// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not). +pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 { + bounds_of(d, e, 0, true) +} + +fn bounds_of(d: &Drawing, e: &Entity, depth: usize, off_counts: bool) -> Bounds2 { // A top-level annotative object measures as it draws at the current annotation scale. if depth == 0 { match d.anno_draw(e) { crate::AnnoDraw::Plain => {} crate::AnnoDraw::Hidden => return Bounds2::EMPTY, - crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, &mut HashMap::new()), + crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, &mut HashMap::new(), off_counts), } } - bounds_in(d, e, depth, &mut HashMap::new()) + bounds_in(d, e, depth, &mut HashMap::new(), off_counts) } /// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed, @@ -93,7 +119,7 @@ pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 { /// definition per depth instead of one per reference (which grows exponentially with the nesting /// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its /// bounds must not stand in for a shallower reference to the same block (#706). -fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 { +fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>, off_counts: bool) -> Bounds2 { match &e.kind { EntityKind::Table(t) if t.is_broken() => t.bounds(), EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY, @@ -115,8 +141,8 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< Some(b) => *b, None => { let mut inner = Bounds2::EMPTY; - for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) { - inner = inner.union(&bounds_in(d, be, depth + 1, blocks)); + for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) { + inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts)); } blocks.insert((blk.name.as_str(), depth), inner); inner @@ -131,7 +157,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } } for a in &ins.attribs { - if !a.invisible { + if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) { b = b.union(&match a.multiline_text() { Some(m) => mtext_box(&m), None => text_box(&a.text, a.text.value.chars().count()), @@ -172,8 +198,8 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< Some(cached) => *cached, None => { let mut inner = Bounds2::EMPTY; - for be in blk.entities.iter().filter(|be| in_block_visible(d, be)) { - inner = inner.union(&bounds_in(d, be, depth + 1, blocks)); + for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) { + inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts)); } blocks.insert((blk.name.as_str(), depth), inner); inner @@ -193,7 +219,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } if let Some(ins) = &m.block { let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) }; - b = b.union(&bounds_in(d, &be, depth, blocks)); + b = b.union(&bounds_in(d, &be, depth, blocks, off_counts)); } b } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d970a6a56..e07a08609 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}; +pub use extents::{MAX_BLOCK_DEPTH, entity_bounds, extent_bounds}; pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; @@ -369,13 +369,19 @@ impl Drawing { !self.hidden_objects.is_empty() && self.hidden_objects.contains(&h) } - /// Bounds of all visible entities in a space. + /// Whether an entity counts in the extents: as AutoCAD 2024 counts it for ZOOM Extents and + /// EXTMIN/EXTMAX, on a layer that is off too, but not on a frozen one. + pub fn in_extents(&self, e: &Entity) -> bool { + e.common.visible && self.layer(&e.common.layer).is_none_or(|l| !l.frozen) && !self.is_hidden_object(e.handle) + } + + /// Bounds of the entities in a space that count in its extents ([`Drawing::in_extents`]). pub fn extents(&self, space: &Space) -> cadcraft_geom::Bounds2 { let mut b = cadcraft_geom::Bounds2::EMPTY; if let Some(store) = self.space(space) { for e in store.iter() { - if self.is_visible(e) { - b = b.union(&entity_bounds(self, e, 0)); + if self.in_extents(e) { + b = b.union(&extent_bounds(self, e)); } } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 067d42ac0..f0f979f12 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -44,15 +44,85 @@ fn add_and_extents() { } #[test] -fn hidden_layers_excluded_from_extents() { +fn frozen_layers_are_left_out_of_extents_and_layers_turned_off_are_not() { let mut d = Drawing::new_imperial(); let c = Common { layer: "Hidden".into(), ..Default::default() }; d.add(&Space::Model, c, line((100.0, 100.0), (200.0, 200.0))).unwrap(); d.add(&Space::Model, Common::default(), line((0.0, 0.0), (1.0, 1.0))).unwrap(); d.layer_mut("Hidden").unwrap().on = false; + assert_eq!(d.extents(&Space::Model).max, Vec2::new(200.0, 200.0)); + d.layer_mut("Hidden").unwrap().frozen = true; assert_eq!(d.extents(&Space::Model).max, Vec2::new(1.0, 1.0)); } +/// ZOOM Extents in AutoCAD 2024 (accoreconsole, EXTMIN/EXTMAX read back; AutoCAD pads them by a +/// few hundredths): a layer turned off counts and a frozen one does not, for an entity, for an +/// entity inside a block, and for a block reference itself. +#[test] +fn extents_count_layers_turned_off_as_autocad() { + let mut d = Drawing::new_imperial(); + for (name, on, frozen) in [("OFFL", false, false), ("FRZ", true, true), ("BOFF", false, false), ("BFRZ", true, true)] { + let mut l = Layer::new(name); + (l.on, l.frozen) = (on, frozen); + d.layers.push(l); + } + for (layer, b) in [("0", (10.0, 10.0)), ("OFFL", (100.0, 0.0)), ("FRZ", (0.0, 200.0))] { + d.add(&Space::Model, Common { layer: layer.into(), ..Default::default() }, line((0.0, 0.0), b)).unwrap(); + } + // AutoCAD: (-0.013, -0.009)…(100.027, 10.006). + assert_eq!(extents_pair(&d), (Vec2::ZERO, Vec2::new(100.0, 10.0))); + + let mut d = Drawing::new_imperial(); + for (name, on, frozen) in [("FRZ", true, true), ("BOFF", false, false), ("BFRZ", true, true)] { + let mut l = Layer::new(name); + (l.on, l.frozen) = (on, frozen); + d.layers.push(l); + } + let mut blk = Block::new("BX"); + blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1)); + blk.entities.push(on_layer("BOFF", line((0.0, 0.0), (50.0, 0.0)), 2)); + blk.entities.push(on_layer("BFRZ", line((0.0, 0.0), (0.0, 70.0)), 3)); + d.blocks.insert("BX".into(), std::sync::Arc::new(blk)); + let at = |x: f64| match plain_insert("BX") { + EntityKind::Insert(i) => EntityKind::Insert(Insert { insert: Vec3::new(x, x, 0.0), ..i }), + k => k, + }; + d.add(&Space::Model, Common::default(), at(1000.0)).unwrap(); + d.add(&Space::Model, Common { layer: "FRZ".into(), ..Default::default() }, at(-500.0)).unwrap(); + // AutoCAD: (1000, 1000)…(1050, 1001). + assert_eq!(extents_pair(&d), (Vec2::new(1000.0, 1000.0), Vec2::new(1050.0, 1001.0))); + + // An insert's attributes lie on their own layer, else on their definition's: one on a frozen + // layer either way does not count, one on a layer turned off does. + let mut d = Drawing::new_imperial(); + for (name, on, frozen) in [("IOFF", false, false), ("AOFF", false, false), ("AFRZ", true, true)] { + let mut l = Layer::new(name); + (l.on, l.frozen) = (on, frozen); + d.layers.push(l); + } + let attrib = |tag: &str, at: (f64, f64), layer: Option<&str>| { + let mut a = plain_attrib(tag); + a.text.insert = Vec3::new(at.0, at.1, 0.0); + a.props.layer = layer.map(str::to_string); + a + }; + let mut blk = Block::new("BA"); + blk.entities.push(on_layer("0", line((0.0, 0.0), (1.0, 1.0)), 1)); + blk.entities.push(on_layer("AFRZ", EntityKind::AttDef(plain_attrib("DEF")), 2)); + d.blocks.insert("BA".into(), std::sync::Arc::new(blk)); + let ins = match plain_insert("BA") { + EntityKind::Insert(i) => { + let attribs = + vec![attrib("OWN", (0.0, 300.0), Some("AFRZ")), attrib("DEF", (0.0, -400.0), None), attrib("OFF", (40.0, 0.0), Some("AOFF"))]; + EntityKind::Insert(Insert { attribs, ..i }) + } + k => k, + }; + d.add(&Space::Model, Common { layer: "IOFF".into(), ..Default::default() }, ins).unwrap(); + let (min, max) = extents_pair(&d); + assert!(min.y > -1.0 && max.y < 50.0 && max.x > 40.0, "{min:?} {max:?}"); +} + #[test] fn rays_and_xlines_do_not_stretch_extents() { // ZOOM Extents ignores infinite lines; real drawings carry stray rays millions of units away. @@ -315,6 +385,31 @@ fn plain_insert(block: &str) -> EntityKind { }) } +/// An attribute (or its definition) `tag` at the origin, one unit high, reading "x". +fn plain_attrib(tag: &str) -> Attrib { + Attrib { + tag: tag.into(), + text: Text { + insert: Vec3::ZERO, + align_pt: None, + height: 1.0, + value: "x".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + }, + invisible: false, + constant: false, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + } +} + fn on_layer(layer: &str, kind: EntityKind, h: u64) -> Entity { Entity { handle: Handle(h), common: Common { layer: layer.into(), ..Default::default() }, kind } } @@ -383,24 +478,18 @@ fn block_entity_with_invisible_flag_is_ignored_in_insert_extents() { } #[test] -fn block_entity_on_off_or_frozen_layer_is_ignored() { - for frozen in [false, true] { - let mut d = drawing_with_block(far_line("Hidden")); - assert!(d.layer("Hidden").is_none(), "block contents do not create layers"); - let mut layer = Layer::new("Hidden"); - if frozen { - layer.frozen = true; - } else { - layer.on = false; - } - d.layers.push(layer); - assert_eq!(extents_pair(&d), (Vec2::ZERO, Vec2::new(1.0, 1.0)), "frozen = {frozen}"); - // Turned back on, it counts again. - let l = d.layer_mut("Hidden").unwrap(); - l.on = true; - l.frozen = false; - assert_eq!(d.extents(&Space::Model).max, Vec2::new(6000.0, 6000.0)); - } +fn block_entity_on_frozen_layer_is_ignored_and_on_a_layer_turned_off_counts() { + let mut d = drawing_with_block(far_line("Hidden")); + assert!(d.layer("Hidden").is_none(), "block contents do not create layers"); + let mut layer = Layer::new("Hidden"); + layer.frozen = true; + d.layers.push(layer); + assert_eq!(extents_pair(&d), (Vec2::ZERO, Vec2::new(1.0, 1.0))); + // Thawed but turned off, it counts. + let l = d.layer_mut("Hidden").unwrap(); + l.frozen = false; + l.on = false; + assert_eq!(d.extents(&Space::Model).max, Vec2::new(6000.0, 6000.0)); } #[test] @@ -558,10 +647,10 @@ fn invisible_dimblock_entity_is_ignored_in_dimension_extents() { hidden.common.visible = false; dim(&mut d, hidden); assert!(d.extents(&Space::Model).max.x < 100.0); - // Hidden by its layer state. + // Hidden by its layer state (frozen; a layer turned off still counts). let mut d = Drawing::new_imperial(); let mut l = Layer::new("*ADSK_CONSTRAINTS"); - l.on = false; + l.frozen = true; d.layers.push(l); dim(&mut d, on_layer("*ADSK_CONSTRAINTS", line((5000.0, 5000.0), (6000.0, 6000.0)), 2)); assert!(d.extents(&Space::Model).max.x < 100.0); From 29584fa4c415a2df989697091621f0acf9e1e112 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:46:16 +0700 Subject: [PATCH 229/900] SOLID: draw 2D solids, chained as AutoCAD chains them (#2489) * SOLID: draw 2D solids, chained as AutoCAD chains them CADCraft had the SOLID entity but no command to draw it. As AutoCAD 2024 asks from AutoLISP: first, second, third point, then "fourth point or " (Enter makes a triangle); further solids take the previous one's last two corners and ask their third and fourth points until Enter. Corners stay in the order given. The command (alias SO) has a JSON form taking the points chained the same way. solid_chains_its_corners_as_autocad pins seven measured calls to 1e-9. Co-Authored-By: Claude Opus 5.5 * SOLID: offer it in the Draw menu Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/draw.rs | 9 +- crates/engine/src/cmd/draw/solid.rs | 79 ++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/solid_command.rs | 115 ++++++++++++++++++++++++ 4 files changed, 203 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/draw/solid.rs create mode 100644 crates/engine/tests/it/solid_command.rs diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index 52bf23ace..1b0e0c1cf 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -1,5 +1,5 @@ //! Draw commands: LINE, PLINE, CIRCLE, ARC, RECTANG, POLYGON, ELLIPSE, POINT, XLINE, RAY, -//! SPLINE, DONUT, TEXT, MTEXT. Each has a JSON form and an interactive prompt sequence. +//! SPLINE, DONUT, SOLID, TEXT, MTEXT. Each has a JSON form and an interactive prompt sequence. use cadcraft_doc::{EntityKind, HAlign, MText, Point, RayLine, Text, VAlign}; use cadcraft_geom::{Arc, Circle, Ellipse, PolyVertex, Polyline, Spline, Vec2, arc_to_bulge, bulge_to_arc}; @@ -21,6 +21,7 @@ mod ellipse; mod line_pline; mod point; mod polygon; +mod solid; mod spline; mod text; @@ -30,6 +31,7 @@ use ellipse::{EllipseM, run_ellipse}; 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 solid::{SolidM, run_solid}; use spline::{SplineM, run_spline}; use text::{MTextM, TextM, run_mtext, run_text}; @@ -100,6 +102,11 @@ pub fn specs() -> Vec { .alias(&["do", "doughnut"]) .params("{center, inside, outside}") .interactive(|_| Ok(Box::new(DonutM::default()))), + CommandSpec::new("solid", "2D Solid", run_solid) + .menu(&["Draw", "2D Solid"]) + .alias(&["so"]) + .params("{points: [[x,y],...]} (three or four for the first solid, two more for each next one, chained on its last two corners)") + .interactive(|_| Ok(Box::new(SolidM::default()))), CommandSpec::new("text", "Single Line Text", run_text) .menu(&["Draw", "Text", "Single Line Text"]) .alias(&["dt", "dtext"]) diff --git a/crates/engine/src/cmd/draw/solid.rs b/crates/engine/src/cmd/draw/solid.rs new file mode 100644 index 000000000..835772a45 --- /dev/null +++ b/crates/engine/src/cmd/draw/solid.rs @@ -0,0 +1,79 @@ +//! SOLID: filled triangles and quadrilaterals (2D solids), chained as AutoCAD 2024 chains them. +//! +//! The prompts are "Specify first point", "Specify second point", "Specify third point" and +//! "Specify fourth point or "; Enter there makes a triangle (the fourth corner repeats the +//! third). Then "Specify third point" and "Specify fourth point or " come again for the next +//! solid, whose first two corners are the previous one's last two, until Enter at "Specify third +//! point". Enter there right after the second point makes nothing. + +use cadcraft_doc::Solid; + +use super::{Accept, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Value, Vec2, bad, json, points_param, v3}; + +/// A 2D solid from its corners in AutoCAD's order (the fourth is drawn opposite the first). +fn solid(c: [Vec2; 4]) -> EntityKind { + EntityKind::Solid(Solid { corners: c.map(v3) }) +} + +/// `{points}`: the first solid takes three or four points, each further one two more, its first +/// two corners being the previous one's last two; a solid given three points is a triangle. +pub(super) fn run_solid(s: &mut Session, p: &Value) -> Result { + let pts = points_param(p, "points").ok_or_else(|| bad("solid", "`points` is required"))?; + let mut it = pts.into_iter(); + let (Some(mut a), Some(mut b), Some(_)) = (it.next(), it.next(), it.clone().next()) else { + return Err(bad("solid", "`points` needs at least three points")); + }; + let mut hs = Vec::new(); + while let Some(c) = it.next() { + let d = it.next().unwrap_or(c); + hs.push(s.add_entity(solid([a, b, c, d]))?.hex()); + (a, b) = (c, d); + } + Ok(json!({ "handles": hs })) +} + +#[derive(Default)] +pub(super) struct SolidM { + /// The corners of the solid being drawn (the first two from the previous one after it). + pts: Vec, +} + +impl Interactive for SolidM { + fn name(&self) -> &'static str { + "SOLID" + } + fn prompt(&self, _s: &Session) -> Prompt { + let last = self.pts.last().copied(); + match self.pts.len() { + 0 => Prompt::new("Specify first point", Accept::POINT), + 1 => Prompt::new("Specify second point", Accept::POINT).base_opt(last), + 2 => Prompt::new("Specify third point", Accept::POINT).base_opt(last), + _ => Prompt::new("Specify fourth point or", Accept::POINT).default("exit").base_opt(last), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match (i, self.pts.as_slice()) { + (Input::Point(p), &[a, b, c]) => self.make(s, [a, b, c, p])?, + (Input::Point(p), _) => self.pts.push(p), + (Input::Enter, &[a, b, c]) => self.make(s, [a, b, c, c])?, + (Input::Enter, _) => return Ok(Step::Done), + _ => {} + } + Ok(Step::Continue) + } + fn preview(&self, _s: &Session, cursor: Vec2) -> Vec { + match *self.pts.as_slice() { + [a, b] => vec![solid([a, b, cursor, cursor])], + [a, b, c] => vec![solid([a, b, c, cursor])], + _ => Vec::new(), + } + } +} + +impl SolidM { + fn make(&mut self, s: &mut Session, c: [Vec2; 4]) -> Result<()> { + s.add_entity(solid(c))?; + self.pts = vec![c[2], c[3]]; + Ok(()) + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ed88a2316..d0d3aedc8 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -126,6 +126,7 @@ mod snap_nearest; mod snap_overrides; mod snap_tracking; mod snaps_more; +mod solid_command; mod space_is_enter; mod spline_degree; mod spline_options; diff --git a/crates/engine/tests/it/solid_command.rs b/crates/engine/tests/it/solid_command.rs new file mode 100644 index 000000000..4e92f38e9 --- /dev/null +++ b/crates/engine/tests/it/solid_command.rs @@ -0,0 +1,115 @@ +//! SOLID (2D solids) as AutoCAD 2024 draws them from AutoLISP's `command` (accoreconsole, every +//! solid read back with `entget`). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use serde_json::json; + +/// The corners of every solid, in drawing order. +fn solids(s: &Session) -> Vec<[Vec2; 4]> { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Solid(so) => Some(so.corners.map(|c| Vec2::new(c.x, c.y))), + _ => None, + }) + .collect() +} + +#[test] +fn solid_chains_its_corners_as_autocad() { + let p = |x: f64, y: f64| (x, y); + // (points, Enters after them, each solid as indexes into the points) + let cases: [(Vec<(f64, f64)>, usize, Vec<[usize; 4]>); 7] = [ + // Enter at the fourth point: a triangle repeating its third corner. + ( + vec![p(19.451648928934738, -21.25585202371201), p(34.61693931374715, -3.839951210926415), p(14.55170247613551, -36.00688291519149)], + 1, + vec![[0, 1, 2, 2]], + ), + // Two solids, the second on the first one's last two corners. + ( + vec![ + p(612336.9748522255, 2398742.6897319513), + p(612351.3507889743, 2398794.3456611084), + p(612371.7043989347, 2398771.9517326546), + p(612379.1755178814, 2398787.9912080113), + p(612308.5250187548, 2398780.014694856), + p(612356.1118879627, 2398726.474738389), + ], + 1, + vec![[0, 1, 2, 3], [2, 3, 4, 5]], + ), + // A solid, then a triangle. + ( + vec![ + p(15.962585354071173, 3.3526103822549587), + p(-0.8095657933516947, 13.123790321338404), + p(-19.412229808271626, -27.60123059493223), + p(-33.66123919971652, 12.18177290955613), + p(14.002713873827737, -8.925735622823005), + ], + 1, + vec![[0, 1, 2, 3], [2, 3, 4, 4]], + ), + // Three solids, the last a triangle. + ( + vec![ + p(29.3005193409103, -24.874809106460187), + p(-21.460879071052776, 35.356609837704795), + p(-31.347336242570112, -21.756568658673665), + p(-39.08169761088666, 23.588062542950155), + p(23.0763904721503, 10.219805555956789), + p(-22.701751810515756, 22.76615204356692), + p(4.338066830902321, -37.50391578060281), + ], + 1, + vec![[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 6]], + ), + // Enter twice: the triangle, then Enter at the third point ends the command. + ( + vec![p(612325.6793323631, 2398757.396299568), p(612370.1009101832, 2398796.2224137546), p(612378.8199480829, 2398804.1981022176)], + 2, + vec![[0, 1, 2, 2]], + ), + // Corners stay in the order given (a "Z" order makes a rectangle). + (vec![p(0.0, 0.0), p(30.0, 0.0), p(0.0, 20.0), p(30.0, 20.0)], 1, vec![[0, 1, 2, 3]]), + // Enter after two points: nothing. + (vec![p(-34769.59558954922, 81960.0236700466), p(-35927.22173307072, 79264.64372697374)], 1, vec![]), + ]; + let same = |a: Vec2, b: (f64, f64)| (a.x - b.0).abs() <= 1e-9 * b.0.abs().max(1.0) && (a.y - b.1).abs() <= 1e-9 * b.1.abs().max(1.0); + for (pts, enters, want) in cases { + let mut s = Session::new(); + let args: Vec = pts.iter().map(|(x, y)| format!("'({x:?} {y:?})")).chain(std::iter::repeat_n("\"\"".to_string(), enters)).collect(); + s.cmdline(&format!("(command \"_.SOLID\" {})", args.join(" "))).unwrap(); + // One Enter leaves the command at "Specify third point", as AutoCAD's does (its log then + // shows the measuring routine ending it). + if s.running.is_some() { + assert!(s.prompt_text().contains("Specify third point"), "{pts:?}: {}", s.prompt_text()); + s.cancel(); + } + let got = solids(&s); + assert_eq!(got.len(), want.len(), "{pts:?}: {got:?}"); + for (g, w) in got.iter().zip(&want) { + assert!(g.iter().zip(w).all(|(c, &i)| same(*c, pts[i])), "{pts:?}: {got:?}"); + } + } +} + +#[test] +fn solid_json_chains_the_same_way() { + let mut s = Session::new(); + s.execute("solid", &json!({ "points": [[0, 0], [10, 0], [0, 5], [10, 5], [0, 10]] })).unwrap(); + let got = solids(&s); + let v = |x: f64, y: f64| Vec2::new(x, y); + assert_eq!(got, vec![[v(0.0, 0.0), v(10.0, 0.0), v(0.0, 5.0), v(10.0, 5.0)], [v(0.0, 5.0), v(10.0, 5.0), v(0.0, 10.0), v(0.0, 10.0)]]); + assert!(s.execute("solid", &json!({ "points": [[0, 0], [1, 0]] })).is_err()); + // The alias. + s.cmdline("so 20,0 30,0 20,5").unwrap(); + s.cmdline("").unwrap(); + s.cmdline("").unwrap(); + assert_eq!(solids(&s).len(), 3); +} From 8252d0e9bd94652a968bf57e634f137573d8dc24 Mon Sep 17 00:00:00 2001 From: Books Date: Sat, 31 Oct 2026 06:46:20 +1100 Subject: [PATCH 230/900] Extents: an MTEXT's wrap width only narrows its box (#2465) (#2491) * Extents: an MTEXT's wrap width only narrows its box (#2465) A garbage group 41 width (3e14) became the box width, so the drawing extents were 3e14 wide. The width is now capped at the longest line's estimate. The width 0 branch is unchanged. Tests: a_huge_mtext_wrap_width_does_not_inflate_the_extents and a_narrow_mtext_wrap_width_still_sets_the_box_width. * Parity checklist: regenerated after merging main * Parity checklist: regenerated after merging main --- crates/doc/src/extents.rs | 35 ++++++++++++++++++++++++++++++++++- docs/parity-checklist.md | 3 +-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 1971acadd..72742dbe7 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -67,7 +67,9 @@ fn blank(s: &str) -> bool { fn mtext_box(t: &crate::MText) -> Bounds2 { let lines = t.contents.split("\\P").count().max(1); let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1); - let mut w = if t.width > 0.0 { t.width } else { t.height * 0.8 * longest as f64 }; + let estimate = t.height * 0.8 * longest as f64; + // The wrap width only narrows the box: a garbage width must not stretch the drawing extents (#2465). + let mut w = if t.width > 0.0 { t.width.min(estimate) } else { estimate }; let mut h = t.height * 1.66 * lines as f64; if let Some(c) = t.columns.as_ref().filter(|_| t.width > 0.0) { // Columns side by side, the text flowing down each in turn. @@ -335,6 +337,37 @@ mod tests { entity_bounds(&Drawing::default(), &Entity::new(crate::Handle(1), kind), 0) } + fn mtext(contents: &str, width: f64) -> crate::MText { + crate::MText { + insert: Vec3::new(10.0, 10.0, 0.0), + height: 2.5, + width, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: contents.into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + } + } + + /// A garbage wrap width only narrows an MTEXT's box, never widens it: a huge group 41 must not + /// stretch the drawing extents (#2465). + #[test] + fn a_huge_mtext_wrap_width_does_not_inflate_the_extents() { + let b = bounds(EntityKind::MText(mtext("AB", 300_000_009_519_104.0))); + // "AB" at height 2.5 is 2 chars * 0.8 * 2.5 = 4 wide. + assert!(b.max.x <= 10.0 + 4.0 + 1e-9, "box ends at x = {}", b.max.x); + assert!(b.min.x >= 10.0 - 1e-9); + } + + /// A wrap width narrower than the text still bounds the box to that width. + #[test] + fn a_narrow_mtext_wrap_width_still_sets_the_box_width() { + let b = bounds(EntityKind::MText(mtext("A LONG LINE OF WRAPPING TEXT", 5.0))); + assert!((b.max.x - b.min.x - 5.0).abs() < 1e-9, "width {}", b.max.x - b.min.x); + } #[test] fn right_justified_text_is_left_of_alignment_point() { let b = bounds(EntityKind::Text(text(HAlign::Right, VAlign::Baseline))); 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 189bfcbf08c47bd777c7ba5e8ee0fe84c9805ddc Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:46:24 +0100 Subject: [PATCH 231/900] Draw annotative text with Match orientation to layout upright, ignoring its stored rotation (#2498) (#2504) --- crates/doc/src/entity/common.rs | 17 +++++ crates/doc/src/extents.rs | 5 ++ crates/io/tests/it/annotative_orientation.rs | 45 +++++++++++++ crates/io/tests/it/main.rs | 1 + crates/render/src/draw.rs | 13 +++- .../render/tests/it/annotative_orientation.rs | 66 +++++++++++++++++++ crates/render/tests/it/main.rs | 1 + 7 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 crates/io/tests/it/annotative_orientation.rs create mode 100644 crates/render/tests/it/annotative_orientation.rs diff --git a/crates/doc/src/entity/common.rs b/crates/doc/src/entity/common.rs index 17fc43c75..45cf04e12 100644 --- a/crates/doc/src/entity/common.rs +++ b/crates/doc/src/entity/common.rs @@ -130,3 +130,20 @@ pub struct RawTag { pub code: i32, pub value: String, } + +impl Common { + /// Whether "Match orientation to layout" is on for this annotative object (AutoCAD's + /// `AcadAnnoPO` xdata = 1). AutoCAD draws such text upright and ignores its stored rotation. + /// The object's own `AcadAnnotative` xdata never reaches [`Common::xdata`] (the reader drops + /// it), so the `AcadAnnoPO` flag alone decides. + pub fn matches_layout_orientation(&self) -> bool { + let app = self.xdata.iter().position(|t| t.code == 1001 && t.value.trim().eq_ignore_ascii_case("AcadAnnoPO")); + let Some(at) = app else { return false }; + self.xdata + .iter() + .skip(at + 1) + .take_while(|t| t.code != 1001) + .find(|t| t.code == 1070) + .is_some_and(|t| t.value.trim().parse::().is_ok_and(|v| v != 0)) + } +} diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 72742dbe7..353a42b53 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -126,6 +126,11 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< EntityKind::Table(t) if t.is_broken() => t.bounds(), EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY, EntityKind::MText(t) if blank(&t.contents) => Bounds2::EMPTY, + // Text that matches the layout's orientation is drawn upright (#2498). + EntityKind::Text(t) if e.common.matches_layout_orientation() => { + text_box(&crate::Text { rotation: 0.0, ..t.clone() }, t.value.chars().count()) + } + EntityKind::MText(t) if e.common.matches_layout_orientation() => mtext_box(&crate::MText { rotation: 0.0, ..t.clone() }), EntityKind::Text(t) => text_box(t, t.value.chars().count()), EntityKind::AttDef(a) => text_box(&a.text, a.tag.chars().count()), EntityKind::MText(t) => mtext_box(t), diff --git a/crates/io/tests/it/annotative_orientation.rs b/crates/io/tests/it/annotative_orientation.rs new file mode 100644 index 000000000..c11688de6 --- /dev/null +++ b/crates/io/tests/it/annotative_orientation.rs @@ -0,0 +1,45 @@ +//! Annotative TEXT read from a file with "Match orientation to layout" on (`AcadAnnoPO` xdata = 1) +//! is drawn and measured upright, ignoring its stored rotation, as AutoCAD shows it (#2498). + +use cadcraft_doc::{EntityKind, Space, entity_bounds}; + +/// The xdata AutoCAD writes on such text: the `AcadAnnotative` data, then `AcadAnnoPO`. +const ANNO_PO: &str = "1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nAcadAnnoPO\n1070\n1\n"; + +/// One TEXT "TITLE" at 10,5, height 2.5, rotated `deg` degrees, followed by `xdata`. +fn dxf(deg: f64, xdata: &str) -> String { + format!("0\nSECTION\n2\nENTITIES\n0\nTEXT\n5\n2A\n8\n0\n10\n10\n20\n5\n40\n2.5\n1\nTITLE\n50\n{deg}\n{xdata}0\nENDSEC\n0\nEOF\n") +} + +/// (rendered box, extents box) of the drawing's only object, as (min x, min y, max x, max y). +fn boxes(text: &str) -> ([f64; 4], [f64; 4]) { + let d = cadcraft_io::read(text.as_bytes(), "t.dxf").unwrap(); + let r = cadcraft_render::build(&d, &Space::Model, &cadcraft_render::Options::default()).bounds; + let e = d.model.iter().find(|e| matches!(e.kind, EntityKind::Text(_))).map(|e| entity_bounds(&d, e, 0)).unwrap(); + ([r.min.x, r.min.y, r.max.x, r.max.y], [e.min.x, e.min.y, e.max.x, e.max.y]) +} + +fn same(a: [f64; 4], b: [f64; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6) +} + +#[test] +fn match_orientation_to_layout_draws_the_text_upright() { + let d = cadcraft_io::read(dxf(180.0, ANNO_PO).as_bytes(), "t.dxf").unwrap(); + assert!(d.model.iter().any(|e| e.common.matches_layout_orientation()), "the AcadAnnoPO flag is read"); + let (upright_r, upright_e) = boxes(&dxf(0.0, "")); + let (r, e) = boxes(&dxf(180.0, ANNO_PO)); + assert!(same(r, upright_r), "drawn at {r:?}, upright at {upright_r:?}"); + assert!(same(e, upright_e), "extents {e:?}, upright {upright_e:?}"); +} + +#[test] +fn without_the_flag_the_stored_rotation_applies() { + let (upright_r, upright_e) = boxes(&dxf(0.0, "")); + let off = ANNO_PO.replace("AcadAnnoPO\n1070\n1\n", "AcadAnnoPO\n1070\n0\n"); + for xdata in ["", off.as_str()] { + let (r, e) = boxes(&dxf(180.0, xdata)); + assert!(!same(r, upright_r), "drawn at {r:?}"); + assert!(!same(e, upright_e), "extents {e:?}"); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 51e7f1965..07b1e8c2e 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -2,6 +2,7 @@ mod acad_interop; #[cfg(not(target_arch = "wasm32"))] mod acis_data_store; mod angle_header; +mod annotative_orientation; mod annotative_roundtrip; mod assoc_array_roundtrip; mod attrib_modes; diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index cf37e28f7..7e00b4c8c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -103,6 +103,13 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if !b.opts.text { return; } + let upright; + let t = if e.common.matches_layout_orientation() && t.rotation != 0.0 { + upright = cadcraft_doc::Text { rotation: 0.0, ..t.clone() }; + &upright + } else { + t + }; let (sh, _) = place_text_entity(ctx.d, t, &t.value); b.shaped(ctx, rgb, lw, &sh); } @@ -114,7 +121,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { if !b.opts.text { return; } - mtext(b, ctx, t, rgb, lw); + if e.common.matches_layout_orientation() && t.rotation != 0.0 { + mtext(b, ctx, &cadcraft_doc::MText { rotation: 0.0, ..t.clone() }, rgb, lw); + } else { + mtext(b, ctx, t, rgb, lw); + } } EntityKind::Insert(ins) => insert(b, ctx, e, ins, rgb), EntityKind::Dimension(dm) => draw_dimension(b, ctx, e, dm, lw, lt.as_ref(), ltscale), diff --git a/crates/render/tests/it/annotative_orientation.rs b/crates/render/tests/it/annotative_orientation.rs new file mode 100644 index 000000000..ee28b0624 --- /dev/null +++ b/crates/render/tests/it/annotative_orientation.rs @@ -0,0 +1,66 @@ +//! Annotative text with "Match orientation to layout" (`AcadAnnoPO` xdata = 1) draws upright, +//! ignoring its stored rotation (#2498). + +use cadcraft_doc::{Common, Drawing, EntityKind, RawTag, Space, Text}; +use cadcraft_geom::{Bounds2, Vec3}; +use cadcraft_render::{Options, build}; + +fn tag(code: i32, value: &str) -> RawTag { + RawTag { code, value: value.into() } +} + +fn bounds(rotation: f64, match_orientation: Option<&str>) -> Bounds2 { + let mut d = Drawing::new_metric(); + let mut common = Common::default(); + if let Some(flag) = match_orientation { + common.xdata = vec![ + tag(1001, "AcadAnnotative"), + tag(1000, "AnnotativeData"), + tag(1002, "{"), + tag(1070, "1"), + tag(1070, "1"), + tag(1002, "}"), + tag(1001, "AcadAnnoPO"), + tag(1070, flag), + ]; + } + let text = Text { + insert: Vec3::new(10.0, 5.0, 0.0), + align_pt: None, + height: 2.5, + value: "TITLE".into(), + rotation, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }; + d.add(&Space::Model, common, EntityKind::Text(text)).unwrap(); + let l = build(&d, &Space::Model, &Options::default()); + let mut b = Bounds2::EMPTY; + for p in &l.prims { + for q in l.points(p) { + b.add(*q); + } + } + b +} + +fn same(a: &Bounds2, b: &Bounds2) -> bool { + (a.min.x - b.min.x).abs() < 1e-9 && (a.min.y - b.min.y).abs() < 1e-9 && (a.max.x - b.max.x).abs() < 1e-9 && (a.max.y - b.max.y).abs() < 1e-9 +} + +#[test] +fn match_orientation_ignores_the_stored_rotation() { + let upright = bounds(0.0, None); + assert!(!upright.is_empty()); + assert!(same(&bounds(std::f64::consts::PI, Some("1")), &upright)); +} + +#[test] +fn stored_rotation_applies_without_the_flag() { + let upright = bounds(0.0, None); + assert!(!same(&bounds(std::f64::consts::PI, None), &upright)); + assert!(!same(&bounds(std::f64::consts::PI, Some("0")), &upright)); +} diff --git a/crates/render/tests/it/main.rs b/crates/render/tests/it/main.rs index 5f0005496..fbeede7f8 100644 --- a/crates/render/tests/it/main.rs +++ b/crates/render/tests/it/main.rs @@ -1,4 +1,5 @@ mod aci7_display; +mod annotative_orientation; mod annotative_viewport; mod dim_angular_centre; mod dim_post_tolerance; From 18d3aa4ed805ea5a7b9546b62f53013608909466 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 02:46:27 +0700 Subject: [PATCH 232/900] CHPROP: change properties at the command line, as AutoCAD asks for them (#2497) * Add CHPROP, asking for properties as AutoCAD does CHPROP selects objects, then asks "Enter property to change [Color/LAyer/LType/ltScale/LWeight/Thickness/TRansparency]" until Enter, applying each value through properties.set. Measured from AutoCAD 2024 through AutoLISP's command: colours 1-255, names, BYLAYER, BYBLOCK or Truecolor; 0, 256 and 300 refused; a layer must exist; a linetype not loaded is loaded from the standard file; a lineweight goes to the nearest standard one with a note. Keyword prefixes now have to reach past the keyword's last capital, so "L" alone matches none of LAyer, LType, ltScale and LWeight, as in AutoCAD. Co-Authored-By: Claude Opus 5.5 * CHPROP tests: transparency, and refused true colours and transparencies Co-Authored-By: Claude Opus 5.5 * CHPROP leaves objects on locked layers out, as AutoCAD does Each pick and the pickfirst selection lose the objects on locked layers, followed by "1 was on a locked layer." or "N were on a locked layer."; with none of the pickfirst selection left, CHPROP asks for objects. The JSON chprop leaves them out too and returns {changed, locked}. The keywords test also pins QDIM's DA and PEDIT's vertex E, which AutoCAD 2024 refuses although only one keyword starts with them. Co-Authored-By: Claude Opus 5.5 * chprop: look up locked handles in a set, and always report "locked" (CodeRabbit) --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/props.rs | 7 +- crates/engine/src/cmd/props/chprop.rs | 338 +++++++++++++++++++++++ crates/engine/src/prompt.rs | 34 ++- crates/engine/tests/it/chprop_command.rs | 149 ++++++++++ crates/engine/tests/it/main.rs | 1 + 5 files changed, 526 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/cmd/props/chprop.rs create mode 100644 crates/engine/tests/it/chprop_command.rs diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index dfe69fd8f..daf963f67 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1,5 +1,7 @@ -//! Properties: per-object property edits, current properties, MATCHPROP, linetypes, units, RENAME. +//! Properties: per-object property edits, current properties, CHPROP, MATCHPROP, linetypes, units, +//! RENAME. +mod chprop; mod matchprop; mod rename; @@ -18,6 +20,9 @@ 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) + .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("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) diff --git a/crates/engine/src/cmd/props/chprop.rs b/crates/engine/src/cmd/props/chprop.rs new file mode 100644 index 000000000..0949abee9 --- /dev/null +++ b/crates/engine/src/cmd/props/chprop.rs @@ -0,0 +1,338 @@ +//! CHPROP: change object properties at the command line, as AutoCAD 2024 asks for them. +//! +//! "Enter property to change [Color/LAyer/LType/ltScale/LWeight/Thickness/TRansparency]" comes +//! back after each answer until Enter; each property asks for its value and applies it at once +//! (through `properties.set`). Measured from AutoLISP's `command` (accoreconsole, every object read +//! back with `entget`): +//! - a colour is 1–255, a name (red … white), BYLAYER or BYBLOCK, or Truecolor and then "r,g,b"; +//! 0, 256 and 300 are refused with "Invalid color number."; +//! - a layer must exist: `Cannot find layer "KHONGCO".`; +//! - a linetype not loaded yet is loaded from the standard ones (PHANTOM2); +//! - a lineweight goes to the nearest standard one, with a note: 0.33 gives "Lineweight rounded to +//! nearest valid value of 0.35 mm"; +//! - `L` alone is "Ambiguous response, please clarify..."; +//! - objects on locked layers are left out at "Select objects", which says how many after what was +//! found ("1 was on a locked layer.", "2 were on a locked layer."); with none left, Enter ends +//! the command. + +use std::collections::HashSet; + +use cadcraft_color::Color; +use cadcraft_doc::{Entity, Handle, Lineweight}; +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"]; + +/// What CHPROP asks for. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Ask { + Property, + Color, + TrueColor, + Layer, + Linetype, + LtScale, + Lineweight, + Thickness, + Transparency, +} + +pub(super) struct ChpropM { + select: SelectPhase, + handles: Vec, + /// `None` while objects are selected. + ask: Option, +} + +impl ChpropM { + pub(super) fn new() -> Self { + ChpropM { select: SelectPhase::default(), handles: Vec::new(), ask: None } + } + + /// The selection's common value of a property, or "varies". + fn current(&self, s: &Session, f: impl Fn(&Entity) -> String) -> String { + let Ok(d) = s.doc() else { return String::new() }; + let mut vals = self.handles.iter().filter_map(|h| d.entity(*h)).map(|e| f(e)); + let first = vals.next().unwrap_or_default(); + if vals.all(|v| v == first) { first } else { "varies".into() } + } + + /// Apply `props` to the selection through `properties.set`. + 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(|_| ()) + } + + /// Take an answer to `ask`; `false` when it was refused (the prompt comes again). + fn answer(&mut self, s: &mut Session, ask: Ask, t: &str) -> Result { + let t = t.trim(); + let word = t.strip_prefix('_').unwrap_or(t); + match ask { + Ask::Color => match color(word) { + Some(c) => self.apply(s, json!({ "color": color_json(c) }))?, + None => { + s.echo("Invalid color number."); + return Ok(false); + } + }, + Ask::TrueColor => match Color::parse(word) { + Some(c @ Color::True(_)) => self.apply(s, json!({ "color": color_json(c) }))?, + _ => { + s.echo("Requires three integers from 0 to 255, separated by commas."); + return Ok(false); + } + }, + Ask::Layer => match s.doc()?.layer(word).map(|l| l.name.clone()) { + Some(name) => self.apply(s, json!({ "layer": name }))?, + None => { + s.echo(format!("Cannot find layer \"{word}\".")); + return Ok(false); + } + }, + Ask::Linetype => { + let by = ["ByLayer", "ByBlock"].into_iter().find(|b| b.eq_ignore_ascii_case(word)); + let name = match by { + Some(b) => Some(b.to_string()), + None => { + // Not loaded yet: load it from the standard linetypes, as AutoCAD does. + if s.doc()?.linetype(word).is_none() { + let _ = super::run_linetype(s, &json!({ "load": word })); + } + s.doc()?.linetype(word).map(|l| l.name.clone()) + } + }; + match name { + Some(n) => self.apply(s, json!({ "linetype": n }))?, + None => { + s.echo(format!("Cannot find linetype \"{word}\".")); + return Ok(false); + } + } + } + Ask::LtScale | Ask::Thickness => { + let v = number(word).filter(|v| v.is_finite() && (ask == Ask::Thickness || *v > 0.0)); + match v { + Some(v) => self.apply(s, if ask == Ask::LtScale { json!({ "ltscale": v }) } else { json!({ "thickness": v }) })?, + None => { + s.echo(if ask == Ask::LtScale { "Requires a positive number." } else { "Requires a number." }); + return Ok(false); + } + } + } + Ask::Lineweight => match lineweight(word) { + Some((lw, rounded)) => { + if let (true, Lineweight::Mm100(v)) = (rounded, lw) { + s.echo(format!("Lineweight rounded to nearest valid value of {:.2} mm", f64::from(v) / 100.0)); + } + let v = match lw { + Lineweight::Mm100(v) => json!(f64::from(v) / 100.0), + Lineweight::ByLayer => json!("ByLayer"), + Lineweight::ByBlock => json!("ByBlock"), + Lineweight::Default => json!("Default"), + }; + self.apply(s, json!({ "lineweight": v }))?; + } + None => { + s.echo("Invalid lineweight."); + return Ok(false); + } + }, + Ask::Transparency => { + if self.apply(s, json!({ "transparency": word })).is_err() { + s.echo("Requires ByLayer, ByBlock or an integer from 0 to 90."); + return Ok(false); + } + } + Ask::Property => {} + } + Ok(true) + } +} + +/// The objects among `hs` on locked layers. +fn locked(s: &Session, hs: &[Handle]) -> HashSet { + hs.iter().copied().filter(|h| is_locked(s, *h)).collect() +} + +fn say_locked(s: &mut Session, n: usize) { + match n { + 0 => {} + 1 => s.echo("1 was on a locked layer."), + n => s.echo(format!("{n} were on a locked layer.")), + } +} + +/// 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()) { + return t.parse::().ok().filter(|i| (1..=255).contains(i)).and_then(|i| u8::try_from(i).ok()).map(Color::Index); + } + Color::parse(t).filter(|c| !matches!(c, Color::True(_))) +} + +fn color_json(c: Color) -> Value { + match c { + Color::Index(i) => json!(i), + Color::True(rgb) => json!(format!("{},{},{}", rgb.0, rgb.1, rgb.2)), + other => json!(other.name()), + } +} + +fn lineweight_name(lw: Lineweight) -> String { + match lw { + Lineweight::Mm100(v) => format!("{:.2} mm", f64::from(v) / 100.0), + Lineweight::ByLayer => "ByLayer".into(), + Lineweight::ByBlock => "ByBlock".into(), + Lineweight::Default => "Default".into(), + } +} + +/// A lineweight typed in millimetres (the nearest standard one, and whether that rounded it), or +/// ByLayer, ByBlock or Default. +fn lineweight(t: &str) -> Option<(Lineweight, bool)> { + match t.to_ascii_lowercase().as_str() { + "bylayer" => return Some((Lineweight::ByLayer, false)), + "byblock" => return Some((Lineweight::ByBlock, false)), + "default" => return Some((Lineweight::Default, false)), + _ => {} + } + let mm = number(t).filter(|v| v.is_finite() && *v >= 0.0)?; + let want = mm * 100.0; + let near = Lineweight::STANDARD.iter().copied().min_by(|a, b| (f64::from(*a) - want).abs().total_cmp(&(f64::from(*b) - want).abs()))?; + Some((Lineweight::Mm100(near), (f64::from(near) - want).abs() > 1e-9)) +} + +impl Interactive for ChpropM { + fn name(&self) -> &'static str { + "CHPROP" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.select = SelectPhase::begin(s); + if self.select.done { + let locked = locked(s, &self.select.picked); + if !locked.is_empty() { + self.select.picked.retain(|h| !locked.contains(h)); + say_locked(s, locked.len()); + s.set_selection(self.select.picked.clone()); + // Nothing left of the pickfirst selection: ask for objects instead. + self.select.done = !self.select.picked.is_empty(); + } + } + if self.select.done { + self.handles = self.select.picked.clone(); + self.ask = Some(Ask::Property); + } + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + let Some(ask) = self.ask else { return self.select.prompt() }; + match ask { + Ask::Property => Prompt::new("Enter property to change", Accept::TEXT).kw(&PROPERTIES), + Ask::Color => { + Prompt::new("New color", Accept::TEXT).kw(&["Truecolor"]).default(self.current(s, |e| e.common.color.name().to_ascii_uppercase())) + } + Ask::TrueColor => Prompt::new("Red,Green,Blue", Accept::TEXT), + Ask::Layer => Prompt::new("Enter new layer name", Accept::TEXT).default(self.current(s, |e| e.common.layer.clone())), + Ask::Linetype => Prompt::new("Enter new linetype name", Accept::TEXT).default(self.current(s, |e| e.common.linetype.clone())), + Ask::LtScale => { + Prompt::new("Specify new linetype scale", Accept::NUMBER).default(self.current(s, |e| format!("{:.4}", e.common.ltscale))) + } + Ask::Lineweight => Prompt::new("Enter new lineweight", Accept::TEXT).default(self.current(s, |e| lineweight_name(e.common.lineweight))), + Ask::Thickness => Prompt::new("Specify new thickness", Accept::NUMBER).default(self.current(s, |e| format!("{:.4}", e.common.thickness))), + Ask::Transparency => Prompt::new("Enter transparency value", KW).default(self.current(s, |e| e.common.transparency.name())), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let Some(ask) = self.ask else { + // Objects on locked layers are left out, and said after what was found. + let (i, n) = match i { + Input::Pick(hs) if !self.select.removing => { + let locked = locked(s, &hs); + (Input::Pick(hs.into_iter().filter(|h| !locked.contains(h)).collect()), locked.len()) + } + i => (i, 0), + }; + let outcome = self.select.feed(s, &i)?; + say_locked(s, n); + return Ok(match outcome { + SelOutcome::More => Step::Continue, + SelOutcome::Done(hs) => { + self.handles = hs; + self.ask = Some(Ask::Property); + Step::Continue + } + SelOutcome::Empty => { + s.set_selection(Vec::new()); + Step::Done + } + }); + }; + match (ask, i) { + (Ask::Property, Input::Enter) => { + s.set_selection(Vec::new()); + return Ok(Step::Done); + } + (Ask::Property, Input::Keyword(k)) => { + self.ask = Some(match k.as_str() { + "Color" => Ask::Color, + "LAyer" => Ask::Layer, + "LType" => Ask::Linetype, + "ltScale" => Ask::LtScale, + "LWeight" => Ask::Lineweight, + "Thickness" => Ask::Thickness, + _ => Ask::Transparency, + }); + } + (Ask::Property, Input::Text(t)) => { + let t = t.trim().trim_start_matches('_').to_ascii_lowercase(); + let n = PROPERTIES.iter().filter(|k| k.to_ascii_lowercase().starts_with(&t)).count(); + s.echo(if n > 1 { "Ambiguous response, please clarify..." } else { "Invalid option keyword." }); + } + (Ask::Color, Input::Keyword(k)) if k == "Truecolor" => self.ask = Some(Ask::TrueColor), + // Enter keeps the value. + (_, Input::Enter) => self.ask = Some(Ask::Property), + (ask, Input::Text(t) | Input::Keyword(t)) => { + // A refused answer asks again. + let taken = self.answer(s, ask, &t)?; + self.ask = Some(if taken { Ask::Property } else { ask }); + } + _ => {} + } + Ok(Step::Continue) + } +} diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index c02551b80..1563be702 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -180,10 +180,13 @@ impl Prompt { (k, k.to_ascii_lowercase(), shortcut) }); // A whole keyword or its capital-letter shortcut wins over a prefix of another keyword - // (`M` is Multiple, not a prefix of mEthod). + // (`M` is Multiple, not a prefix of mEthod). A prefix reaches past the keyword's last + // capital, as in AutoCAD: `L` is none of LAyer, LType, ltScale or LWeight (AutoCAD 2024's + // CHPROP: "Ambiguous response, please clarify..."), `LTS` is ltScale. + let past_capitals = |k: &str| k.char_indices().rfind(|(_, c)| c.is_ascii_uppercase() || c.is_ascii_digit()).map_or(1, |(i, _)| i + 1); keys.clone() .find(|(_, kl, sc)| tl == *kl || tl == *sc) - .or_else(|| keys.clone().find(|(_, kl, sc)| tl.len() >= sc.len() && kl.starts_with(&tl))) + .or_else(|| keys.clone().find(|(k, kl, _)| tl.len() >= past_capitals(k) && kl.starts_with(&tl))) .map(|(k, _, _)| k.clone()) } } @@ -341,5 +344,32 @@ mod tests { let q = Prompt::new("", Accept::POINT).kw(&["3P", "2P", "Ttr"]); assert_eq!(q.match_keyword("3p").as_deref(), Some("3P")); assert_eq!(q.match_keyword("t").as_deref(), Some("Ttr")); + // A prefix reaches past the last capital (AutoCAD 2024's CHPROP: `L` is ambiguous). + let c = + Prompt::new("Enter property to change", Accept::TEXT).kw(&["Color", "LAyer", "LType", "ltScale", "LWeight", "Thickness", "TRansparency"]); + assert_eq!(c.match_keyword("l"), None); + assert_eq!(c.match_keyword("la").as_deref(), Some("LAyer")); + assert_eq!(c.match_keyword("lts").as_deref(), Some("ltScale")); + assert_eq!(c.match_keyword("s").as_deref(), Some("ltScale")); + assert_eq!(c.match_keyword("tr").as_deref(), Some("TRansparency")); + // Even when no other keyword starts with it: AutoCAD 2024 answers QDIM's `DA` with "Point or + // option keyword required." and PEDIT's vertex `E` with "Invalid option keyword.". + let q = Prompt::new("", Accept::POINT).kw(&[ + "Continuous", + "Staggered", + "Baseline", + "Ordinate", + "Radius", + "Diameter", + "datumPoint", + "Edit", + "seTtings", + ]); + assert_eq!(q.match_keyword("da"), None); + assert_eq!(q.match_keyword("datump").as_deref(), Some("datumPoint")); + assert_eq!(q.match_keyword("p").as_deref(), Some("datumPoint")); + let v = Prompt::new("", Accept::TEXT).kw(&["Next", "Previous", "Break", "Insert", "Move", "Regen", "Straighten", "Tangent", "Width", "eXit"]); + assert_eq!(v.match_keyword("e"), None); + assert_eq!(v.match_keyword("ex").as_deref(), Some("eXit")); } } diff --git a/crates/engine/tests/it/chprop_command.rs b/crates/engine/tests/it/chprop_command.rs new file mode 100644 index 000000000..8e22c90af --- /dev/null +++ b/crates/engine/tests/it/chprop_command.rs @@ -0,0 +1,149 @@ +//! CHPROP as AutoCAD 2024 runs it from AutoLISP's `command` (accoreconsole, every object read back +//! with `entget`). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::color::{Color, Rgb}; +use cadcraft_engine::doc::{Handle, Lineweight, Transparency}; +use serde_json::json; + +/// A session with line A (0,0)-(50,0) on layer 0 and line B (0,20)-(50,30) on layer L1, as `a` and +/// `b` in LISP, after `code`; the properties of A then B. +fn run(code: &str) -> (Session, [cadcraft_engine::doc::Common; 2]) { + let mut s = Session::new(); + s.doc_mut().unwrap().ensure_layer("L1"); + s.execute("line", &json!({ "points": [[0, 0], [50, 0]] })).unwrap(); + s.cmdline("(setq a (entlast))").unwrap(); + s.execute("line", &json!({ "points": [[0, 20], [50, 30]] })).unwrap(); + s.cmdline("(setq b (entlast))").unwrap(); + s.cmdline("(command \"_.CHPROP\" b \"\" \"_LA\" \"L1\" \"\")").unwrap(); + s.cmdline(&format!("(progn {code})")).unwrap(); + if s.running.is_some() { + s.cancel(); + } + let common = { + let d = s.doc().unwrap(); + let mut it = d.model.iter().map(|e| e.common.clone()); + [it.next().unwrap(), it.next().unwrap()] + }; + (s, common) +} + +#[test] +fn chprop_sets_each_property_as_autocad() { + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_C\" 1 \"\")"); + assert_eq!(a.color, Color::Index(1)); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_C\" \"blue\" \"\")"); + assert_eq!(a.color, Color::Index(5)); + let (_, [_, b]) = run("(command \"_.CHPROP\" b \"\" \"_C\" \"_BYBLOCK\" \"\")"); + assert_eq!(b.color, Color::ByBlock); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_C\" 3 \"\") (command \"_.CHPROP\" a \"\" \"_C\" \"_BYLAYER\" \"\")"); + assert_eq!(a.color, Color::ByLayer); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_C\" \"_T\" \"255,128,0\" \"\")"); + assert_eq!(a.color, Color::True(Rgb(255, 128, 0))); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_LA\" \"L1\" \"\")"); + assert_eq!(a.layer, "L1"); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_LT\" \"DASHED\" \"\")"); + assert_eq!(a.linetype, "DASHED"); + // Not loaded yet: loaded and given, as AutoCAD loads it from acadiso.lin. + let (s, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_LT\" \"PHANTOM2\" \"\")"); + assert_eq!(a.linetype, "PHANTOM2"); + assert!(s.doc().unwrap().linetype("PHANTOM2").is_some()); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_S\" 2.5 \"\")"); + assert_eq!(a.ltscale, 2.5); + let (s, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_LW\" 0.33 \"\")"); + assert_eq!(a.lineweight, Lineweight::Mm100(35)); + assert!(s.log.iter().any(|l| l == "Lineweight rounded to nearest valid value of 0.35 mm"), "{:?}", s.log); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_T\" 5.0 \"\")"); + assert_eq!(a.thickness, 5.0); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_TR\" 50 \"\")"); + assert_eq!(a.transparency, Transparency::Percent(50)); + let (_, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_TR\" \"_BYBLOCK\" \"\")"); + assert_eq!(a.transparency, Transparency::ByBlock); + // Several objects and several properties in one go. + let (_, [a, b]) = run("(command \"_.CHPROP\" a b \"\" \"_C\" 3 \"_LA\" \"L1\" \"_LW\" 0.5 \"\")"); + for c in [a, b] { + assert_eq!((c.color, c.layer.as_str(), c.lineweight), (Color::Index(3), "L1", Lineweight::Mm100(50))); + } + let (_, [a, _]) = run( + "(command \"_.CHPROP\" a \"\" \"_C\" 3 \"\") (command \"_.CHPROP\" a \"\" \"_C\" \"_BYLAYER\" \"_LT\" \"_BYBLOCK\" \"_LW\" \"_BYLAYER\" \"\")", + ); + assert_eq!((a.color, a.linetype.as_str(), a.lineweight), (Color::ByLayer, "ByBlock", Lineweight::ByLayer)); +} + +#[test] +fn chprop_refuses_what_autocad_refuses() { + let (s, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_LA\" \"KHONGCO\" \"\")"); + assert_eq!(a.layer, "0"); + assert!(s.log.iter().any(|l| l == "Cannot find layer \"KHONGCO\"."), "{:?}", s.log); + for n in [0, 256, 300] { + let (s, [a, _]) = run(&format!("(command \"_.CHPROP\" a \"\" \"_C\" {n} \"\")")); + assert_eq!(a.color, Color::ByLayer, "{n}"); + assert!(s.log.iter().any(|l| l == "Invalid color number."), "{n}: {:?}", s.log); + } + let (s, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_C\" \"_T\" \"300,0,0\" \"\")"); + assert_eq!(a.color, Color::ByLayer); + assert!(s.log.iter().any(|l| l == "Requires three integers from 0 to 255, separated by commas."), "{:?}", s.log); + let (s, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_TR\" 95 \"\")"); + assert_eq!(a.transparency, Transparency::ByLayer); + assert!(s.log.iter().any(|l| l == "Requires ByLayer, ByBlock or an integer from 0 to 90."), "{:?}", s.log); + // `L` is LAyer, LType, ltScale or LWeight: none of them. + let (s, [a, _]) = run("(command \"_.CHPROP\" a \"\" \"_L\")"); + assert_eq!(a.layer, "0"); + assert!(s.log.iter().any(|l| l == "Ambiguous response, please clarify..."), "{:?}", s.log); +} + +/// Line a on layer 0 and lines b and c on the locked layer L1 (`a`, `b` and `c` in LISP); their +/// handles. +fn locked_drawing() -> (Session, Vec) { + let mut s = Session::new(); + s.doc_mut().unwrap().ensure_layer("L1"); + for (v, y) in [("a", 0), ("b", 20), ("c", 40)] { + s.execute("line", &json!({ "points": [[0, y], [50, y]] })).unwrap(); + s.cmdline(&format!("(setq {v} (entlast))")).unwrap(); + } + s.cmdline("(command \"_.CHPROP\" b c \"\" \"_LA\" \"L1\" \"\")").unwrap(); + s.execute("layer.set", &json!({ "name": "L1", "locked": true })).unwrap(); + s.log.clear(); + let hs = s.doc().unwrap().model.iter().map(|e| e.handle).collect(); + (s, hs) +} + +fn colors(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.common.color).collect() +} + +/// AutoCAD 2024 leaves objects on locked layers out at "Select objects" and says how many after +/// what was found; with none left, Enter ends the command. +#[test] +fn chprop_leaves_objects_on_locked_layers_alone() { + // The colours of a, b and c after `code`, run with `pickfirst` selected. + let after = |code: &str, pickfirst: &[usize]| { + let (mut s, hs) = locked_drawing(); + s.set_selection(pickfirst.iter().map(|i| hs[*i]).collect()); + s.cmdline(code).unwrap(); + (colors(&s), s.log.clone(), s.running.is_some()) + }; + let (c, log, _) = after("(command \"_.CHPROP\" (ssadd b (ssadd a)) \"\" \"_C\" 3 \"\")", &[]); + assert_eq!(c, [Color::Index(3), Color::ByLayer, Color::ByLayer]); + assert!(log.iter().any(|l| l == "1 was on a locked layer."), "{log:?}"); + let (c, log, _) = after("(command \"_.CHPROP\" (ssadd c (ssadd b (ssadd a))) \"\" \"_C\" 4 \"\")", &[]); + assert_eq!(c, [Color::Index(4), Color::ByLayer, Color::ByLayer]); + assert!(log.iter().any(|l| l == "2 were on a locked layer."), "{log:?}"); + // Nothing left: Enter ends the command. + let (_, log, running) = after("(command \"_.CHPROP\" b \"\")", &[]); + assert!(log.iter().any(|l| l == "1 was on a locked layer."), "{log:?}"); + assert!(!running); + // The pickfirst selection loses them too; with none of it left, CHPROP asks for objects. + let (c, log, _) = after("(command \"_.CHPROP\" \"_C\" 5 \"\")", &[0, 1]); + assert_eq!(c, [Color::Index(5), Color::ByLayer, Color::ByLayer]); + assert!(log.iter().any(|l| l == "1 was on a locked layer."), "{log:?}"); + let (c, _, _) = after("(command \"_.CHPROP\" a \"\" \"_C\" 6 \"\")", &[1]); + assert_eq!(c, [Color::Index(6), Color::ByLayer, Color::ByLayer]); + // The JSON form leaves them out as well, and says how many. + let (mut s, hs) = locked_drawing(); + let r = s.execute("chprop", &json!({ "handles": [hs[0].hex(), hs[1].hex()], "color": 3 })).unwrap(); + assert_eq!((r["changed"].as_u64(), r["locked"].as_u64()), (Some(1), Some(1)), "{r}"); + let r = s.execute("chprop", &json!({ "handles": [hs[2].hex()], "color": 4 })).unwrap(); + assert_eq!((r["changed"].as_u64(), r["locked"].as_u64()), (Some(0), Some(1)), "{r}"); + assert_eq!(colors(&s), [Color::Index(3), Color::ByLayer, Color::ByLayer]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index d0d3aedc8..5c0a37f45 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 burst; +mod chprop_command; mod compare_export; mod constraint_geometry; mod constraint_infer; From 43c41b8e684ce5a7eaf5dc9d2d72aa0c43bfd0dd Mon Sep 17 00:00:00 2001 From: Nine <136345161+nine-codes@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:46:30 +0100 Subject: [PATCH 233/900] bs: Add Bosnian (bs) to the interface languages (#2502) * Add Bosnian (bs) to the interface languages bs.tsv: Bosnian (Latin script, Ijekavian) catalog covering every key of CADCraft's other catalogs, its wording shared with storytold/craft-i18n locales/bs/ and the strings craft-i18n lacks translated new. Every bs-* locale selects it; counts use one/few/other. Locale and plural tests, localization docs and an attribution entry (AI-assisted, not yet reviewed by a native speaker). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013Tayw8nmxoLLmKv13jK93z * docs(localization-parity): Bosnian in the Languages table (CodeRabbit) --------- Co-authored-by: Claude Co-authored-by: Brandon Thomas --- ATTRIBUTION.md | 1 + crates/ui-egui/src/i18n.rs | 14 +- crates/ui-egui/src/i18n/bs.tsv | 1449 ++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/tests.rs | 10 + crates/ui-egui/src/options.rs | 2 +- docs/localization-parity.md | 8 +- 6 files changed, 1478 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/i18n/bs.tsv diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index e124d102a..31ea4b474 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -65,6 +65,7 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/de.tsv` | the CADCraft contributors | Original German translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/es.tsv` | @PedroGuille | Original Spanish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/pt_br.tsv` | @WladmirJunior | Original Brazilian Portuguese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | +| `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker | | `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index ed252f88b..7bb00ec17 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -45,10 +45,12 @@ pub enum Preference { Hungarian, #[serde(rename = "tr")] Turkish, + #[serde(rename = "bs")] + Bosnian, } 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::Bosnian, ]; /// Every preference in the order the Interface Language dialog lists them: Auto, then English @@ -113,6 +116,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Bosnian => "bs", } } @@ -141,6 +145,7 @@ impl Preference { Self::Arabic => "العربية", Self::Hungarian => "Magyar", Self::Turkish => "Türkçe", + Self::Bosnian => "Bosanski", } } @@ -171,6 +176,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Bosnian => "bs", Self::Auto => locales.iter().find_map(|s| locale_language(s)).unwrap_or("en"), } } @@ -187,7 +193,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 { @@ -234,6 +240,9 @@ pub static LANGUAGES: [Language; 16] = [ Language { code: "hu", name: "Magyar", source: include_str!("i18n/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!("i18n/tr.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() }, + // Bosnian (Latin script, Ijekavian): one (1, 21), few (2–4, 22–24, not 12–14), other — the + // Ukrainian rule for integer counts. + Language { code: "bs", name: "Bosanski", source: include_str!("i18n/bs.tsv"), plural: plural_uk, plural_forms: 3, catalog: OnceLock::new() }, ]; /// BCP 47 and POSIX locale tags, including `uk-UA`, `uk_UA.UTF-8` and `pt_BR.UTF-8`. @@ -437,6 +446,7 @@ mod picker_order_tests { assert!(pos(Preference::Czech) < pos(Preference::German), "Čeština sorts under C"); assert!(pos(Preference::Italian) < pos(Preference::Hungarian), "Magyar sorts under M"); assert!(pos(Preference::Turkish) < pos(Preference::Greek), "Latin names come before Greek"); + assert!(pos(Preference::Bosnian) < pos(Preference::Czech), "Bosanski sorts under B"); assert_eq!(name_sort_key("Türkçe"), "turkce"); } } diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv new file mode 100644 index 000000000..14565ce2f --- /dev/null +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -0,0 +1,1449 @@ +# CADCraft Bosnian interface catalog — original translations by Nine (@nine-codes) with Claude Code (AI-assisted). +# SPDX-License-Identifier: MIT OR Apache-2.0 +# Written from the meaning of CADCraft English strings; no proprietary translations copied. +# Latin script, Ijekavian; the wording is shared with storytold/craft-i18n (locales/bs/cadcraft.tsv +# and common.tsv). Not yet reviewed by a native speaker. +# UTF-8: contextEnglish sourceBosnian translation. +# @plural = one|few|other forms for integer counts. + Apply Primijeni + Attach DWG... Priloži DWG... + Bind Veži + Detach Odvoji + Loaded Učitano + Make it a block of this drawing, keeping its layer names Pretvori u blok ovog crteža, zadržavajući nazive slojeva + Make it a block of this drawing; its layers become NAME$0$LAYER Pretvori u blok ovog crteža; slojevi postaju NAZIV$0$SLOJ + No external references are attached. Nisu priložene vanjske reference. + Not Found Nije pronađeno + Not loaded Nije učitano + Open Otvori + Overlay Prekrivanje + Reference Manager Upravitelj referenci + Reference Name Naziv reference + References: {n} Reference: {n} + Reload Ponovo učitaj + Reload All Ponovo učitaj sve + Saved Path Sačuvana putanja + Unload Isprazni iz memorije + Unloaded Ispražnjeno iz memorije + Unreferenced Nereferencirano + Unresolved Neriješeno + Cancel Otkaži + OK U redu + or [ ili [ + % of all commits % svih commitova + * Wildcard Match * Podudaranje zamjenskim znakom + *VARIES* *RAZLIČITO* + + | Top | 2D Wireframe + | Vrh | 2D žičani model + +Bin +Bin + +LOC +LOC + 1 Viewport 1 prozor prikaza + 2 Points 2 tačke + 2 Viewports 2 prozora prikaza + 2D Solid 2D puno tijelo + 3 Points 3 tačke + 3 Viewports 3 prozora prikaza + 3D Face 3D lice + 3D Operations 3D operacije + 3D Polyline 3D polilinija + 4 Viewports 4 prozora prikaza + < Less than < Manje od + <> Not Equal <> Nije jednako + = Equals = Jednako + > Greater than > Veće od + A variable name starts with a letter and has only letters, digits and _ Naziv varijable počinje slovom i sadrži samo slova, cifre i _ + About O programu + About CADCraft O CADCraftu + Absolute Apsolutno + Add Leader Dodaj pokaznu liniju + Additional angles Dodatni uglovi + Align Poravnaj + Align Text Poravnaj tekst + Aligned Poravnato + All Sve + All Annotation Objects Svi objekti napomena + All Used Layers Svi korišteni slojevi + All files Sve datoteke + Angle Ugao + Angular Ugaono + Annotation Visibility Vidljivost napomena + Annotation scale Skala napomena + Apparent Intersection Prividni presjek + Append to current selection set Dodaj trenutnom skupu odabira + Apply to: Primijeni na: + Apply true color Primijeni pravu boju + Arc Luk + Arc Length Dužina luka + Area Područje + Arrange Panel Panel rasporeda + Array Niz + Attach Priloži + Attribute Atribut + Attribute Definition Definicija atributa + Attribute Display Prikaz atributa + Audit Revizija + Auto (system language) Automatski (jezik sistema) + Auto Constrain Automatska ograničenja + AutoConstrain Automatska ograničenja + Axis, End Osa, kraj + Base Baza + Baseline Osnovna linija + Batch Publish Paketno objavljivanje + Binary assets added Dodani binarni resursi + Binary assets removed Uklonjeni binarni resursi + Bind... Veži... + Blend Prelaz + Block Blok + Block Attribute Manager... Upravitelj atributa blokova... + Block Description... Opis bloka... + Block Editor Uređivač blokova + Block Reference Referenca bloka + Block... Blok... + Blocks Blokovi + Blue Plava + Bold Podebljano + Boolean Booleova operacija + Boundary Granica + Boundary... Granica... + Box Kvadar + Break Prekini + Break At Point Prekini u tački + Bring Above Objects Postavi iznad objekata + Bring Annotations to Front Postavi napomene na vrh + Bring to Front Postavi na vrh + Bulleted list Lista s oznakama + ByBlock PoBloku + ByColor PoBoji + ByLayer PoSloju + CADCraft Help Pomoć za CADCraft + Cancel Otkaži + Cartesian (x, y) Kartezijske (x, y) + Center Sredina + Center Line Središnja linija + Center Mark Oznaka središta + Center X Središte X + Center Y Središte Y + Center Z Središte Z + Center, Diameter Središte, prečnik + Center, Radius Središte, poluprečnik + Center, Start, Angle Središte, početak, ugao + Center, Start, End Središte, početak, kraj + Center, Start, Length Središte, početak, dužina + Chamfer Zakošenje + Change Space Promijeni prostor + Change to Current Layer Promijeni u trenutni sloj + Changed: {n} Promijenjeno: {n} + Circle Krug + Circumference Obim kruga + Clear History Očisti historiju + Clear Očisti + Clip Odsijeci + Clip Viewport Odsijeci prozor prikaza + Clipboard Međuspremnik + Close Zatvori + Close All Zatvori sve + Close All Other Drawings Zatvori sve ostale crteže + Closed Zatvoreno + Close Comparison Zatvori poređenje + Export Comparison Izvezi poređenje + Coincident Podudarno + Collapse Tool Sets Skupi skupove alata + Collinear Kolinearno + Color Boja + Color 8 Boja 8 + Color 9 Boja 9 + Color Index Indeks boje + Color... Boja... + Command Aliases Pseudonimi naredbi + Command History Historija naredbi + Clear Command History Očisti historiju naredbi + Command Line Komandna linija + Command Line History Lines Redovi historije komandne linije + Command Reference Referenca naredbi + Commits Commitovi + Company Firma + Compare Drawings... Uporedi crteže... + Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust. Računarski potpomognuto projektovanje i crtanje: CAD aplikacija otvorenog koda, napisana od nule u čistom Rustu. + Concentric Koncentrično + Cone Kupa + Constraint Bars Trake ograničenja + Constraint Settings Postavke ograničenja + Construction Line Konstrukcijska linija + Contents Sadržaj + Continue Nastavi + Contributors Saradnici + Control Vertices Kontrolna tjemena + Convert Pretvori + Copy Kopiraj + Copy Full File Path Kopiraj punu putanju datoteke + Copy History Kopiraj historiju + Copy Layout Kopiraj raspored + Copy Nested Objects Kopiraj ugniježđene objekte + Copy Selection Kopiraj odabir + Copy with Base Point Kopiraj s baznom tačkom + Count Broj + Count List Lista brojanja + Count Table Tabela brojanja + Create Block Kreiraj blok + Creates a user parameter Kreira korisnički parametar + Ctrl+Enter to finish Ctrl+Enter za završetak + Current layer Trenutni sloj + Current selection Trenutni odabir + Current: {color} Trenutno: {color} + Cut Izreži + Cut with Base Point Izreži s baznom tačkom + Cyan Cijan + Cylinder Valjak + DWG DWG + DWG Reference... DWG referenca... + DXF DXF + Dark Tamno + Data Extraction... Izdvajanje podataka... + Default Zadano + Data Link... Veza s podacima... + Default Save Format Zadani format čuvanja + Default Save Version Zadana verzija čuvanja + Define Attributes Definiši atribute + Define Attributes... Definiši atribute... + Defined width Definisana širina + Degree Stepen + Degrees of Freedom Stepeni slobode + Degrees of freedom: {n} Stepeni slobode: {n} + Delete Izbriši + Delete Column Izbriši kolonu + Delete Constraints Izbriši ograničenja + Delete Dimension Style Izbriši stil kotiranja + Delete Duplicate Objects Izbriši duplikate objekata + Delete Layer Izbriši sloj + Delete Layer State Izbriši stanje slojeva + Delete Layout Izbriši raspored + Delete Row Izbriši red + Delete Text Style Izbriši stil teksta + Delta X Delta X + Delta Y Delta Y + Description Opis + Deselect All Poništi sav odabir + Diameter Prečnik + Dim style Stil kote + Dimension Break Prekid kote + Dimension Edit Uređivanje kote + Dimension Kota + Dimension Objects Only Samo objekti kota + Dimension Space Razmak kota + Dimension Style Override Zamjena stila kotiranja + Dimension Style... Stil kotiranja... + Dimension Text Edit Uređivanje teksta kote + Dimension style Stil kotiranja + Dimensional Constraint Dimenzionalno ograničenje + Dimensional Constraint Parameters Parametri dimenzionalnih ograničenja + Dimensional Constraints Dimenzionalna ograničenja + Disassociate Dimensions Razdruži kote + Display name Ime za prikaz + Distance Udaljenost + Divide Podijeli + Do not plot (click: plot) Ne iscrtavaj (klik: iscrtaj) + Donut Prsten + Double-click to edit the description Dvostruki klik za uređivanje opisa + Down Dolje + Drafting Crtanje + Drafting Settings Postavke crtanja + Drafting Settings... Postavke crtanja... + Draw Crtaj + Draw Order Redoslijed crtanja + Drawing (DWG) Crtež (DWG) + Drawing (DXF) Crtež (DXF) + Drawing Limits Granice crteža + Drawing Template (DWT) Predložak crteža (DWT) + Drawing Utilities Uslužni programi za crteže + Drawings (DWG, DXF) Crteži (DWG, DXF) + Dynamic Dinamično + Dynamic Dimensions Dinamičke kote + Dynamic Input Dinamički unos + Dynamic Input (F12) Dinamički unos (F12) + E E + Edit Uredi + Edit Attributes... Uredi atribute... + Edit Text... Uredi tekst... + Edit Table Cell Uredi ćeliju tabele + Elevation Elevacija + Ellipse Elipsa + Elliptical Arc Eliptični luk + Enable Dynamic Input (F12) Omogući dinamički unos (F12) + End Object Isolation Završi izolaciju objekata + End Width Krajnja širina + End X Kraj X + End Y Kraj Y + End angle Krajnji ugao + Endpoint Krajnja tačka + Enter Enter + Enter Top, Zero or Bottom. Unesite Vrh, Nula ili Dno. + Enter a fit data option Unesite opciju podataka uklapanja + Enter a pattern name Unesite naziv uzorka + Enter a vertex editing option Unesite opciju uređivanja tjemena + Enter an option Unesite opciju + Enter angle of xline Unesite ugao konstrukcijske linije + Enter angle of xline (0) or Unesite ugao konstrukcijske linije (0) ili + Enter area of rectangle in current units Unesite površinu pravougaonika u trenutnim jedinicama + Enter attribute prompt Unesite upit atributa + Enter attribute tag name Unesite naziv oznake atributa + Enter attribute value Unesite vrijednost atributa + Enter block name Unesite naziv bloka + Enter constraint type Unesite vrstu ograničenja + Enter continuity Unesite kontinuitet + Enter default attribute value Unesite zadanu vrijednost atributa + Enter degree of spline Unesite stepen splajna + Enter delta angle Unesite delta ugao + Enter delta length or Unesite delta dužinu ili + Enter dimension text Unesite tekst kote + Enter dimension text (<> = measurement) Unesite tekst kote (<> = mjera) + Enter dimension value or [name=expression] Unesite vrijednost kote ili [naziv=izraz] + Enter dimension variable name to override Unesite naziv varijable kotiranja za zamjenu + Enter justification type Unesite vrstu poravnanja + Enter leader text Unesite tekst pokazne linije + Enter mline scale Unesite skalu višestruke linije + Enter mode Unesite način + Enter name of block to insert Unesite naziv bloka za umetanje + Enter new text Unesite novi tekst + Enter next point Unesite sljedeću tačku + Enter number of columns Unesite broj kolona + Enter number of data rows Unesite broj redova podataka + Enter number of items Unesite broj stavki + Enter number of items along path Unesite broj stavki duž putanje + Enter number of sides Unesite broj stranica + Enter number of turns Unesite broj zavoja + Enter percentage length Unesite postotak dužine + Enter rectangle length Unesite dužinu pravougaonika + Enter rectangle width Unesite širinu pravougaonika + Enter scale factor Unesite faktor skale + Enter text Unesite tekst + Enter text (use \P for new paragraphs) Unesite tekst (koristite \P za nove pasuse) + Enter the number of segments Unesite broj segmenata + Enter twist direction of helix Unesite smjer uvijanja spirale + Entire drawing Cijeli crtež + Equal Jednako + Erase Briši + Evaluate Izračunaj + Exclude from new selection set Isključi iz novog skupa odabira + Explode Rastavi + Export Izvezi + Export Table Izvezi tabelu + Export to PDF... Izvezi u PDF... + Expression Izraz + Extend Produži + Extension Produžetak + Extents Opseg + External Reference Vanjska referenca + External References Vanjske reference + Extrude Istisni + File Datoteka + File Tab Kartica datoteke + Fillet Zaobljenje + Filter Filter + Filters Filteri + Find and Replace Pronađi i zamijeni + Find... Pronađi... + First Prvo + First commit Prvi commit + Fit Points Tačke uklapanja + Fix Fiksiraj + Flatten Objects Spljošti objekte + Format Format + Freehand Prostoručno + Freeze Zamrzni + Freeze Layer Zamrzni sloj + Freeze in new viewports Zamrzni u novim prozorima prikaza + Freeze/Thaw Zamrzni/odmrzni + Freeze/Thaw in all viewports Zamrzni/odmrzni u svim prozorima prikaza + Freeze/Thaw in the current viewport Zamrzni/odmrzni u trenutnom prozoru prikaza + From Od + From Template... Iz predloška... + General Općenito + Geometric Center Geometrijsko središte + Geometric Constraint Geometrijsko ograničenje + Geometric Constraints Geometrijska ograničenja + Geometry Geometrija + Get from the Drawing Preuzmi iz crteža + Get Variable Preuzmi varijablu + Get View Preuzmi pogled + Global Globalno + Global width Globalna širina + Grab bag Svaštara + Gradient Gradijent + Gradient... Gradijent... + Green Zelena + Grid (F7) Mreža (F7) + Grid Display Prikaz mreže + Grid On (F7) Mreža uključena (F7) + Grid snap Hvatanje mreže + Grid spacing Razmak mreže + Grip Edit Uređivanje hvataljkama + Grip Mirror Zrcaljenje hvataljkom + Grip Option Opcija hvataljke + Grip Rotate Rotacija hvataljkom + Grip Scale Skaliranje hvataljkom + Grip Stretch Razvlačenje hvataljkom + Group Grupiši + Group Edit Uređivanje grupe + Group Options Opcije grupe + Group Selection Odabir grupe + Hatch Šrafura + Hatch Edit Uređivanje šrafure + Hatch Patterns Uzorci šrafure + Hatch... Šrafura... + Height Visina + Height: {height} Visina: {height} + Helix Spirala + Help Pomoć + Hide All Sakrij sve + Hide All Constraint Bars Sakrij sve trake ograničenja + Hide All Dynamic Dimensions Sakrij sve dinamičke kote + Hide Layer List Sakrij listu slojeva + Hide Objects Sakrij objekte + Hide Palettes Sakrij palete + History Historija + Home Početna + Horizontal Vodoravno + HorizontalDistance Vodoravna udaljenost + How to apply: Kako primijeniti: + ID Point Identifikuj tačku + Import Uvezi + In In + In-window Menu Bar Traka menija u prozoru + Include in new selection set Uključi u novi skup odabira + Increment angle Ugao koraka + Index Color Indeksna boja + Index color: {index} Indeksna boja: {index} + Infer Constraints Zaključi ograničenja + Inquiry Upit + Insert Umetni + Insert Block Umetni blok + Insert Column Umetni kolonu + Insert Row Umetni red + Insert tab Umetni tabulator + Insert this block Umetni ovaj blok + Insert Table Formula Umetni formulu tabele + Insertion Umetanje + Insertion X Umetanje X + Insertion Y Umetanje Y + Insertion Z Umetanje Z + Inspect Constraints Pregledaj ograničenja + Inspect Drawing Pregledaj crtež + Inspection Inspekcija + Interface Language Jezik interfejsa + Interface Theme Tema interfejsa + Intersect Presijeci + Intersection Presjek + Isolate Izoliraj + Isolate Layer Izoliraj sloj + Isolate Objects Izoliraj objekte + Isometric Drafting Izometrijsko crtanje + Jogged Prelomljeno + Jogged Linear Prelomljeno linearno + Join Spoji + Join the ArtCraft Discord… Pridružite se ArtCraft Discordu… + Join us on Discord Pridružite nam se na Discordu + Isometric Plane Izometrijska ravan + Isometric snap Izometrijsko hvatanje + Language Jezik + Last Posljednje + Last commit Posljednji commit + Layer Sloj + Layer Delete Brisanje sloja + Layer Match Uskladi sloj + Layer Merge Spoji slojeve + Layer Off Isključi sloj + Layer Properties Svojstva sloja + Layer Properties Manager Upravitelj svojstava slojeva + Layer Properties Manager — current viewport Upravitelj svojstava slojeva — trenutni prozor prikaza + Layer State Stanje slojeva + Layer States Manager... Upravitelj stanja slojeva... + Layer Tools Alati za slojeve + Layer contains objects (double-click to make current) Sloj sadrži objekte (dvostruki klik da postane trenutni) + Layer is empty (double-click to make current) Sloj je prazan (dvostruki klik da postane trenutni) + Layers Slojevi + Layers Palette Paleta slojeva + Hide Palette Sakrij paletu + Layers displayed: {shown} of {total}. Current layer: {layer} Prikazani slojevi: {shown} od {total}. Trenutni sloj: {layer} + Layout Raspored + Layout list Lista rasporeda + Leader Pokazna linija + Leaders Only Samo pokazne linije + Left Lijevo + Length Dužina + Length X Dužina X + Length Y Dužina Y + Lengthen Produlji + Light Svijetlo + Line Linija + Line delta Razlika u linijama + Linear Linearno + Lines +/− Linije +/− + Lines added Dodane linije + Lines deleted Izbrisane linije + Lines of Command History Redovi historije naredbi + Linetype Vrsta linije + Linetype Scale Skala vrste linije + Linetype scale Skala vrste linije + Ltscale Ltscale + Linetype... Vrsta linije... + Lineweight Debljina linije + Lineweight... Debljina linije... + List Lista + List Blocks Izlistaj blokove + List Dimension Styles Izlistaj stilove kotiranja + List Groups Izlistaj grupe + List Layer States Izlistaj stanja slojeva + List Layouts Izlistaj rasporede + List System Variables Izlistaj sistemske varijable + List Text Styles Izlistaj stilove teksta + Load all Učitaj sve + Load... Učitaj... + Loaded linetypes Učitane vrste linija + Lock Zaključaj + Lock Layer Zaključaj sloj + Lock viewport Zaključaj prozor prikaza + Lock/Unlock Zaključaj/otključaj + Loft Prelazno tijelo + MIT OR Apache-2.0. Not affiliated with Autodesk, Inc. MIT OR Apache-2.0. Nije povezano s Autodesk, Inc. + MODEL MODEL + MText MText + Magenta Magenta + Major line every Glavna linija svakih + Make Current Postavi kao trenutno + Make Object's Layer Current Postavi sloj objekta kao trenutni + Make... Napravi... + Match Layer Uskladi sloj + Match Properties Uskladi svojstva + Measure Mjeri + Measure Distance Izmjeri udaljenost + Measure Geometry Izmjeri geometriju + Merge Cells Spoji ćelije + Merged PRs Spojeni PR-ovi + Mid Between 2 Points Sredina između 2 tačke + Midpoint Srednja tačka + Mirror Zrcali + Model Model + Model Space (in viewport) Prostor modela (u prozoru prikaza) + Modeling Modeliranje + Models Modeli + Modify Izmijeni + Move Pomakni + Multileader Višestruka pokazna linija + Multileader Style... Stil višestruke pokazne linije... + Multileader style Stil višestruke pokazne linije + Multiline Višestruka linija + Multiline Text Višeredni tekst + Multiline Text... Višeredni tekst... + Multiple Višestruko + Multiple Point Višestruka tačka + My Moje + My properties: not available yet Moja svojstva: još nisu dostupna + N N + Name Naziv + Name (A–Z) Naziv (A–Z) + Named Viewports... Imenovani prozori prikaza... + Named Views... Imenovani pogledi... + Nearest Najbliže + New Novo + New (metric) Novo (metrički) + New Drawing Novi crtež + New Drawing (⌘N) Novi crtež (⌘N) + New Drawing... Novi crtež... + New Layer Novi sloj + New Layout Novi raspored + New VP Freeze Zamrzni u novom PP + New Viewports... Novi prozori prikaza... + New from Template... Novo iz predloška... + New layout Novi raspored + New state name Naziv novog stanja + Next Change Sljedeća promjena + No Ne + No blocks defined in this drawing. U ovom crtežu nisu definisani blokovi. + No contributor data was built into this copy. U ovu kopiju nisu ugrađeni podaci o saradnicima. + No model credits were built into this copy. U ovu kopiju nisu ugrađene zasluge za modele. + No saved layer states Nema sačuvanih stanja slojeva + No selection Nema odabira + Node Čvor + None Ništa + Normal Normalno + Not available Nije dostupno + Not available yet Još nije dostupno + Numbered list Numerisana lista + OK U redu + Object Objekat + Object Snap Hvatanje objekata + Object Snap (F3) Hvatanje objekata (F3) + Object Snap On (F3) Hvatanje objekata uključeno (F3) + Object Snap Tracking Praćenje hvatanja objekata + Object Snap Tracking (F11) Praćenje hvatanja objekata (F11) + Object Snap Tracking Settings Postavke praćenja hvatanja objekata + Object type: Vrsta objekta: + Oblique Koso + Off Isključeno + Offset Pomak + On Uključeno + On/Off Uključi/isključi + One of the Crafting Apps by the ArtCraft team and community. Jedna od Crafting aplikacija ArtCraft tima i zajednice. + Only in this drawing: {n} Samo u ovom crtežu: {n} + Only in {name}: {n} Samo u {name}: {n} + Open (⌘O) Otvori (⌘O) + Open Sample Drawing Otvori primjer crteža + Open sample drawing Otvori primjer crteža + Open Xref Otvori vanjsku referencu + Open... Otvori... + Operator: Operator: + Orbit Orbita + Ordinate Ordinata + Ortho (F8) Orto (F8) + Ortho Mode Orto način + Ortho Mode (F8) Orto način (F8) + Osnap Settings... Postavke hvatanja objekata... + Out Out + Over-constrained Previše ograničeno + Override Zamjena + PAPER PAPIR + Percent Postotak + Polar (distance < angle) Polarne (udaljenost < ugao) + PRs PR-ovi + Page Setup Manager Upravitelj postavki stranice + Page Setup Manager... Upravitelj postavki stranice... + Pan Pomicanje pogleda + Pan Down Pomakni pogled dolje + Pan Left Pomakni pogled lijevo + Pan Right Pomakni pogled desno + Pan Up Pomakni pogled gore + Paper Space Prostor papira + Parallel Paralelno + Parameters Manager Upravitelj parametara + Parametric Parametarsko + Paste Zalijepi + Paste as Block Zalijepi kao blok + Paste to Command Line Zalijepi u komandnu liniju + Paste to Original Coordinates Zalijepi na originalne koordinate + Path Array Niz po putanji + Pattern Uzorak + Perpendicular Okomito + Plot Iscrtaj + Plot (click: do not plot) Iscrtaj (klik: ne iscrtavaj) + Plot Preview Pregled iscrtavanja + Plot Window Prozor iscrtavanja + Plot style Stil iscrtavanja + Plot style attached to Stil iscrtavanja priložen uz + Plot style table Tabela stilova iscrtavanja + Plot Style... Stil iscrtavanja... + Plot Style Manager Upravitelj stilova iscrtavanja + Plot Style Manager... Upravitelj stilova iscrtavanja... + Plot Styles... Stilovi iscrtavanja... + Plotter Manager Upravitelj plotera + Plotter Manager... Upravitelj plotera... + New CTB Novi CTB + New STB Novi STB + New style Novi stil + Reset Panel Layout Vrati raspored panela na početno + Send Hatches to Back Postavi šrafure na dno + Send Under Objects Postavi ispod objekata + Text Objects Only Samo tekstualni objekti + Use for this layout Koristi za ovaj raspored + Display plot styles Prikaži stilove iscrtavanja + No plot style tables. Nema tabela stilova iscrtavanja. + A built-in table: editing it keeps an edited copy in the drawing. Ugrađena tabela: njeno uređivanje čuva uređenu kopiju u crtežu. + Keep an editable copy of this table in the drawing Zadrži kopiju ove tabele za uređivanje u crtežu + Layout {name}: {table} Raspored {name}: {table} + Grayscale Nijanse sive + Screening Prigušenje + Use object linetype Koristi vrstu linije objekta + Use object lineweight Koristi debljinu linije objekta + Remove Ukloni + Add Dodaj + Open a drawing first. Prvo otvorite crtež. + Plot table type Vrsta tabele iscrtavanja + Color-dependent Zavisno od boje + Named Imenovano + Plus/minus Plus/minus + Point Tačka + Point Filters Filteri tačaka + Point Style... Stil tačke... + Polar Array Polarni niz + Polar Tracking Polarno praćenje + Polar Tracking (F10) Polarno praćenje (F10) + Polar Tracking On (F10) Polarno praćenje uključeno (F10) + Polar angle measurement Mjerenje polarnog ugla + Polar distance Polarna udaljenost + Polar: {distance} < {angle}° Polarno: {distance} < {angle}° + PolarSnap Polarno hvatanje + Polygon Mnogougao + Polygonal Mnogougaono + Polygonal Viewport Mnogougaoni prozor prikaza + Polyline Izlomljena linija + Polyline Edit Uređivanje polilinije + Position X Položaj X + Position Y Položaj Y + Position Z Položaj Z + Previous Prethodno + Previous Change Prethodna promjena + Previous Layer Prethodni sloj + Primitives Primitivi + Print Štampaj + Print... Štampaj... + Properties Svojstva + Properties Inspector Inspektor svojstava + Properties: Svojstva: + Proxy Proksi + Purge Očisti neiskorišteno + Pyramid Piramida + Quadrant Kvadrant + Query Entities Upit o entitetima + Quick Brzo + Quick Dimension Brza kota + Quick Properties Brza svojstva + Quick Select Brzi odabir + Quick Select Properties Svojstva brzog odabira + Quick Select... Brzi odabir... + QuickCalc Brzi kalkulator + QuickCalc Pick Odabir za brzi kalkulator + Quit CADCraft Zatvori CADCraft + Radius Poluprečnik + Raster Image Rasterska slika + Ray Zraka + Read-only Samo za čitanje + Real name Pravo ime + Realtime U stvarnom vremenu + Reassociate Dimensions Ponovo poveži kote + Recent Nedavno + Recent Commands Nedavne naredbe + Recent Input Nedavni unos + Recover... Oporavi... + Rectangle Pravougaonik + Recalculate Table Formulas Ponovo izračunaj formule tabele + Rectangular Pravougaono + Rectangular snap Pravougaono hvatanje + Rectangular Array Pravougaoni niz + Red Crvena + Redo Ponovi + Redo (⇧⌘Z) Ponovi (⇧⌘Z) + Redraw Ponovo iscrtaj + Regen Regeneriši + Regen All Regeneriši sve + Region Regija + Region/Mass Properties Svojstva regije/mase + Reinitialize Ponovo inicijaliziraj + Relative Relativno + Relative to last segment U odnosu na posljednji segment + Remove Leader Ukloni pokaznu liniju + Remove the viewport override Ukloni zamjenu za prozor prikaza + Rename Dimension Style Preimenuj stil kotiranja + Rename Layer Preimenuj sloj + Rename Layer State Preimenuj stanje slojeva + Rename Layout Preimenuj raspored + Rename Text Style Preimenuj stil teksta + Rename... Preimenuj... + Repeat {command} Ponovi {command} + Replace Block... Zamijeni blok... + Requires a point (x,y, @dx,dy or @d Navedite drugu tačku ili + Specify second source point Navedite drugu izvornu tačku + Specify side to offset Navedite stranu za odmak + Specify start angle Navedite početni ugao + Specify start point Navedite početnu tačku + Specify start point of arc Navedite početnu tačku luka + Specify start point of polyline Navedite početnu tačku polilinije + Specify start point of text Navedite početnu tačku teksta + Specify starting width Navedite početnu širinu + Specify starting width for next segment Navedite početnu širinu za sljedeći segment + Specify tangent direction for the start point of arc Navedite smjer tangente za početnu tačku luka + Specify the elevation for rectangles Navedite elevaciju za pravougaonike + Specify thickness for rectangles Navedite debljinu za pravougaonike + Specify third point on circle Navedite treću tačku na krugu + Specify third point on circle: _tan to Navedite treću tačku na krugu: _tan na + Specify third source point or Navedite treću izvornu tačku ili + Specify through point Navedite tačku kroz koju prolazi + Specify top diameter Navedite gornji prečnik + Specify top radius or Navedite gornji poluprečnik ili + Specify total angle Navedite ukupni ugao + Specify total length or Navedite ukupnu dužinu ili + Specify width for rectangles Navedite širinu za pravougaonike + Sphere Sfera + Spline Splajn + Spline Edit Uređivanje splajna + Stack (type 1/2 then select) Složi (upišite 1/2 pa odaberite) + Standard Standardno + Start Početak + Start Width Početna širina + Start X Početak X + Start Y Početak Y + Start angle Početni ugao + Start, Center, Angle Početak, središte, ugao + Start, Center, End Početak, središte, kraj + Start, Center, Length Početak, središte, dužina + Start, End, Angle Početak, kraj, ugao + Start, End, Direction Početak, kraj, smjer + Start, End, Radius Početak, kraj, poluprečnik + Status Status + Status Bar Statusna traka + Stretch Razvuci + Style: Standard Stil: Standard + Subtract Oduzmi + Sweep Izvlačenje po putanji + Switch Drawing Promijeni crtež + Switch Layout Promijeni raspored + Switch between model space in a viewport and paper space Prebacuj između prostora modela u prozoru prikaza i prostora papira + Symmetric Simetrično + Synchronize Attributes Sinhronizuj atribute + To Do + Toggle PICKADD (off: each pick replaces the selection) Uključi/isključi PICKADD (isključeno: svaki odabir zamjenjuje odabir) + Toggle PICKADD (on: picks add to the selection) Uključi/isključi PICKADD (uključeno: odabiri se dodaju u odabir) + TOP VRH + Table Tabela + Table Breaks Prelomi tabele + Table Cell Style Stil ćelije tabele + Table Style... Stil tabele... + Table style Stil tabele + Table... Tabela... + Tan, Tan, Radius Tan, tan, poluprečnik + Tan, Tan, Tan Tan, tan, tan + Tangent Tangenta + Temporary track point Privremena tačka praćenja + Text Tekst + Text Editor Uređivač teksta + Text Height Visina teksta + Text Style... Stil teksta... + Text height Visina teksta + Text override Zamjena teksta + Text style Stil teksta + Thaw All Layers Odmrzni sve slojeve + Thaw Layer Odmrzni sloj + There is nothing here yet. Ovdje još nema ničega. + Thickness Debljina + Time Vrijeme + To get started, create or open a drawing. Za početak kreirajte ili otvorite crtež. + Tool Bar Traka s alatima + Tool Sets Skupovi alata + Tools Alati + Torus Torus + Trace Trag + Track orthogonally only Prati samo pravougaono + Track using all polar angle settings Prati koristeći sve postavke polarnih uglova + Transparency Prozirnost + Trim Odsijeci + True Color Prava boja + Turn All Layers On Uključi sve slojeve + Turn Off Layer Isključi sloj + Turn On Layer Uključi sloj + Turn Quick Properties off (QPMODE) Isključi brza svojstva (QPMODE) + Type Vrsta + Type a command Upišite naredbu + Type text; Enter starts a new paragraph Upišite tekst; Enter započinje novi pasus + UCS Icon Ikona KKS + Undo Poništi + Undo (⌘Z) Poništi (⌘Z) + Ungroup Razgrupiši + Union Unija + Unisolate Layer Prekini izolaciju sloja + Units Conversion Pretvaranje jedinica + Units... Jedinice... + Unlock Layer Otključaj sloj + Unlock viewport Otključaj prozor prikaza + Unmerge Cells Razdvoji spojene ćelije + Unsaved Layer State Nesačuvano stanje slojeva + Up Gore + Update Data Links Ažuriraj veze s podacima + Update Ažuriraj + Use System Setting Koristi sistemsku postavku + User Korisnik + User Parameters Korisnički parametri + Username Korisničko ime + Volume Zapremina + VP Color Boja u PP + VP Freeze Zamrzni u PP + Value Vrijednost + Value: Vrijednost: + Variables Varijable + Version Verzija + Version 2000 Verzija 2000 + Version 2004 Verzija 2004 + Version 2007 Verzija 2007 + Version 2010 Verzija 2010 + Version 2013 Verzija 2013 + Version 2018 Verzija 2018 + Version {version} Verzija {version} + Vertical Okomito + VerticalDistance Okomita udaljenost + View Prikaz + ViewCube ViewCube + Viewport Prozor prikaza + Viewport Layer Freeze Zamrzavanje slojeva u prozoru prikaza + Viewport Properties Svojstva prozora prikaza + Viewport is locked Prozor prikaza je zaključan + Viewport scale Skala prozora prikaza + Viewport {id} Prozor prikaza {id} + Viewports Prozori prikaza + W W + WCS WCS + White Bijela + Width factor Faktor širine + Window Prozor + Wipeout Prekrivanje + Workspace Switching Promjena radnog prostora + Write Block Zapiši blok + Xline Konstrukcijska linija + Yellow Žuta + Yes Da + Zoom Zumiranje + Zoom All Zumiraj sve + Zoom Dynamic Dinamičko zumiranje + Zoom Extents Zumiraj na opseg + Zoom In Uvećaj + Zoom Object Zumiraj objekat + Zoom Out Umanji + Zoom Previous Prethodno zumiranje + Zoom Realtime Zumiranje u stvarnom vremenu + Zoom Window Zumiraj prozor + error greška + {contributors} · {commits} {contributors} · {commits} + {kind} (constraint {id}) {kind} (ograničenje {id}) + {kind} constraint {name} = {expression} (double-click to edit) {kind} ograničenje {name} = {expression} (dvostruki klik za uređivanje) + {name}: {distance} < {angle}° {name}: {distance} < {angle}° + ƒx New User Parameter ƒx Novi korisnički parametar + ΔLOC ΔLOC + −Bin −Bin + −LOC −LOC + ⌘↩ to finish ⌘↩ za završetak +@plural {n} commit {n} commit|{n} commita|{n} commitova +@plural {n} contributor {n} saradnik|{n} saradnika|{n} saradnika + Drawing as bytes Crtež kao bajtovi + Services Usluge + Hide CADCraft Sakrij CADCraft + Hide Others Sakrij ostale + Accessibility Pristupačnost + Show System Cursor Prikaži sistemski kursor + Animation Effects Animacijski efekti + Animation effects Animacijski efekti + Import... Uvezi... + Export... Izvezi... + Batch Publish... Paketno objavljivanje... + Scale List... Lista skala... + Annotative Object Scale Skala objekta napomene + Add Current Scale Dodaj trenutnu skalu + Delete Current Scale Izbriši trenutnu skalu + Add/Delete Scales... Dodaj/izbriši skale... + Synchronize Multiple-scale Positions Sinhronizuj položaje za više skala + Annotative Update Ažuriranje napomena + Show Annotative Objects Prikaži objekte napomena + Current Scale Only Samo trenutna skala + All Scales Sve skale + Drawing Recovery Manager... Upravitelj oporavka crteža... + Tolerance... Tolerancija... + Add Vertex Dodaj tjeme + Remove Vertex Ukloni tjeme + Convert to Arc Pretvori u luk + Convert to Line Pretvori u liniju + Stretch Vertex Razvuci tjeme + Edit Array Uredi niz + Close Array Editing Zatvori uređivanje niza + Multiline... Višestruka linija... + Multiline Style... Stil višestruke linije... + Solid Editing Uređivanje punih tijela + X X + Y Y + B B + CADCraft CADCraft + More toolbar commands Više naredbi trake s alatima +menu View Prikaz +menu Draw Crtaj +menu Dimension Kotiranje +menu Modify Izmijeni + Hatch Pattern Uzorak šrafure + Search for pattern Traži uzorak + Not a number or distance: {text} Nije broj ili udaljenost: {text} + Query Texts Upit o tekstovima + Analyze Shapes Analiziraj oblike + Check for Updates… Provjeri ažuriranja… + CADCraft is up to date. CADCraft je ažuran. + Could not check for updates. Nije moguće provjeriti ažuriranja. + 3D Mouse 3D miš + 3D Mouse Navigation Navigacija 3D mišem + 3D Mouse... 3D miš... + 3D mouse busy, possibly 3DxWare or missing device permissions 3D miš je zauzet, možda zbog 3DxWare ili nedostajućih dozvola za uređaj + 3D mouse connected 3D miš je povezan + 3D mouse disconnected 3D miš je isključen + 3D mouse input could not be started Unos 3D mišem nije moguće pokrenuti + 3D mouse input is unavailable on this platform Unos 3D mišem nije dostupan na ovoj platformi + Automatic save every Automatsko čuvanje svakih + Automatic save file location Lokacija datoteke automatskog čuvanja + Calibrate Kalibriraj + Calibrate 3D Mouse Kalibriraj 3D miš + Collapse Palettes Skupi palete + Default save version Zadana verzija čuvanja + Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. Crteži koji još nemaju datoteku čuvaju se u zadanoj verziji. 0 minuta isključuje automatsko čuvanje. + Enable 3D mouse navigation Omogući navigaciju 3D mišem + Left device button: zoom extents. Right device button: calibrate. Lijevo dugme uređaja: zumiraj na opseg. Desno dugme uređaja: kalibriraj. + Move sideways to pan; push/pull or twist to zoom. Pomjerite postrance za pomicanje pogleda; gurnite/povucite ili zakrenite za zumiranje. + No supported 3D mouse found Nije pronađen podržani 3D miš + Pan sensitivity Osjetljivost pomicanja pogleda + Release the 3D mouse to calibrate its resting position Pustite 3D miš da kalibrirate njegov položaj mirovanja + Reverse zoom direction Obrni smjer zumiranja + Run Script... Pokreni skriptu... + SVG drawings (SVG, SVGZ) SVG crteži (SVG, SVGZ) + Show and hide the tools of this category Prikaži i sakrij alate ove kategorije + Show in Tool Sets Prikaži u skupovima alata + Time-sensitive right-click: a quick click is Enter, holding opens the menu Desni klik osjetljiv na vrijeme: brzi klik je Enter, držanje otvara meni + Turned off, a right-click while a command runs always opens the shortcut menu. Kad je isključeno, desni klik dok se naredba izvršava uvijek otvara kontekstni meni. + Zoom sensitivity Osjetljivost zumiranja + min min + Align Multileaders Poravnaj višestruke pokazne linije + Collect Prikupi + Collect Multileaders Prikupi višestruke pokazne linije + Edit Multileader Uredi višestruku pokaznu liniju + Italic Kurziv + Underline Podvučeno + Overline Nadvučeno + Justify Poravnaj obostrano + Text color Boja teksta + Click the ruler to add a tab stop, right-click to remove one Kliknite ravnalo da dodate tabulator, desni klik da ga uklonite + Add: Pick points Dodaj: odaberi tačke + Add: Select objects Dodaj: odaberi objekte + Associative Asocijativno + Block to create or edit Blok za kreiranje ili uređivanje + Bottom left Dolje lijevo + Bottom right Dolje desno + Boundaries Granice + Boundaries picked: {n} Odabrane granice: {n} + Centered Centrirano + Clear Recent Files Očisti nedavne datoteke + Click to set new origin Kliknite da postavite novo ishodište + Close Block Editor Zatvori uređivač blokova + Color 1 Boja 1 + Color 2 Boja 2 + contains authoring elements. Open in Block Editor? sadrži elemente za izradu. Otvoriti u uređivaču blokova? + Create separate hatches Kreiraj zasebne šrafure + Crossing selection color: Boja odabira presijecanjem: + Curved Zakrivljeno + Custom Prilagođeno + Default to boundary extents Zadano na opseg granice + Drag Dynamic Grip Prevuci dinamičku hvataljku + Dynamic Block Data Podaci dinamičkog bloka + Dynamic Block Grips Hvataljke dinamičkog bloka + Dynamic Block Reference Referenca dinamičkog bloka + Edit Block Definition Uredi definiciju bloka + Evaluate LISP Izračunaj LISP + Exclude: Isključi: + Grips Hvataljke + Groups Grupe + Hatch and Gradient Šrafura i gradijent + Hatch origin Ishodište šrafure + Hatch Pick Odabir šrafure + Hatches Šrafure + Hemispherical Polusferno + Ignore Zanemari + Indicate selection area Označite područje odabira + Inverted Obrnuto + Island detection Otkrivanje ostrva + Load Application... Učitaj aplikaciju... + Multiline text Višeredni tekst + New block Novi blok + Object grouping Grupisanje objekata + Object selection limit for display of grips Ograničenje odabira objekata za prikaz hvataljki + Objects on locked layers Objekti na zaključanim slojevima + Open in Block Editor Otvori u uređivaču blokova + Open Recent Otvori nedavno + Origin: {x}, {y} Ishodište: {x}, {y} + Outer Vanjsko + Preview Pregled + Save Block Sačuvaj blok + Save Block As Sačuvaj blok kao + Selection Area Effect Efekat područja odabira + Selection area opacity: Neprozirnost područja odabira: + Selection effect color Boja efekta odabira + Selection modes Načini odabira + Selection preview Pregled odabira + Selection Preview Filter Filter pregleda odabira + Set Dynamic Property Postavi dinamičko svojstvo + Shape Oblik + Sheet Books to PDF... Knjige listova u PDF... + Show grips Prikaži hvataljke + Specified origin Navedeno ishodište + Spherical Sferno + Tables Tabele + This drawing Ovaj crtež + Top left Gore lijevo + Top right Gore desno + Unsaved changes Nesačuvane promjene + Use current origin Koristi trenutno ishodište + Visual Effect Settings Postavke vizuelnih efekata + Visual Effect Settings... Postavke vizuelnih efekata... + When a command is active Kad je naredba aktivna + When no command is active Kad nijedna naredba nije aktivna + Window selection color: Boja odabira prozorom: + Xrefs Vanjske reference + Arrow size Veličina strelice + Dim scale overall Ukupna skala kote + Precision Preciznost + Break-line Symbol Simbol linije prekida + Convert Text to Mtext Pretvori tekst u višeredni tekst + Explode Attributes to Text Rastavi atribute u tekst + Express Tools Express alati + Move/Copy/Rotate Pomjeri/kopiraj/rotiraj + Type an alias name. Unesite naziv aliasa. + Choose the command the alias starts. Odaberite naredbu koju alias pokreće. + {command} is an unknown command. {command} je nepoznata naredba. + {alias} is already defined; select it and use Edit. {alias} je već definisan; odaberite ga i koristite Uredi. + More than {n} aliases. Više od {n} aliasa. + Alias file: {file} Datoteka aliasa: {file} + No alias file loaded. REINIT replaces these aliases with a file's. Nije učitana datoteka aliasa. REINIT zamjenjuje ove aliase onima iz datoteke. + Alias Alias + Command Naredba + overrides built-in zamjenjuje ugrađeni + built-in ugrađeni + Add… Dodaj… + Edit… Uredi… + Save alias Sačuvaj alias + Discard Odbaci + Customize Prilagodi + Edit Command Aliases (PGP)... Uredi aliase naredbi (PGP)... + Interface scale Skala interfejsa + Select boundaries to remove Odaberite granice za uklanjanje + Island Ostrvo + Select using two clicks only Odabir samo s dva klika + Define each corner of the selection window with a separate click. Definišite svaki ugao prozora za odabir posebnim klikom. + Apply to Layout Primijeni na raspored + Center the plot Centriraj iscrtavanje + Enter block names to extract Unesite nazive blokova za izdvajanje + Enter geometric characteristic Unesite geometrijsku karakteristiku + Enter name of LISP file to load Unesite naziv LISP datoteke za učitavanje + First corner Prvi ugao + Fit to paper Uklopi na papir + Landscape Položeno + Limits Granice + Opposite corner Suprotni ugao + Orientation Orijentacija + Paper size Veličina papira + Plot area Oblast iscrtavanja + Plot object lineweights Iscrtaj debljine linija objekata + Plot offset Pomak iscrtavanja + Plot transparency Iscrtaj prozirnost + Portrait Uspravno + Printer/plotter Štampač/ploter + Window < Prozor < + X offset (mm) X pomak (mm) + Y offset (mm) Y pomak (mm) + AutoLISP (LSP) AutoLISP (LSP) + Units of new drawings Jedinice novih crteža + Imperial (inches) Imperijalne (inči) + Metric (millimetres) Metričke (milimetri) + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). Novi i prvi crtež pri pokretanju koriste ove jedinice osim ako je postavljen zadani šablon (QNEWTEMPLATE). + Analyze Usage Analiziraj upotrebu + Implied Loops Implicirane petlje + Angstroms Angstremi + Architectural Arhitektonske + Astronomical Units Astronomske jedinice + Centimeters Centimetri + Decameters Dekametri + Decimal Decimalne + Decimal Degrees Decimalni stepeni + Decimeters Decimetri + Deg/Min/Sec Step/Min/Sek + Don't Save Nemoj sačuvati + Drawing Units Jedinice crteža + Engineering Inženjerske + Feet Stope + Fractional Razlomačke + Gigameters Gigametri + Grads Gradi + Hectometers Hektometri + Inches Inči + Insertion scale Skala umetanja + Kilometers Kilometri + Light Years Svjetlosne godine + Meters Metri + Microinches Mikroinči + Microns Mikroni + Miles Milje + Millimeters Milimetri + Mils Milsi + Nanometers Nanometri + Parsecs Parseci + Radians Radijani + Sample output Primjer izlaza + Save changes to {name}? Sačuvati promjene u {name}? + Scientific Naučne + Surveyor's Units Geodetske jedinice + Unitless Bez jedinica + Units to scale inserted content Jedinice za skaliranje umetnutog sadržaja + US Survey Feet Američke geodetske stope + US Survey Inch Američki geodetski inč + US Survey Mile Američka geodetska milja + US Survey Yard Američki geodetski jard + Yards Jardi + Your changes will be lost if you don't save them. Vaše promjene će biti izgubljene ako ih ne sačuvate. + Save changes to block "{name}"? Sačuvati promjene u bloku „{name}”? + Layouts Rasporedi + Associate Poveži diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0e1e23e19..6bf85f2c3 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -186,6 +186,7 @@ fn assert_additional_locale_aliases() { ("sv", &["sv", "sv-SE", "sv_SE.UTF-8", "SV-se", " sv-SE ", "sv-FI"]), ("hu", &["hu", "hu-HU", "hu_HU.UTF-8", "HU-hu", " hu-HU "]), ("tr", &["tr", "tr-TR", "tr_TR.UTF-8", "TR-tr", " tr-TR ", "tr-CY"]), + ("bs", &["bs", "bs-BA", "bs_BA.UTF-8", "BS-ba", " bs-BA ", "bs-Latn-BA"]), ("el", &["el", "el-GR", "el_GR.UTF-8", "EL-cy"]), ("zh", &["zh", "zh-CN"]), ] { @@ -556,3 +557,12 @@ fn production_font_chain_covers_latin_and_shortcut_symbols() { assert!(view.has_glyph(&egui::FontId::monospace(12.0), '\u{21e7}'), "U+21E7 shift symbol missing in Monospace"); }); } + +/// Bosnian counts: 1, 21 `one`; 2–4, 22–24 (not 12–14) `few`; everything else `other`. +#[test] +fn bosnian_counts_take_one_few_other() { + let forms: Vec = [0, 1, 2, 4, 5, 11, 12, 14, 21, 22, 25, 111].into_iter().map(plural_uk).collect(); + assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 0, 1, 2, 2]); + assert_eq!(Preference::parse("bs"), Some(Preference::Bosnian)); + assert_eq!(Preference::Bosnian.native_name(), "Bosanski"); +} diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index 8bf147bcf..4c7cf6b1f 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.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"`, `"bs"` or `"el"` | //! | `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 b4ff05f68..ff44de470 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-22 · **Change:** minor (the command line enables the OS IME and handles composition/commit, so single-line TEXT edits accept CJK input; previously: Brazilian Portuguese row updated and terminology reviewed; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (Bosnian added; previously minor: the command line enables the OS IME and handles composition/commit, so single-line TEXT edits accept CJK input; previously: Brazilian Portuguese row updated and terminology reviewed; 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). @@ -74,9 +74,10 @@ plus native review by a human; extending the catalog to the remaining English-on | 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 | | 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 | -Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian and Turkish. -Czech, Swedish, Hungarian and Brazilian Portuguese cover the reference catalog and every marked UI literal; engine diagnostics and uncatalogued text +Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian, Turkish and Bosnian. +Czech, Swedish, Hungarian, Brazilian Portuguese and Bosnian (1,442 rows, AI-assisted, not yet native-reviewed) 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. @@ -89,6 +90,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-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 | From 8d1bd19ee29aa3a7f7d8730214fa8d6b90a4e7a6 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Sat, 31 Oct 2026 01:46:34 +0600 Subject: [PATCH 234/900] Save As suggests the default save format for opened drawings too (#2199) (#2509) * Save As suggests the default save format for opened drawings too (#2199) Options > Open and Save > "Save as" in AutoCAD is the format every drawing is saved in. CADCraft applied File > Default Save Format only to untitled drawings, so Save As on an opened DWG kept DWG with DXF chosen, and the other way round. Save As now swaps a DWG, DXF or DWT extension for the chosen format; other names, and Save of an opened file, are unchanged. Co-Authored-By: Claude Opus 5.5 * Default Save Format's echo says Save As will suggest the format (#2199) "Save As will save drawings as DWG" promised more than Save As does: it only swaps a DWG, DXF or DWT extension in the name it suggests, and the path picked in the dialog decides the format. The echo now reads "Save As will suggest DWG", and default_save_format_applies_to_opened_drawings pins it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 36 ++++++++++++++++++---------- crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/tests/save_version.rs | 34 ++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 311dd4cbf..91902017f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -118,7 +118,7 @@ pub struct UiState { /// Animation effects (dialog and menu fades, smoothed scrolling): "system" (follow the OS /// setting), "on" or "off". pub animations: animation::AnimationPref, - /// The format Save As suggests for a drawing that has no file yet: "dxf" or "dwg". + /// The format Save As suggests: "dxf" or "dwg", for new drawings and opened files alike. pub save_format: SaveFormat, /// The version Save As writes for a drawing that has no file yet ("2000" … "2018"); a /// drawing opened from a file keeps that file's version. @@ -132,8 +132,8 @@ pub struct UiState { /// A DXF/DWG file version (2000 … 2018). pub use cadcraft_engine::cmd::file::Version as SaveVersion; -/// The default save format for new drawings, like AutoCAD's Options > Open and Save > "Save as". -/// A drawing opened from a file keeps that file's format. +/// The default save format, like AutoCAD's Options > Open and Save > "Save as": the format Save As +/// suggests for every drawing, an opened DWG or DXF too. Save (QSAVE) of an opened file keeps its file. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SaveFormat { @@ -158,13 +158,19 @@ impl SaveFormat { SaveFormat::ALL.into_iter().find(|f| f.as_str().eq_ignore_ascii_case(s.trim().trim_start_matches('.'))) } - /// The name Save As suggests: a title that already has an extension (a drawing opened from a - /// file) keeps it; an untitled drawing gets this format's extension. + /// The name Save As suggests: this format's extension, replacing a drawing's own (DWG, DXF or + /// DWT, from a drawing opened from a file); any other extension is kept. pub fn suggested_name(self, title: Option<&str>) -> String { - match title.map(str::trim).filter(|t| !t.is_empty()) { - Some(t) if std::path::Path::new(t).extension().is_some() => t.to_owned(), - Some(t) => format!("{t}.{}", self.as_str()), - None => format!("Drawing.{}", self.as_str()), + let Some(t) = title.map(str::trim).filter(|t| !t.is_empty()) else { return format!("Drawing.{}", self.as_str()) }; + let path = std::path::Path::new(t); + match path.extension().and_then(|e| e.to_str()) { + Some(e) if ["dwg", "dxf", "dwt"].iter().any(|d| d.eq_ignore_ascii_case(e)) => { + // the extension is ASCII, so this is a char boundary + let stem = t.get(..t.len().saturating_sub(e.len() + 1)).unwrap_or(t); + format!("{stem}.{}", self.as_str()) + } + Some(_) => t.to_owned(), + None => format!("{t}.{}", self.as_str()), } } } @@ -1142,11 +1148,17 @@ mod tests { b.start("ui.saveformat.dwg"); b.start("ui.resetpalettes"); assert_eq!(b.ui.save_format, SaveFormat::Dwg); - // Untitled drawings get the format's extension; files keep their own. + // Untitled drawings get the format's extension, and so do opened drawings (#2199). assert_eq!(SaveFormat::Dwg.suggested_name(Some("Drawing1")), "Drawing1.dwg"); assert_eq!(SaveFormat::Dxf.suggested_name(Some("Drawing1")), "Drawing1.dxf"); - assert_eq!(SaveFormat::Dwg.suggested_name(Some("Floorplan.dxf")), "Floorplan.dxf"); - assert_eq!(SaveFormat::Dxf.suggested_name(Some("Floorplan.DWG")), "Floorplan.DWG"); + assert_eq!(SaveFormat::Dwg.suggested_name(Some("Floorplan.dxf")), "Floorplan.dwg"); + assert_eq!(SaveFormat::Dxf.suggested_name(Some("Floorplan.DWG")), "Floorplan.dxf"); + assert_eq!(SaveFormat::Dxf.suggested_name(Some("Floorplan.dxf")), "Floorplan.dxf"); + assert_eq!(SaveFormat::Dwg.suggested_name(Some("Title block.dwt")), "Title block.dwg"); + assert_eq!(SaveFormat::Dwg.suggested_name(Some("v1.2 plan.Dxf")), "v1.2 plan.dwg"); + assert_eq!(SaveFormat::Dwg.suggested_name(Some("平面図.dxf")), "平面図.dwg"); + assert_eq!(SaveFormat::Dwg.suggested_name(Some(".dxf")), ".dxf.dwg", "a dot file has no extension"); + assert_eq!(SaveFormat::Dxf.suggested_name(Some("logo.svg")), "logo.svg", "other files keep their type"); assert_eq!(SaveFormat::Dwg.suggested_name(None), "Drawing.dwg"); assert_eq!(SaveFormat::Dwg.suggested_name(Some(" ")), "Drawing.dwg"); let ui: UiState = serde_json::from_value(json!({ "saveFormat": "dwg" })).unwrap_or_default(); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 58055542f..797952edf 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -520,7 +520,7 @@ fn saveas_params(ui: &crate::UiState, session: &cadcraft_engine::Session, path: fn set_save_format(app: &mut CadApp, format: crate::SaveFormat) -> Value { app.ui.save_format = format; - app.session.echo(format!("New drawings will be saved as {}", format.as_str().to_ascii_uppercase())); + app.session.echo(format!("Save As will suggest {}", format.as_str().to_ascii_uppercase())); json!({ "saveFormat": format.as_str() }) } diff --git a/crates/ui-egui/tests/save_version.rs b/crates/ui-egui/tests/save_version.rs index 47b716b89..402c43623 100644 --- a/crates/ui-egui/tests/save_version.rs +++ b/crates/ui-egui/tests/save_version.rs @@ -44,3 +44,37 @@ fn default_save_version_applies_to_new_drawings_and_persists() { b.start("ui.resetpalettes"); assert_eq!(b.ui.save_version, "2004"); } + +/// The default save format (#2199) is what Save As suggests for an opened DWG or DXF too, as +/// AutoCAD's Options > Open and Save > "Save as" does; Save keeps the opened file. +#[test] +fn default_save_format_applies_to_opened_drawings() { + set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(b"plain".to_vec()), plot: None }); + set_write_as(with_options); + let dir = std::env::temp_dir().join(format!("cadcraft-ui-save-format-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let suggested = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let (seen, to) = (suggested.clone(), dir.clone()); + let pick = move |name: &str| { + seen.lock().unwrap().push(name.to_string()); + Some(to.join(name).to_string_lossy().to_string()) + }; + let mut app = CadApp::new(Session::empty(), Services { pick_save: Some(Box::new(pick)), ..Services::default() }); + for (opened, format, expected) in + [("Plan.dwg", "dxf", "Plan.dxf"), ("Plan.DXF", "dwg", "Plan.dwg"), ("Plan.dxf", "dxf", "Plan.dxf"), ("Sheet.dwt", "dwg", "Sheet.dwg")] + { + let file = dir.join(opened); + std::fs::write(&file, b"0\nEOF\n").unwrap(); + app.run("open", json!({ "path": file.to_string_lossy() })).unwrap(); + app.run("ui.saveformat", json!({ "format": format })).unwrap(); + // the picker's path decides the format, so the echo promises only the suggestion + let echo = format!("Save As will suggest {}", format.to_ascii_uppercase()); + assert_eq!(app.session.log.last(), Some(&echo), "{opened} with {format}"); + app.run("ui.saveas", Value::Null).unwrap(); + assert_eq!(suggested.lock().unwrap().last().map(String::as_str), Some(expected), "{opened} with {format}"); + let path = app.session.state().unwrap().path.clone().unwrap_or_default(); + assert!(path.ends_with(expected), "{opened}: saved as {path}"); + assert!(dir.join(expected).exists()); + } + let _ = std::fs::remove_dir_all(&dir); +} From 8038de04e4650d1ee3a383ff6bfc8126e9a5a61f Mon Sep 17 00:00:00 2001 From: assamaral Date: Fri, 30 Oct 2026 17:35:29 -0300 Subject: [PATCH 235/900] fix(io): an MTEXT with columns takes its width from the column groups ZWCAD and AutoCAD write the total width of the columns in the entity's group 41 and the column width in the embedded object's 44 (48 of the legacy groups). `mtext_from` took 41 whenever it was positive, so a three-column MTEXT of 50 came back 175 wide and the R2018 object was written with 44 = 175, 42 = 550. With columns and a positive column width, that width is the MTEXT's (it is one column's throughout). Review of #2467. Co-Authored-By: Claude Fable 5.1 --- crates/io/src/dxf_read/text.rs | 4 +++- crates/io/tests/it/mtext_columns_roundtrip.rs | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_read/text.rs b/crates/io/src/dxf_read/text.rs index 158015169..492825df7 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -76,8 +76,10 @@ pub(super) fn mtext_from(tags: &[Tag], c: &Common) -> MText { MText { insert: t.p(10), height: t.fd(40, 0.2).max(1e-9), + // An MTEXT's width is one column's: with columns, the column width (48, or 44 of the + // embedded object) rather than 41, which ZWCAD and AutoCAD write as the total width. width: match &columns { - Some((_, w)) if t.fd(41, 0.0) <= 0.0 => *w, + Some((_, w)) if *w > 0.0 => *w, _ => t.fd(41, 0.0).max(0.0), }, attach, diff --git a/crates/io/tests/it/mtext_columns_roundtrip.rs b/crates/io/tests/it/mtext_columns_roundtrip.rs index b147f311e..be8ac1088 100644 --- a/crates/io/tests/it/mtext_columns_roundtrip.rs +++ b/crates/io/tests/it/mtext_columns_roundtrip.rs @@ -232,3 +232,22 @@ fn dynamic_auto_height_count_comes_from_the_widths_when_72_is_zero() { let c = t.columns.expect("columns"); assert_eq!((c.kind, c.auto_height, c.count), (MTextColumnType::Dynamic, true, 3)); } + +#[test] +fn embedded_column_width_wins_over_the_entitys_width() { + // ZWCAD (and AutoCAD) write the total width of the columns in the entity's 41 and the column + // width in the object's 44: an MTEXT's `width` is one column's, so 44 is what is read, and + // what the R2018 object gets back (#2467 review). + let mut tags = embedded_tags(3, 50.0, 12.5, &[20.0, 20.0, 20.0]); + let own_41 = tags.iter().position(|t| t.code == 41).unwrap(); + tags[own_41] = cadcraft_dxf::Tag::f(41, 175.0); + for code in [40, 42] { + let at = tags.iter().rposition(|t| t.code == code).unwrap(); + tags[at] = cadcraft_dxf::Tag::f(code, 175.0); + } + let (_, t) = mtext_from_groups(&tags); + assert_eq!(t.width, 50.0, "the column width, not the total"); + let (_, r2018) = dxf_as(&t, Version::R2018); + assert!(r2018.contains(" 42\r\n175.0\r\n"), "total width kept:\n{r2018}"); + assert!(r2018.contains(" 44\r\n50.0\r\n 45\r\n12.5\r\n"), "column width and gutter kept:\n{r2018}"); +} From ba3196e3f737f2fed0d4d8ae9c065b20773dec16 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 30 Oct 2026 20:12:28 -0400 Subject: [PATCH 236/900] fix(flatpak): allow reading launcher version pins (#2515) * fix(flatpak): allow reading launcher version pins * fix(flatpak): allow reading launcher version pins --- packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml | 1 + packaging/linux/flatpak/ai.storyteller.cadcraft.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml index 651b9a358..448ba058d 100644 --- a/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.cadcraft.bundle.yml @@ -17,6 +17,7 @@ runtime-version: '26.08' sdk: org.freedesktop.Sdk command: cadcraft finish-args: + - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 diff --git a/packaging/linux/flatpak/ai.storyteller.cadcraft.yml b/packaging/linux/flatpak/ai.storyteller.cadcraft.yml index 88a49e136..e4b19cb81 100644 --- a/packaging/linux/flatpak/ai.storyteller.cadcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.cadcraft.yml @@ -18,6 +18,7 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: cadcraft finish-args: + - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 From 66f65b763e579502ca61cf8e913d8e2f263487ba Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 31 Oct 2026 04:38:42 +0400 Subject: [PATCH 237/900] 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 238/900] 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 282ad11e60f22d4d7bc93d300eeff985a508df8a Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 12:28:21 +1100 Subject: [PATCH 239/900] Save note: a DWG loses SAT-text solids from 2013 on, and the note says so (#2334) A real DWG write and read-back keeps a SAT-text REGION's groups up to 2010 and returns it without them at 2013 and 2018, so the SAT-text skip in not_saved_as applies before 2013 only. The DWG note now says solids are kept in a DXF only when saved as 2010 or earlier. --- crates/engine/src/cmd/file.rs | 11 ++++++---- crates/engine/tests/save_reports_not_saved.rs | 14 ++++++------- crates/io/tests/it/acis_data_store.rs | 21 +++++++++++++++++++ 3 files changed, 35 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 0bccbfb4f..683bd26f8 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -550,10 +550,10 @@ 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 { - // A DWG writer converts SAT text to its own form at any version, and from 2013 a data - // store record keeps the geometry too: neither loses the solid. + // A DWG before 2013 writes a solid's SAT text as it is; from 2013 the geometry has to be + // in the data store, and SAT text alone is lost (#2334). if MODELER_TYPES.iter().any(|t| u.dxf_type.eq_ignore_ascii_case(t)) - && (stored.contains(&e.handle) || cadcraft_doc::foreign::has_sat_text(&u.tags)) + && (stored.contains(&e.handle) || (version < Version::R2013 && cadcraft_doc::foreign::has_sat_text(&u.tags))) { continue; } @@ -570,7 +570,10 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap) -> Op return None; } let list: Vec = lost.iter().map(|(t, n)| format!("{n} {t}")).collect(); - Some(format!("Not saved in the DWG file (its writer can't write these object types yet; DXF keeps them): {}", list.join(", "))) + Some(format!( + "Not saved in the DWG file (its writer can't write these object types yet; DXF keeps them, solids only when saved as 2010 or earlier): {}", + list.join(", ") + )) } /// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index d50b1a503..295877d5c 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -29,7 +29,7 @@ fn save_lists_the_entities_the_file_does_not_keep() { let r = s.execute("saveas", &json!({ "path": path.to_string_lossy() })).unwrap(); let _ = std::fs::remove_file(&path); assert_eq!(r["notSaved"], json!({ "3DSOLID": 1, "MLINE": 2, "REGION": 1 })); - let msg = "Not saved in the DWG file (its writer can't write these object types yet; DXF keeps them): 1 3DSOLID, 2 MLINE, 1 REGION"; + let msg = "Not saved in the DWG file (its writer can't write these object types yet; DXF keeps them, solids only when saved as 2010 or earlier): 1 3DSOLID, 2 MLINE, 1 REGION"; assert!(s.log.iter().any(|l| l == msg), "{:?}", s.log); // DXF keeps them. @@ -145,17 +145,17 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() { assert_eq!(r["notSaved"], json!({ "REGION": 1 })); } -/// A DWG writer converts a solid's SAT text itself (at any version), so a DWG save doesn't list -/// solids that hold it as left out; ones with neither SAT text nor a data store record are (#2334). +/// A DWG before 2013 writes a solid's SAT text as it is, so a save there doesn't list a solid that +/// holds it; from 2013 the geometry must be in the data store and SAT text alone is lost, so the +/// save lists it. A solid with neither is always listed (#2334). #[test] -fn a_dwg_keeps_solids_that_hold_sat_text() { +fn a_dwg_keeps_sat_text_solids_only_before_2013() { use cadcraft_engine::cmd::file::{Version, not_saved_as}; let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; let solid = |tags: Vec| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags }); let mut d = Drawing::new_imperial(); d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 1 1 0")])).unwrap(); d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap(); - for v in [Version::R2010, Version::R2018] { - assert_eq!(not_saved_as(&d, v), [("3DSOLID".to_string(), 1)].into_iter().collect(), "{v:?}"); - } + assert_eq!(not_saved_as(&d, Version::R2010), [("3DSOLID".to_string(), 1)].into_iter().collect(), "2010 keeps the SAT-text solid"); + assert_eq!(not_saved_as(&d, Version::R2018), [("3DSOLID".to_string(), 2)].into_iter().collect(), "2018 loses it"); } diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index 5bb4bc8ee..f0ad2039c 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -196,3 +196,24 @@ fn a_data_store_record_stores_only_its_first_entity() { let store = Foreign { data_store: vec![tag(0, "ACDSRECORD"), tag(320, "2B"), tag(320, "2C"), tag(2, "ASM_Data")], ..Foreign::default() }; assert_eq!(store.data_store_entities(), [Handle(0x2B)].into()); } + +/// A real DWG round trip of a SAT-text REGION: the DWG writer keeps the SAT groups up to 2010, and +/// from 2013 they come back empty (the solid's geometry is not in the file), which the DWG save +/// note has to say (#2334). +#[test] +fn a_dwg_keeps_a_sat_text_region_only_before_2013() { + let sat = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n\ + 0\nREGION\n5\n2B\n100\nAcDbEntity\n8\n0\n100\nAcDbModelerGeometry\n70\n1\n1\n400 1 1 0\n3\nEnd-of-ACIS-data\n0\nENDSEC\n0\nEOF\n"; + let d = cadcraft_io::read_dxf(sat.as_bytes()).unwrap(); + let holds_sat = |v: cadcraft_io::Version| { + let dwg = cadcraft_io::write_with(&d, "x.dwg", &cadcraft_io::SaveOptions { version: Some(v), binary: false }).unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + let region = back.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) if u.dxf_type == "REGION" => Some(u.clone()), + _ => None, + }); + region.is_some_and(|u| cadcraft_doc::foreign::has_sat_text(&u.tags)) + }; + assert!(holds_sat(cadcraft_io::Version::R2010), "2010 keeps the SAT text"); + assert!(!holds_sat(cadcraft_io::Version::R2018), "2018 comes back without it"); +} From 57e6a89d10a8bff40391fcfa0a697d71ea8ab26d Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 12:31:34 +1100 Subject: [PATCH 240/900] 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 5f6dbede5ca24082119edf164286b500519e7cea Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 31 Oct 2026 06:00:43 +0400 Subject: [PATCH 241/900] 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 04e74a165c12dd99c51a4feffa179c59cc672e69 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 30 Oct 2026 19:10:52 -0700 Subject: [PATCH 242/900] Panic hunt covers every command, and a panic after a command restores the drawing (#2517) panic_hunt runs every command in a fresh session and fails on real panics. The guard now covers the steps after a command, so a late panic restores the drawing instead of ending the app. --- AGENTS.md | 4 +- CLAUDE.md | 4 +- crates/engine/src/guard.rs | 43 +++++++- crates/engine/src/session/execute.rs | 20 ++++ crates/engine/src/session/interactive.rs | 16 +++ crates/engine/src/tests.rs | 19 ---- crates/engine/tests/panic_hunt.rs | 126 +++++++++++++++++++++++ 7 files changed, 208 insertions(+), 24 deletions(-) create mode 100644 crates/engine/tests/panic_hunt.rs diff --git a/AGENTS.md b/AGENTS.md index e3d7418d7..657e57dec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,8 +17,8 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - **Errors are `Result`** through the crate's error type and `?`. An unfinished feature returns an error or reports "not available yet"; it never panics. - **Input-derived numbers are hostile** (DXF/DWG files, command-line text, MCP/control params): `get()` not `[i]`, checked arithmetic, no NaN casts, cap input-sized allocations and loop counts. - **Bound recursion** (nested/cyclic block references: `MAX_BLOCK_DEPTH`). -- **Last-resort guard:** `Session::execute` and every step of an interactive command (its factory, `begin`, input, `prompt` and `preview`; `crates/engine/src/guard.rs`) run under `catch_unwind`; an escaped panic restores the drawing and reports an error. -- **Prove it:** every crash fix lands with a regression test (see `hostile_params_never_panic`, `hostile_dxf_does_not_panic`). +- **Last-resort guard:** `Session::execute` and every step of an interactive command (its factory, `begin`, input, `prompt`, `preview` and the passes after it; `crates/engine/src/guard.rs`) run under `catch_unwind`; an escaped panic restores the drawing and reports an error. It does nothing on wasm, where a panic aborts. +- **Prove it:** every crash fix lands with a regression test (see `crates/engine/tests/panic_hunt.rs` and `hostile_dxf_does_not_panic` in `crates/io/src/tests.rs`). - Every workspace crate manifest carries `[lints] workspace = true` to inherit `[workspace.lints]`; every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. ## Non-negotiables diff --git a/CLAUDE.md b/CLAUDE.md index 8e4a1fdfa..964a00124 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,8 +17,8 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - **Errors are `Result`** through the crate's error type and `?`. An unfinished feature returns an error or reports "not available yet"; it never panics. - **Input-derived numbers are hostile** (DXF/DWG files, command-line text, MCP/control params): `get()` not `[i]`, checked arithmetic, no NaN casts, cap input-sized allocations and loop counts. - **Bound recursion** (nested/cyclic block references: `MAX_BLOCK_DEPTH`). -- **Last-resort guard:** `Session::execute` and every step of an interactive command (its factory, `begin`, input, `prompt` and `preview`; `crates/engine/src/guard.rs`) run under `catch_unwind`; an escaped panic restores the drawing and reports an error. -- **Prove it:** every crash fix lands with a regression test (see `hostile_params_never_panic`, `hostile_dxf_does_not_panic`). +- **Last-resort guard:** `Session::execute` and every step of an interactive command (its factory, `begin`, input, `prompt`, `preview` and the passes after it; `crates/engine/src/guard.rs`) run under `catch_unwind`; an escaped panic restores the drawing and reports an error. It does nothing on wasm, where a panic aborts. +- **Prove it:** every crash fix lands with a regression test (see `crates/engine/tests/panic_hunt.rs` and `hostile_dxf_does_not_panic` in `crates/io/src/tests.rs`). - Every workspace crate manifest carries `[lints] workspace = true` to inherit `[workspace.lints]`; every production crate root carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`. ## Non-negotiables diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 8a64e2b74..799b7046d 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -105,10 +105,51 @@ impl Interactive for Guarded { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::Running; + thread_local! { + static PANIC_AFTER_COMMAND: Cell = const { Cell::new(false) }; + } + + /// Called at the start of the passes after a command, which nothing can make panic on demand. + pub(crate) fn panic_if_armed() { + assert!(!PANIC_AFTER_COMMAND.get(), "a pass after the command panicked"); + } + + /// A panic in the passes after a JSON command: an error, and the drawing as it was. + #[test] + fn a_panic_after_a_command_restores_the_drawing() { + let mut s = Session::new(); + s.execute("line", &serde_json::json!({"points": [[0, 0], [1, 0]]})).unwrap(); + let undo = s.state().unwrap().undo.len(); + PANIC_AFTER_COMMAND.set(true); + let r = s.execute("circle", &serde_json::json!({"center": [0, 0], "radius": 1})); + PANIC_AFTER_COMMAND.set(false); + assert!(matches!(&r, Err(EngineError::Internal(id, m)) if id == "circle" && m.contains("after the command")), "{r:?}"); + assert_eq!(points(&s), 1, "the circle is gone with the failed command"); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step for it"); + s.execute("circle", &serde_json::json!({"center": [0, 0], "radius": 1})).unwrap(); + assert_eq!(points(&s), 2, "the session still works"); + } + + /// The same at the end of an interactive command, where nothing returns the error to a caller. + #[test] + fn a_panic_after_an_interactive_command_restores_the_drawing() { + let mut s = Session::new(); + s.cmdline("line 0,0 1,0").unwrap(); + PANIC_AFTER_COMMAND.set(true); + let r = s.input(Input::Enter); + PANIC_AFTER_COMMAND.set(false); + assert!(r.is_ok(), "{r:?}"); + assert!(s.running.is_none()); + assert_eq!(points(&s), 0, "the drawing is restored"); + assert!(s.log.iter().any(|l| l.contains("Internal error in line")), "{:?}", s.log); + s.cmdline("line 0,0 1,0").unwrap(); + assert!(s.running.is_some(), "the session still works"); + } + fn dot(p: Vec2) -> EntityKind { EntityKind::Point(cadcraft_doc::Point { p: p.to3(0.0), angle: 0.0 }) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 7b0547404..a4c57eec5 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -4,7 +4,27 @@ impl Session { // ---------------- programmatic execution ---------------- /// Run a command with JSON parameters (no dialogs). Records undo when the drawing changes. + /// + /// The command itself is guarded below, where its own panic can be told apart. This guard is + /// for everything around it: the passes after a command (constraints, associativity, groups) + /// are as able to panic as the command, and a panic there restores the drawing the same way. pub fn execute(&mut self, id: &str, params: &Value) -> Result { + let before = self.state().ok().map(|s| (s.doc.clone(), s.selection.clone(), s.uid)); + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.execute_guarded(id, params))) { + Ok(r) => r, + Err(p) => { + if let Some((doc, sel, uid)) = before + && let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) + { + st.doc = doc; + st.selection = sel; + } + Err(EngineError::Internal(id.into(), crate::guard::message(&*p))) + } + } + } + + fn execute_guarded(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; (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) { diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 13d944d63..d90c91683 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -341,7 +341,21 @@ impl Session { } } + /// End a command: every way out of one comes through here. The passes after a command + /// (constraints, associativity, groups) can panic like the command itself; a panic restores + /// the drawing as it was before the command, as a panic in its `input` does. fn finish(&mut self, run: Running, cancelled: bool) { + let (id, before, selection) = (run.id.clone(), run.before.clone(), run.selection_before.clone()); + if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.finish_guarded(run, cancelled))) { + if let Ok(st) = self.state_mut() { + st.doc = before; + st.selection = selection; + } + self.echo(format!("Internal error in {id}: {}", crate::guard::message(&*p))); + } + } + + fn finish_guarded(&mut self, run: Running, cancelled: bool) { // A typed selection mode or SIngle never outlives its command. self.select_mode = None; self.select_single = false; @@ -391,6 +405,8 @@ impl Session { /// started in, so associativity is not applied across a document switch; `ok` is false for a /// failed or non-undoable programmatic command, which skips the constraint pass. pub(super) fn after_command(&mut self, before: Option<&Arc>, uid: Option, ok: bool) { + #[cfg(test)] + crate::guard::tests::panic_if_armed(); cmd::groups::after_command(self, before); cmd::constraints::after_command(self, before, ok); assoc::after_command(self, before, uid); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 427bfe8d4..1f3d0e8e1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -700,25 +700,6 @@ fn cancel_keeps_partial_line_as_one_undo() { assert_eq!(s.doc().unwrap().model.len(), 0); } -#[test] -fn hostile_params_never_panic() { - let mut s = Session::new(); - for c in command_specs() { - for p in [ - json!(null), - json!([]), - json!("x"), - json!({"points": [[1e308, -1e308], ["a"]]}), - json!({"handles": ["zz", 99999]}), - json!({"radius": -1, "center": [0, 0]}), - json!({"gradient": {"name": 5, "color1": [1], "angle": "x", "centered": "y"}}), - json!({"points": [[0, 0]], "handles": ["1"], "gradient": "x", "name": "RAINBOW"}), - ] { - let _ = s.execute(c.id, &p); - } - } -} - #[test] fn every_interactive_command_starts_and_cancels() { for c in command_specs().iter().filter(|c| c.interactive.is_some()) { diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs new file mode 100644 index 000000000..a42e48278 --- /dev/null +++ b/crates/engine/tests/panic_hunt.rs @@ -0,0 +1,126 @@ +//! Fuzz every registered command with adversarial params: a command must return `Err`, never panic +//! or hang. Each call gets a fresh, populated session on its own thread with a deadline, so one bad +//! command can't change what the next one sees or wedge the run. +//! +//! `Session::execute` contains a command's panic and returns an ordinary `Err`, so looking at the +//! result can't find one, and neither can `catch_unwind` here. A panic hook counts them instead, +//! on whichever thread they happen. `contained_panics_count_and_graceful_errors_do_not` proves it. + +use cadcraft_engine::{Session, command_specs}; +use serde_json::{Value, json}; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, Once, PoisonError, mpsc}; +use std::time::Duration; + +/// A drawing with something to act on, so commands reach their real work: with nothing in it most +/// of them stop at "nothing to do", and with no drawing at all they don't run. +fn fresh() -> Session { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0], [10, 10]]})).unwrap(); + s.execute("circle", &json!({"center": [5, 5], "radius": 2})).unwrap(); + s +} + +/// Wall-clock budget for one command on the small drawing. Real work takes milliseconds, so this +/// only catches hangs and work that grows with a number in the params. +const DEADLINE: Duration = Duration::from_secs(4); + +/// Budget for the self-test, which checks how panics are counted: the hook prints a backtrace +/// under `RUST_BACKTRACE=1`, and the first symbol lookup can be slow on a loaded runner. +const SELF_TEST_DEADLINE: Duration = Duration::from_secs(120); + +/// Panics anywhere in the process, counted by a hook. +static PANICS: AtomicUsize = AtomicUsize::new(0); +/// One run at a time, so a panic is charged to the run that caused it. +static RUN: Mutex<()> = Mutex::new(()); + +/// Run `f` on a worker thread. `None` if it took longer than `deadline`, else whether it finished +/// without panicking, contained or not (returning `Ok` or a graceful `Err` both count). +fn run_watched(deadline: Duration, f: impl FnOnce() + Send + 'static) -> Option { + static HOOK: Once = Once::new(); + HOOK.call_once(|| { + let default = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + PANICS.fetch_add(1, Ordering::SeqCst); + default(info); + })); + }); + let _one = RUN.lock().unwrap_or_else(PoisonError::into_inner); + let before = PANICS.load(Ordering::SeqCst); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let r = catch_unwind(AssertUnwindSafe(f)); + let _ = tx.send(r.is_ok()); + }); + rx.recv_timeout(deadline).ok().map(|ok| ok && PANICS.load(Ordering::SeqCst) == before) +} + +fn run_once(id: &str, p: &Value) -> Option { + let (id, p) = (id.to_string(), p.clone()); + run_watched(DEADLINE, move || { + let mut s = fresh(); + let _ = s.execute(&id, &p); + }) +} + +/// `Err` with a reason on a panic or a hang. A real hang reproduces and one-time setup (the first +/// font scan) doesn't, so a timeout counts only if a rerun on a fresh session times out too. +fn run_guarded(id: &str, p: &Value) -> Result<(), String> { + match run_once(id, p).or_else(|| run_once(id, p)) { + Some(true) => Ok(()), + Some(false) => Err("panicked".into()), + None => Err(format!("hung (>{}s, twice)", DEADLINE.as_secs())), + } +} + +/// Shapes and sizes a hostile script, drawing or agent could send. No param names a real path: +/// the hunt must not write files. +fn adversarial() -> Vec { + let long = "x".repeat(100_000); + vec![ + json!(null), + json!({}), + json!([]), + json!("x"), + json!({"points": [[1e308, -1e308], ["a"]], "handles": ["zz", 99999]}), + json!({"points": [], "handles": [], "center": [], "from": [], "to": [], "name": "", "layer": "", "style": "", "text": ""}), + json!({"center": [1e308, 1e308], "radius": 1e308, "angle": 1e308, "scale": 1e308, "height": 1e308, "width": 1e308, "distance": 1e308}), + json!({"center": [0, 0], "radius": -1, "angle": -1e308, "scale": 0, "height": 0, "width": 0, "distance": -1, "factor": 0}), + json!({"count": 1e9, "rows": 1e9, "columns": 1e9, "levels": 1e9, "items": 1e9, "sides": 1e9, "segments": 1e9, "index": 1e9}), + json!({"count": -1, "rows": -1, "columns": -1, "levels": -1, "items": -1, "sides": -1, "segments": -1, "index": -1}), + json!({"name": long, "layer": long, "text": long, "style": long, "mode": long}), + json!({"name": "\u{0}\u{202e}\u{1f4a5}", "text": r"%%%\P{\H0;", "gradient": {"name": 5, "color1": [1], "angle": "x", "centered": "y"}}), + ] +} + +#[test] +fn no_command_panics_or_hangs_on_adversarial_params() { + let params = adversarial(); + let mut bad: Vec = Vec::new(); + for spec in command_specs() { + for p in ¶ms { + if let Err(why) = run_guarded(spec.id, p) { + let shown: String = p.to_string().chars().take(120).collect(); + bad.push(format!("{} [{why}] <- {shown}", spec.id)); + break; + } + } + } + assert!(bad.is_empty(), "{} commands panicked or hung:\n{}", bad.len(), bad.join("\n")); +} + +/// A panic the code under test contains still fails the run; a graceful `Err` does not. Without +/// this the hunt could quietly stop detecting anything. +#[test] +fn contained_panics_count_and_graceful_errors_do_not() { + let contained = run_watched(SELF_TEST_DEADLINE, || { + let _ = catch_unwind(|| panic!("contained, as Session::execute does")); + }); + assert_eq!(contained, Some(false)); + let graceful = run_watched(SELF_TEST_DEADLINE, || { + let mut s = fresh(); + assert!(s.execute("no-such-command", &json!({})).is_err()); + }); + assert_eq!(graceful, Some(true)); +} From 3d623fc4d4636da86b793aa77756eb1c85335f48 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 30 Oct 2026 19:10:57 -0700 Subject: [PATCH 243/900] Saving over a DWG asks before it loses content, and saves keep a .bak (#2518) Includes the .bak work from #1003. Co-authored-by: Aldo Zarate --- crates/engine/src/atomic_write.rs | 34 ++- crates/engine/src/autosave.rs | 12 ++ crates/engine/src/cmd/file.rs | 196 +++++++++++++++++- crates/engine/src/sysvars.rs | 3 + crates/engine/tests/save_backup.rs | 296 +++++++++++++++++++++++++++ crates/ui-egui/src/autosave.rs | 9 +- crates/ui-egui/src/control.rs | 3 +- crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/lib.rs | 12 +- crates/ui-egui/src/menus.rs | 12 +- crates/ui-egui/src/options.rs | 12 +- crates/ui-egui/src/options/dialog.rs | 11 + crates/ui-egui/src/save_loss.rs | 154 ++++++++++++++ crates/ui-egui/tests/save_loss.rs | 108 ++++++++++ docs/gaps.md | 9 +- 16 files changed, 860 insertions(+), 15 deletions(-) create mode 100644 crates/engine/tests/save_backup.rs create mode 100644 crates/ui-egui/src/save_loss.rs create mode 100644 crates/ui-egui/tests/save_loss.rs diff --git a/crates/engine/src/atomic_write.rs b/crates/engine/src/atomic_write.rs index ff9e141d3..0d7459b1b 100644 --- a/crates/engine/src/atomic_write.rs +++ b/crates/engine/src/atomic_write.rs @@ -36,13 +36,20 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { Err(e) if e.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e), }; + write_atomic_with(path, permissions, |file| file.write_all(bytes)) +} + +/// [`write_atomic`] filling the temporary file through `fill` (streamed rather than one buffer), +/// with `permissions` given to it from its creation (`None`: the usual creation mode). A symlink +/// at `path` is replaced by the new file, never written through. +pub fn write_atomic_with(path: &Path, permissions: Option, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { let dir = path.parent().filter(|p| !p.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf); let (mut file, tmp) = create_temp(&dir, permissions.as_ref())?; let write = (|| { if let Some(permissions) = permissions { file.set_permissions(permissions)?; } - file.write_all(bytes)?; + fill(&mut file)?; file.flush()?; file.sync_all() })(); @@ -55,9 +62,22 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { let _ = std::fs::remove_file(&tmp); return Err(e); } + sync_dir(&dir); Ok(()) } +/// Flush `dir` so a rename just made in it survives a crash or power loss (POSIX records a +/// rename in the directory, not in the file). Best effort: some file systems (network shares) +/// refuse to sync a directory, and the file itself is already on disk. +fn sync_dir(dir: &Path) { + #[cfg(unix)] + if let Ok(d) = File::open(dir) { + let _ = d.sync_all(); + } + #[cfg(not(unix))] + let _ = dir; +} + /// Create a fresh, exclusively-owned temporary file inside `dir`, returning its handle and path. /// /// `create_new(true)` opens with `O_CREAT | O_EXCL`, which refuses to follow or reuse an existing @@ -116,6 +136,18 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// A write into a folder whose entries can be listed syncs that folder without failing, and + /// a folder that can't be opened (gone) is no error for the sync itself. + #[test] + fn the_folder_is_synced_after_the_rename() { + let dir = std::env::temp_dir().join(format!("cadcraft-aw-sync-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir_all(&dir).unwrap(); + write_atomic(&dir.join("a.bin"), b"x").unwrap(); + assert_eq!(std::fs::read(dir.join("a.bin")).unwrap(), b"x"); + sync_dir(&dir.join("missing")); + std::fs::remove_dir_all(&dir).ok(); + } + #[cfg(unix)] #[test] fn does_not_follow_a_planted_temp_symlink() { diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index 480d14c3b..c6b41cce4 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -34,6 +34,18 @@ pub const STALE_LOCK_SECS: u64 = 5 * 60; const HEARTBEAT_SECS: f64 = 60.0; static SAVETIME: AtomicU32 = AtomicU32::new(DEFAULT_SAVETIME); +static ISAVEBAK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// ISAVEBAK: whether saving over a drawing keeps the previous file as `.bak` (on by +/// default, as in AutoCAD). A profile setting like SAVETIME. +pub fn isavebak() -> bool { + ISAVEBAK.load(Ordering::Relaxed) +} + +/// Turn ISAVEBAK on or off. +pub fn set_isavebak(on: bool) { + ISAVEBAK.store(on, Ordering::Relaxed); +} static SAVEFILEPATH: Mutex = Mutex::new(String::new()); /// SAVETIME: minutes between autosaves; 0 turns autosave off. diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 7c26a71f9..8bb4c5c75 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -420,11 +420,20 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result.bak` (ISAVEBAK, +/// #540). fn store(path: &str, bytes: &[u8]) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { + if is_drawing_file(path) && crate::autosave::isavebak() { + backup(std::path::Path::new(path)) + .map_err(|e| bad("save", format!("{path}: the backup copy could not be written ({e}); nothing was saved")))?; + } // Exclusively create a fresh temporary file and rename it over `path`, so a planted // `.cadcraft-tmp` symlink cannot redirect the write onto another file (CWE-59). crate::atomic_write::write_atomic(std::path::Path::new(path), bytes).map_err(|e| bad("save", format!("{path}: {e}"))) @@ -437,6 +446,178 @@ fn store(path: &str, bytes: &[u8]) -> Result<()> { } } +/// The backup of the drawing file `path`: `.bak` beside it, as AutoCAD names it. +pub fn backup_path(path: &std::path::Path) -> std::path::PathBuf { + path.with_extension("bak") +} + +/// Whether `bytes` read as a DWG or a DXF (ASCII or binary) by their start: what a save keeps as +/// the backup. A file that doesn't (truncated, overwritten by another program) never replaces a +/// good `.bak`. +pub fn looks_like_drawing(bytes: &[u8]) -> bool { + // DWG: a version tag like `AC1032` (R12 is `AC1009`). + let dwg = bytes.len() >= 6 && bytes.starts_with(b"AC") && bytes[2..6].iter().all(|b| b.is_ascii_digit()); + if dwg || cadcraft_dxf::is_binary(bytes) { + return true; + } + // ASCII DXF: optional comments (999), then group 0 SECTION. + let text = String::from_utf8_lossy(&bytes[..bytes.len().min(4096)]); + let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty()); + loop { + match (lines.next(), lines.next()) { + (Some("999"), Some(_)) => continue, + (Some("0"), Some(v)) => return v.eq_ignore_ascii_case("SECTION"), + _ => return false, + } + } +} + +/// How much of a drawing's end [`looks_complete`] reads. +const TAIL_BYTES: u64 = 256; + +/// Whether a drawing that [`looks_like_drawing`] (`head`, its first bytes, at least 256 of them +/// for a DWG) is whole, from its end (`tail`, its last bytes) and size `len`, without reading it +/// all: a DXF ends with `0`/`EOF` (a binary one with `EOF` and its NUL); a DWG reaches the end its +/// own header gives ([`dwg_complete`]). `None` when that can't be told (a 2007 DWG), so a file cut +/// off by a failed save or another program doesn't replace a good backup. +pub fn completeness(head: &[u8], tail: &[u8], len: u64) -> Option { + let dwg = head.len() >= 6 && head.starts_with(b"AC") && head[2..6].iter().all(|b| b.is_ascii_digit()); + if dwg { + // Too short for any DWG's header: cut off, not unknown. + return if head.len() < 256 { Some(false) } else { dwg_complete(head, len) }; + } + if cadcraft_dxf::is_binary(head) { + return Some(tail.ends_with(b"EOF\0")); + } + let text = String::from_utf8_lossy(tail); + let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty()).rev(); + Some(matches!((lines.next(), lines.next()), (Some(last), Some("0")) if last.eq_ignore_ascii_case("EOF"))) +} + +/// [`completeness`] known to be whole. +pub fn looks_complete(head: &[u8], tail: &[u8], len: u64) -> bool { + completeness(head, tail, len) != Some(false) +} + +/// Whether a DWG of `len` bytes reaches the end its header gives (Open Design Specification for +/// .dwg files): from 2004 on, the copy of the file header that ends the file (its address is in +/// the encrypted header at 0x80, and the copy is 0x6C bytes); up to 2000, the end of every section +/// the locator records give. `None` for another layout (2007, or before R13). +fn dwg_complete(head: &[u8], len: u64) -> Option { + let version = head.get(..6)?; + match version { + b"AC1018" | b"AC1024" | b"AC1027" | b"AC1032" => { + // The header at 0x80 is XORed with the generator the specification gives. + let enc = head.get(0x80..0x80 + 0x6C)?; + let mut seed: u32 = 1; + let h: Vec = enc + .iter() + .map(|b| { + seed = seed.wrapping_mul(0x343FD).wrapping_add(0x0026_9EC3); + b ^ (seed >> 16) as u8 + }) + .collect(); + if h.get(..12) != Some(&b"AcFssFcAJMB\0"[..]) { + return Some(false); + } + let second = u64::from_le_bytes(h.get(0x34..0x3C)?.try_into().ok()?); + Some(second >= 0x100 && second.checked_add(0x6C).is_some_and(|end| len >= end)) + } + b"AC1012" | b"AC1014" | b"AC1015" => { + let n = i32::from_le_bytes(head.get(0x15..0x19)?.try_into().ok()?); + if !(1..=16).contains(&n) { + return Some(false); + } + let mut end = 0u64; + for i in 0..n as usize { + let r = head.get(0x19 + i * 9..0x19 + i * 9 + 9)?; + let seek = u64::from(u32::from_le_bytes(r.get(1..5)?.try_into().ok()?)); + let size = u64::from(u32::from_le_bytes(r.get(5..9)?.try_into().ok()?)); + end = end.max(seek + size); + } + Some(len >= end) + } + _ => None, + } +} + +/// A file's first bytes, last bytes and length, left positioned just after the first bytes. +#[cfg(not(target_arch = "wasm32"))] +fn ends(src: &mut std::fs::File) -> std::io::Result<(Vec, Vec, u64)> { + use std::io::{Read, Seek, SeekFrom}; + let mut head = Vec::with_capacity(4096); + (&mut *src).take(4096).read_to_end(&mut head)?; + // Its end too (a DXF's EOF), then on from where the start left off for the copy. + let len = src.metadata()?.len(); + let mut tail = Vec::new(); + src.seek(SeekFrom::Start(len.saturating_sub(TAIL_BYTES)))?; + (&mut *src).take(TAIL_BYTES).read_to_end(&mut tail)?; + src.seek(SeekFrom::Start(head.len() as u64))?; + Ok((head, tail, len)) +} + +/// Whether saving replaces the `.bak` with this file. A file known to be cut off never replaces a +/// backup already there. One that can't be told (a 2007 DWG) does: it is most likely fine, and it +/// is about to be replaced. With no backup yet any file is kept, because the checks can be wrong +/// about a real file and this save replaces the only copy. +fn backup_replaced(head: &[u8], tail: &[u8], len: u64, backup_exists: bool) -> bool { + (looks_like_drawing(head) && completeness(head, tail, len) != Some(false)) || (len > 0 && !backup_exists) +} + +/// Whether a save over `path` now would leave the current file in its `.bak`, for a warning that +/// must not promise a backup the save won't write. +#[cfg(not(target_arch = "wasm32"))] +pub fn save_keeps_current(path: &std::path::Path) -> bool { + let Ok(mut src) = std::fs::File::open(path) else { return false }; + crate::autosave::isavebak() && ends(&mut src).is_ok_and(|(head, tail, len)| backup_replaced(&head, &tail, len, backup_path(path).exists())) +} + +#[cfg(target_arch = "wasm32")] +pub fn save_keeps_current(_path: &std::path::Path) -> bool { + false +} + +/// Before `path` is replaced: copy it to its `.bak`, streamed and written atomically too +/// ([`crate::atomic_write::write_atomic_with`]). Nothing +/// to keep when there is no file yet. A file that doesn't look like a drawing +/// ([`looks_like_drawing`]) is not backed up, and the `.bak` already there is left alone. +#[cfg(not(target_arch = "wasm32"))] +fn backup(path: &std::path::Path) -> std::io::Result<()> { + let mut src = match std::fs::File::open(path) { + Ok(f) if f.metadata()?.is_file() => f, + Ok(_) => return Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(e), + }; + let (head, tail, len) = ends(&mut src)?; + let bak = backup_path(path); + if !backup_replaced(&head, &tail, len, bak.exists()) { + log::warn!("save: {} doesn't look like a whole drawing; its backup is left as it was", path.display()); + return Ok(()); + } + // The backup is no more readable than the drawing, nor than the .bak it replaces (a private + // 0600 drawing or .bak stays private). The mode is set as the new file is created, so a + // failed write leaves the old .bak as it was; a symlink at the .bak is replaced, never + // written through. + #[cfg(unix)] + let permissions = { + use std::os::unix::fs::PermissionsExt; + let mut mode = src.metadata()?.permissions().mode() & 0o777; + if let Ok(m) = std::fs::symlink_metadata(&bak) + && m.is_file() + { + mode &= m.permissions().mode(); + } + Some(std::fs::Permissions::from_mode(mode)) + }; + #[cfg(not(unix))] + let permissions = None; + crate::atomic_write::write_atomic_with(&bak, permissions, |out| { + std::io::Write::write_all(out, &head)?; + std::io::copy(&mut src, out).map(|_| ()) + }) +} + /// Store the bytes, then mark the drawing saved under `path`. If storing fails the drawing keeps /// its unsaved changes, file name and title. On the web a started download counts as saved: the /// browser owns the file from there (we can't see whether the user keeps it), and the name stays so @@ -564,6 +745,17 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap) -> Op Some(format!("Not saved in the DWG file (its writer can't write these object types yet; DXF keeps them): {}", list.join(", "))) } +/// What saving the active drawing to `path` would leave out, before anything is written: empty +/// when the format keeps everything. The interactive save asks with this; [`save_reporting`] +/// reports the same list afterwards to callers that never get a dialog. +pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap { + if !drops_unknown(path) { + return Default::default(); + } + let version = drawing_version(s, path); + s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default() +} + /// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG /// bridge drops types it doesn't know); DXF writes them back as read. pub fn drops_unknown(path: impl AsRef) -> bool { diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 5c0f3951c..b532f66dd 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -70,6 +70,7 @@ const SESSION_VARS: &[&str] = &[ "FONTFALLBACK", "SAVETIME", "SAVEFILEPATH", + "ISAVEBAK", ]; pub fn get(s: &Session, name: &str) -> Option { @@ -154,6 +155,7 @@ pub fn get(s: &Session, name: &str) -> Option { // Autosave (profile settings too). "SAVETIME" => json!(crate::autosave::savetime()), "SAVEFILEPATH" => json!(crate::autosave::savefilepath()), + "ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())), "CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()), "DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()), "DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)), @@ -366,6 +368,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { as_f64(v).filter(|m| *m >= 0.0 && *m <= f64::from(crate::autosave::MAX_SAVETIME)).ok_or_else(bad)?.round() as u32, ), "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). "ANGBASE" => { let a = match v { diff --git a/crates/engine/tests/save_backup.rs b/crates/engine/tests/save_backup.rs new file mode 100644 index 000000000..afa5a14cb --- /dev/null +++ b/crates/engine/tests/save_backup.rs @@ -0,0 +1,296 @@ +//! Saving over a drawing keeps the previous file as `.bak` (ISAVEBAK, #540), and the +//! save itself replaces the file atomically: no temporary files are left behind. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, backup_path, looks_complete, looks_like_drawing, save_keeps_current, set_io}; +use serde_json::json; + +fn hooks() { + set_io(IoHooks { + read: |b, n| cadcraft_io::read(b, n).map_err(|e| e.to_string()), + write: |d, n| cadcraft_io::write(d, n).map_err(|e| e.to_string()), + plot: None, + }); + // Saves at a chosen version (a DWG 2000), as the app's. + cadcraft_engine::cmd::file::set_write_as(|d, n, o| { + cadcraft_io::write_with(d, n, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) + }); +} + +fn temp_dir(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("cadcraft-bak-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn circles(path: &std::path::Path) -> usize { + let d = cadcraft_io::read(&std::fs::read(path).unwrap(), &*path.to_string_lossy()).unwrap(); + d.model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Circle(_))).count() +} + +/// Only the drawing and its backup are in the folder: atomic saves leave no staging files. +fn files(dir: &std::path::Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect(); + v.sort(); + v +} + +/// ISAVEBAK is process-wide: the tests that save hold this lock, so one turning it off can't +/// race another's save. Dropping the guard turns it back on, also when a test fails. +static SAVES: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +struct Saving(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>); + +impl Drop for Saving { + fn drop(&mut self) { + cadcraft_engine::autosave::set_isavebak(true); + } +} + +fn saving() -> Saving { + let g = SAVES.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cadcraft_engine::autosave::set_isavebak(true); + Saving(g) +} + +fn add_circle(s: &mut Session, x: f64) { + s.execute("circle", &json!({ "center": [x, 0], "radius": 1 })).unwrap(); +} + +#[test] +fn each_save_keeps_the_previous_file_as_bak() { + let _saving = saving(); + hooks(); + let dir = temp_dir("rotate"); + let path = dir.join("Plan.dxf"); + let p = path.to_string_lossy().to_string(); + let mut s = Session::new(); + add_circle(&mut s, 0.0); + s.execute("saveas", &json!({ "path": p })).unwrap(); + assert_eq!(files(&dir), ["Plan.dxf"], "a first save has nothing to back up"); + + add_circle(&mut s, 5.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(files(&dir), ["Plan.bak", "Plan.dxf"]); + assert_eq!((circles(&path), circles(&backup_path(&path))), (2, 1), "the .bak is the previous save"); + + add_circle(&mut s, 10.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!((circles(&path), circles(&backup_path(&path))), (3, 2)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_damaged_file_never_replaces_a_good_backup_and_isavebak_0_keeps_none() { + let _saving = saving(); + hooks(); + let dir = temp_dir("damaged"); + let path = dir.join("Plan.dxf"); + let p = path.to_string_lossy().to_string(); + let mut s = Session::new(); + add_circle(&mut s, 0.0); + s.execute("saveas", &json!({ "path": p })).unwrap(); + add_circle(&mut s, 5.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(circles(&backup_path(&path)), 1); + + // Another program truncates the drawing; the next save keeps the good backup. + std::fs::write(&path, b"").unwrap(); + add_circle(&mut s, 10.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!((circles(&path), circles(&backup_path(&path))), (3, 1)); + + // Cut off with a drawing's start kept (half a DXF, a DWG's version tag alone): the backup + // stays too. + let whole = std::fs::read(&path).unwrap(); + std::fs::write(&path, &whole[..whole.len() / 2]).unwrap(); + add_circle(&mut s, 11.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(circles(&backup_path(&path)), 1, "half a DXF"); + std::fs::write(&path, b"AC1032").unwrap(); + add_circle(&mut s, 12.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(circles(&backup_path(&path)), 1, "a DWG's tag alone"); + + // ISAVEBAK 0: the backup is left as it was. + s.execute("setvar", &json!({ "name": "ISAVEBAK", "value": 0 })).unwrap(); + add_circle(&mut s, 15.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!((circles(&path), circles(&backup_path(&path))), (6, 1)); + assert_eq!(files(&dir), ["Plan.bak", "Plan.dxf"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn drawings_are_recognised_by_their_start() { + assert!(looks_like_drawing(b"AC1032\0\0\0\0\0")); + assert!(looks_like_drawing(b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n")); + assert!(looks_like_drawing(b"999\ndxfrw\n0\nSECTION\n")); + assert!(looks_like_drawing(b"AutoCAD Binary DXF\r\n\x1a\0")); + for junk in [&b""[..], b"\0\0\0\0", b"0\nEOF\n", b"", b"hello"] { + assert!(!looks_like_drawing(junk), "{junk:?}"); + } +} + +/// A private drawing (0600) keeps a private backup: a new .bak, and a .bak already there that +/// others could read, both take the drawing's mode. +#[cfg(unix)] +#[test] +fn the_backup_is_no_more_readable_than_the_drawing() { + use std::os::unix::fs::PermissionsExt; + let _saving = saving(); + hooks(); + let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + let dir = temp_dir("mode"); + let path = dir.join("Plan.dxf"); + let p = path.to_string_lossy().to_string(); + let mut s = Session::new(); + add_circle(&mut s, 0.0); + s.execute("saveas", &json!({ "path": p })).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + add_circle(&mut s, 5.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(mode(&backup_path(&path)), 0o600, "a new .bak"); + + std::fs::set_permissions(backup_path(&path), std::fs::Permissions::from_mode(0o644)).unwrap(); + add_circle(&mut s, 10.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(mode(&backup_path(&path)), 0o600, "a .bak already there"); + assert_eq!(circles(&backup_path(&path)), 2); + + // A .bak kept more private than the drawing is never widened. + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + std::fs::set_permissions(backup_path(&path), std::fs::Permissions::from_mode(0o600)).unwrap(); + add_circle(&mut s, 15.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(mode(&backup_path(&path)), 0o600, "a more private .bak"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A symlink planted at the .bak is replaced by the backup, never written through: the file it +/// pointed at is left as it was. +#[cfg(unix)] +#[test] +fn a_symlink_at_the_backup_is_not_followed() { + let _saving = saving(); + hooks(); + let dir = temp_dir("link"); + let path = dir.join("Plan.dxf"); + let p = path.to_string_lossy().to_string(); + let other = dir.join("other.txt"); + std::fs::write(&other, b"someone else's file").unwrap(); + let mut s = Session::new(); + add_circle(&mut s, 0.0); + s.execute("saveas", &json!({ "path": p })).unwrap(); + std::os::unix::fs::symlink(&other, backup_path(&path)).unwrap(); + add_circle(&mut s, 5.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(std::fs::read(&other).unwrap(), b"someone else's file"); + assert!(std::fs::symlink_metadata(backup_path(&path)).unwrap().is_file(), "the .bak is a file now"); + assert_eq!(circles(&backup_path(&path)), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A drawing looks whole from its end: an ASCII DXF ends with 0/EOF, a binary one with EOF and +/// its NUL, and a DWG is not a few bytes long. +#[test] +fn whole_drawings_are_told_from_cut_off_ones() { + let ascii = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert!(looks_complete(ascii, ascii, ascii.len() as u64)); + let cut = &ascii[..30]; + assert!(!looks_complete(cut, cut, cut.len() as u64)); + let mut binary = b"AutoCAD Binary DXF\r\n\x1a\0".to_vec(); + binary.extend_from_slice(b"\0\0SECTION\0\0\0EOF\0"); + assert!(looks_complete(&binary, &binary, binary.len() as u64)); + assert!(!looks_complete(&binary, &binary[..binary.len() - 5], binary.len() as u64 - 5)); + assert!(!looks_complete(b"AC1032", b"AC1032", 6)); + assert!(!looks_complete(b"AC1032", b"", 30_000), "a DWG tag without its header is not whole"); +} + +/// A DWG reaches the end its own header gives: cut off anywhere (not only right after its start), +/// in a 2018 and a 2000 file, it doesn't replace the good backup; whole, it does. +#[test] +fn a_dwg_cut_off_anywhere_keeps_the_good_backup() { + let _saving = saving(); + hooks(); + for version in [2018, 2000] { + let dir = temp_dir(&format!("dwg{version}")); + let path = dir.join("Plan.dwg"); + let p = path.to_string_lossy().to_string(); + let mut s = Session::new(); + add_circle(&mut s, 0.0); + s.execute("saveas", &json!({ "path": p, "version": version })).unwrap(); + add_circle(&mut s, 5.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(circles(&backup_path(&path)), 1, "{version}: the first save is backed up"); + let whole = std::fs::read(&path).unwrap(); + let head = &whole[..whole.len().min(4096)]; + assert!(looks_complete(head, &whole[whole.len().saturating_sub(256)..], whole.len() as u64), "{version}: whole"); + for keep in [whole.len() / 2, whole.len() * 9 / 10, whole.len() - 1] { + assert!(!looks_complete(head, &[], keep as u64), "{version}: cut to {keep} of {}", whole.len()); + } + // Another program leaves it cut off at 90%: the next save keeps the good backup. + std::fs::write(&path, &whole[..whole.len() * 9 / 10]).unwrap(); + add_circle(&mut s, 10.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(circles(&backup_path(&path)), 1, "{version}: the cut-off file didn't replace it"); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// The checks can be wrong about a real file. With no backup yet, a file that doesn't look whole +/// is still kept, because the save is about to replace the only copy of it. +#[test] +fn a_file_that_looks_damaged_is_kept_when_there_is_no_backup_yet() { + let _saving = saving(); + hooks(); + let dir = temp_dir("first"); + let path = dir.join("Plan.dxf"); + let p = path.to_string_lossy().to_string(); + let mut s = Session::new(); + add_circle(&mut s, 0.0); + s.execute("saveas", &json!({ "path": p })).unwrap(); + let odd = b"AC1032 but not as this header expects it".to_vec(); + std::fs::write(&path, &odd).unwrap(); + add_circle(&mut s, 5.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(std::fs::read(backup_path(&path)).unwrap(), odd); + let _ = std::fs::remove_dir_all(&dir); +} + +/// What the warning promises and what the save does agree. A 2007 DWG, whose completeness can't +/// be told, replaces an older backup; a file known to be cut off doesn't. +#[test] +fn the_backup_a_save_promises_is_the_one_it_writes() { + let _saving = saving(); + hooks(); + let dir = temp_dir("promise"); + let path = dir.join("Plan.dxf"); + let p = path.to_string_lossy().to_string(); + let mut s = Session::new(); + add_circle(&mut s, 0.0); + s.execute("saveas", &json!({ "path": p })).unwrap(); + add_circle(&mut s, 5.0); + s.execute("qsave", &json!({})).unwrap(); + let old = std::fs::read(backup_path(&path)).unwrap(); + + let mut dwg2007 = b"AC1021".to_vec(); + dwg2007.resize(4096, 7); + std::fs::write(&path, &dwg2007).unwrap(); + assert!(save_keeps_current(&path)); + add_circle(&mut s, 10.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(std::fs::read(backup_path(&path)).unwrap(), dwg2007, "the promise was kept"); + + std::fs::write(backup_path(&path), &old).unwrap(); + std::fs::write(&path, b"AC1032").unwrap(); + assert!(!save_keeps_current(&path)); + add_circle(&mut s, 15.0); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(std::fs::read(backup_path(&path)).unwrap(), old, "cut off: nothing was promised"); + + cadcraft_engine::autosave::set_isavebak(false); + assert!(!save_keeps_current(&path), "backups off"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/autosave.rs b/crates/ui-egui/src/autosave.rs index d062f69e9..012231683 100644 --- a/crates/ui-egui/src/autosave.rs +++ b/crates/ui-egui/src/autosave.rs @@ -1,5 +1,5 @@ //! Autosave and Drawing Recovery in the app. The engine decides what to write and writes it -//! ([`cadcraft_engine::autosave`]); this runs it every frame, keeps SAVETIME and SAVEFILEPATH with +//! ([`cadcraft_engine::autosave`]); this runs it every frame, keeps SAVETIME, SAVEFILEPATH and ISAVEBAK with //! the preferences, and shows the Drawing Recovery list after a crash: each autosaved drawing can //! be opened (as an unsaved copy) or discarded. On the web there is no autosave yet. @@ -13,9 +13,9 @@ use crate::theme::Tokens; /// The host storage key for [`prefs_json`]. pub const PREFS_KEY: &str = "cadcraft.autosave"; -/// SAVETIME and SAVEFILEPATH as JSON for the host's storage. +/// SAVETIME, SAVEFILEPATH and ISAVEBAK as JSON for the host's storage. pub fn prefs_json() -> String { - json!({ "savetime": autosave::savetime(), "saveFilePath": autosave::savefilepath() }).to_string() + json!({ "savetime": autosave::savetime(), "saveFilePath": autosave::savefilepath(), "backup": autosave::isavebak() }).to_string() } /// Restore what [`prefs_json`] saved; malformed values are ignored. @@ -27,6 +27,9 @@ pub fn load_prefs(json: &str) { if let Some(p) = v.get("saveFilePath").and_then(Value::as_str) { autosave::set_savefilepath(p); } + if let Some(b) = v.get("backup").and_then(Value::as_bool) { + autosave::set_isavebak(b); + } } /// What the GPU error notice says (see [`gpu_notice`]). diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7330681db..8d0a39bf4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -500,7 +500,8 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou let Some(path) = s("path") else { return err("missing path") }; wrap(app.run("open", json!({"path": path}))) } - "app.save" => wrap(app.run(if s("path").is_some() { "saveas" } else { "qsave" }, p.clone())), + // Never `null` params: those mean a user's Save, which may pick a file or ask. + "app.save" => wrap(app.run(if s("path").is_some() { "saveas" } else { "qsave" }, if p.is_null() { json!({}) } else { p.clone() })), "app.quit" => { // Programmatic calls never open dialogs: quit without the unsaved-changes prompt. app.quit_confirmed = true; diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2dde91eac..b24970979 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -74,6 +74,8 @@ AutoConstrain Restricciones automáticas Automatic save every Guardado automático cada Automatic save file location Ubicación de los archivos de guardado automático + Backup copy Copia de seguridad + Create backup copy with each save Crear una copia de seguridad en cada guardado Axis, End Eje, extremo B N Base Base diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3f2de02df..714ce6c4c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1283,6 +1283,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. Якщо вимкнено, клік правою кнопкою під час команди завжди відкриває контекстне меню. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 91902017f..0253a2cec 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -56,6 +56,7 @@ pub mod palettes; pub mod parametric; pub mod plotstyles; pub mod quick; +pub mod save_loss; pub mod shortcut_menus; pub mod theme; #[cfg(not(target_arch = "wasm32"))] @@ -290,6 +291,10 @@ pub struct CadApp { pub quit_confirmed: bool, /// A close request waiting for "Save changes?" answers ([`closing`]). pub closing: Option, + /// A save waiting for an answer about the content the file can't keep ([`save_loss`]). + pub save_loss: Option, + /// The loss the user last agreed to, so saving again doesn't ask again ([`save_loss`]). + pub save_loss_accepted: Option, /// Autosave (desktop; `None` until [`Self::enable_autosave`]). pub autosave: Option, /// Drawing Recovery: autosave files a crashed app left behind. @@ -350,6 +355,8 @@ impl CadApp { quit_requested: false, quit_confirmed: false, closing: None, + save_loss: None, + save_loss_accepted: None, autosave: None, recovery: autosave::Recovery::default(), gpu_faults: std::sync::Arc::default(), @@ -691,11 +698,11 @@ impl CadApp { ctx.request_repaint_of(egui::ViewportId::ROOT); } - /// Whether a modal dialog is up: the "Save changes?" prompt or Drawing Recovery. The + /// Whether a modal dialog is up: the "Save changes?" prompt, the lossy-save warning or Drawing Recovery. The /// floating panels' own OS windows take no input meanwhile (egui's `Modal` blocks only the /// main window). The app's other dialogs are ordinary windows that leave the drawing usable. pub fn shows_modal(&self) -> bool { - self.close_prompt().is_some() || !self.recovery.items.is_empty() + self.close_prompt().is_some() || self.save_loss.is_some() || !self.recovery.items.is_empty() } /// Input hook: refresh the raw surface snapshot, put in keys forwarded from floating panels' @@ -875,6 +882,7 @@ impl CadApp { dialogs::show(self, ui.ctx()); palettes::patterns::prompt_picker(self, ui.ctx()); closing::prompt(self, ui.ctx()); + save_loss::prompt(self, ui.ctx()); autosave::show(self, ui.ctx()); autosave::gpu_notice(self, ui.ctx()); self.frame_ms = now_ms() - t0; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 797952edf..906ccb707 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -292,6 +292,16 @@ fn should_pick_file_path(id: &str, params: &Value) -> bool { if id.starts_with("ui.") { params.is_null() || (params.get("path").is_none() && params.get("data").is_none()) } else { params.is_null() } } +/// A user's QSAVE: a drawing with no file yet picks one, and saving over a file that would lose +/// content asks first. `None` lets the engine save. JSON calls carry params and never get here; +/// they report the loss in their result instead. +fn user_qsave(app: &mut CadApp) -> Option> { + if app.session.state().is_ok_and(|s| s.path.is_none()) { + return run_ui_command(app, "ui.saveas", &Value::Null); + } + app.hold_lossy_save().then_some(Ok(Value::Null)) +} + fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option> { if let Some(result) = route_ui_subsystems(app, id, params) { return Some(result); @@ -370,7 +380,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option return run_ui_command(app, "ui.saveas", &Value::Null), + "qsave" if no_path => return user_qsave(app), // EXPORTPDF from the menu or typed: ask where to save the PDF (PLOT and PRINT open the Plot // dialog, `managers::route`). JSON calls (scripts, control channel, MCP) always carry // params, never get here and never open a dialog. diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index 4c7cf6b1f..dba0814b7 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -15,6 +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 | +//! | `ISAVEBAK` | 1: saving over a drawing keeps the previous file as `.bak` (default); 0: no backup | //! | `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 | //! | `systemCursor` | keep the system cursor visible over the drawing area | //! | `historyLines` | command-line history lines, 0–12 | @@ -23,7 +24,7 @@ //! | `snapMarkerSize` | object snap marker size in points, 5–31 | //! | `interfaceScale` | the interface's size, 0.5–3 (1: the system's own) | //! -//! SAVETIME and SAVEFILEPATH are the engine's autosave settings, kept with the autosave state +//! 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 @@ -147,6 +148,7 @@ struct UiChanges { save_version: Option, savetime: Option, savefilepath: Option, + isavebak: Option, time_sensitive_right_click: Option, interface_scale: Option, } @@ -203,6 +205,10 @@ fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result { let p = v.as_str().map(str::trim).filter(|p| p.chars().count() <= MAX_PATH_CHARS && !p.chars().any(char::is_control)); c.savefilepath = Some(p.ok_or("SAVEFILEPATH must be a folder path")?.to_string()); } + k if k.eq_ignore_ascii_case("ISAVEBAK") => { + let on = v.as_bool().or_else(|| v.as_i64().filter(|n| matches!(n, 0 | 1)).map(|n| n == 1)); + c.isavebak = Some(on.ok_or("ISAVEBAK must be 0 or 1")?); + } _ => return Ok(false), } Ok(true) @@ -226,6 +232,7 @@ fn ui_json(app: &CadApp) -> Map { m.insert("saveVersion".into(), json!(app.ui.save_version)); m.insert("SAVETIME".into(), json!(cadcraft_engine::autosave::savetime())); m.insert("SAVEFILEPATH".into(), json!(cadcraft_engine::autosave::savefilepath())); + m.insert("ISAVEBAK".into(), json!(i32::from(cadcraft_engine::autosave::isavebak()))); m.insert("timeSensitiveRightClick".into(), json!(o.time_sensitive_right_click)); m } @@ -297,6 +304,9 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result { if let Some(p) = &ui.savefilepath { cadcraft_engine::autosave::set_savefilepath(p); } + if let Some(b) = ui.isavebak { + cadcraft_engine::autosave::set_isavebak(b); + } if let Some(b) = ui.time_sensitive_right_click { app.options.time_sensitive_right_click = b; } diff --git a/crates/ui-egui/src/options/dialog.rs b/crates/ui-egui/src/options/dialog.rs index 93f051fd9..45be0ce67 100644 --- a/crates/ui-egui/src/options/dialog.rs +++ b/crates/ui-egui/src/options/dialog.rs @@ -225,6 +225,8 @@ fn files(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map) { ui.end_row(); autosave_row(ui, changes); ui.end_row(); + backup_row(ui, changes); + ui.end_row(); savefile_row(ui, changes); ui.end_row(); }); @@ -285,6 +287,15 @@ fn autosave_row(ui: &mut egui::Ui, changes: &mut Map) { } } +/// ISAVEBAK: keep the previous file as `.bak` when saving over a drawing. +fn backup_row(ui: &mut egui::Ui, changes: &mut Map) { + ui.label(crate::tl!("Backup copy")); + let mut bak = cadcraft_engine::autosave::isavebak(); + if ui.checkbox(&mut bak, crate::tl!("Create backup copy with each save")).changed() { + changes.insert("ISAVEBAK".into(), json!(i32::from(bak))); + } +} + fn savefile_row(ui: &mut egui::Ui, changes: &mut Map) { let savefile_label = ui.label(crate::tl!("Automatic save file location")); // Edited as text; the folder changes when the field loses focus. diff --git a/crates/ui-egui/src/save_loss.rs b/crates/ui-egui/src/save_loss.rs new file mode 100644 index 000000000..50e77978b --- /dev/null +++ b/crates/ui-egui/src/save_loss.rs @@ -0,0 +1,154 @@ +//! Asking before a save throws content away. DWG can't yet hold everything a drawing read from +//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), and QSAVE replaces the file +//! that still has it, so File ▸ Save, its shortcut or typing QSAVE says what would go first: +//! Save Anyway / Save As... / Cancel. Agreeing lasts for that same loss on that same file, so +//! later saves in the session don't ask again; the file no longer holds what was agreed to. +//! +//! Programmatic saves (`engine.execute`, the control channel, MCP, scripts) never ask: they keep +//! reporting the loss in the result's `notSaved` and on the command line. + +use std::collections::BTreeMap; + +use egui::{RichText, vec2}; +use serde_json::{Value, json}; + +use cadcraft_engine::autosave::isavebak; +use cadcraft_engine::cmd::file::{backup_path, loss_on_save, save_keeps_current}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// How many object types the warning lists; a file can name as many as it likes. +const MAX_LISTED: usize = 8; +/// How many characters of a type name the warning shows; a file chooses these too. +const MAX_NAME_CHARS: usize = 40; + +/// The user's answer to the warning. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Choice { + SaveAnyway, + SaveAs, + Cancel, +} + +/// A loss the user agreed to: this drawing, this file, these objects. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Accepted { + uid: u64, + path: String, + lost: BTreeMap, +} + +/// A save held back until the user answers. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Pending { + loss: Accepted, +} + +impl Pending { + /// The file the save would replace. + pub fn path(&self) -> &str { + &self.loss.path + } + + /// The objects the file wouldn't keep, as "2 MLINE, 1 3DSOLID". + pub fn summary(&self) -> String { + let lost = &self.loss.lost; + let name = |t: &str| t.chars().take(MAX_NAME_CHARS).collect::(); + let mut parts: Vec = lost.iter().take(MAX_LISTED).map(|(t, n)| format!("{n} {}", name(t))).collect(); + if lost.len() > MAX_LISTED { + parts.push(crate::tf!("{count} more types", count = lost.len() - MAX_LISTED)); + } + parts.join(", ") + } +} + +impl CadApp { + /// Hold a user's QSAVE of the active drawing if it would lose content the user hasn't agreed + /// to lose, and ask. Returns whether it was held. + pub fn hold_lossy_save(&mut self) -> bool { + let Ok(st) = self.session.state() else { return false }; + let (uid, Some(path)) = (st.uid, st.path.clone()) else { return false }; + let lost = loss_on_save(&self.session, &path); + if lost.is_empty() { + return false; + } + let loss = Accepted { uid, path, lost }; + if self.save_loss_accepted.as_ref() == Some(&loss) { + return false; + } + self.save_loss = Some(Pending { loss }); + true + } + + /// Answer the open warning (no-op without one). + pub fn answer_save_loss(&mut self, choice: Choice) { + let Some(Pending { loss }) = self.save_loss.take() else { return }; + // The drawing can go away, or stop being the active one, while the warning is up. + let i = self.session.docs.iter().position(|d| d.uid == loss.uid); + match (choice, i) { + (Choice::Cancel, _) | (_, None) => self.session.echo(crate::tf!("Save cancelled: {path} was not changed.", path = loss.path)), + (Choice::SaveAs, Some(i)) => { + self.activate_doc(i); + let _ = self.run("ui.saveas", Value::Null); + } + (Choice::SaveAnyway, Some(i)) => { + self.activate_doc(i); + self.save_loss_accepted = Some(loss); + let _ = self.run("qsave", json!({})); + } + } + } + + fn activate_doc(&mut self, i: usize) { + if self.session.active != i { + let _ = self.run("document.switch", json!({ "index": i })); + } + } +} + +/// The warning, while a save waits for an answer. Cancel is what Escape does. +pub fn prompt(app: &mut CadApp, ctx: &egui::Context) { + let Some(pending) = app.save_loss.clone() else { return }; + let t = Tokens::get(); + let path = std::path::Path::new(pending.path()); + let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| pending.path().to_string()); + let backup = backup_path(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let mut choice = None; + crate::modal::instant(ctx, egui::Id::unique("cc_save_loss_prompt")).show(ctx, |ui| { + ui.set_width(420.0); + ui.label(RichText::new(crate::tf!("Saving {name} will remove content", name = file)).strong()); + ui.add_space(4.0); + ui.label(crate::tf!("This format can't keep these objects yet: {objects}.", objects = pending.summary())); + ui.label(RichText::new(crate::tl!("DXF keeps them. Use Save As to keep them in the drawing.")).color(t.text_dim)); + let on_disk = if save_keeps_current(path) { + crate::tf!("The current file is kept as {name} until the next save.", name = backup) + } else if isavebak() { + crate::tf!("The current file doesn't look whole, so {name} stays as it is and the current file will be replaced.", name = backup) + } else { + crate::tl!("Backup copies are off, so the current file will be replaced.").to_string() + }; + ui.label(RichText::new(on_disk).color(t.text_dim)); + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let size = vec2(96.0, 22.0); + let save_as = ui.add(egui::Button::new(RichText::new(crate::tl!("Save As...")).color(t.text)).fill(t.accent).min_size(size)); + if save_as.clicked() { + choice = Some(Choice::SaveAs); + } + if ui.add(egui::Button::new(crate::tl!("Cancel")).min_size(size)).clicked() { + choice = Some(Choice::Cancel); + } + if ui.add(egui::Button::new(crate::tl!("Save Anyway")).min_size(size)).clicked() { + choice = Some(Choice::SaveAnyway); + } + }); + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + choice = Some(Choice::Cancel); + } + }); + if let Some(c) = choice { + app.answer_save_loss(c); + ctx.request_repaint(); + } +} diff --git a/crates/ui-egui/tests/save_loss.rs b/crates/ui-egui/tests/save_loss.rs new file mode 100644 index 000000000..cdb212f94 --- /dev/null +++ b/crates/ui-egui/tests/save_loss.rs @@ -0,0 +1,108 @@ +//! Saving over a file that would lose content asks first, and only when a user saves. These run +//! in their own test binary because the engine's I/O hooks are set once per process, and the +//! library's unit tests register a writer that always fails. + +use std::path::{Path, PathBuf}; + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::{Common, Drawing, EntityKind, RawTag, Space, Unknown}; +use serde_json::json; + +use cadcraft_ui_egui::save_loss::{Choice, Pending}; +use cadcraft_ui_egui::{CadApp, Services, menus}; + +const ORIGINAL: &[u8] = b"original"; + +fn unknown(kind: &str) -> EntityKind { + EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] }) +} + +/// A drawing with objects of `types`, which DWG can't keep, opened from a DWG file on disk. +fn opened(tag: &str, types: &[&str]) -> (CadApp, PathBuf) { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + let dir = std::env::temp_dir().join(format!("cadcraft-loss-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Plan.dwg"); + std::fs::write(&path, ORIGINAL).unwrap(); + let mut d = Drawing::new_metric(); + for t in types { + d.add(&Space::Model, Common::default(), unknown(t)).unwrap(); + } + let mut s = Session::empty(); + s.open_drawing(d, "Plan.dwg", Some(path.to_string_lossy().into_owned())); + (CadApp::new(s, Services::default()), path) +} + +fn cleanup(path: &Path) { + if let Some(d) = path.parent() { + let _ = std::fs::remove_dir_all(d); + } +} + +#[test] +fn a_users_save_asks_before_the_file_changes_and_cancel_leaves_it() { + let (mut app, path) = opened("cancel", &["3DSOLID", "MLINE", "MLINE"]); + menus::activate(&mut app, "qsave"); + let pending = app.save_loss.clone().expect("the save waits for an answer"); + assert_eq!(pending.summary(), "1 3DSOLID, 2 MLINE"); + assert!(app.shows_modal()); + assert_eq!(std::fs::read(&path).unwrap(), ORIGINAL, "nothing is written before the answer"); + + app.answer_save_loss(Choice::Cancel); + assert!(app.save_loss.is_none()); + assert_eq!(std::fs::read(&path).unwrap(), ORIGINAL); + cleanup(&path); +} + +#[test] +fn save_anyway_saves_and_the_same_loss_is_not_asked_again() { + let (mut app, path) = opened("anyway", &["MLINE"]); + menus::activate(&mut app, "qsave"); + app.answer_save_loss(Choice::SaveAnyway); + assert!(app.save_loss.is_none()); + assert_ne!(std::fs::read(&path).unwrap(), ORIGINAL); + + menus::activate(&mut app, "qsave"); + assert!(app.save_loss.is_none(), "already agreed to"); + + // A new kind of loss is a new question. + app.session.doc_mut().unwrap().add(&Space::Model, Common::default(), unknown("3DSOLID")).unwrap(); + menus::activate(&mut app, "qsave"); + assert_eq!(app.save_loss.as_ref().map(Pending::summary).as_deref(), Some("1 3DSOLID, 1 MLINE")); + cleanup(&path); +} + +#[test] +fn a_save_that_loses_nothing_does_not_ask() { + let (mut app, path) = opened("clean", &[]); + menus::activate(&mut app, "qsave"); + assert!(app.save_loss.is_none()); + assert_ne!(std::fs::read(&path).unwrap(), ORIGINAL); + cleanup(&path); +} + +/// Programmatic calls never open dialogs: the loss is in the result instead. +#[test] +fn programmatic_saves_never_ask() { + let (mut app, path) = opened("json", &["MLINE"]); + let r = app.run("qsave", json!({})).unwrap(); + assert!(app.save_loss.is_none()); + assert_eq!(r["notSaved"], json!({ "MLINE": 1 })); + cleanup(&path); +} + +/// Type names come from the file: however many, however long, the warning stays readable. +#[test] +fn a_hostile_list_of_types_is_capped() { + let long = "X".repeat(5000); + let many: Vec = (0..50).map(|i| format!("{long}{i}")).collect(); + let refs: Vec<&str> = many.iter().map(String::as_str).collect(); + let (mut app, path) = opened("hostile", &refs); + menus::activate(&mut app, "qsave"); + let s = app.save_loss.as_ref().unwrap().summary(); + assert!(s.chars().count() < 500, "{}", s.len()); + assert!(s.ends_with("42 more types"), "{s}"); + cleanup(&path); +} diff --git a/docs/gaps.md b/docs/gaps.md index b270525d6..1d6dca7e5 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-28 · **Change:** minor (BEDIT in the Block Editor switches blocks: F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **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,7 +13,7 @@ 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) | +| 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; a user's QSAVE now asks before replacing the file and keeps the previous one as `.bak`, which reduces the harm but does not close this row) | 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) | @@ -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. 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 Open and Save has the backup copy checkbox (ISAVEBAK). | `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 | @@ -73,7 +73,7 @@ Detail: [file-format-parity.md](file-format-parity.md). | # | Gap | User impact | Est. | |---|---|---|---| -| FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data | High | 6–10 | +| FF1 | **[alpha blocker]** Round-trip what we don't model. DXF done (#528): unknown entities and objects (with their CLASS records), foreign xdata (hyperlinks included), extension dictionaries, persistent reactors, DICTIONARYVAR and XRECORDs, layer states, colour book colours, references remapped on save; IMAGE, VIEW/UCS, groups, block descriptions, true colours, transparency (#201, #204, #208, #209, #213, #223); WIPEOUT and gradients (#147, #162). Left: through DWG, acadrust drops custom-class entities and objects, xdata on table records and blocks, entity colour book names and reactors; UCS elevation; MTEXT background colours; unknown entities follow only layer edits, and renamed layers and blocks lose their foreign data A user's QSAVE now asks before such a loss and keeps the previous file as `.bak`; the loss itself remains. | High | 6–10 | | FF2 | Multileader leftovers (native MULTILEADER read/write landed, #459): several landings per multileader (extra leader roots are folded into the lines), per-object overrides (leader colour and linetype, arrowhead symbol, text frame), annotative scale contexts; check the text placement of our MULTILEADER output in AutoCAD | Medium | 3–5 | | FF3 | Save-version leftovers (DXF/DWG 2000–2018, binary DXF, SAVEAS `version`/`binary` and the default save version landed, #421): no R14 DWG or R12 DXF output; the Save dialog can't pick the version per file (the file picker doesn't report the chosen type; File > Default Save Format sets it); no command-line SAVEAS format prompt | Low | 2–4 | | FF4 | Code-page leftovers (pre-2007 DXF read in their `$DWGCODEPAGE` landed, #505): Johab (ANSI_1361) and DOS 855/857/860–865/869 read as ANSI_1252; saving declares `ANSI_1252` instead of the file's code page (the text is pure ASCII, so still correct); acadrust approximates DOS code pages in pre-2007 DWG (DOS437 as 866, DOS850 as 1252) | Low | 1–2 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-30 | minor | QSAVE asks before replacing a file with content the DWG writer can't keep, and ISAVEBAK keeps the previous file as `.bak`: row 1 narrowed, FF1 and F20 updated | | 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-26 | minor | BEDIT in the Block Editor (typed, Edit Block, or the Edit Block Definition dialog) switches to another block as AutoCAD's does, asking whether to save the changes not saved yet; the JSON form takes `save`: F3 evidence | From 47ed3af26c04d24067d09d05b93924e07ed73449 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 30 Oct 2026 19:11:01 -0700 Subject: [PATCH 244/900] Parity docs are updated by maintainers in batches, not in each PR (#2520) docs/gaps.md conflicts in 153 open PRs and docs/ui-parity.md in 75, because every PR had to edit them. A PR now names its rows in the description. --- AGENTS.md | 2 +- CLAUDE.md | 2 +- docs/gaps.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 657e57dec..f805cdddd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,7 +47,7 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. It follows craftrules' `standards/progress-docs.md`: the assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the affected rows and the docs' status lines and revision history. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. +`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. It follows craftrules' `standards/progress-docs.md`: the assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. PRs don't edit these docs: name the affected rows in the PR description, and maintainers update the rows, status lines and revision history in batches, which keeps open PRs from conflicting. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. ## Contributor credits (About window) diff --git a/CLAUDE.md b/CLAUDE.md index 964a00124..f5036db11 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,7 +46,7 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. It follows craftrules' `standards/progress-docs.md`: the assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. When work lands, update the affected rows and the docs' status lines and revision history. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. +`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. It follows craftrules' `standards/progress-docs.md`: the assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. PRs don't edit these docs: name the affected rows in the PR description, and maintainers update the rows, status lines and revision history in batches, which keeps open PRs from conflicting. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. ## CI workflows - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. diff --git a/docs/gaps.md b/docs/gaps.md index 1d6dca7e5..a7548c4d2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -3,8 +3,8 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (QSAVE asks before losing content and keeps a `.bak`: rows 1, FF1 and F20 updated) · **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 -that closes it. Numbers and weights live in [target-app-parity.md](target-app-parity.md); hours +list: agents pick from here (top of a section first). A PR names the rows it closes in its +description, and maintainers update them in batches. Numbers and weights live in [target-app-parity.md](target-app-parity.md); hours are Opus 5.5 agent-hours, calibrated as explained there. "Est." means a judgement from the cited evidence. Rows marked **[alpha blocker]** are what fails the [alpha gate](roadmap.md#alpha-gate); do them first. From 0ab812c12a66a5b261abe5971a75127ca2252a12 Mon Sep 17 00:00:00 2001 From: assamaral Date: Fri, 30 Oct 2026 23:16:25 -0300 Subject: [PATCH 245/900] fix(io): write $PSTYLEMODE as read, in DXF and DWG (#2400) * test(io): `$PSTYLEMODE` round-trips through DXF and DWG (#2332) Red test: a drawing read from a DXF with `$PSTYLEMODE` 0 (named plot styles) is written back without the variable, so readers default to colour-dependent plot styles. Co-Authored-By: Claude Fable 5.1 * fix(io): write `$PSTYLEMODE` as read, in DXF and DWG (#2332) `HEADER_VARS` did not list `$PSTYLEMODE`, so a drawing read from a named-plot-style file (0) was saved without it; the DWG bridge then defaulted to colour-dependent plot styles (1) and the plot came out with thicker edges. One more entry in the list; a drawing that never had the variable still writes nothing. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: assamaral <217119886+assamaral@users.noreply.github.com> --- crates/io/src/dxf_write/header.rs | 1 + crates/io/tests/it/dwg_header_vars.rs | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index b628a5c3d..27a9019a5 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -41,6 +41,7 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("PLINEWID", 40), ("CELWEIGHT", 370), ("LWDISPLAY", 290), + ("PSTYLEMODE", 290), ("INSUNITS", 70), ("MEASUREMENT", 70), ("PSLTSCALE", 70), diff --git a/crates/io/tests/it/dwg_header_vars.rs b/crates/io/tests/it/dwg_header_vars.rs index 1bebee75e..644fe375c 100644 --- a/crates/io/tests/it/dwg_header_vars.rs +++ b/crates/io/tests/it/dwg_header_vars.rs @@ -60,6 +60,21 @@ fn header_settings_round_trip_through_dwg() { check("DWG", &r); } +/// `$PSTYLEMODE` (0 = named plot styles, 1 = colour-dependent) is written as read, as DXF and +/// as DWG: left out, readers default to colour-dependent and the drawing plots with the wrong +/// table (#2332). +#[test] +fn plot_style_mode_round_trips() { + let dxf = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$PSTYLEMODE\n290\n0\n0\nENDSEC\n0\nEOF\n"; + let d = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap(); + assert_eq!(d.header.i64("PSTYLEMODE", -1), 0, "read"); + let as_dxf = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(as_dxf.header.i64("PSTYLEMODE", -1), 0, "DXF"); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let as_dwg = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(as_dwg.header.i64("PSTYLEMODE", -1), 0, "DWG"); +} + /// The current layer (`$CLAYER`) survives a DWG save and reopen, ASCII or not. A DWG stores a /// handle to the layer, and the writer used the null handle, so the drawing came back on "0" (#2252). #[test] From 1ecc2a130b15dc3c5c2605b35fd00c825a4de177 Mon Sep 17 00:00:00 2001 From: AI Slopapalooza Date: Fri, 30 Oct 2026 22:16:30 -0400 Subject: [PATCH 246/900] DXF: no CLASS instance counts in R2000 files (AutoCAD LT 2026 hung opening them) (#1060) * DXF: no CLASS instance counts in R2000 files (AutoCAD LT 2026 hung on them) Since #635 every CLASS record carries group 91, the instance count, at every version. The count came with the 2004 format: R2000 CLASS records are 1, 2, 3, 90, 280, 281. AutoCAD LT 2026 stops responding when it opens an R2000 DXF whose CLASS records have a 91, so every R2000 file CADCraft saved locked it up (a drawing opened from an R2000 file is saved as R2000 again). Isolated black-box in AutoCAD LT 2026 with synthetic files: the same R2000 file without the 91 groups opens, as does the same content declared AC1032. The counts are now written only when the file (or the DWG the bridge writes) is 2004 or later; R2000 output drops the group from every CLASS record, classes kept from a newer file included. Co-Authored-By: Claude Opus 5.5 * Test: binary R2000 drops group 91 from a kept foreign CLASS too Review follow-up: the kept-class check covered R2000 only through ASCII saves; it now also saves the fixture as binary R2000 and checks that the ACME_OBJECT CLASS record is 1, 2, 3, 90, 280, 281. Co-Authored-By: Claude Opus 5.5 * Test: binary 2018 keeps a kept foreign CLASS's instance count Review follow-up: the kept-class check now saves the fixture as binary at both R2000 (no group 91) and 2018 (group 91 after the proxy flags, with the class's count), through one helper. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Slopapalooza <307952167+Slopapalooza@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/io/src/dxf_write.rs | 6 ++-- crates/io/src/dxf_write/sections.rs | 21 +++++++++--- crates/io/tests/it/dxf_versions.rs | 25 ++++++++++++++ crates/io/tests/it/roundtrip_audit.rs | 47 ++++++++++++++++++++++----- docs/file-format-parity.md | 5 +-- 5 files changed, 87 insertions(+), 17 deletions(-) diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 4ec9fc636..a0ae2f95a 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -1,7 +1,7 @@ //! Drawing → DXF (AC1015 / R2000 structure, readable by every DXF consumer since 2000). Later -//! versions keep that structure (the groups they add are optional, DXF Reference) and differ in -//! `$ACADVER`, from 2004 in the newer DIMSTYLE groups, and from 2007 in UTF-8 text (the caller -//! picks the text encoding) and MULTILEADER entities (older files get LEADER + MTEXT). +//! versions keep that structure and differ in `$ACADVER`, from 2004 in CLASS instance counts and +//! the newer DIMSTYLE groups, and from 2007 in UTF-8 text (the caller picks the text encoding) and +//! MULTILEADER entities (older files get LEADER + MTEXT). use std::collections::HashMap; diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index fe865515b..9a21ef7a9 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1117,14 +1117,27 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec= Version::R2013); - add_class_instance_counts(&mut w.t); + add_class_instance_counts(&mut w.t, target); mark_xrefs(&mut w.t, d); 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. -fn add_class_instance_counts(tags: &mut Vec) { +/// DXF Reference group 91 of CLASS records, the instance count, which came with the 2004 format. +/// From 2004 every CLASS record gets its actual count, counted after `dxf_raw::finish` restores +/// foreign classes and objects (AutoCAD rejects a 2004+ file without it, #635). An R2000 file has +/// none, not even on a class kept from a newer file: AutoCAD LT 2026 stops responding when an +/// R2000 file's CLASS records carry a 91. +fn add_class_instance_counts(tags: &mut Vec, target: Version) { + if target < Version::R2004 { + let mut in_class = false; + tags.retain(|t| { + if t.code == 0 { + in_class = t.str() == "CLASS"; + } + !(in_class && t.code == 91) + }); + return; + } let mut counts: HashMap = HashMap::new(); for t in tags.iter().filter(|t| t.code == 0) { let kind = t.str(); diff --git a/crates/io/tests/it/dxf_versions.rs b/crates/io/tests/it/dxf_versions.rs index 3fc2f1c73..40aaa878c 100644 --- a/crates/io/tests/it/dxf_versions.rs +++ b/crates/io/tests/it/dxf_versions.rs @@ -99,6 +99,31 @@ fn dxf_at_every_version_reads_back_the_same() { } } +/// CLASS records (DXF Reference, CLASSES): group 91, the instance count, came with the 2004 +/// format and follows the proxy flags. AutoCAD LT 2026 stops responding on an R2000 file whose +/// CLASS records carry a 91, and AutoCAD rejects a 2004+ file without it (#635). +#[test] +fn class_records_follow_the_version() { + let d = sample(); + for v in Version::ALL { + for binary in [false, true] { + let tags = cadcraft_dxf::parse(&write_with(&d, "x.dxf", &opts(v, binary)).unwrap()).unwrap(); + let classes: Vec> = cadcraft_dxf::sections(&tags) + .into_iter() + .filter(|s| s.name == "CLASSES") + .flat_map(|s| cadcraft_dxf::records(&s.tags)) + .filter(|(kind, _)| kind == "CLASS") + .map(|(_, t)| t.iter().map(|x| x.code).collect()) + .collect(); + assert!(!classes.is_empty(), "{v} binary={binary}"); + let want: &[i32] = if v >= Version::R2004 { &[1, 2, 3, 90, 91, 280, 281] } else { &[1, 2, 3, 90, 280, 281] }; + for codes in classes { + assert_eq!(codes, want, "{v} binary={binary}"); + } + } + } +} + /// R2000 ASCII is exactly the R2000 DXF CADCraft always wrote. #[test] fn r2000_ascii_is_unchanged() { diff --git a/crates/io/tests/it/roundtrip_audit.rs b/crates/io/tests/it/roundtrip_audit.rs index 10f910ae8..0b15f3181 100644 --- a/crates/io/tests/it/roundtrip_audit.rs +++ b/crates/io/tests/it/roundtrip_audit.rs @@ -9,7 +9,7 @@ use std::collections::HashMap; use cadcraft_doc::{Drawing, EntityKind}; use cadcraft_dxf::{Tag, records, sections}; -use cadcraft_io::{read_dxf, write_dxf}; +use cadcraft_io::{SaveOptions, Version, read_dxf, write_dxf, write_with}; /// DXF text from lines of `code value` (the value may be empty). fn dxf(src: &str) -> String { @@ -878,19 +878,50 @@ fn saving_twice_writes_the_same_records() { assert_eq!(a.counts(), b.counts()); } +/// CLASS group 91, the instance count, came with the 2004 format (DXF Reference, CLASSES). A +/// 2004+ save counts the records of every class, generated and kept; an R2000 save has none, +/// even for a kept class whose record had one (AutoCAD LT 2026 stops responding on an R2000 file +/// whose CLASS records carry a 91). #[test] -fn class_records_have_instance_counts_for_generated_and_preserved_records() { - let (_, a, b) = saves(&fixture()); +fn class_records_have_instance_counts_from_2004_only() { + // The fixture's ACME_OBJECT class as a 2004+ writer has it, with its count. + let src = fixture().replacen("ACME_OBJECT\n2\nAcmeObject\n3\nAcmeApp\n90\n0\n", "ACME_OBJECT\n2\nAcmeObject\n3\nAcmeApp\n90\n0\n91\n1\n", 1); + assert_ne!(src, fixture()); + let (d, a, b) = saves(&src); for out in [&a, &b] { - let counts = out.counts(); for class in out.in_section("CLASSES", "CLASS") { - let name = s(class, 1); - let instance_count = class.iter().find(|t| t.code == 91).map(Tag::i64); - assert_eq!(instance_count, counts.get(&name).map(|n| *n as i64), "CLASS {name}"); + let codes: Vec = class.iter().map(|t| t.code).collect(); + assert_eq!(codes, [1, 2, 3, 90, 280, 281], "R2000 CLASS {}", s(class, 1)); } assert!(out.in_section("CLASSES", "CLASS").iter().any(|c| s(c, 1) == "ACME_OBJECT")); - assert_eq!(counts.get("ACME_OBJECT"), Some(&1)); } + // Binary files the same way: none at R2000, the count at 2018. + let acme = |version: Version| { + let bytes = write_with(&d, "x.dxf", &SaveOptions { version: Some(version), binary: true }).expect("save binary"); + let tags = cadcraft_dxf::parse(&bytes).expect("parse binary"); + let class = sections(&tags) + .into_iter() + .filter(|sec| sec.name == "CLASSES") + .flat_map(|sec| records(&sec.tags)) + .find(|(kind, class)| kind == "CLASS" && s(class, 1) == "ACME_OBJECT") + .map(|(_, class)| class) + .expect("ACME_OBJECT CLASS"); + let codes: Vec = class.iter().map(|t| t.code).collect(); + (codes, class.iter().find(|t| t.code == 91).map(Tag::i64)) + }; + assert_eq!(acme(Version::R2000), (vec![1, 2, 3, 90, 280, 281], None), "binary R2000 ACME_OBJECT CLASS"); + assert_eq!(acme(Version::R2018), (vec![1, 2, 3, 90, 91, 280, 281], Some(1)), "binary 2018 ACME_OBJECT CLASS"); + let r2018 = write_with(&d, "x.dxf", &SaveOptions { version: Some(Version::R2018), binary: false }).expect("save 2018"); + let out = Out::new(std::str::from_utf8(&r2018).expect("UTF-8")); + let counts = out.counts(); + for class in out.in_section("CLASSES", "CLASS") { + let name = s(class, 1); + let codes: Vec = class.iter().map(|t| t.code).collect(); + assert_eq!(codes, [1, 2, 3, 90, 91, 280, 281], "2018 CLASS {name}"); + let instance_count = class.iter().find(|t| t.code == 91).map(Tag::i64); + assert_eq!(instance_count, Some(counts.get(&name).map_or(0, |n| *n as i64)), "CLASS {name}"); + } + assert_eq!(counts.get("ACME_OBJECT"), Some(&1)); } #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d2af85803..1bc1529c1 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-28 · **Change:** minor (attribute value edits refresh exported baselines) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them) · **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 @@ -64,7 +64,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | R12 (AC1009), ASCII | read, write | yes: no version gating; old-style POLYLINE/VERTEX read (polyface meshes flattened to 3D polylines) | **no** | | R12 binary | read, write | **no** (binary parser expects R13+ 2-byte group codes) | no | -| R13–R2018, ASCII | read, write each of 2000/2004/2007/2010/2013/2018 | yes, one reader for all versions | yes, each of 2000–2018 (#421): R2000 structure (later versions add only optional groups) with that `$ACADVER`; UTF-8 text from 2007; no CLASS instance counts (91) | +| R13–R2018, ASCII | read, write each of 2000/2004/2007/2010/2013/2018 | yes, one reader for all versions | yes, each of 2000–2018 (#421): R2000 structure with that `$ACADVER`; UTF-8 text from 2007; CLASS instance counts (91) from 2004 only (#635; with them, AutoCAD LT 2026 stops responding on an R2000 file) | | R13–R2018, binary | read, write | yes | yes, each of 2000–2018 (SAVEAS `binary`; a binary file stays binary on QSAVE) | | Code pages (`$DWGCODEPAGE`, ANSI_932/936/949/950/125x) | yes | yes (#505): ASCII and binary DXF before 2007 decode from their code page (ANSI_874/932/936/949/950/1250–1258, DOS437/850/852/866, ISO 8859, Macintosh); a file that is valid UTF-8 reads as UTF-8; Johab and other DOS code pages read as ANSI_1252 (`dxf/src/codepage.rs`) | writes `\U+` escapes (#169), which is correct; declares `ANSI_1252` | | `\U+`/`\M+` escapes | yes | yes (`\M+` since #505; Johab `\M+4` stays literal) | `\U+` yes | @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 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-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) | From 2701983688995047bbfa21a9f2db540043f9310e Mon Sep 17 00:00:00 2001 From: ATARYS-LAB Date: Sat, 31 Oct 2026 03:16:34 +0100 Subject: [PATCH 247/900] Ctrl/Cmd+W closes the drawing, as the File menu shows (#2057) * Ctrl/Cmd+W closes the drawing, as the File menu shows File > Close shows Cmd+W (Ctrl+W on Windows and Linux), but the keyboard table had no entry for it, so the key did nothing outside the macOS native menu. The table moves into builtin_shortcuts() (the shape #1703 also uses), and a test checks that every shortcut a command shows runs that command. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG * Clippy: assign operators in the shortcut test's key parser Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG --------- Co-authored-by: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/menus.rs | 60 +++++++++++++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 906ccb707..d7c1c9078 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -790,18 +790,20 @@ pub fn run_transparent(app: &mut CadApp, id: &str) { } } -/// Keyboard shortcuts and function keys. -pub fn shortcuts(app: &mut CadApp, ctx: &egui::Context) { +/// CADCraft's keyboard shortcuts and function keys, each with the command it runs. Every shortcut a +/// command shows (its registry `key`, or a UI command's) must be here, or pressing it does nothing. +pub(crate) fn builtin_shortcuts() -> Vec<(egui::KeyboardShortcut, &'static str)> { use egui::{Key, KeyboardShortcut, Modifiers}; let sc = |m: Modifiers, k: Key| KeyboardShortcut::new(m, k); let cmd = Modifiers::COMMAND; let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT; - let pairs: &[(KeyboardShortcut, &str)] = &[ + vec![ (sc(cmd_shift, Key::A), "pickstyle"), (sc(cmd_shift, Key::Z), "redo"), (sc(cmd, Key::Z), "u"), (sc(cmd, Key::Y), "redo"), (sc(cmd, Key::N), "new"), + (sc(cmd, Key::W), "close"), (sc(cmd, Key::O), "ui.open"), (sc(cmd_shift, Key::S), "ui.saveas"), (sc(cmd, Key::S), "qsave"), @@ -826,7 +828,15 @@ pub fn shortcuts(app: &mut CadApp, ctx: &egui::Context) { (sc(Modifiers::NONE, Key::F10), "polar"), (sc(Modifiers::NONE, Key::F11), "otrack"), (sc(Modifiers::NONE, Key::F12), "dynmode"), - ]; + ] +} + +/// Keyboard shortcuts and function keys. +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(); crate::clipboard::mirror(app, ctx); if app.closing.is_some() { return; @@ -841,7 +851,7 @@ pub fn shortcuts(app: &mut CadApp, ctx: &egui::Context) { // Cmd/Ctrl+C, X and V arrive as clipboard events, not key presses. let mut fire = crate::clipboard::shortcut_commands(app, ctx); ctx.input_mut(|i| { - for (s, id) in pairs { + for (s, id) in &pairs { if i.consume_shortcut(s) && !fire.contains(id) { fire.push(*id); } @@ -895,6 +905,46 @@ mod tests { (CadApp::new(Session::new(), services), asked) } + /// A registry shortcut ("Cmd+Shift+Z", "F8") as egui reads it. + fn parse_shortcut(s: &str) -> Option { + let mut m = egui::Modifiers::NONE; + let (mods, key) = s.rsplit_once('+').unwrap_or(("", s)); + for part in mods.split('+').filter(|p| !p.is_empty()) { + match part { + "Cmd" => m |= egui::Modifiers::COMMAND, + "Shift" => m |= egui::Modifiers::SHIFT, + "Alt" => m |= egui::Modifiers::ALT, + _ => return None, + } + } + Some(egui::KeyboardShortcut::new(m, egui::Key::from_name(key)?)) + } + + #[test] + fn every_shown_shortcut_runs_its_command() { + // Handled outside the table: Delete by the command line (it erases the selection only when + // the line is empty), Cmd+8 before it (QuickCalc's own field keeps focus), Cmd+Q by the + // macOS app menu, the only place that shows it. + let elsewhere = [("Delete", "erase.selection"), ("Cmd+8", "ui.toggle.quickcalc"), ("Cmd+Q", "ui.quit")]; + let table = super::builtin_shortcuts(); + let shown = cadcraft_engine::command_specs() + .iter() + .filter_map(|c| Some((c.shortcut?, c.id))) + .chain(super::UI_COMMANDS.iter().filter_map(|(id, _, _, sc)| Some(((*sc)?, *id)))); + let mut missing = Vec::new(); + for (key, id) in shown { + if elsewhere.contains(&(key, id)) { + continue; + } + let sc = parse_shortcut(key).unwrap_or_else(|| panic!("{id}: unreadable shortcut {key}")); + // The table may run a command's UI form (`ui.open` for `open`), which does the same. + if !table.iter().any(|(s, i)| *s == sc && (*i == id || i.strip_prefix("ui.") == Some(id))) { + missing.push(format!("{key} {id}")); + } + } + assert!(missing.is_empty(), "shown but not run: {missing:?}"); + } + #[test] fn plot_and_print_open_the_plot_dialog_and_exportpdf_asks_for_a_file() { set_io(IoHooks { read: |_, _| Err("no reader in tests".into()), write: |_, _| Err("no writer in tests".into()), plot: Some(fake_plot) }); From dc6a0e9ec3c11a904bbe035ea006c1cb61f9f981 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:16:38 +0300 Subject: [PATCH 248/900] engine: renaming a layer repoints every viewport's frozen list and colour overrides (#1264) --- crates/engine/src/cmd/layer.rs | 1 + crates/engine/src/cmd/layer/merge.rs | 33 ++++++++++++++++++++ crates/engine/tests/it/layer_merge_delete.rs | 13 ++++++++ 3 files changed, 47 insertions(+) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 582a93635..806641ef6 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -250,6 +250,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { repoint(&mut std::sync::Arc::make_mut(block).entities, &old, &nn); } } + merge::rename_in_viewports(d, &old, &nn); if cur.eq_ignore_ascii_case(&old) { d.header.set_str("CLAYER", &nn); } diff --git a/crates/engine/src/cmd/layer/merge.rs b/crates/engine/src/cmd/layer/merge.rs index b2ac19e1f..de8c31800 100644 --- a/crates/engine/src/cmd/layer/merge.rs +++ b/crates/engine/src/cmd/layer/merge.rs @@ -115,6 +115,39 @@ pub(super) fn forget_in_viewports(d: &mut Drawing, set: &HashSet) { } } +/// Point every layout viewport's frozen list and colour overrides at a renamed layer. +pub(super) fn rename_in_viewports(d: &mut Drawing, old: &str, new: &str) { + for layout in &mut d.layouts { + let hs: Vec = layout + .entities + .iter() + .filter(|e| match &e.kind { + EntityKind::Viewport(v) => { + v.frozen_layers.iter().any(|l| l.eq_ignore_ascii_case(old)) || v.layer_colors.iter().any(|(l, _)| l.eq_ignore_ascii_case(old)) + } + _ => false, + }) + .map(|e| e.handle) + .collect(); + for h in hs { + layout.entities.modify(h, |e| { + if let EntityKind::Viewport(v) = &mut e.kind { + for l in &mut v.frozen_layers { + if l.eq_ignore_ascii_case(old) { + *l = new.to_string(); + } + } + for (l, _) in &mut v.layer_colors { + if l.eq_ignore_ascii_case(old) { + *l = new.to_string(); + } + } + } + }); + } + } +} + fn lower_set(names: &[String]) -> HashSet { names.iter().map(|n| n.to_ascii_lowercase()).collect() } diff --git a/crates/engine/tests/it/layer_merge_delete.rs b/crates/engine/tests/it/layer_merge_delete.rs index 4778a4c57..bcbc2ed0f 100644 --- a/crates/engine/tests/it/layer_merge_delete.rs +++ b/crates/engine/tests/it/layer_merge_delete.rs @@ -159,3 +159,16 @@ fn layer_delete_clears_viewport_overrides_for_the_layer() { s.execute("layer.new", &json!({ "name": "C" })).unwrap(); assert!(viewport_lists(&s).iter().all(|(f, _)| !f.contains(&"C".to_string()))); } + +#[test] +fn renaming_a_layer_repoints_viewport_lists() { + let mut s = drawing(); + assert_eq!(viewport_lists(&s), vec![(vec!["A".to_string(), "C".to_string()], vec!["B".to_string()])]); + s.execute("rename", &json!({ "table": "layer", "from": "A", "to": "Murs" })).unwrap(); + assert_eq!(viewport_lists(&s), vec![(vec!["Murs".to_string(), "C".to_string()], vec!["B".to_string()])]); + // layer.set's newName form (what the Properties palette sends) goes through the same path. + s.execute("layer.set", &json!({ "name": "B", "newName": "Cloisons" })).unwrap(); + assert_eq!(viewport_lists(&s), vec![(vec!["Murs".to_string(), "C".to_string()], vec!["Cloisons".to_string()])]); + s.undo().unwrap(); + assert_eq!(viewport_lists(&s), vec![(vec!["Murs".to_string(), "C".to_string()], vec!["B".to_string()])], "undo brings the old name back"); +} From 9b7149676bbda71a158d68f468baf5225b310ef7 Mon Sep 17 00:00:00 2001 From: assamaral Date: Fri, 30 Oct 2026 23:16:42 -0300 Subject: [PATCH 249/900] fix(io): MTEXT legacy column groups no longer leak into the entity (#2247) (#2416) * test(io): MTEXT legacy column groups stay in the AcDbMText subclass (#2247) `legacy_column_groups_stay_in_the_mtext_subclass` (red: the column width 48 is read as the entity's ltscale, 12.5; the height count 50 as a column height). Co-Authored-By: Claude Sonnet 5.5 * fix(io): MTEXT legacy column groups no longer leak into the entity (#2247) `common()` read the linetype scale (48) and the other AcDbEntity groups from the whole record, so the column width 48 of an MTEXT's legacy column groups became its ltscale. They are now read from the AcDbEntity subclass only. `read_columns` took the height count (the first 50) for a column height and `column_tags` did not write it; both follow the DXF layout now. Co-Authored-By: Claude Sonnet 5.5 * test(engine): the MTEXT entmake column heights carry their count (#2247) Group 50 after the column type is the height count, then the heights. Thanks to austin62jake for the report and the fix. Co-Authored-By: Claude Sonnet 5.5 * test(io): a marker-less MTEXT with an embedded object keeps its own ltscale (#2247) Case from #2276 (Zaxaerith): without subclass markers, the 48 of an embedded object (101) was read as Common.ltscale. Co-Authored-By: Claude Sonnet 5.5 * fix(io): stop the entity's own groups at an embedded object (#2247) Without subclass markers, an embedded object's 48 was read as Common.ltscale. Suggested by austin62jake; case and test from #2276 (Zaxaerith). Co-Authored-By: Claude Sonnet 5.5 * style(io): rustfmt the new MTEXT test Co-Authored-By: Claude Sonnet 5.5 * fix(io): keep layer and colour that follow a subclass marker in a list with no AcDbEntity marker entity_groups ended the common region at the first subclass marker other than AcDbEntity, so an entmake list such as (0 . "LINE") (100 . "AcDbLine") (8 . "Walls") was read on layer 0. The region now ends at a marker only when the record has an AcDbEntity marker (files from R13 on always do); other records are read as a whole up to an embedded object (101), as before the column change. Co-Authored-By: Claude Sonnet 5.5 * fix(io): markers inside an application-defined group do not end the entity's groups A `102 {...102 }` group before AcDbEntity may hold any code, 100 and 101 included: `entity_groups` stopped there and the layer and colour that followed fell back to defaults. The scan now skips the contents of such groups when looking for the AcDbEntity marker and for the end of its groups. Review of #2416. Co-Authored-By: Claude Fable 5.1 * fix(io): keep every column height of files written before the height count CADCraft up to f536bf4 wrote group 76 = n and n group-50 heights, no count. Reading those with the counted format dropped the first height and rewrote 76 as n - 1. The first 50 is a count only when there are 76 + 1 of them. Co-Authored-By: Claude Fable 5.1 * fix(io): MTEXT column heights skip application-defined groups; no count for an empty list A `102 {...}` group inside the MTEXT record may hold a 50 of its own: it counted as a height and made a legacy record (76 = n, n heights, no count) look counted, dropping the first height. `read_columns` now filters the record with `outside_app` (shared with `entity_groups`). `column_tags` wrote a lone `50 = 0` for a dynamic manual column with no heights, which read back as one height of 0; the count is omitted for an empty list, so `heights: []` round trips. ZWCAD 2025 also read that lone 50 as the rotation and zeroed it. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/lisp/tests.rs | 2 +- crates/io/src/dxf_read/common.rs | 39 ++++- crates/io/src/dxf_read/mtext_dxf.rs | 17 +- crates/io/tests/it/mtext_columns_roundtrip.rs | 154 +++++++++++++++++- 4 files changed, 199 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 31e78bd15..0cb31f395 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -405,7 +405,7 @@ fn entity_lists_hold_angles_in_radians() { // MTEXT: 50 before the column type (75) is the rotation, after it a column height. ok( &mut s, - "(entmake (list '(0 . \"MTEXT\") '(10 0.0 0.0 0.0) '(40 . 2.5) '(41 . 10.0) '(1 . \"abc\") (cons 50 (/ pi 3)) '(75 . 2) '(76 . 2) '(79 . 0) '(48 . 10.0) '(49 . 1.0) '(50 . 30.0) '(50 . 20.0)))", + "(entmake (list '(0 . \"MTEXT\") '(10 0.0 0.0 0.0) '(40 . 2.5) '(41 . 10.0) '(1 . \"abc\") (cons 50 (/ pi 3)) '(75 . 2) '(76 . 2) '(79 . 0) '(48 . 10.0) '(49 . 1.0) '(50 . 2.0) '(50 . 30.0) '(50 . 20.0)))", ); let mtext = s.doc().unwrap().model.iter().find_map(|e| match &e.kind { cadcraft_doc::EntityKind::MText(t) => Some((t.rotation, t.columns.as_ref().map(|c| c.heights.clone()))), diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 9cba18171..e46f3c09d 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -43,28 +43,53 @@ fn transparency_440(v: i64) -> Transparency { } } +/// The tags outside application-defined groups (`102 {` to `102 }`, whose codes are the +/// application's), with their positions in `tags`. +pub(super) fn outside_app(tags: &[Tag]) -> impl Iterator { + let mut in_app = false; + tags.iter().enumerate().filter(move |(_, t)| { + if t.code == 102 { + in_app = t.str().starts_with('{'); + } + !in_app && t.code != 102 + }) +} + +/// The groups of the AcDbEntity subclass: the record up to the entity's own subclass marker (all +/// of it in files without markers, and in lists with no AcDbEntity marker, whose layer and colour +/// may follow the entity's marker), or up to an embedded object (101). Later groups reuse the +/// codes: an MTEXT's column width is 48. Markers inside an application-defined group (`102 {` +/// to `102 }`, whose codes are the application's) do not count. +fn entity_groups(tags: &[Tag]) -> &[Tag] { + let outside_app = || outside_app(tags); + let marked = outside_app().any(|(_, t)| t.code == 100 && t.str() == "AcDbEntity"); + let end = outside_app().find(|(_, t)| (marked && t.code == 100 && t.str() != "AcDbEntity") || t.code == 101).map_or(tags.len(), |(i, _)| i); + tags.get(..end).unwrap_or(tags) +} + pub(super) fn common(t: &T) -> Common { - let mut c = Common { layer: t.s(8).unwrap_or_else(|| "0".into()), linetype: t.s(6).unwrap_or_else(|| "ByLayer".into()), ..Common::default() }; - if let Some(v) = t.i(62) { + let e = T(entity_groups(t.0)); + let mut c = Common { layer: e.s(8).unwrap_or_else(|| "0".into()), linetype: e.s(6).unwrap_or_else(|| "ByLayer".into()), ..Common::default() }; + if let Some(v) = e.i(62) { c.color = Color::from_aci(v as i16); if v < 0 { c.color = Color::ByLayer; c.visible = true; } } - if let Some(tc) = t.i(420) { + if let Some(tc) = e.i(420) { c.color = Color::True(Rgb::from_u32(tc as u32)); } - if let Some(lw) = t.i(370) { + if let Some(lw) = e.i(370) { c.lineweight = Lineweight::from_dxf(lw as i16); } - if let Some(s) = t.f(48) { + if let Some(s) = e.f(48) { c.ltscale = if s > 0.0 { s } else { 1.0 }; } - if t.i(60) == Some(1) { + if e.i(60) == Some(1) { c.visible = false; } - if let Some(v) = t.i(440) { + if let Some(v) = e.i(440) { c.transparency = transparency_440(v); } c.thickness = t.fd(39, 0.0); diff --git a/crates/io/src/dxf_read/mtext_dxf.rs b/crates/io/src/dxf_read/mtext_dxf.rs index f955603e6..9ab133e44 100644 --- a/crates/io/src/dxf_read/mtext_dxf.rs +++ b/crates/io/src/dxf_read/mtext_dxf.rs @@ -74,16 +74,21 @@ fn finite(v: f64) -> f64 { /// The columns of an MTEXT, and the column width (group 48) when there are columns. pub(crate) fn read_columns(tags: &[Tag]) -> Option<(MTextColumns, f64)> { - let tags = own(tags); + // An application-defined group in the record may hold any code, 50 included. + let tags: Vec<&Tag> = super::common::outside_app(own(tags)).map(|(_, t)| t).collect(); let start = tags.iter().position(|t| t.code == 75)?; - let kind = match tags.get(start).map(Tag::i64) { + let kind = match tags.get(start).map(|t| t.i64()) { Some(1) => MTextColumnType::Static, Some(2) => MTextColumnType::Dynamic, _ => return None, }; let cols = tags.get(start..).unwrap_or_default(); - let first = |code: i32| cols.iter().find(|t| t.code == code); - let heights: Vec = cols.iter().filter(|t| t.code == 50).take(MAX_COLUMNS).map(|t| finite(t.f64()).max(0.0)).collect(); + let first = |code: i32| cols.iter().find(|t| t.code == code).copied(); + // The first 50 is the number of heights that follow, unless the file predates the count + // (CADCraft up to f536bf4 wrote the n heights of group 76 alone). + let fifties = cols.iter().filter(|t| t.code == 50); + let counted = first(76).is_some_and(|t| fifties.clone().count() as i64 - 1 == t.i64()); + let heights: Vec = fifties.skip(usize::from(counted)).take(MAX_COLUMNS).map(|t| finite(t.f64()).max(0.0)).collect(); let count = first(76).map(Tag::i64).unwrap_or(heights.len() as i64).clamp(1, MAX_COLUMNS as i64); let auto_height = first(79).map(Tag::i64).unwrap_or(0) != 0; let defined = tags.iter().find(|t| t.code == 46).map(|t| finite(t.f64()).max(0.0)).unwrap_or(0.0); @@ -115,6 +120,10 @@ pub(crate) fn column_tags(t: &MText) -> Vec { Tag::f(48, t.width), Tag::f(49, c.gutter), ]; + // No count for an empty list: a lone 50 = 0 would read back as one height of 0. + if !heights.is_empty() { + v.push(Tag::i(50, heights.len() as i64)); + } v.extend(heights.into_iter().map(|h| Tag::f(50, h))); v } diff --git a/crates/io/tests/it/mtext_columns_roundtrip.rs b/crates/io/tests/it/mtext_columns_roundtrip.rs index 7db9ed685..4273afa12 100644 --- a/crates/io/tests/it/mtext_columns_roundtrip.rs +++ b/crates/io/tests/it/mtext_columns_roundtrip.rs @@ -2,8 +2,9 @@ //! 75/76/78/79/48/49/50, tabs as `^I`, carets as `^ `. use cadcraft_doc::{Common, Drawing, EntityKind, MText, MTextColumnType, MTextColumns, Space}; +use cadcraft_dxf::Tag; use cadcraft_geom::Vec3; -use cadcraft_io::{read_dxf, write_dxf}; +use cadcraft_io::{entity_from_groups, read_dxf, write_dxf}; fn mtext(contents: &str, rotation: f64, columns: Option) -> MText { MText { @@ -76,6 +77,115 @@ fn paragraph_codes_tabs_and_carets_round_trip() { assert!(back.model.iter().any(|e| matches!(&e.kind, EntityKind::MText(m) if m.contents == contents))); } +#[test] +fn legacy_column_groups_stay_in_the_mtext_subclass() { + // Columns as other programs write them (#2247): the column width (48) and the height count + // (the first 50) are groups of the AcDbMText subclass, not the entity's linetype scale and a + // column height. + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::MText(mtext("x", 0.0, None))).unwrap(); + let legacy = + " 75\r\n1\r\n 76\r\n3\r\n 78\r\n0\r\n 79\r\n0\r\n 48\r\n12.5\r\n 49\r\n2.5\r\n 50\r\n3\r\n 50\r\n20.0\r\n 50\r\n20.0\r\n 50\r\n20.0\r\n"; + let dxf = write_dxf(&d).replacen(" 44\r\n1.0\r\n", &format!(" 44\r\n1.0\r\n{legacy}"), 1); + assert!(dxf.contains(" 75\r\n"), "legacy groups inserted"); + let back = read_dxf(dxf.as_bytes()).unwrap(); + let Some(e) = back.model.iter().find(|e| matches!(e.kind, EntityKind::MText(_))) else { panic!("no mtext") }; + assert_eq!(e.common.ltscale, 1.0, "48 is the column width, not the linetype scale"); + let EntityKind::MText(t) = &e.kind else { panic!("no mtext") }; + let c = MTextColumns { kind: MTextColumnType::Static, count: 3, gutter: 2.5, height: 20.0, ..Default::default() }; + assert_eq!(t.columns, Some(c)); + // Written back as read: the height count before the heights. + let out = write_dxf(&back); + assert!(out.contains(" 50\r\n3\r\n 50\r\n20.0\r\n"), "height count before the heights"); +} + +#[test] +fn heights_written_without_a_count_are_all_kept() { + // Files written before the height count (CADCraft up to f536bf4) have group 76 = n and n + // heights, no count: the first 50 is a height there (#2247 review). + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::MText(mtext("x", 0.0, None))).unwrap(); + let dxf = write_dxf(&d); + for (heights, old) in [ + (vec![7.0], " 75\r\n2\r\n 76\r\n1\r\n 78\r\n0\r\n 79\r\n0\r\n 48\r\n12.5\r\n 49\r\n2.5\r\n 50\r\n7.0\r\n"), + ( + vec![5.0, 3.0, 4.0], + " 75\r\n2\r\n 76\r\n3\r\n 78\r\n0\r\n 79\r\n0\r\n 48\r\n12.5\r\n 49\r\n2.5\r\n 50\r\n5.0\r\n 50\r\n3.0\r\n 50\r\n4.0\r\n", + ), + ] { + let back = read_dxf(dxf.replacen(" 44\r\n1.0\r\n", &format!(" 44\r\n1.0\r\n{old}"), 1).as_bytes()).unwrap(); + let Some(EntityKind::MText(t)) = back.model.iter().map(|e| &e.kind).find(|k| matches!(k, EntityKind::MText(_))) else { panic!("no mtext") }; + let n = heights.len(); + let c = MTextColumns { + kind: MTextColumnType::Dynamic, + count: n as u16, + gutter: 2.5, + height: heights.iter().copied().fold(0.0, f64::max), + auto_height: false, + heights: heights.clone(), + flow_reversed: false, + }; + assert_eq!(t.columns, Some(c), "{n} heights without a count"); + // Written back with the count, and still n columns. + let out = write_dxf(&back); + assert!(out.contains(&format!(" 76\r\n{n}\r\n 78\r\n")), "76 stays {n}: {out}"); + assert!(out.contains(&format!(" 50\r\n{n}\r\n 50\r\n{:.1}\r\n", heights[0])), "count then the first height: {out}"); + } +} + +#[test] +fn heights_inside_an_application_group_are_not_column_heights() { + // An application-defined group (102 {...}) in the record may hold a 50 of its own: it is + // neither a height nor the count that tells a legacy record apart (#2247 review). + let tags = [ + Tag::s(8, "0"), + Tag::f(40, 0.5), + Tag::f(41, 12.5), + Tag::s(1, "x"), + Tag::i(75, 2), + Tag::i(76, 3), + Tag::i(78, 0), + Tag::i(79, 0), + Tag::f(48, 12.5), + Tag::f(49, 2.5), + Tag::f(50, 5.0), + Tag::f(50, 3.0), + Tag::f(50, 4.0), + Tag::s(102, "{ACME_APP"), + Tag::f(50, 8.0), + Tag::s(102, "}"), + ]; + let Some((_, EntityKind::MText(t))) = entity_from_groups("MTEXT", &tags) else { panic!("MTEXT was not read") }; + let c = MTextColumns { + kind: MTextColumnType::Dynamic, + count: 3, + gutter: 2.5, + height: 5.0, + auto_height: false, + heights: vec![5.0, 3.0, 4.0], + flow_reversed: false, + }; + assert_eq!(t.columns, Some(c)); +} + +#[test] +fn empty_manual_heights_round_trip() { + // A dynamic manual column with no heights stays without heights: no count is written for an + // empty list (a lone 50 = 0 would read back as one height of 0) (#2247 review). + let c = MTextColumns { + kind: MTextColumnType::Dynamic, + count: 1, + gutter: 0.5, + height: 0.0, + auto_height: false, + heights: Vec::new(), + flow_reversed: false, + }; + let (t, dxf) = round_trip(mtext("x", 0.0, Some(c.clone()))); + assert_eq!(t.columns, Some(c)); + assert!(!dxf.contains(" 50\r\n0\r\n"), "no height count for an empty list: {dxf}"); +} + #[test] fn hostile_column_groups_do_not_panic() { let mut d = Drawing::new_metric(); @@ -91,3 +201,45 @@ fn hostile_column_groups_do_not_panic() { let _ = read_dxf(bad.as_bytes()); } } + +#[test] +fn embedded_groups_do_not_supply_mtext_common_ltscale() { + // Without subclass markers, an embedded object (101) reuses 48 for its own data (#2247, test from #2276). + let tags = [Tag::s(8, "0"), Tag::f(40, 0.5), Tag::f(41, 12.5), Tag::s(1, "own text"), Tag::s(101, "Embedded Object"), Tag::f(48, 99.0)]; + let Some((common, _)) = entity_from_groups("MTEXT", &tags) else { panic!("MTEXT was not read") }; + assert_eq!(common.ltscale, 1.0, "48 after 101 belongs to the embedded object"); +} + +#[test] +fn layer_after_an_entmake_subclass_marker_is_kept() { + // An entity list built by hand may put a subclass marker before the layer and have no AcDbEntity + // marker at all: the whole list is then the entity's (#2247 review). + let tags = [Tag::s(100, "AcDbLine"), Tag::s(8, "Walls"), Tag::i(62, 3), Tag::f(10, 0.0), Tag::f(20, 0.0), Tag::f(11, 1.0), Tag::f(21, 0.0)]; + let Some((common, _)) = entity_from_groups("LINE", &tags) else { panic!("LINE was not read") }; + assert_eq!(common.layer, "Walls"); + assert_eq!(common.color, cadcraft_color::Color::from_aci(3)); +} + +#[test] +fn markers_inside_an_application_group_do_not_end_the_entity_groups() { + // An application-defined group (102 {...} before AcDbEntity) may hold any code, 100 and 101 + // included: the entity's layer and colour come after it (#2247 review). + let tags = [ + Tag::s(5, "A1"), + Tag::s(102, "{ACME_APP"), + Tag::s(100, "AcmeMarker"), + Tag::s(101, "AcmeObject"), + Tag::s(102, "}"), + Tag::s(100, "AcDbEntity"), + Tag::s(8, "Walls"), + Tag::i(62, 3), + Tag::s(100, "AcDbLine"), + Tag::f(10, 0.0), + Tag::f(20, 0.0), + Tag::f(11, 1.0), + Tag::f(21, 0.0), + ]; + let Some((common, _)) = entity_from_groups("LINE", &tags) else { panic!("LINE was not read") }; + assert_eq!(common.layer, "Walls"); + assert_eq!(common.color, cadcraft_color::Color::from_aci(3)); +} From 85fc3991b1d313f50f73ac204ac07fb7861ffa21 Mon Sep 17 00:00:00 2001 From: assamaral Date: Fri, 30 Oct 2026 23:16:47 -0300 Subject: [PATCH 250/900] fix(io): an attached ATTRIB keeps its Constant mode through DXF and DWG (#2246) (#2418) * test(io): the Constant mode of an attached ATTRIB survives DXF and DWG (#2246) Co-Authored-By: Claude Sonnet 5.5 * fix(io): an attached ATTRIB keeps its Constant mode through DXF and DWG (#2246) Co-Authored-By: Claude Sonnet 5.5 * test(io): attached ATTRIB Constant mode over every save version and encoding The regression covered the default DXF and DWG saves only. It now also saves with each Version::ALL entry as ASCII DXF, binary DXF and DWG. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/io/src/dxf_read/entities.rs | 2 +- crates/io/tests/it/attrib_modes.rs | 32 ++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index aba1bdc4e..fc55fe335 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -539,7 +539,7 @@ pub(super) fn insert_attribs(recs: &[(String, Vec)], i: &mut usize, ins_lay tag: own.s(2).unwrap_or_default(), text, invisible: own.i(70).unwrap_or(0) & 1 != 0, - constant: false, + constant: own.i(70).unwrap_or(0) & 2 != 0, prompt: String::new(), props: attrib_props(&tt, ins_layer), multiline, diff --git a/crates/io/tests/it/attrib_modes.rs b/crates/io/tests/it/attrib_modes.rs index 625ead939..3dfa8e321 100644 --- a/crates/io/tests/it/attrib_modes.rs +++ b/crates/io/tests/it/attrib_modes.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use cadcraft_doc::*; use cadcraft_geom::Vec3; -use cadcraft_io::{read_dxf, write_dxf}; +use cadcraft_io::{SaveOptions, Version, read_dxf, write_dxf, write_with}; fn attrib(tag: &str, modes: AttribModes) -> Attrib { let text = Text { @@ -28,6 +28,10 @@ const LOCKED: AttribModes = AttribModes { verify: false, preset: false, lock_pos /// Block TAG with definitions A (every mode) and B (none), and a reference whose A is locked. fn drawing() -> Drawing { + drawing_c(false) +} + +fn drawing_c(constant: bool) -> Drawing { let mut d = Drawing::new_metric(); let mut b = Block::new("TAG"); for a in [attrib("A", ALL), attrib("B", AttribModes::default())] { @@ -40,7 +44,7 @@ fn drawing() -> Drawing { insert: Vec3::ZERO, scale: Vec3::new(1.0, 1.0, 1.0), rotation: 0.0, - attribs: vec![attrib("A", LOCKED), attrib("B", AttribModes::default())], + attribs: vec![Attrib { constant, ..attrib("A", LOCKED) }, attrib("B", AttribModes::default())], cols: 1, rows: 1, col_spacing: 0.0, @@ -113,3 +117,27 @@ fn a_280_before_the_tag_is_the_version_not_lock_position() { .collect(); assert!(!modes(&read_dxf(text.as_bytes()).expect("read")).0[0].lock_position); } + +/// The Constant mode (flag 2) of an ATTRIB attached to an INSERT, not only of an ATTDEF (#2246). +#[test] +fn constant_attached_attrib_survives_dxf_and_dwg() { + let d = drawing_c(true); + let constants = |d: &Drawing| -> Vec { + d.model + .iter() + .find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.attribs.iter().map(|a| a.constant).collect()) } else { None }) + .unwrap_or_default() + }; + assert_eq!(constants(&d), [true, false]); + let dxf = cadcraft_io::write(&d, "x.dxf").expect("dxf"); + assert_eq!(constants(&cadcraft_io::read(&dxf, "x.dxf").expect("read dxf")), [true, false], "dxf"); + let dwg = cadcraft_io::write(&d, "x.dwg").expect("dwg"); + assert_eq!(constants(&cadcraft_io::read(&dwg, "x.dwg").expect("read dwg")), [true, false], "dwg"); + // Every save version, in both DXF encodings and in DWG. + for version in Version::ALL { + for (name, binary) in [("x.dxf", false), ("x.dxf", true), ("x.dwg", false)] { + let bytes = write_with(&d, name, &SaveOptions { version: Some(version), binary }).expect("write"); + assert_eq!(constants(&cadcraft_io::read(&bytes, name).expect("read")), [true, false], "{version:?} {name} binary={binary}"); + } + } +} From b4b8ae294ae3a87bb518ff3976ad7f02370993f2 Mon Sep 17 00:00:00 2001 From: assamaral Date: Fri, 30 Oct 2026 23:16:51 -0300 Subject: [PATCH 251/900] fix(io): write a LINE's extrusion (210/220/230) (#2241) (#2417) * test(io): a LINE keeps its extrusion through DXF and DWG (#2241) `line_extrusion_roundtrips_with_world_endpoints` (red: group 230 is not written for a LINE with normal (0, 0, -1), so it comes back with (0, 0, 1)). Co-Authored-By: Claude Sonnet 5.5 * fix(io): write a LINE's extrusion (210/220/230) (#2241) A LINE's points are world coordinates and the reader already keeps its extrusion (the direction of its thickness), but the writer left the groups out, so a normal (0, 0, -1) came back as (0, 0, 1) from DXF and from DWG, which is written through DXF. Co-Authored-By: Claude Sonnet 5.5 * test(io): a LINE's extrusion is written as a unit vector or not at all (#2241) Co-Authored-By: Claude Sonnet 5.5 * fix(io): write a LINE's extrusion normalized, nothing for a zero or NaN normal (#2241) Co-Authored-By: Claude Sonnet 5.5 * fix(io): write a tiny extrusion's direction, drop a non-finite one Vec3::normalized returns zero at or below the drawing tolerance, so a LINE with extrusion (0, 0, -1e-10) saved with no 210/220/230 and reopened as +Z, flipping a thickness; an infinite component normalized to NaN and was written as a zero vector. The writer now normalizes by the vector's own length and writes nothing only for a zero or non-finite vector. Co-Authored-By: Claude Sonnet 5.5 * fix(io): keep the direction of a huge finite extrusion The length of (0, -1.5e308, 1.5e308) overflows to infinity, so the normal came out as (0, 0, 0) and was written as such. The vector is scaled by its largest component before it is normalized; the case is in `line_extrusion_is_written_as_a_unit_vector_or_not_at_all`. Review of #2417. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/io/src/dxf_write/entity.rs | 19 +++++++++ crates/io/tests/it/entity_props_roundtrip.rs | 43 ++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 9c2f12896..fd7c265d8 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -53,6 +53,7 @@ fn write_basic_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: b thickness(w, e); w.p(10, l.a); w.p(11, l.b); + extrusion(w, e); } EntityKind::Point(p) => { w.s(0, "POINT"); @@ -752,6 +753,24 @@ fn thickness(w: &mut W, e: &Entity) { } } +/// The extrusion (210) of an entity whose points are world coordinates, when it is not the Z axis. +fn extrusion(w: &mut W, e: &Entity) { + // Zero and non-finite vectors are not a direction: nothing is written. `Vec3::normalized` would + // also drop a tiny one (its zero threshold is the drawing tolerance) and turn infinity into NaN. + let v = e.common.extrusion; + let max = v.x.abs().max(v.y.abs()).max(v.z.abs()); + if !v.is_finite() || max == 0.0 { + return; + } + // Scaled by the largest component first: the length of a huge one would overflow to infinity. + let v = Vec3::new(v.x / max, v.y / max, v.z / max); + let len = v.len(); + let n = Vec3::new(v.x / len, v.y / len, v.z / len); + if n != Vec3::Z { + w.p(210, n); + } +} + /// Hatch origin and background colour as `CADCRAFT` xdata: `1000 HATCH`, the origin as a /// world position (`1011`, moved with the hatch by other programs) and the background colour /// name (`1000`, empty for none). The DXF Reference has no HATCH groups for either: other diff --git a/crates/io/tests/it/entity_props_roundtrip.rs b/crates/io/tests/it/entity_props_roundtrip.rs index d86d0b4b8..38d325604 100644 --- a/crates/io/tests/it/entity_props_roundtrip.rs +++ b/crates/io/tests/it/entity_props_roundtrip.rs @@ -24,6 +24,49 @@ fn square(size: f64) -> Vec { [(0.0, 0.0), (size, 0.0), (size, size), (0.0, size)].into_iter().map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).collect() } +#[test] +fn line_extrusion_roundtrips_with_world_endpoints() { + // A LINE's endpoints are world coordinates whatever its extrusion, which only directs its + // thickness; a mirrored normal (0, 0, -1) must come back from DXF and DWG (#2241). + let mut d = Drawing::new_metric(); + let common = Common { extrusion: Vec3::new(0.0, 0.0, -1.0), ..Common::default() }; + let line = Line { a: Vec3::new(1.0, 2.0, 0.0), b: Vec3::new(11.0, 7.0, 0.0) }; + let h = d.add(&Space::Model, common, EntityKind::Line(line.clone())).expect("add"); + let dxf = write_dxf(&d); + assert!(dxf.contains("230\r\n-1.0\r\n"), "the extrusion is written"); + let back = roundtrip(&d); + let e = get(&back, h); + assert_eq!(e.common.extrusion, Vec3::new(0.0, 0.0, -1.0)); + assert_eq!(e.kind, EntityKind::Line(line.clone())); + let dwg = cadcraft_io::write(&d, "x.dwg").expect("dwg"); + let back = cadcraft_io::read(&dwg, "x.dwg").expect("reopen dwg"); + let Some(e) = back.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))) else { panic!("no line") }; + assert_eq!(e.common.extrusion, Vec3::new(0.0, 0.0, -1.0), "through DWG"); + assert_eq!(e.kind, EntityKind::Line(line)); +} + +#[test] +fn line_extrusion_is_written_as_a_unit_vector_or_not_at_all() { + // A normal that is not a direction (zero, NaN) is dropped and one that is not unit length is + // normalized, so a bad 210/220/230 read from a file is not passed on as it is (#2241). + let line = Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }; + let dxf = |extrusion| { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common { extrusion, ..Common::default() }, EntityKind::Line(line.clone())).expect("add"); + write_dxf(&d) + }; + let default = dxf(Vec3::Z); + for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(f64::INFINITY, 0.0, 0.0), Vec3::new(0.0, 0.0, 5.0)] { + assert_eq!(dxf(bad), default, "{bad:?} writes nothing, like the Z axis"); + } + assert!(dxf(Vec3::new(0.0, 0.0, -5.0)).contains("230\r\n-1.0\r\n")); + // A tiny normal is still a direction: it must not read back as +Z (it would flip a thickness). + assert!(dxf(Vec3::new(0.0, 0.0, -1e-10)).contains("230\r\n-1.0\r\n"), "a tiny normal keeps its direction"); + // A huge finite normal's length overflows to infinity: it is a direction all the same. + let huge = dxf(Vec3::new(0.0, -1.5e308, 1.5e308)); + assert!(huge.contains("220\r\n-0.7071067811865475\r\n230\r\n0.7071067811865475\r\n"), "a huge normal keeps its direction:\n{huge}"); +} + #[test] fn thickness_roundtrips_on_every_entity_that_has_one() { let mut d = Drawing::new_metric(); From 4792ca2941e09813e3973b14e42807d574da071d Mon Sep 17 00:00:00 2001 From: assamaral Date: Fri, 30 Oct 2026 23:16:55 -0300 Subject: [PATCH 252/900] fix(io): a centred ATTDEF keeps its insertion point in a DWG (#2464) (#2466) * test(io): a centred ATTDEF keeps its insertion point in a DWG (#2464) Co-Authored-By: Claude Sonnet 5.5 * fix(io): an ATTDEF with no default value is placed by its tag's width in DWG (#2464) The writer keeps a justified text's stored insertion point only when it is near where the baseline starts for the text's width; an ATTDEF with an empty default value has width 0, so every AutoCAD insertion point further than half a height from the alignment point was replaced by the alignment point. The tag is what is drawn: judge against its width. Co-Authored-By: Claude Sonnet 5.5 * fix(io): keep a stored ATTDEF point that is close to the empty text's start The tag-width baseline check replaced a point read from a drawing whenever the font's width of the tag put the computed start further than the allowance away, e.g. a centred LONGTAG with group 10 at x=99.5 and group 11 at x=100 moved to about 92.17 in DXF and DWG. A stored point close to the empty text's own start is now kept as before; only otherwise is it judged against the tag. Co-Authored-By: Claude Sonnet 5.5 * test(io): store an ATTDEF point that differs from the computed baseline `assert_kept(start)` stored exactly the baseline the tag-width fallback computes, so a write that replaced group 10 with that baseline passed too. The point is now 1 off the start, within the tolerance. Review of #2466. Co-Authored-By: Claude Fable 5.1 * test(io): an empty-value ATTDEF keeps its point with an empty or absent prompt too The tag-width check applies to every ATTDEF with no default value, since the CAD displays the tag whatever the prompt: the guard now says `attdef` instead of reading as a prompt test, and the test covers a prompt, an empty one and none. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/io/src/dxf_write/common.rs | 15 +++++++- crates/io/tests/it/attdef_insert_dwg.rs | 49 +++++++++++++++++++++++++ crates/io/tests/it/main.rs | 1 + 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 crates/io/tests/it/attdef_insert_dwg.rs diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index 6ba3ce8ef..b09d90410 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -241,8 +241,19 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 { if q.is_finite() { Vec3::new(q.x, q.y, t.insert.z) } else { t.insert } } +/// `attdef_prompt` is `Some` for an ATTDEF (its prompt, which may be empty) and `None` for an ATTRIB. pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) { - w.p(10, text_insert(d, t)); + let attdef = attdef_prompt.is_some(); + // An attribute definition with no default value is drawn as its tag, whatever its prompt: the + // baseline start AutoCAD stored is judged against the tag's width too. A stored point that is + // close to the empty text's own start is kept as it is, so the font's width of the tag never + // moves it. + let own = text_insert(d, t); + let insert = match attrib { + Some((a, _)) if attdef && t.value.is_empty() && own != t.insert => text_insert(d, &Text { value: a.tag.clone(), ..t.clone() }), + _ => own, + }; + w.p(10, insert); w.f(40, t.height); w.s(1, &t.value); if t.rotation != 0.0 { @@ -277,7 +288,7 @@ pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attri } match attrib { Some((a, target)) => { - w.s(100, if attdef_prompt.is_some() { "AcDbAttributeDefinition" } else { "AcDbAttribute" }); + w.s(100, if attdef { "AcDbAttributeDefinition" } else { "AcDbAttribute" }); if target >= Version::R2010 { w.i(280, 0); } diff --git a/crates/io/tests/it/attdef_insert_dwg.rs b/crates/io/tests/it/attdef_insert_dwg.rs new file mode 100644 index 000000000..9fd1a1a3a --- /dev/null +++ b/crates/io/tests/it/attdef_insert_dwg.rs @@ -0,0 +1,49 @@ +//! A centre-justified ATTDEF keeps its insertion point in a DWG (#2464): AutoCAD puts it where the +//! baseline of the displayed tag starts, which for an attribute with an empty default value is +//! further from the alignment point than half a height. + +use cadcraft_doc::EntityKind; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +/// The `insert` x of the only ATTDEF in `d`. +fn attdef_x(d: &cadcraft_doc::Drawing) -> f64 { + d.model.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.text.insert.x) } else { None }).expect("an ATTDEF") +} + +#[test] +fn centred_attdef_with_an_empty_value_keeps_its_insertion_point() { + // The tag "LONGTAG" at height 2.5, centred on x = 100: its baseline starts half a width left. + // The stored point is 1 off that start (within the tolerance), so a write that recomputed + // it from the tag would not pass for keeping it. + let width = cadcraft_fonts::line_width("LONGTAG", 2.5, 1.0); + let start = 100.0 - width / 2.0 - 1.0; + assert!(100.0 - start > 3.0, "the point is well over a height from the alignment point"); + assert_kept(start); +} + +/// A stored point that a tag-width baseline would move is kept too (review of #2466): the check +/// does not rely on the font's width of the tag, so this one is only 0.5 from the alignment point. +#[test] +fn centred_attdef_point_near_the_alignment_point_is_kept() { + assert_kept(99.5); +} + +/// A centred ATTDEF with an empty default value and group 10 at `start`, group 11 at x = 100 is +/// read from DXF and kept by a write as DXF and as DWG (both versions). The displayed text is the +/// tag whatever the prompt: with a prompt, an empty one (group 3 empty) and none (no group 3). +fn assert_kept(start: f64) { + for prompt in ["3\nprompt\n", "3\n\n", ""] { + let dxf = format!( + "0\nSECTION\n2\nENTITIES\n0\nATTDEF\n8\n0\n10\n{start}\n20\n5.0\n40\n2.5\n1\n\n7\nSTANDARD\n72\n1\n11\n100.0\n21\n5.0\n{prompt}2\nLONGTAG\n70\n8\n0\nENDSEC\n0\nEOF\n" + ); + let d = read(dxf.as_bytes(), "t.dxf").unwrap(); + assert!((attdef_x(&d) - start).abs() < 1e-6, "read from DXF"); + let as_dxf = cadcraft_io::write(&d, "t.dxf").unwrap(); + assert!((attdef_x(&read(&as_dxf, "t.dxf").unwrap()) - start).abs() < 1e-6, "DXF, prompt {prompt:?}: insertion point changed"); + for version in [Version::R2000, Version::R2018] { + let dwg = write_with(&d, "t.dwg", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let back = read(&dwg, "t.dwg").unwrap(); + assert!((attdef_x(&back) - start).abs() < 1e-6, "{version:?}, prompt {prompt:?}: insertion point {} instead of {start}", attdef_x(&back)); + } + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 07b1e8c2e..5d6c343d0 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -5,6 +5,7 @@ mod angle_header; mod annotative_orientation; mod annotative_roundtrip; mod assoc_array_roundtrip; +mod attdef_insert_dwg; mod attrib_modes; mod attrib_props; mod block_expansion; From 75efe07d855388e450895e1928c11eb04ffa1c5e Mon Sep 17 00:00:00 2001 From: Elarionus <29511515+Elarionus@users.noreply.github.com> Date: Fri, 30 Oct 2026 19:16:59 -0700 Subject: [PATCH 253/900] Enter on a partly typed command runs the highlighted suggestion (#2135) Co-authored-by: Ethan Dale --- crates/ui-egui/src/cmdline.rs | 39 ++++++++++++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 13 +++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 9d8bd9821..40397df99 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -443,7 +443,9 @@ pub fn submit(app: &mut CadApp) { } return; } - app.cmdline(&text); + // A partly typed command name runs the highlighted (first) AutoComplete suggestion. + let completion = if app.session.prompting() { None } else { suggestions(text.trim()).into_iter().next() }; + app.cmdline_or(&text, completion.map(|s| s.id.to_ascii_lowercase()).as_deref()); } fn visible_lines(app: &CadApp, canvas: Rect, bar: Rect) -> usize { @@ -924,4 +926,39 @@ mod autocomplete_tests { tab(&mut app); assert_eq!(app.cmd.buffer, "RECTANG"); } + + fn app() -> CadApp { + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + app.start("ui.sample"); + app + } + + #[test] + fn enter_on_a_partial_name_runs_the_highlighted_suggestion() { + let mut app = app(); + app.cmd.buffer = "RECT".to_string(); + submit(&mut app); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("rectang")); + assert!(!app.session.log.iter().any(|l| l.contains("unknown command")), "{:?}", app.session.log); + } + + #[test] + fn enter_keeps_exact_names_and_reports_names_nothing_matches() { + let mut app = app(); + // An exact alias is not replaced by a longer suggestion. + app.cmd.buffer = "l".to_string(); + submit(&mut app); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("line")); + app.session.cancel(); + // A system variable name still acts as SETVAR. + app.cmd.buffer = "orthomode".to_string(); + submit(&mut app); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("setvar")); + app.session.cancel(); + // No suggestion: still an unknown command. + app.cmd.buffer = "zzqx".to_string(); + submit(&mut app); + assert!(app.session.running.is_none()); + assert!(app.session.log.iter().any(|l| l.contains("unknown command")), "{:?}", app.session.log); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0253a2cec..97ab2faf4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -422,6 +422,13 @@ 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.cmdline_or(text, None) + } + + /// [`CadApp::cmdline`], but a command name nothing knows (no command, alias, UI command, LISP + /// command or system variable) runs `fallback` instead: Enter on a partly typed name accepts + /// the highlighted AutoComplete suggestion. + pub fn cmdline_or(&mut self, text: &str, fallback: Option<&str>) -> Option { 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. @@ -430,7 +437,11 @@ impl CadApp { return None; } } - let e = self.session.cmdline(text).err()?.to_string(); + let e = match (self.session.cmdline(text), fallback) { + (Ok(()), _) => return None, + (Err(cadcraft_engine::EngineError::UnknownCommand(_)), Some(f)) => return self.cmdline(f), + (Err(e), _) => e.to_string(), + }; self.session.echo(e.clone()); Some(e) } From b187af646aca987dbf6c7dae18cddc081e8f8d97 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 30 Oct 2026 19:19:06 -0700 Subject: [PATCH 254/900] Save helpers used only by the file system build stay out of the wasm one (#2521) --- crates/engine/src/cmd/file.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 8bb4c5c75..9aaff4631 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -473,6 +473,7 @@ pub fn looks_like_drawing(bytes: &[u8]) -> bool { } /// How much of a drawing's end [`looks_complete`] reads. +#[cfg(not(target_arch = "wasm32"))] const TAIL_BYTES: u64 = 256; /// Whether a drawing that [`looks_like_drawing`] (`head`, its first bytes, at least 256 of them @@ -560,6 +561,7 @@ fn ends(src: &mut std::fs::File) -> std::io::Result<(Vec, Vec, u64)> { /// backup already there. One that can't be told (a 2007 DWG) does: it is most likely fine, and it /// is about to be replaced. With no backup yet any file is kept, because the checks can be wrong /// about a real file and this save replaces the only copy. +#[cfg(not(target_arch = "wasm32"))] fn backup_replaced(head: &[u8], tail: &[u8], len: u64, backup_exists: bool) -> bool { (looks_like_drawing(head) && completeness(head, tail, len) != Some(false)) || (len > 0 && !backup_exists) } From 5bc93ccf18c6700964ef9df6ff4db3514437b641 Mon Sep 17 00:00:00 2001 From: Jonas <80707953+jonascloud@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:24:31 +0100 Subject: [PATCH 255/900] test(io): add independent DXF/DWG conformance and preservation matrices (#2237) * test(dxf): add deterministic codec and drawing round-trip matrices Exercise typed tags and model-space LINE/CIRCLE/TEXT through in-memory ASCII and binary DXF at every save version. Compare both reads with the original model and check independent handwritten byte/entity fixtures. Keep desired-behaviour tests for extrusion and ByBlock plot-style loss explicitly ignored until fixed. No production or docs changes. * test(dxf): independently verify common entity properties * test(io): add a broad DWG preservation matrix with focused pending regressions Share deterministic Drawing cases and exact assertions between DXF and DWG without reducing DXF coverage. Run representable DWG cases at all six save versions, twice in RAM. Test R2000 color/transparency and the single TEXT elevation as explicit format limits. Keep six independently reproduced loss regressions ignored without weakening comparisons. No production or docs changes. * test(io): close binary-width and referenced-linetype coverage gaps Check every integer group range against independently constructed binary payloads, catching shared reader/writer width mistakes. Resolve linetypes with Drawing lookup and compare layer linetypes too. Add missing/changed-reference self-tests and inherited-pattern DXF/DWG round trips. Reproduced the review counterexamples before and after; full CI passes with two nextest threads. Test-only changes. * test(io): expand DXF and DWG matrices across entities and drawing collections Add basic coverage for all 29 modeled entity kinds, block graphs and attributes, all ACI colors, richer properties/XDATA, sparse handles, headers, symbol tables, views, groups, layouts and foreign payloads. Preserve typed fields and authored references through two RAM saves. Add independent DXF groups and native DWG bridge checks, plus explicit refusal-or-preservation tests for unknown entities. Keep confirmed discrepancies and unresolved preservation contracts as focused ignored tests; native linetype angles and silently dropped unknown DWG entities are independently reproduced. Version limits and foreign object handle remapping are explicit contracts, not blanket normalization. Tests only; no production or docs changes. Full CI passes with two nextest threads: 2777 passed, 27 skipped. * test(io): cover bounded property domains and targeted field interactions Independently check all ACI values and transparency percentages, native layer/style flag combinations, and literal large handles. Add shared DXF/DWG cases for alignment with mirrored styles, inherited versus explicit zero properties, repeated nested attributes, and integer-boundary handles. Keep exhausted handle allocation separate: DWG refuses the save; a focused ignored DXF regression reproduces silent loss of all nine model entities. No production or documentation changes. Validation: full cargo xtask ci with NEXTEST_TEST_THREADS=2 passes all seven gates (2792 passed, 28 skipped). The pending DXF regression fails explicitly when run with --ignored. * test(dxf): separate chunk conformance from binary reader tolerance Address PR #2237 review: shared exact-tag round trips only use hex chunks within the documented 127-byte group limit. Independently inspect ASCII and binary writer bytes, reassemble payloads, and verify following-record framing. Keep full 0..255 length-byte read tolerance in handwritten fixtures, not as a claim of conforming writer output. Add two focused ignored regressions for oversized ASCII/binary output, reproduced with 128-byte payloads. They extend existing issue #1025. No production changes. Validation: cargo xtask ci passes all seven gates with nextest 0.9.150 and two test threads (2782 passed, 30 skipped). Both new pending checks fail explicitly when run with --ignored. * test(io): compare DWG dimension blocks through their references Anonymous dimension-block suffixes may change between drawing sessions (Autodesk documentation; ODA DWG section 20.4.52.1). Resolve their names through preserved dimension identities and keep strict checks for cache content, entity handles, block properties and reference integrity. Enable the pending dimensions test across all six DWG versions and two saves. Add a paired-cache fixture and comparator controls rejecting swapped/merged/dangling references, geometry and property changes, stale caches, and named-block renaming. Leave the shared comparator and DXF contract unchanged. Validation: cargo xtask ci (all seven stages; 2786 passed, 29 skipped); roundtrip matrix (211 passed, 26 ignored). Resolves the preservation-contract decision in #2257 (tracker #2238, B4); no production codec fix. * test(io): specify WIPEOUT explicit closure on roundtrip An implicit WIPEOUT boundary gains one explicit closing marker in DXF/DWG. Compare against independently authored explicit boundaries in both winding directions across all six versions and two saves; retain strict field and resave comparisons. Enable the two pending closure checks without changing the shared comparator. Distinguish this valid file representation from the grip-edit defect: the latter is fixed separately in PR #2284, with engine, outline and rendering regressions. No production change in this test-only branch. Validation: cargo xtask ci, all seven stages passed (2788 passed, 27 skipped); active roundtrip matrix 213 passed; remaining ignored checks reproduce 24 drawing failures and two codec failures. One unrelated HTTP control-server test failed transiently, then passed in isolation and in the full rerun. Related #2256 and tracker #2238 B3. * test(io): expose multiline ATTRIB alignment corruption Keep the original origin witness and add distinct nonzero TEXT/MTEXT anchors. An active R2018 ASCII/binary two-save check verifies world-space multiline geometry and value edits; this does not excuse corrupted fallback TEXT fields. Retain the strict pending #2255 check and add comparison of independently downgraded R2000/R2004 geometry. The observed Left -> Center change is a real reader error, not permitted alignment-point canonicalization. The reader hunk from existing PR #1942 makes the extended strict check pass in an isolated experiment; no competing production fix is included here. Validation of this test-only tree: all seven cargo xtask ci stages pass (2789 passed, 27 skipped); active matrix 214 passed; remaining 24 drawing and two codec diagnostics still fail. An unrelated HTTP control-server test failed transiently, then passed alone and in the complete rerun. Related #2255, #1942 and tracker #2238 B2. * test(io): separate ATTRIB value and legacy-placement guarantees Assert exact saved ATTRIB values, read_as and authored embedded MTEXT contents before and after value edits. A mutation test rejects corrupt fields, including a value/read_as pair whose rendered geometry remains unchanged. Make legacy placement an independently runnable pending regression instead of a callback behind the failing field comparator. Compare direct R2000/R2004 exports with exports after one/two R2018 roundtrips, both encodings in each stage, and verify that the primary single-line fallback actually survives. Keep all three contracts local and distinct; remove the old cross-module callback. The new legacy test fails directly on world-space geometry with the unchanged reader. Both pending ATTRIB tests pass with the reader hunk from existing PR #1942 in an isolated experiment (548 IO tests also pass). No production fix is included. Validation: all seven cargo xtask ci stages pass with NEXTEST_TEST_THREADS=1 (2790 passed, 28 skipped). Earlier parallel runs and one isolated retry hit pre-existing HTTP/busy control-server failures; no exclusions or test changes. Active matrix 215 passed; all 25 drawing and two codec pending diagnostics still fail. Addresses review of #2237; related #2255, #1942 and tracker #2238 B2. --------- Co-authored-by: cloudj --- crates/dxf/tests/conformance.rs | 145 +++++++ crates/dxf/tests/hex_chunks.rs | 119 ++++++ crates/dxf/tests/roundtrip.rs | 148 +++++++ crates/io/tests/it/main.rs | 1 + crates/io/tests/it/roundtrip/cases.rs | 308 ++++++++++++++ crates/io/tests/it/roundtrip/cases/blocks.rs | 234 +++++++++++ crates/io/tests/it/roundtrip/cases/complex.rs | 131 ++++++ .../io/tests/it/roundtrip/cases/geometry.rs | 301 +++++++++++++ .../io/tests/it/roundtrip/cases/properties.rs | 351 ++++++++++++++++ crates/io/tests/it/roundtrip/collections.rs | 263 ++++++++++++ crates/io/tests/it/roundtrip/compare.rs | 374 +++++++++++++++++ .../io/tests/it/roundtrip/dwg/conformance.rs | 87 ++++ .../io/tests/it/roundtrip/dwg/dimensions.rs | 210 ++++++++++ crates/io/tests/it/roundtrip/dwg/entities.rs | 171 ++++++++ crates/io/tests/it/roundtrip/dwg/extended.rs | 395 ++++++++++++++++++ crates/io/tests/it/roundtrip/dwg/mod.rs | 75 ++++ .../io/tests/it/roundtrip/dxf/attributes.rs | 163 ++++++++ crates/io/tests/it/roundtrip/dxf/common.rs | 197 +++++++++ .../io/tests/it/roundtrip/dxf/conformance.rs | 185 ++++++++ crates/io/tests/it/roundtrip/dxf/entities.rs | 121 ++++++ crates/io/tests/it/roundtrip/dxf/extended.rs | 334 +++++++++++++++ .../tests/it/roundtrip/dxf/geometry_groups.rs | 138 ++++++ crates/io/tests/it/roundtrip/dxf/mod.rs | 56 +++ .../io/tests/it/roundtrip/dxf/table_flags.rs | 128 ++++++ crates/io/tests/it/roundtrip/handle_limits.rs | 40 ++ crates/io/tests/it/roundtrip/mod.rs | 11 + crates/io/tests/it/roundtrip/unknown.rs | 106 +++++ 27 files changed, 4792 insertions(+) create mode 100644 crates/dxf/tests/conformance.rs create mode 100644 crates/dxf/tests/hex_chunks.rs create mode 100644 crates/dxf/tests/roundtrip.rs create mode 100644 crates/io/tests/it/roundtrip/cases.rs create mode 100644 crates/io/tests/it/roundtrip/cases/blocks.rs create mode 100644 crates/io/tests/it/roundtrip/cases/complex.rs create mode 100644 crates/io/tests/it/roundtrip/cases/geometry.rs create mode 100644 crates/io/tests/it/roundtrip/cases/properties.rs create mode 100644 crates/io/tests/it/roundtrip/collections.rs create mode 100644 crates/io/tests/it/roundtrip/compare.rs create mode 100644 crates/io/tests/it/roundtrip/dwg/conformance.rs create mode 100644 crates/io/tests/it/roundtrip/dwg/dimensions.rs create mode 100644 crates/io/tests/it/roundtrip/dwg/entities.rs create mode 100644 crates/io/tests/it/roundtrip/dwg/extended.rs create mode 100644 crates/io/tests/it/roundtrip/dwg/mod.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/attributes.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/common.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/conformance.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/entities.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/extended.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/geometry_groups.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/mod.rs create mode 100644 crates/io/tests/it/roundtrip/dxf/table_flags.rs create mode 100644 crates/io/tests/it/roundtrip/handle_limits.rs create mode 100644 crates/io/tests/it/roundtrip/mod.rs create mode 100644 crates/io/tests/it/roundtrip/unknown.rs diff --git a/crates/dxf/tests/conformance.rs b/crates/dxf/tests/conformance.rs new file mode 100644 index 000000000..089ed8063 --- /dev/null +++ b/crates/dxf/tests/conformance.rs @@ -0,0 +1,145 @@ +//! Small independent byte fixtures for DXF tag types, text encoding, framing and failures. +//! Handwritten examples, not files from a CAD application or generated by our writer. +//! Background on the tag model and file structure: +//! https://ezdxf.readthedocs.io/en/stable/dxfinternals/dxftags.html +//! https://ezdxf.readthedocs.io/en/stable/dxfinternals/filestructure.html +//! ASCII spacing is our writer's documented convention; binary fixtures specify actual bytes. + +use cadcraft_dxf::{DxfError, Tag, Value, parse, parse_with_limit, write_ascii_as, write_binary}; + +const SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0"; + +fn fixtures() -> Vec<(Tag, &'static [u8], &'static [u8])> { + vec![ + (Tag::s(1, " A "), b" 1\r\n A \r\n", b"\x01\0 A \0"), + (Tag::s(1, ""), b" 1\r\n\r\n", b"\x01\0\0"), + (Tag::s(105, "AB12"), b"105\r\nAB12\r\n", b"\x69\0AB12\0"), + (Tag::new(10, Value::Real(-3.25)), b" 10\r\n-3.25\r\n", b"\x0a\0\0\0\0\0\0\0\x0a\xc0"), + (Tag::i(70, -32768), b" 70\r\n-32768\r\n", b"\x46\0\0\x80"), + (Tag::i(90, -2147483648), b" 90\r\n-2147483648\r\n", b"\x5a\0\0\0\0\x80"), + (Tag::i(160, 9223372036854775807), b"160\r\n9223372036854775807\r\n", b"\xa0\0\xff\xff\xff\xff\xff\xff\xff\x7f"), + (Tag::new(290, Value::Bool(false)), b"290\r\n0\r\n", b"\x22\x01\0"), + (Tag::new(299, Value::Bool(true)), b"299\r\n1\r\n", b"\x2b\x01\x01"), + (Tag::new(310, Value::Hex("00FF80".into())), b"310\r\n00FF80\r\n", b"\x36\x01\x03\0\xff\x80"), + (Tag::new(1004, Value::Hex(String::new())), b"1004\r\n\r\n", b"\xec\x03\0"), + (Tag::i(1070, -2), b"1070\r\n-2\r\n", b"\x2e\x04\xfe\xff"), + (Tag::i(1071, 65536), b"1071\r\n65536\r\n", b"\x2f\x04\0\0\x01\0"), + ] +} + +#[test] +fn reads_independently_authored_ascii_and_binary_values() { + for (expected, ascii, binary) in fixtures() { + assert_eq!(parse(ascii).unwrap(), std::slice::from_ref(&expected), "ASCII code {}", expected.code); + let bytes = [SENTINEL, binary].concat(); + assert_eq!(parse(&bytes).unwrap(), std::slice::from_ref(&expected), "binary code {}", expected.code); + } +} + +#[test] +fn writes_independently_specified_ascii_and_binary_bytes() { + for (tag, ascii, binary) in fixtures() { + for utf8 in [false, true] { + let tags = std::slice::from_ref(&tag); + assert_eq!(write_ascii_as(tags, utf8).as_bytes(), ascii, "ASCII code {}", tag.code); + assert_eq!(write_binary(tags, utf8), [SENTINEL, binary].concat(), "binary code {}", tag.code); + } + } +} + +#[test] +fn integer_code_ranges_have_independent_binary_widths() { + // Specification ranges and widths, never kind_of(): a shared reader/writer mistake + // can round-trip every boundary value while still using the wrong number of bytes. + let widths = [ + (vec![60..=79, 170..=179, 270..=289, 370..=389, 400..=409, 1060..=1070], 2, i64::from(i16::MIN), i64::from(i16::MAX)), + (vec![90..=99, 420..=429, 440..=459, 1071..=1071], 4, i64::from(i32::MIN), i64::from(i32::MAX)), + (std::iter::once(160..=169).collect(), 8, i64::MIN, i64::MAX), + ]; + for (ranges, width, min, max) in widths { + for code in ranges.into_iter().flatten() { + for value in [min, min + 1, -1, 0, 1, max - 1, max] { + // Binary DXF uses a little-endian 16-bit group code and a fixed-width, + // little-endian two's-complement integer. Encoding is version-independent. + let code_bytes = u16::try_from(code).unwrap().to_le_bytes(); + let value_bytes = value.to_le_bytes(); + let expected = [SENTINEL, &code_bytes, &value_bytes[..width]].concat(); + let tags = [Tag::i(code, value)]; + for utf8 in [false, true] { + assert_eq!(write_binary(&tags, utf8), expected, "code={code} value={value} utf8={utf8}"); + } + assert_eq!(parse(&expected).unwrap(), tags, "code={code} value={value}"); + } + } + } +} + +#[test] +fn text_encoding_has_independent_wire_expectations() { + let tags = [Tag::s(1, "é😀")]; + let escaped = b"\\U+00E9\\U+D83D\\U+DE00"; + let utf8 = b"\xc3\xa9\xf0\x9f\x98\x80"; + for (unicode, text) in [(false, escaped.as_slice()), (true, utf8.as_slice())] { + let ascii = [b" 1\r\n".as_slice(), text, b"\r\n"].concat(); + let binary = [SENTINEL, b"\x01\0", text, b"\0"].concat(); + assert_eq!(write_ascii_as(&tags, unicode).as_bytes(), ascii, "utf8={unicode}"); + assert_eq!(write_binary(&tags, unicode), binary, "utf8={unicode}"); + assert_eq!(parse(&ascii).unwrap(), tags); + assert_eq!(parse(&binary).unwrap(), tags); + } + // Pre-2007 code-page bytes are independent of the writer, which emits Unicode escapes. + let ascii = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DWGCODEPAGE\n3\nANSI_1252\n0\nENDSEC\n1\n\x80\xe9\n0\nEOF\n"; + let binary = [ + SENTINEL, + b"\0\0SECTION\0\x02\0HEADER\0\x09\0$ACADVER\0\x01\0AC1015\0\x09\0$DWGCODEPAGE\0\x03\0ANSI_1252\0\0\0ENDSEC\0\x01\0\x80\xe9\0\0\0EOF\0", + ] + .concat(); + for bytes in [ascii.as_slice(), binary.as_slice()] { + let tags = parse(bytes).unwrap(); + assert_eq!(tags[7], Tag::s(1, "€é")); + } +} + +#[test] +fn ascii_accepts_line_endings_padding_and_no_final_newline() { + let expected = [Tag::i(70, -7), Tag::s(1, " text "), Tag::s(0, "EOF")]; + for newline in ["\n", "\r\n"] { + for final_newline in [false, true] { + let mut text = [" 70 ", " -7 ", "1", " text ", "0", "EOF"].join(newline); + if final_newline { + text.push_str(newline); + } + assert_eq!(parse(text.as_bytes()).unwrap(), expected, "newline={newline:?} final={final_newline}"); + } + } +} + +#[test] +fn malformed_and_truncated_values_are_errors_not_panics() { + assert!(matches!(parse(b""), Err(DxfError::NotDxf))); + assert!(matches!(parse(b"oops\nvalue\n"), Err(DxfError::BadCode { line: 1, .. }))); + assert!(matches!(parse(b"10\n"), Err(DxfError::Eof))); + assert!(matches!(parse(SENTINEL), Err(DxfError::NotDxf))); + for (_, _, binary) in fixtures() { + // Every cut inside the first record is an error, unlike cuts between complete records: + // the tag API deliberately accepts streams without an EOF record. + for cut in 1..binary.len() { + let bytes = [SENTINEL, &binary[..cut]].concat(); + assert!(matches!(parse(&bytes), Err(DxfError::Eof)), "binary={binary:?} cut={cut}"); + } + } +} + +#[test] +fn tag_limit_accepts_the_exact_boundary_and_rejects_one_less() { + let ascii = b"1\nA\n70\n-7\n0\nEOF\n"; + let binary = [SENTINEL, b"\x01\0A\0\x46\0\xf9\xff\0\0EOF\0"].concat(); + for bytes in [ascii.as_slice(), binary.as_slice()] { + for limit in 0..3 { + assert!(matches!(parse_with_limit(bytes, limit), Err(DxfError::TooLarge { limit: actual, .. }) if actual == limit)); + } + for limit in [3, 4] { + assert_eq!(parse_with_limit(bytes, limit).unwrap(), [Tag::s(1, "A"), Tag::i(70, -7), Tag::s(0, "EOF")]); + } + } +} diff --git a/crates/dxf/tests/hex_chunks.rs b/crates/dxf/tests/hex_chunks.rs new file mode 100644 index 000000000..e3fdc6948 --- /dev/null +++ b/crates/dxf/tests/hex_chunks.rs @@ -0,0 +1,119 @@ +//! Hex payload conformance is distinct from binary framing capacity: DXF groups 310–319 and +//! 1004 specify at most 127 payload bytes per chunk, even though a length byte represents 255. +//! Inspect writer bytes without our parser; accept any compliant partition preserving payload, +//! code and following-record framing. Oversized binary read fixtures test tolerance only. +//! Pending writer regressions extend the chunk-size finding in issue #1025. +//! Public DXF Reference, Group Codes in Numerical Order and Binary DXF Files: +//! https://help.autodesk.com/cloudhelp/2025/ENU/AutoCAD-DXF/files/GUID-3F0380A5-1C15-464D-BC66-2C5F094BCFB9.htm +//! https://help.autodesk.com/cloudhelp/2025/ENU/AutoCAD-DXF/files/GUID-FC1C3C69-DBC2-49E4-893A-000D6538C0FE.htm + +use cadcraft_dxf::{Tag, Value, parse, write_ascii_as, write_binary}; + +const SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0"; +const FOLLOWING_BINARY: &[u8] = b"\x46\0\xf9\xff"; // group 70, signed i16 -7 + +fn payload(length: usize) -> Vec { + (0..length).map(|index| u8::try_from(index * 37 % 256).unwrap()).collect() +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02X}")).collect() +} + +fn input(code: i32, bytes: &[u8]) -> [Tag; 2] { + [Tag::new(code, Value::Hex(hex(bytes))), Tag::i(70, -7)] +} + +fn check_ascii(code: i32, bytes: &[u8], utf8: bool) { + let wire = write_ascii_as(&input(code, bytes), utf8); + let lines: Vec<_> = wire.lines().collect(); + let (chunks, following) = lines.split_at(lines.len().checked_sub(2).unwrap()); + assert_eq!(following[0].trim(), "70"); + assert_eq!(following[1], "-7"); + assert!(!chunks.is_empty(), "an empty payload must still have a tag"); + let (records, remainder) = chunks.as_chunks::<2>(); + assert!(remainder.is_empty(), "incomplete group/value pair"); + let context = format!("ASCII code={code} bytes={} utf8={utf8}", bytes.len()); + let mut back = Vec::new(); + for record in records { + assert_eq!(record[0].trim().parse::().unwrap(), code, "{context}"); + let text = record[1]; + assert!(text.len() <= 254, "{context}: {} hex characters exceed 127 payload bytes", text.len()); + assert!(text.bytes().all(|b| b.is_ascii_hexdigit()), "{context}: invalid hex"); + let (pairs, remainder) = text.as_bytes().as_chunks::<2>(); + assert!(remainder.is_empty(), "{context}: partial byte"); + back.extend(pairs.iter().map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())); + } + assert_eq!(back, bytes, "{context}: complete payload and byte order"); +} + +fn check_binary(code: i32, bytes: &[u8], utf8: bool) { + let wire = write_binary(&input(code, bytes), utf8); + let mut chunks = wire.strip_prefix(SENTINEL).unwrap().strip_suffix(FOLLOWING_BINARY).unwrap(); + assert!(!chunks.is_empty(), "an empty payload must still have a tag"); + let context = format!("binary code={code} bytes={} utf8={utf8}", bytes.len()); + let mut back = Vec::new(); + while !chunks.is_empty() { + let (&[lo, hi, length], rest) = chunks.split_first_chunk::<3>().unwrap(); + assert_eq!(i32::from(u16::from_le_bytes([lo, hi])), code, "{context}"); + assert!(length <= 127, "{context}: {length} bytes exceed the documented group limit"); + let (chunk, next) = rest.split_at(usize::from(length)); + back.extend_from_slice(chunk); + chunks = next; + } + assert_eq!(back, bytes, "{context}: complete payload and byte order"); +} + +#[test] +fn conforming_payloads_have_independent_ascii_and_binary_wire_checks() { + for code in (310..=319).chain([1004]) { + for length in [0, 1, 2, 126, 127] { + for utf8 in [false, true] { + let bytes = payload(length); + check_ascii(code, &bytes, utf8); + check_binary(code, &bytes, utf8); + } + } + } +} + +#[test] +fn binary_reader_tolerates_the_full_length_byte_domain() { + // This is deliberately permissive input, not an assertion that oversized chunks conform + // or that the writer should produce them. The following record catches framing mistakes. + for code in (310_u16..=319).chain([1004]) { + for length in 0..=u8::MAX { + let bytes = payload(usize::from(length)); + let mut wire = SENTINEL.to_vec(); + wire.extend_from_slice(&code.to_le_bytes()); + wire.push(length); + wire.extend_from_slice(&bytes); + wire.extend_from_slice(FOLLOWING_BINARY); + assert_eq!(parse(&wire).unwrap(), input(i32::from(code), &bytes), "code={code} length={length}"); + } + } +} + +#[test] +#[ignore = "Confirmed ASCII DXF writer nonconformance: hex payloads above 127 bytes are emitted as one oversized chunk"] +fn ascii_writer_splits_large_payloads_into_conforming_chunks() { + for code in (310..=319).chain([1004]) { + for length in [128, 254, 255, 256, 1024] { + for utf8 in [false, true] { + check_ascii(code, &payload(length), utf8); + } + } + } +} + +#[test] +#[ignore = "Confirmed binary DXF writer nonconformance: 255-byte partitioning exceeds the documented 127-byte group limit"] +fn binary_writer_splits_large_payloads_into_conforming_chunks() { + for code in (310..=319).chain([1004]) { + for length in [128, 254, 255, 256, 1024] { + for utf8 in [false, true] { + check_binary(code, &payload(length), utf8); + } + } + } +} diff --git a/crates/dxf/tests/roundtrip.rs b/crates/dxf/tests/roundtrip.rs new file mode 100644 index 000000000..acdcb7a78 --- /dev/null +++ b/crates/dxf/tests/roundtrip.rs @@ -0,0 +1,148 @@ +//! Deterministic tag preservation through the public byte API, in both encodings and every +//! supported version. Inputs have the group code's type and representable values; lossy +//! coercions are not accepted as round-trip equality. Real values must retain their bits. + +use cadcraft_dxf::{Tag, Value, Version, is_binary, parse, write_ascii_as, write_binary}; + +fn check(case: &str, body: &[Tag]) { + for version in Version::ALL { + let mut original = vec![ + Tag::s(0, "SECTION"), + Tag::s(2, "HEADER"), + Tag::s(9, "$ACADVER"), + Tag::s(1, version.code()), + Tag::s(9, "$DWGCODEPAGE"), + Tag::s(3, "ANSI_1252"), + Tag::s(0, "ENDSEC"), + Tag::s(0, "SECTION"), + Tag::s(2, "ENTITIES"), + ]; + original.extend_from_slice(body); + original.extend([Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")]); + for binary in [false, true] { + let mut current = original.clone(); + for pass in 1..=2 { + let context = format!("{case} · {version} · binary={binary} · pass={pass}"); + let bytes = if binary { write_binary(¤t, version.utf8()) } else { write_ascii_as(¤t, version.utf8()).into_bytes() }; + assert_eq!(is_binary(&bytes), binary, "{context}"); + let back = parse(&bytes).unwrap_or_else(|e| panic!("{context}: {e}")); + assert_eq!(back.len(), original.len(), "{context}: tag count"); + for (index, (expected, actual)) in original.iter().zip(&back).enumerate() { + assert_eq!(actual, expected, "{context}: tag[{index}]"); + if let (Value::Real(a), Value::Real(b)) = (&expected.value, &actual.value) { + assert_eq!(b.to_bits(), a.to_bits(), "{context}: tag[{index}] real bits"); + } + } + assert_eq!(back, current, "{context}: no additional changes on resave"); + current = back; + } + } + } +} + +#[test] +fn integer_width_boundaries() { + // Explicit reference ranges, not obtained from the codec's kind_of(). + let widths = [ + (vec![60..=79, 170..=179, 270..=289, 370..=389, 400..=409, 1060..=1070], i64::from(i16::MIN), i64::from(i16::MAX)), + (vec![90..=99, 420..=429, 440..=459, 1071..=1071], i64::from(i32::MIN), i64::from(i32::MAX)), + (std::iter::once(160..=169).collect(), i64::MIN, i64::MAX), + ]; + for (ranges, min, max) in widths { + for value in [min, min + 1, -1, 0, 1, max - 1, max] { + let tags: Vec<_> = ranges.iter().cloned().flatten().map(|code| Tag::i(code, value)).collect(); + check(&format!("integer/{min}..{max}/{value}"), &tags); + } + } +} + +#[test] +fn finite_reals_keep_all_bits() { + let values = [ + 0.0, + -0.0, + f64::from_bits(1), + -f64::from_bits(1), + f64::MIN_POSITIVE, + f64::MIN_POSITIVE.next_down(), + 0.1, + -3.25, + 1.0_f64.next_down(), + 1.0, + 1.0_f64.next_up(), + 1e-100, + -1e100, + f64::MAX, + f64::MIN, + ]; + for value in values { + let tags: Vec<_> = + [10..=59, 110..=149, 210..=239, 460..=469, 1010..=1059].into_iter().flatten().map(|code| Tag::new(code, Value::Real(value))).collect(); + check(&format!("real/{:016X}", value.to_bits()), &tags); + } +} + +#[test] +fn booleans() { + for value in [false, true] { + let tags: Vec<_> = (290..=299).map(|code| Tag::new(code, Value::Bool(value))).collect(); + check(&format!("bool/{value}"), &tags); + } +} + +#[test] +fn strings_preserve_whitespace_unicode_and_literal_escapes() { + // No CR/LF or NUL: those are line/string delimiters, not losslessly writable payloads. + let values = [ + ("empty", ""), + ("spaces", " leading and trailing "), + ("tabs", "\tindented\t"), + ("unicode", "Café Ø 图号 Україна 😀 e\u{301}"), + ("literal-escapes", r"\U+0041 \M+183A4 \U+D83D\U+DE00 \\U+005C \P %%c"), + ("malformed-escapes", r"\U+ \U+ZZZZ \U+D800 \U+DC00 \M+9FFFF"), + ]; + for (case, value) in values { + let tags: Vec<_> = + [0..=9, 100..=100, 102..=102, 105..=105, 300..=309, 320..=369, 410..=419, 430..=439, 470..=479, 480..=481, 1000..=1003, 1005..=1005] + .into_iter() + .flatten() + .map(|code| Tag::s(code, value)) + .collect(); + check(case, &tags); + } + for length in [1, 254, 255, 256, 1024] { + check(&format!("string/length={length}"), &[Tag::s(1, "x".repeat(length))]); + } +} + +#[test] +fn hex_chunks_keep_bytes_and_order() { + // DXF groups 310–319 and 1004 permit 127 payload bytes per chunk. A binary length + // byte can represent more, but that is reader tolerance, not writer conformance. + // Larger payloads need chunk-size/reassembly checks rather than exact tag equality; + // see hex_chunks.rs for the independent wire checks and pending writer regressions. + for length in [0, 1, 2, 126, 127] { + let hex: String = (0..length).map(|i| format!("{:02X}", (i * 37) % 256)).collect(); + let tags: Vec<_> = (310..=319).chain([1004]).map(|code| Tag::new(code, Value::Hex(hex.clone()))).collect(); + check(&format!("hex/bytes={length}"), &tags); + } +} + +#[test] +fn mixed_values_and_repeated_codes_keep_order() { + check( + "mixed/repeated-codes", + &[ + Tag::s(0, "TEST"), + Tag::f(10, 1.25), + Tag::s(1, "first"), + Tag::f(10, -2.5), + Tag::i(70, -7), + Tag::s(1, "second"), + Tag::new(290, Value::Bool(true)), + Tag::new(310, Value::Hex("00FF80".into())), + Tag::i(160, i64::MAX), + Tag::s(1, ""), + ], + ); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 5d6c343d0..7f6ad8f20 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -54,6 +54,7 @@ mod plot_layout_scale; mod plot_model_png_scale; mod plot_styles; mod region_roundtrip; +mod roundtrip; mod roundtrip_audit; mod skipped_records; mod sortents; diff --git a/crates/io/tests/it/roundtrip/cases.rs b/crates/io/tests/it/roundtrip/cases.rs new file mode 100644 index 000000000..a6031ec8f --- /dev/null +++ b/crates/io/tests/it/roundtrip/cases.rs @@ -0,0 +1,308 @@ +//! Deterministic drawing inputs shared by DXF and DWG tests, independent of either writer. +//! Each family isolates a property so a known failure need not disable unrelated coverage. +//! Format/version limits and pending failures belong to the callers, not these generators. + +pub(super) mod blocks; +pub(super) mod complex; +pub(super) mod geometry; +pub(super) mod properties; + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::{ + AnnoScale, Circle, Common, Drawing, EntityKind, HAlign, Layer, Line, Linetype, Lineweight, RawTag, Space, Text, TextStyle, Transparency, VAlign, +}; +use cadcraft_geom::Vec3; + +pub(super) struct Case { + pub name: String, + pub drawing: Drawing, +} + +pub(super) fn drawing() -> Drawing { + let mut d = Drawing::new_metric(); + d.layers.push(Layer { name: "Survey_Ä".into(), color: Color::Index(3), ..Layer::default() }); + d.linetypes.push(Linetype::simple("Dash_test", "Original synthetic dash pattern", &[2.0, -0.75, 0.0, -0.25])); + d.text_styles.push(TextStyle { name: "Notes".into(), ..TextStyle::default() }); + d +} + +pub(super) fn text() -> Text { + Text { + insert: Vec3::new(2.5, -3.75, 4.125), + align_pt: None, + height: 2.25, + value: "CAD Ø".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + } +} + +pub(super) fn entity_case(name: &str, common: Common, kind: EntityKind) -> Case { + let mut drawing = drawing(); + drawing.add(&Space::Model, common, kind).unwrap(); + Case { name: name.into(), drawing } +} + +pub(super) fn common_case(name: &str, common: Common) -> Case { + let mut drawing = drawing(); + for kind in [ + EntityKind::Line(Line { a: Vec3::new(-1.25, 2.5, 3.75), b: Vec3::new(8.125, -13.5, 21.25) }), + EntityKind::Circle(Circle { center: Vec3::new(-7.25, 11.5, 4.75), radius: 3.125 }), + EntityKind::Text(text()), + ] { + drawing.add(&Space::Model, common.clone(), kind).unwrap(); + } + Case { name: name.into(), drawing } +} + +pub(super) fn empty_and_defaults() -> Vec { + vec![Case { name: "empty-model".into(), drawing: drawing() }, common_case("common/default", Common::default())] +} + +pub(super) fn geometry() -> Vec { + let mut cases = Vec::new(); + for (name, a, b) in [ + ("zero-start", Vec3::ZERO, Vec3::new(1.0, 2.0, 3.0)), + ("zero-end", Vec3::new(-3.0, -2.0, -1.0), Vec3::ZERO), + ("small", Vec3::new(1e-9, -2e-9, 3e-9), Vec3::new(-4e-9, 5e-9, -6e-9)), + ("survey", Vec3::new(1e7 + 0.125, -2e7 - 0.25, 123.75), Vec3::new(1e7 + 0.5, -2e7 + 0.75, -42.5)), + ] { + for (direction, start, end) in [("forward", a, b), ("reverse", b, a)] { + cases.push(entity_case(&format!("line/{name}/{direction}"), Common::default(), EntityKind::Line(Line { a: start, b: end }))); + } + for radius in [1e-9, 0.125, 3.25, 1e8] { + cases.push(entity_case(&format!("circle/{name}/radius={radius}"), Common::default(), EntityKind::Circle(Circle { center: a, radius }))); + } + } + cases +} + +pub(super) fn layers() -> Vec { + ["0", "Survey_Ä"].map(|layer| common_case(&format!("common/layer={layer}"), Common { layer: layer.into(), ..Common::default() })).into() +} + +pub(super) fn layer_linetypes() -> Vec { + ["0", "Survey_Ä"] + .map(|layer| { + let mut case = common_case(&format!("common/layer={layer}/inherited-linetype"), Common { layer: layer.into(), ..Common::default() }); + case.drawing.layer_mut(layer).unwrap().linetype = "Dash_test".into(); + case + }) + .into() +} + +pub(super) fn colors() -> Vec { + [Color::ByLayer, Color::ByBlock] + .into_iter() + .chain((1..=255).map(Color::Index)) + .chain([Rgb(0, 0, 0), Rgb(255, 255, 255), Rgb(255, 0, 0), Rgb(0, 255, 0), Rgb(0, 0, 255), Rgb(17, 93, 241)].map(Color::True)) + .map(|color| common_case(&format!("common/color={color:?}"), Common { color, ..Common::default() })) + .collect() +} + +pub(super) fn linetypes() -> Vec { + ["ByLayer", "ByBlock", "Continuous", "Dash_test"] + .map(|linetype| common_case(&format!("common/linetype={linetype}"), Common { linetype: linetype.into(), ..Common::default() })) + .into() +} + +pub(super) fn lineweights() -> Vec { + [Lineweight::ByLayer, Lineweight::ByBlock, Lineweight::Default] + .into_iter() + .chain(Lineweight::STANDARD.map(Lineweight::Mm100)) + .map(|lineweight| common_case(&format!("common/lineweight={lineweight:?}"), Common { lineweight, ..Common::default() })) + .collect() +} + +pub(super) fn linetype_scales() -> Vec { + [0.125, 1.0, 3.25, 1e6].map(|ltscale| common_case(&format!("common/ltscale={ltscale}"), Common { ltscale, ..Common::default() })).into() +} + +pub(super) fn transparencies() -> Vec { + [Transparency::ByLayer, Transparency::ByBlock] + .into_iter() + .chain((0..=90).map(Transparency::Percent)) + .map(|transparency| common_case(&format!("common/transparency={transparency:?}"), Common { transparency, ..Common::default() })) + .collect() +} + +pub(super) fn visibility() -> Vec { + [false, true].map(|visible| common_case(&format!("common/visible={visible}"), Common { visible, ..Common::default() })).into() +} + +pub(super) fn thicknesses() -> Vec { + [-2.5, 0.0, 3.75].map(|thickness| common_case(&format!("common/thickness={thickness}"), Common { thickness, ..Common::default() })).into() +} + +pub(super) fn plot_styles() -> Vec { + ["ByLayer", "Review"] + .map(|plot_style| common_case(&format!("common/plot_style={plot_style}"), Common { plot_style: plot_style.into(), ..Common::default() })) + .into() +} + +pub(super) fn byblock_plot_style() -> Vec { + vec![common_case("common/plot_style=ByBlock", Common { plot_style: "ByBlock".into(), ..Common::default() })] +} + +pub(super) fn extrusions() -> Vec { + [Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 1.0, 0.0)] + .map(|extrusion| common_case(&format!("common/extrusion={extrusion:?}"), Common { extrusion, ..Common::default() })) + .into() +} + +pub(super) fn foreign_xdata() -> Vec { + let xdata = vec![ + RawTag { code: 1001, value: "ROUNDTRIP_TEST".into() }, + RawTag { code: 1000, value: "foreign text Ø 😀".into() }, + RawTag { code: 1070, value: "-17".into() }, + RawTag { code: 1040, value: "3.25".into() }, + RawTag { code: 1004, value: "00FF80".into() }, + ]; + vec![common_case("common/foreign-xdata", Common { xdata, ..Common::default() })] +} + +pub(super) fn common_interactions(plot_style: &str) -> Vec { + // Full local product; retain the original DXF case with a named plot style as well as + // an inherited-style counterpart, so a named-style loss does not hide other interactions. + let mut cases = Vec::new(); + for layer in ["0", "Survey_Ä"] { + for color in [Color::ByLayer, Color::ByBlock, Color::True(Rgb(21, 89, 233))] { + for visible in [false, true] { + let common = Common { + layer: layer.into(), + color, + visible, + linetype: "Dash_test".into(), + lineweight: Lineweight::Mm100(53), + ltscale: 2.75, + transparency: Transparency::Percent(37), + thickness: -1.25, + plot_style: plot_style.into(), + ..Common::default() + }; + cases.push(common_case(&format!("common/product/{layer}/{color:?}/visible={visible}/plot_style={plot_style}"), common)); + } + } + } + cases +} + +pub(super) fn text_values() -> Vec { + [("empty", ""), ("whitespace", " a\tb "), ("unicode", "Café 图号 😀 e\u{301}")] + .map(|(name, value)| entity_case(&format!("text/value/{name}"), Common::default(), EntityKind::Text(Text { value: value.into(), ..text() }))) + .into() +} + +pub(super) fn text_literal_escapes() -> Vec { + vec![entity_case("text/value/literal-escapes", Common::default(), EntityKind::Text(Text { value: r"\U+0041 \M+183A4 \P %%c".into(), ..text() }))] +} + +pub(super) fn text_heights() -> Vec { + [1e-9, 0.125, 2.25, 1e5] + .map(|height| entity_case(&format!("text/height={height}"), Common::default(), EntityKind::Text(Text { height, ..text() }))) + .into() +} + +pub(super) fn text_rotations() -> Vec { + [0.0, -0.7, std::f64::consts::FRAC_PI_2, 5.9] + .map(|rotation| entity_case(&format!("text/rotation={rotation}"), Common::default(), EntityKind::Text(Text { rotation, ..text() }))) + .into() +} + +pub(super) fn text_widths() -> Vec { + [0.125, 1.0, 2.75] + .map(|width_factor| { + entity_case(&format!("text/width_factor={width_factor}"), Common::default(), EntityKind::Text(Text { width_factor, ..text() })) + }) + .into() +} + +pub(super) fn text_obliques() -> Vec { + [-0.3, 0.0, 0.4] + .map(|oblique| entity_case(&format!("text/oblique={oblique}"), Common::default(), EntityKind::Text(Text { oblique, ..text() }))) + .into() +} + +pub(super) fn text_styles() -> Vec { + ["Standard", "Notes"] + .map(|style| entity_case(&format!("text/style={style}"), Common::default(), EntityKind::Text(Text { style: style.into(), ..text() }))) + .into() +} + +pub(super) fn annotation_scales() -> Vec { + [vec![], vec![AnnoScale::unit()], vec![AnnoScale::unit(), AnnoScale::new("1:50", 1.0, 50.0)]] + .map(|scales| { + entity_case(&format!("text/anno_scales={scales:?}"), Common { anno_scales: scales, ..Common::default() }, EntityKind::Text(text())) + }) + .into() +} + +pub(super) fn coplanar_text_alignment() -> Vec { + // Construct additional valid single-plane inputs before serialization. Keep the original + // differing-elevation cases separately: DXF can store both XYZ points, DWG TEXT has one Z. + let mut cases = text_alignment(true); + for case in &mut cases { + case.name.push_str("/coplanar"); + let handles: Vec<_> = case.drawing.model.iter().map(|e| e.handle).collect(); + for handle in handles { + case.drawing.model.modify(handle, |e| { + if let EntityKind::Text(t) = &mut e.kind { + t.align_pt = t.align_pt.map(|p| Vec3::new(p.x, p.y, t.insert.z)); + } + }); + } + } + cases +} + +pub(super) fn noncoplanar_text_alignment() -> Vec { + text_alignment(true) + .into_iter() + .filter(|case| case.drawing.model.iter().any(|e| matches!(&e.kind, EntityKind::Text(t) if t.align_pt.is_some_and(|p| p.z != t.insert.z)))) + .collect() +} + +pub(super) fn text_alignment(with_point: bool) -> Vec { + let mut cases = Vec::new(); + let points = if with_point { vec![Some(Vec3::ZERO), Some(Vec3::new(17.25, -23.5, 6.75))] } else { vec![None] }; + for halign in [HAlign::Left, HAlign::Center, HAlign::Right, HAlign::Aligned, HAlign::Middle, HAlign::Fit] { + for valign in [VAlign::Baseline, VAlign::Bottom, VAlign::Middle, VAlign::Top] { + if matches!(halign, HAlign::Aligned | HAlign::Middle | HAlign::Fit) && valign != VAlign::Baseline { + continue; + } + for &align_pt in &points { + // The unused second point of left-baseline TEXT has a separate DXF read fixture. + if halign == HAlign::Left && valign == VAlign::Baseline && align_pt.is_some() { + continue; + } + let mut t = Text { halign, valign, align_pt, rotation: 0.7, oblique: -0.2, width_factor: 1.25, style: "Notes".into(), ..text() }; + // Build a consistent baseline before serialization. No writer-derived expected + // data: the font layout API determines a valid input; both points compare exactly. + if let Some(anchor) = align_pt + && !matches!(halign, HAlign::Aligned | HAlign::Fit) + { + let (h, v) = cadcraft_render::text_align(halign, valign); + let params = cadcraft_fonts::TextParams { + insert: t.insert.xy(), + align_pt: Some(anchor.xy()), + height: t.height, + rotation: t.rotation, + width_factor: t.width_factor, + oblique: t.oblique, + h, + v, + backwards: false, + upside_down: false, + }; + t.insert = cadcraft_fonts::baseline_start(&cadcraft_fonts::TextFont::Stroke, &t.value, ¶ms).to3(anchor.z); + } + cases.push(entity_case(&format!("text/alignment/{halign:?}/{valign:?}/point={align_pt:?}"), Common::default(), EntityKind::Text(t))); + } + } + } + cases +} diff --git a/crates/io/tests/it/roundtrip/cases/blocks.rs b/crates/io/tests/it/roundtrip/cases/blocks.rs new file mode 100644 index 000000000..a1af6218a --- /dev/null +++ b/crates/io/tests/it/roundtrip/cases/blocks.rs @@ -0,0 +1,234 @@ +//! Stored block graphs and references, never expanded geometry. Definitions have independent +//! handles; forward, repeated and cyclic references are small bounded synthetic graphs. + +use std::sync::Arc; + +use cadcraft_color::Color; +use cadcraft_doc::{Attrib, AttribModes, AttribProps, Block, Common, Entity, EntityKind, Insert, Line, Lineweight, Space, Text}; +use cadcraft_geom::Vec3; + +use super::{Case, drawing, text}; + +pub(crate) fn insert(block: &str) -> Insert { + Insert { + block: block.into(), + insert: Vec3::new(1.25, -2.5, 3.75), + 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, + } +} + +fn base(name: &str, reference: Insert) -> Case { + let mut drawing = drawing(); + let mut leaf = Block::new("Z_Leaf"); + leaf.entities.push(Entity::new(drawing.new_handle(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(2.0, 3.0, 4.0) }))); + drawing.blocks.insert(leaf.name.clone(), Arc::new(leaf)); + drawing.add(&Space::Model, Common::default(), EntityKind::Insert(reference)).unwrap(); + Case { name: name.into(), drawing } +} + +pub(crate) fn transformations() -> Vec { + let mut cases = Vec::new(); + for scale in [Vec3::new(1.0, 1.0, 1.0), Vec3::new(2.0, 0.5, 3.0), Vec3::new(-1.0, 2.0, 1.0)] { + for rotation in [0.0, 0.7, 5.9] { + cases.push(base(&format!("insert/scale={scale:?}/rotation={rotation}"), Insert { scale, rotation, ..insert("Z_Leaf") })); + } + } + cases +} + +pub(crate) fn arrays() -> Vec { + [(1, 3), (4, 1), (3, 2)] + .map(|(cols, rows)| { + base(&format!("minsert/{cols}x{rows}"), Insert { cols, rows, col_spacing: 5.25, row_spacing: -3.75, rotation: 0.7, ..insert("Z_Leaf") }) + }) + .into() +} + +pub(crate) fn metadata() -> Vec { + let mut case = base("block/metadata", insert("Z_Leaf")); + let block = Arc::make_mut(case.drawing.blocks.get_mut("Z_Leaf").unwrap()); + block.base = Vec3::new(4.0, -3.0, 2.0); + block.description = "Synthetic Ø 图".into(); + block.explodable = false; + block.units = 4; + vec![case] +} + +pub(crate) fn nested(cyclic: bool) -> Vec { + let mut case = base(&format!("block/nested/cyclic={cyclic}"), insert("A_Parent")); + let mut parent = Block::new("A_Parent"); + for x in [2.0, 5.0] { + parent + .entities + .push(Entity::new(case.drawing.new_handle(), EntityKind::Insert(Insert { insert: Vec3::new(x, 0.0, 0.0), ..insert("Z_Leaf") }))); + } + if cyclic { + parent.entities.push(Entity::new(case.drawing.new_handle(), EntityKind::Insert(insert("A_Parent")))); + } + case.drawing.blocks.insert(parent.name.clone(), Arc::new(parent)); + vec![case] +} + +fn attribute(tag: &str) -> Attrib { + Attrib { + tag: tag.into(), + text: Text { insert: Vec3::ZERO, height: 1.0, value: tag.into(), ..text() }, + invisible: false, + constant: false, + prompt: String::new(), + props: AttribProps::default(), + multiline: None, + modes: AttribModes::default(), + } +} + +pub(crate) fn attributes(family: &str) -> Vec { + let mut cases = Vec::new(); + let variants = match family { + "flags" => 0..2, + "constant" => 2..4, + _ => 0..4, + }; + for variant in variants { + let mut definition = attribute("ID"); + definition.prompt = "Synthetic identifier".into(); + let mut value = attribute("ID"); + value.text.value = "Part Ø 图".into(); + match family { + "flags" | "constant" => { + definition.invisible = variant & 1 != 0; + definition.constant = variant & 2 != 0; + value.invisible = definition.invisible; + value.constant = definition.constant; + } + "modes" => { + definition.modes.verify = variant & 1 != 0; + definition.modes.preset = variant & 2 != 0; + } + "lock" => { + definition.modes.lock_position = variant & 1 != 0; + value.modes.lock_position = definition.modes.lock_position; + } + "overrides" => { + value.props = match variant { + 0 => AttribProps { layer: Some("Survey_Ä".into()), ..Default::default() }, + 1 => AttribProps { color: Some(Color::Index(3)), ..Default::default() }, + 2 => AttribProps { linetype: Some("Dash_test".into()), ..Default::default() }, + _ => AttribProps { lineweight: Some(Lineweight::Mm100(53)), ..Default::default() }, + }; + } + _ => panic!("unknown attribute family"), + } + let mut case = base(&format!("attributes/{family}/{variant}"), Insert { attribs: vec![value, attribute("SECOND")], ..insert("Z_Leaf") }); + let handle = case.drawing.new_handle(); + let second = case.drawing.new_handle(); + let block = Arc::make_mut(case.drawing.blocks.get_mut("Z_Leaf").unwrap()); + block.entities.push(Entity::new(handle, EntityKind::AttDef(definition))); + block.entities.push(Entity::new(second, EntityKind::AttDef(attribute("SECOND")))); + cases.push(case); + } + cases +} + +/// Repeated nested instances must retain their own ordered values, including empty text and +/// explicit zero overrides. Depth changes the stored owner chain, not attribute identity. +pub(crate) fn nested_attributes() -> Vec { + [1, 3] + .map(|depth| { + let mut case = attributes("flags").remove(0); + case.name = format!("block/nested-attributes/depth={depth}"); + let mut child = "Z_Leaf".to_owned(); + for level in 0..depth { + let mut parent = Block::new(&format!("Parent_{level}")); + for instance in 0..2 { + let mut value = attribute("ID"); + value.text.value = if instance == 0 { String::new() } else { format!("level={level}/instance={instance} Ø") }; + value.props = if instance == 0 { + AttribProps::default() + } else { + AttribProps { + layer: Some("Survey_Ä".into()), + color: Some(Color::ByBlock), + linetype: Some("Continuous".into()), + lineweight: Some(Lineweight::Mm100(0)), + } + }; + parent.entities.push(Entity::new( + case.drawing.new_handle(), + EntityKind::Insert(Insert { + insert: Vec3::new(f64::from(instance) * 10.0, f64::from(level), 0.0), + attribs: vec![value, attribute("SECOND")], + ..insert(&child) + }), + )); + } + // Each definition owns its own ATTDEF handles, even when its tags are repeated. + for tag in ["ID", "SECOND"] { + parent.entities.push(Entity::new(case.drawing.new_handle(), EntityKind::AttDef(attribute(tag)))); + } + child.clone_from(&parent.name); + case.drawing.blocks.insert(parent.name.clone(), Arc::new(parent)); + } + let handle = case.drawing.model.iter().next().unwrap().handle; + case.drawing.model.modify(handle, |e| { + let EntityKind::Insert(i) = &mut e.kind else { panic!("expected INSERT") }; + i.block = child; + }); + case + }) + .into() +} + +pub(crate) fn multiline_attributes() -> Vec { + // Keep the original origin witness and distinguish the fallback TEXT's point from MTEXT's. + [(Vec3::ZERO, Vec3::ZERO), (Vec3::new(12.0, 7.0, 0.0), Vec3::new(20.0, 8.0, 0.0))] + .into_iter() + .map(|(text_point, mtext_point)| { + let mut case = attributes("flags").remove(0); + case.name = format!("attributes/multiline/text-point={text_point:?}"); + let decorate = |a: &mut Attrib| { + a.text.insert = text_point; + a.text.value = "first\nsecond".into(); + a.multiline = Some(cadcraft_doc::MultilineAttrib { + mtext: cadcraft_doc::MText { + insert: mtext_point, + height: 1.0, + width: 6.0, + contents: "first\\Psecond".into(), + ..super::geometry::mtext() + }, + read_as: "first\nsecond".into(), + }); + }; + let handles: Vec<_> = case.drawing.model.iter().map(|e| e.handle).collect(); + for handle in handles { + case.drawing.model.modify(handle, |e| { + let EntityKind::Insert(i) = &mut e.kind else { panic!("expected INSERT") }; + decorate(i.attribs.first_mut().unwrap()); + }); + } + let block = Arc::make_mut(case.drawing.blocks.get_mut("Z_Leaf").unwrap()); + let handle = block.entities.iter().find(|e| matches!(&e.kind, EntityKind::AttDef(a) if a.tag == "ID")).unwrap().handle; + block.entities.modify(handle, |e| { + let EntityKind::AttDef(a) = &mut e.kind else { panic!("expected ATTDEF") }; + decorate(a); + }); + case + }) + .collect() +} + +pub(crate) fn unreferenced() -> Vec { + let mut case = base("block/unreferenced", insert("Z_Leaf")); + case.drawing.blocks.insert("Empty".into(), Arc::new(Block::new("Empty"))); + let mut unused = Block::new("Unused"); + unused.entities.push(Entity::new(case.drawing.new_handle(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) }))); + case.drawing.blocks.insert(unused.name.clone(), Arc::new(unused)); + vec![case] +} diff --git a/crates/io/tests/it/roundtrip/cases/complex.rs b/crates/io/tests/it/roundtrip/cases/complex.rs new file mode 100644 index 000000000..ab13f4800 --- /dev/null +++ b/crates/io/tests/it/roundtrip/cases/complex.rs @@ -0,0 +1,131 @@ +//! Compound and reference-bearing entities. Geometry and cached values are authored explicitly; +//! unsupported versions are selected by callers rather than normalized after reading. + +use super::{Case, entity_case, geometry}; +use cadcraft_doc::{ + Block, Common, DimKind, DimMarks, Dimension, Entity, EntityKind, Helix, HelixConstrain, Line, MLeader, MLine, MLineJust, MLineStyle, Region, + Tolerance, +}; +use cadcraft_geom::{PolyVertex, Vec2, Vec3}; +use std::sync::Arc; + +pub(crate) fn helices() -> Vec { + [false, true] + .into_iter() + .flat_map(|ccw| { + [HelixConstrain::Height, HelixConstrain::Turns, HelixConstrain::TurnHeight].map(|constrain| { + entity_case( + &format!("helix/{ccw}/{constrain:?}"), + Common::default(), + EntityKind::Helix(Helix { + center: Vec3::new(1.25, -2.5, 3.75), + base_radius: 3.0, + top_radius: 1.5, + height: -7.5, + turns: 2.5, + start_angle: 0.0, + ccw, + constrain, + }), + ) + }) + }) + .collect() +} + +pub(crate) fn mlines() -> Vec { + [false, true] + .into_iter() + .flat_map(|closed| { + [MLineJust::Top, MLineJust::Zero, MLineJust::Bottom].map(|just| { + entity_case( + &format!("mline/{closed}/{just:?}"), + Common::default(), + EntityKind::MLine(MLine::new(&MLineStyle::default(), &[Vec2::ZERO, Vec2::new(5.0, 0.0), Vec2::new(5.0, 4.0)], closed, just, 2.5)), + ) + }) + }) + .collect() +} + +pub(crate) fn mleaders() -> Vec { + [false, true] + .map(|spline| { + entity_case( + &format!("mleader/spline={spline}"), + Common::default(), + EntityKind::MLeader(MLeader { + leaders: vec![vec![Vec3::ZERO, Vec3::new(2.0, 3.0, 0.0)], vec![Vec3::new(1.0, -2.0, 0.0)]], + landing: Vec3::new(5.0, 4.0, 0.0), + dogleg: 0.75, + text: Some(cadcraft_doc::MText { insert: Vec3::new(5.9, 4.0, 0.0), rotation: 0.0, ..geometry::mtext() }), + style: "Standard".into(), + arrow_size: 0.3, + spline, + block: None, + }), + ) + }) + .into() +} + +pub(crate) fn regions() -> Vec { + vec![entity_case( + "region/bulged-loop", + Common::default(), + EntityKind::Region(Region::from_loop(vec![ + PolyVertex::with_bulge(Vec2::ZERO, 0.5), + PolyVertex::new(Vec2::new(5.0, 0.0)), + PolyVertex::new(Vec2::new(5.0, 4.0)), + PolyVertex::new(Vec2::new(0.0, 4.0)), + ])), + )] +} + +pub(crate) fn tolerances() -> Vec { + vec![entity_case( + "tolerance/frame", + Common::default(), + EntityKind::Tolerance(Tolerance { + insert: Vec3::new(1.25, -2.5, 3.75), + dir: Vec3::new(0.0, 1.0, 0.0), + style: "ISO-25".into(), + text: "0.125%%vA%%vB".into(), + }), + )] +} + +pub(crate) fn dimensions() -> Vec { + [DimKind::Linear { rotation: 0.0 }, DimKind::Aligned] + .map(|kind| { + let mut case = entity_case( + &format!("dimension/{kind:?}"), + Common::default(), + EntityKind::Dimension(Dimension { + kind, + defpt: Vec3::new(0.0, 3.0, 0.0), + text_mid: Vec3::new(5.0, 4.0, 0.0), + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: "<> mm".into(), + style: "ISO-25".into(), + measurement: 10.0, + text_rotation: 0.0, + user_text_pos: true, + block: Some("*D42".into()), + overrides: Default::default(), + assoc: Vec::new(), + marks: DimMarks::default(), + }), + ); + let mut block = Block::new("*D42"); + block + .entities + .push(Entity::new(case.drawing.new_handle(), EntityKind::Line(Line { a: Vec3::new(0.0, 3.0, 0.0), b: Vec3::new(10.0, 3.0, 0.0) }))); + case.drawing.blocks.insert(block.name.clone(), Arc::new(block)); + case + }) + .into() +} diff --git a/crates/io/tests/it/roundtrip/cases/geometry.rs b/crates/io/tests/it/roundtrip/cases/geometry.rs new file mode 100644 index 000000000..35a2cc9dc --- /dev/null +++ b/crates/io/tests/it/roundtrip/cases/geometry.rs @@ -0,0 +1,301 @@ +//! Additional entity families with authored geometry and optional fields. No serializer output +//! is used to build an input. New failures are isolated by the format-specific test registrations. + +use cadcraft_doc::{ + Arc, Common, Ellipse, EntityKind, Face3d, Hatch, HatchLoop, Image, Leader, LwPolyline, MText, MTextColumnType, MTextColumns, Point, Polyline3d, + RayLine, Solid, Table, TableCell, Wipeout, +}; +use cadcraft_geom::{PolyVertex, Spline, Vec2, Vec3}; + +use super::{Case, entity_case}; + +fn case(name: &str, kind: EntityKind) -> Case { + entity_case(name, Common::default(), kind) +} + +pub(crate) fn arcs() -> Vec { + let mut cases = Vec::new(); + for radius in [1e-9, 0.125, 3.25, 1e8] { + for (start, end) in [(0.0, std::f64::consts::FRAC_PI_2), (0.7, 5.9), (5.9, 0.7)] { + cases.push(case( + &format!("arc/r={radius}/{start}..{end}"), + EntityKind::Arc(Arc { center: Vec3::new(1.25, -2.5, 3.75), radius, start, end }), + )); + } + } + cases +} + +pub(crate) fn ellipses() -> Vec { + [0.125, 0.5, 1.0] + .into_iter() + .flat_map(|ratio| { + [(0.0, std::f64::consts::TAU), (0.7, 5.9), (5.9, 0.7)].map(|(start, end)| { + case( + &format!("ellipse/{ratio}/{start}..{end}"), + EntityKind::Ellipse(Ellipse { center: Vec3::new(1.25, -2.5, 3.75), major: Vec3::new(3.0, 4.0, 0.0), ratio, start, end }), + ) + }) + }) + .collect() +} + +pub(crate) fn polylines(variable_width: bool) -> Vec { + let mut cases = Vec::new(); + for closed in [false, true] { + for plinegen in [false, true] { + for bulge in [-1.0, 0.0, 0.5, 1.0] { + cases.push(case( + &format!("lwpolyline/closed={closed}/plinegen={plinegen}/bulge={bulge}/widths={variable_width}"), + EntityKind::LwPolyline(LwPolyline { + vertices: vec![ + PolyVertex { + p: Vec2::new(1.25, -2.5), + bulge, + start_width: if variable_width { 0.125 } else { 0.0 }, + end_width: if variable_width { 0.75 } else { 0.0 }, + }, + PolyVertex::with_bulge(Vec2::new(5.0, 3.0), -bulge), + PolyVertex::new(Vec2::new(-2.0, 4.0)), + ], + closed, + plinegen, + const_width: if variable_width { 0.0 } else { 0.25 }, + elevation: -3.75, + }), + )); + } + } + } + cases +} + +pub(crate) fn polylines_3d() -> Vec { + [false, true] + .map(|closed| { + case( + &format!("polyline3d/closed={closed}"), + EntityKind::Polyline3d(Polyline3d { + points: vec![Vec3::new(1.25, -2.5, 3.75), Vec3::new(5.0, 6.0, -7.0), Vec3::new(-3.0, 4.0, 9.0)], + closed, + }), + ) + }) + .into() +} + +pub(crate) fn splines(rational: bool) -> Vec { + [1, 2, 3] + .map(|degree| { + let mut spline = Spline::from_control(vec![Vec2::ZERO, Vec2::new(2.0, 3.0), Vec2::new(5.0, -1.0), Vec2::new(8.0, 2.0)], degree); + if rational { + spline.weights = vec![1.0, 0.5, 2.0, 1.0]; + } + case(&format!("spline/degree={degree}/rational={rational}"), EntityKind::Spline(spline)) + }) + .into() +} + +pub(crate) fn spline_fit(closed: bool) -> Vec { + vec![case( + &format!("spline/fit/closed={closed}"), + EntityKind::Spline(Spline::from_fit(&[Vec2::ZERO, Vec2::new(2.0, 3.0), Vec2::new(5.0, -1.0), Vec2::new(8.0, 2.0)], closed)), + )] +} + +pub(crate) fn points_and_rays() -> Vec { + let base = Vec3::new(1.25, -2.5, 3.75); + vec![ + case("point", EntityKind::Point(Point { p: base, angle: 0.0 })), + case("ray", EntityKind::Ray(RayLine { base, dir: Vec3::new(0.0, 0.0, 1.0) })), + case("xline", EntityKind::XLine(RayLine { base, dir: Vec3::new(0.0, 1.0, 0.0) })), + ] +} + +pub(crate) fn faces() -> Vec { + let corners = [Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 2.0, 3.0), Vec3::new(1.0, 5.0, 3.0), Vec3::new(4.0, 5.0, 3.0)]; + let mut cases = vec![case("solid", EntityKind::Solid(Solid { corners })), case("trace", EntityKind::Trace(Solid { corners }))]; + for hidden_edges in 0..16 { + cases.push(case(&format!("face3d/hidden={hidden_edges}"), EntityKind::Face3d(Face3d { corners, hidden_edges }))); + } + cases +} + +pub(crate) fn mtext() -> MText { + MText { + insert: Vec3::new(1.25, -2.5, 3.75), + height: 2.25, + width: 12.5, + attach: 1, + rotation: 0.0, + style: "Notes".into(), + contents: "first\\Psecond Ø 图 😀".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + } +} + +pub(crate) fn mtext_placement() -> Vec { + (1..=9) + .flat_map(|attach| { + [0.0, 0.7, 5.9] + .map(|rotation| case(&format!("mtext/attach={attach}/rotation={rotation}"), EntityKind::MText(MText { attach, rotation, ..mtext() }))) + }) + .collect() +} + +pub(crate) fn mtext_spacing() -> Vec { + [0.25, 1.0, 1.75, 4.0] + .into_iter() + .flat_map(|line_spacing| { + [false, true].map(|line_spacing_exact| { + case( + &format!("mtext/spacing={line_spacing}/exact={line_spacing_exact}"), + EntityKind::MText(MText { line_spacing, line_spacing_exact, ..mtext() }), + ) + }) + }) + .collect() +} + +pub(crate) fn mtext_contents() -> Vec { + ["", " a\tb ", "{\\H0.7x;\\S1/2;}\\Pnext", "Unicode Ø 图 😀 e\u{301}"] + .map(|contents| case(&format!("mtext/contents={contents:?}"), EntityKind::MText(MText { contents: contents.into(), ..mtext() }))) + .into() +} + +pub(crate) fn mtext_carets() -> Vec { + vec![case("mtext/caret-space", EntityKind::MText(MText { contents: "\\pxi-3,l3,t3;1.\tA\\P2.\tB ^ C".into(), ..mtext() }))] +} + +pub(crate) fn mtext_long() -> Vec { + [249, 250, 251, 255, 256, 1024] + .map(|n| case(&format!("mtext/long={n}"), EntityKind::MText(MText { contents: "Ø😀".repeat(n), ..mtext() }))) + .into() +} + +pub(crate) fn mtext_columns() -> Vec { + [ + MTextColumns { kind: MTextColumnType::Static, count: 3, gutter: 0.5, height: 7.5, ..Default::default() }, + MTextColumns { + kind: MTextColumnType::Dynamic, + count: 3, + gutter: 0.5, + height: 5.0, + heights: vec![5.0, 3.0, 4.0], + flow_reversed: true, + ..Default::default() + }, + MTextColumns { kind: MTextColumnType::Dynamic, count: 1, gutter: 0.5, height: 4.0, auto_height: true, ..Default::default() }, + ] + .into_iter() + .map(|columns| case(&format!("mtext/columns={columns:?}"), EntityKind::MText(MText { columns: Some(columns), ..mtext() }))) + .collect() +} + +pub(crate) fn leaders(elevated: bool) -> Vec { + [false, true] + .into_iter() + .flat_map(|arrow| { + [false, true].map(|spline| { + case( + &format!("leader/arrow={arrow}/spline={spline}/elevated={elevated}"), + EntityKind::Leader(Leader { + vertices: vec![ + Vec3::ZERO, + Vec3::new(2.0, 3.0, if elevated { 4.0 } else { 0.0 }), + Vec3::new(5.0, 6.0, if elevated { 7.0 } else { 0.0 }), + ], + arrow, + spline, + style: "ISO-25".into(), + }), + ) + }) + }) + .collect() +} + +pub(crate) fn hatches() -> Vec { + let vertices = [Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 8.0), Vec2::new(0.0, 8.0)].map(PolyVertex::new).to_vec(); + (0..=2) + .map(|style| { + case( + &format!("hatch/solid/style={style}"), + EntityKind::Hatch(Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style, + elevation: 3.75, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }), + ) + }) + .collect() +} + +pub(crate) fn tables() -> Vec { + vec![case( + "table/cells", + EntityKind::Table(Table { + insert: Vec3::new(1.25, -2.5, 0.0), + col_widths: vec![5.0, 7.5], + row_heights: vec![2.0, 3.0], + cells: vec![ + vec![TableCell { text: "Ø".into(), ..Default::default() }, TableCell { text: "图".into(), ..Default::default() }], + vec![TableCell::default(), TableCell { text: "3.25".into(), ..Default::default() }], + ], + style: "Standard".into(), + text_height: 1.25, + title: false, + header: false, + row_styles: Vec::new(), + breaks: None, + data_link: None, + }), + )] +} + +pub(crate) fn images() -> Vec { + vec![case( + "image/reference-only", + EntityKind::Image(Image { + path: "synthetic-not-loaded.png".into(), + name: "Synthetic".into(), + insert: Vec3::new(1.0, 2.0, 3.0), + u: Vec3::new(0.5, 0.0, 0.0), + v: Vec3::new(0.0, 0.25, 0.0), + size: Vec2::new(32.0, 16.0), + clip: vec![Vec2::new(2.0, 3.0), Vec2::new(20.0, 12.0)], + clipping: true, + brightness: 37, + contrast: 61, + fade: 25, + ..Image::default() + }), + )] +} + +pub(crate) fn wipeouts(explicit_closure: bool) -> Vec { + [false, true] + .into_iter() + .map(|reversed| { + let mut boundary = vec![Vec2::new(1.0, 2.0), Vec2::new(7.0, 3.0), Vec2::new(4.0, 9.0)]; + if reversed { + boundary.reverse(); + } + if explicit_closure { + boundary.push(boundary[0]); + } + case(&format!("wipeout/triangle/explicit-closure={explicit_closure}/reversed={reversed}"), EntityKind::Wipeout(Wipeout { boundary })) + }) + .collect() +} diff --git a/crates/io/tests/it/roundtrip/cases/properties.rs b/crates/io/tests/it/roundtrip/cases/properties.rs new file mode 100644 index 000000000..eab95e8ac --- /dev/null +++ b/crates/io/tests/it/roundtrip/cases/properties.rs @@ -0,0 +1,351 @@ +//! Property, symbol-table and identity inputs. Values are authored before serialization; +//! each family can fail independently without suppressing unrelated preservation checks. + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::{Common, DashElement, Entity, EntityKind, HAlign, Handle, Layer, Line, Lineweight, RawTag, Text, TextStyle, Transparency, VAlign}; +use cadcraft_geom::{Vec2, Vec3}; + +use super::{Case, common_case, drawing, entity_case, text}; + +pub(crate) fn mixed_case_references(kind: &str) -> Vec { + let mut common = Common::default(); + let mut t = text(); + match kind { + "layer" => common.layer = "sURVEY_Ä".into(), + "linetype" => common.linetype = "dASH_TEST".into(), + "style" => t.style = "nOTES".into(), + _ => panic!("unknown reference family"), + } + vec![entity_case(&format!("reference/{kind}/mixed-case"), common, EntityKind::Text(t))] +} + +fn layer_case(name: &str, layer: Layer) -> Case { + let mut case = common_case(name, Common { layer: "Survey_Ä".into(), ..Common::default() }); + *case.drawing.layer_mut("Survey_Ä").unwrap() = Layer { name: "Survey_Ä".into(), ..layer }; + case +} + +pub(crate) fn layer_flags() -> Vec { + (0..32) + .map(|bits| { + layer_case( + &format!("layer/flags={bits}"), + Layer { + on: bits & 1 == 0, + frozen: bits & 2 != 0, + locked: bits & 4 != 0, + plot: bits & 8 == 0, + vp_freeze_new: bits & 16 != 0, + ..Layer::default() + }, + ) + }) + .collect() +} + +pub(crate) fn layer_appearance() -> Vec { + [Color::Index(1), Color::Index(255), Color::True(Rgb(17, 93, 241))] + .into_iter() + .flat_map(|color| { + [0, 37, 90].map(|transparency| { + layer_case( + &format!("layer/{color:?}/alpha={transparency}"), + Layer { + color, + transparency, + linetype: "Dash_test".into(), + lineweight: Lineweight::Mm100(53), + description: "Synthetic survey Ø 图".into(), + ..Layer::default() + }, + ) + }) + }) + .collect() +} + +pub(crate) fn layer_plot_styles() -> Vec { + ["Normal", "Review"] + .map(|plot_style| layer_case(&format!("layer/plot-style={plot_style}"), Layer { plot_style: plot_style.into(), ..Layer::default() })) + .into() +} + +fn style_case(name: &str, style: TextStyle) -> Case { + let mut case = entity_case(name, Common::default(), EntityKind::Text(Text { style: "Notes".into(), ..text() })); + *case.drawing.text_styles.iter_mut().find(|s| s.name == "Notes").unwrap() = TextStyle { name: "Notes".into(), ..style }; + case +} + +pub(crate) fn text_style_metrics() -> Vec { + [0.0, 0.125, 3.5] + .into_iter() + .flat_map(|height| { + [0.5, 1.0, 2.75].map(|width_factor| { + style_case( + &format!("style/height={height}/width={width_factor}"), + TextStyle { height, width_factor, oblique: std::f64::consts::FRAC_PI_4, ..TextStyle::default() }, + ) + }) + }) + .collect() +} + +pub(crate) fn text_style_flags() -> Vec { + (0..16) + .map(|bits| { + style_case( + &format!("style/flags={bits}"), + TextStyle { + backwards: bits & 1 != 0, + upside_down: bits & 2 != 0, + vertical: bits & 4 != 0, + annotative: bits & 8 != 0, + ..TextStyle::default() + }, + ) + }) + .collect() +} + +pub(crate) fn text_style_fonts() -> Vec { + // Names only; no font files are read or required. + [("CADCraft Stroke", ""), ("SyntheticSans.ttf", ""), ("synthetic.shx", "synthetic-big.shx")] + .map(|(font, big_font)| { + style_case( + &format!("style/font={font}/big={big_font}"), + TextStyle { font: font.into(), big_font: big_font.into(), ..TextStyle::default() }, + ) + }) + .into() +} + +pub(crate) fn complex_linetypes(shape: bool) -> Vec { + [false, true] + .map(|absolute| { + let mut case = + common_case(&format!("linetype/shape={shape}/absolute={absolute}"), Common { linetype: "Dash_test".into(), ..Common::default() }); + if shape { + case.drawing.text_styles.iter_mut().find(|s| s.name == "Notes").unwrap().font = "synthetic.shx".into(); + } + let l = case.drawing.linetypes.iter_mut().find(|l| l.name == "Dash_test").unwrap(); + l.pattern.push(DashElement { + text: (!shape).then(|| "GAS Ø".into()), + shape: shape.then_some(7), + style: Some("Notes".into()), + scale: 0.75, + rotation: std::f64::consts::FRAC_PI_2, + offset: Vec2::new(0.125, -0.25), + absolute, + ..DashElement::dash(-1.0) + }); + case + }) + .into() +} + +fn xdata_case(name: &str, tags: Vec<(i32, String)>) -> Case { + common_case(name, Common { xdata: tags.into_iter().map(|(code, value)| RawTag { code, value }).collect(), ..Common::default() }) +} + +pub(crate) fn xdata_lists() -> Vec { + vec![xdata_case( + "xdata/nested-and-multiple-apps", + [ + (1001, "ROUNDTRIP_A"), + (1002, "{"), + (1000, "outer"), + (1002, "{"), + (1070, "-32768"), + (1002, "}"), + (1071, "2147483647"), + (1002, "}"), + (1001, "ROUNDTRIP_B"), + (1000, ""), + (1000, "repeated Ø"), + (1004, "00FF80"), + (1041, "0.125"), + (1042, "2.75"), + ] + .map(|(c, v)| (c, v.into())) + .into(), + )] +} + +pub(crate) fn xdata_points() -> Vec { + (1010..=1013) + .map(|code| { + xdata_case( + &format!("xdata/point={code}"), + vec![(1001, "ROUNDTRIP_POINTS".into()), (code, "1.25".into()), (code + 10, "-2.5".into()), (code + 20, "3.75".into())], + ) + }) + .collect() +} + +pub(crate) fn xdata_handles() -> Vec { + let mut case = common_case("xdata/handle-reference", Common::default()); + let handles: Vec<_> = case.drawing.model.iter().map(|e| e.handle).collect(); + for &handle in &handles { + case.drawing.model.modify(handle, |e| { + e.common.xdata = + vec![RawTag { code: 1001, value: "ROUNDTRIP_HANDLES".into() }, RawTag { code: 1005, value: handles.last().unwrap().hex() }] + }); + } + vec![case] +} + +pub(crate) fn handles_and_order() -> Vec { + sparse_handles(&[0x1_0000, 0x1_0000_0000]) +} + +pub(crate) fn handles_near_integer_limits() -> Vec { + // Cross f64's exact-integer limit and signed i64's limit; leave room below u64::MAX + // for generated table/object handles rather than testing allocator exhaustion here. + sparse_handles(&[(1 << 53) - 0x80, (1 << 63) - 0x80, u64::MAX - 0x1_0000]) +} + +pub(crate) fn exhausted_handles() -> Case { + // The seed and writer's additional 0x1000 reservation leave no allocation room. + sparse_handles(&[u64::MAX - 0x2000]).remove(0) +} + +fn sparse_handles(bases: &[u64]) -> Vec { + bases + .iter() + .map(|&base| { + let mut drawing = drawing(); + for index in [5, 1, 9, 3, 2, 8, 4, 7, 6] { + let kind = if index % 2 == 0 { + EntityKind::Text(Text { value: format!("entity-{index}"), ..text() }) + } else { + EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(index as f64, 2.0, 3.0) }) + }; + drawing.model.push(Entity::new(Handle(base + index * 17), kind)); + } + drawing.handseed = base + 0x1000; + Case { name: format!("handles/sparse/base={base:X}"), drawing } + }) + .collect() +} + +pub(crate) fn degenerate_geometry() -> Vec { + [Vec3::ZERO, Vec3::new(1e9, -1e9, 1e-9)] + .map(|p| entity_case(&format!("line/coincident={p:?}"), Common::default(), EntityKind::Line(Line { a: p, b: p }))) + .into() +} + +pub(crate) fn text_interactions() -> Vec { + let mut cases = Vec::new(); + for rotation in [-0.7, 0.0, 5.9] { + for width_factor in [0.125, 2.75] { + for oblique in [-0.3, 0.4] { + cases.push(entity_case( + &format!("text/product/{rotation}/{width_factor}/{oblique}"), + Common::default(), + EntityKind::Text(Text { + rotation, + width_factor, + oblique, + height: 0.125, + style: "Notes".into(), + value: " Ø 图 😀 ".into(), + ..text() + }), + )); + } + } + } + cases +} + +/// Four independently overridden properties on a deliberately non-default layer. The 16 masks +/// cover inheritance/override pairs without multiplying by every possible property value. +pub(crate) fn layer_inheritance_overrides() -> Vec { + (0..16) + .map(|mask| { + let common = Common { + layer: "Survey_Ä".into(), + color: if mask & 1 == 0 { Color::ByLayer } else { Color::True(Rgb(0, 0, 0)) }, + transparency: if mask & 2 == 0 { Transparency::ByLayer } else { Transparency::Percent(0) }, + lineweight: if mask & 4 == 0 { Lineweight::ByLayer } else { Lineweight::Mm100(0) }, + linetype: if mask & 8 == 0 { "ByLayer" } else { "Continuous" }.into(), + ..Common::default() + }; + let mut case = common_case(&format!("layer/inheritance-overrides={mask:04b}"), common); + *case.drawing.layer_mut("Survey_Ä").unwrap() = Layer { + name: "Survey_Ä".into(), + color: Color::Index(3), + transparency: 67, + lineweight: Lineweight::Mm100(53), + linetype: "Dash_test".into(), + ..Layer::default() + }; + case + }) + .collect() +} + +/// Mirrored styles affect baseline placement; their metrics must not overwrite the entity's +/// own height/width/oblique. Font layout constructs consistent inputs, never expected output. +pub(crate) fn alignment_style_interactions() -> Vec { + let mut cases = Vec::new(); + for (halign, valign) in [ + (HAlign::Left, VAlign::Top), + (HAlign::Center, VAlign::Middle), + (HAlign::Right, VAlign::Baseline), + (HAlign::Aligned, VAlign::Baseline), + (HAlign::Fit, VAlign::Baseline), + ] { + for flags in 0..4 { + let style = TextStyle { + name: "Notes".into(), + height: 7.0, + width_factor: 2.0, + oblique: 0.25, + backwards: flags & 1 != 0, + upside_down: flags & 2 != 0, + ..TextStyle::default() + }; + let mut t = Text { + insert: Vec3::new(-5.0, 3.0, 0.0), + align_pt: Some(Vec3::ZERO), + style: style.name.clone(), + halign, + valign, + height: 1.5, + width_factor: 0.75, + oblique: -0.125, + rotation: 0.7, + ..text() + }; + if !matches!(halign, HAlign::Aligned | HAlign::Fit) { + let (h, v) = cadcraft_render::text_align(halign, valign); + let params = cadcraft_fonts::TextParams { + insert: t.insert.xy(), + align_pt: Some(Vec2::ZERO), + height: t.height, + rotation: t.rotation, + width_factor: t.width_factor, + oblique: t.oblique, + h, + v, + backwards: style.backwards, + upside_down: style.upside_down, + }; + t.insert = cadcraft_fonts::baseline_start(&cadcraft_fonts::TextFont::Stroke, &t.value, ¶ms).to3(0.0); + } + let mut case = entity_case(&format!("text/alignment-style/{halign:?}/{valign:?}/flags={flags}"), Common::default(), EntityKind::Text(t)); + *case.drawing.text_styles.iter_mut().find(|s| s.name == "Notes").unwrap() = style; + cases.push(case); + } + } + cases +} + +pub(crate) fn long_text() -> Vec { + [254, 255, 256, 1024] + .map(|length| { + entity_case(&format!("text/length={length}"), Common::default(), EntityKind::Text(Text { value: "Ø".repeat(length), ..text() })) + }) + .into() +} diff --git a/crates/io/tests/it/roundtrip/collections.rs b/crates/io/tests/it/roundtrip/collections.rs new file mode 100644 index 000000000..9b9acf36b --- /dev/null +++ b/crates/io/tests/it/roundtrip/collections.rs @@ -0,0 +1,263 @@ +//! Drawing-collection contracts beyond model space. Assertions cover explicitly authored data, +//! not generated timestamps/extents, allocation seeds or extra implementation-owned objects. +//! Named tables are compared by identity; paper entities retain order and handles. These are +//! focused collection contracts, not a claim that every Drawing/session field is persistent. + +use super::{ + cases::{self, Case}, + compare, +}; +use cadcraft_color::Color; +use cadcraft_doc::{ + Common, Drawing, EntityKind, Group, HVal, Layer, LayerState, Layout, Line, Linetype, NamedView, Space, TextStyle, Ucs, Viewport, VportConfig, + VportTile, +}; +use cadcraft_geom::{Vec2, Vec3}; + +pub(super) fn foreign_records() -> Case { + use cadcraft_doc::{Handle, RawTag, foreign::ForeignObject}; + let mut drawing = cases::drawing(); + let foreign = std::sync::Arc::make_mut(&mut drawing.foreign); + foreign.dictionary.push(("SYNTHETIC_PAYLOAD".into(), Handle(0xA000))); + foreign.targets.insert(Handle(0xA001), ("NOD".into(), String::new())); + foreign.objects.push(ForeignObject { + handle: Handle(0xA000), + kind: "XRECORD".into(), + tags: [ + (5, "A000"), + (330, "A001"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "Original Ø payload"), + (90, "-7"), + (310, "00FF80"), + (10, "1.25"), + (20, "-2.5"), + (30, "3.75"), + ] + .map(|(code, value)| RawTag { code, value: value.into() }) + .into(), + }); + drawing.handseed = 0xA100; + Case { name: "drawing/foreign-xrecord".into(), drawing } +} + +pub(super) fn assert_foreign_records(a: &Drawing, b: &Drawing, context: &str) { + // Rereads may add implementation-owned dictionaries; this case owns one explicit key. + let key = "SYNTHETIC_PAYLOAD"; + let (_, handle) = a.foreign.dictionary.iter().find(|(name, _)| name == key).expect("authored dictionary entry"); + let (_, target) = b.foreign.dictionary.iter().find(|(name, _)| name == key).unwrap_or_else(|| panic!("{context}.dictionary[{key}]: missing key")); + let source = a.foreign.objects.iter().find(|o| o.handle == *handle).unwrap(); + let back = b.foreign.objects.iter().find(|o| o.handle == *target).expect("dictionary target must resolve"); + assert_eq!(back.kind, source.kind, "{context}.object.kind"); + let owner = back.tags.iter().find(|t| t.code == 330).and_then(|t| cadcraft_doc::Handle::parse_hex(&t.value)).expect("XRECORD owner"); + assert_eq!(b.foreign.targets.get(&owner), Some(&("NOD".into(), String::new())), "{context}.object.owner"); + // Foreign's documented contract reallocates object handles and remaps references. + // Identity here is the NOD key and its resolved target, not the numeric allocation. + // Preserve every payload tag (including its order) after the subclass marker. + fn payload(tags: &[cadcraft_doc::RawTag]) -> &[cadcraft_doc::RawTag] { + let start = + tags.iter().position(|t| t.code == 100 && t.value == "AcDbXrecord").unwrap_or_else(|| panic!("missing XRECORD subclass: {tags:?}")); + &tags[start + 1..] + } + assert_eq!(payload(&back.tags), payload(&source.tags), "{context}.object.payload"); +} + +const HEADER_KEYS: &[&str] = &["LTSCALE", "CELTSCALE", "LUPREC", "AUPREC", "INSBASE", "TEXTSIZE", "CLAYER", "TEXTSTYLE"]; + +pub(super) fn headers() -> Case { + let mut drawing = cases::drawing(); + drawing.header.set_f64("LTSCALE", 2.75); + drawing.header.set_f64("CELTSCALE", 0.125); + drawing.header.set_i64("LUPREC", 7); + drawing.header.set_i64("AUPREC", 3); + drawing.header.set("INSBASE", HVal::Point(Vec3::new(1.25, -2.5, 3.75))); + drawing.header.set_f64("TEXTSIZE", 3.25); + + Case { name: "drawing/header-variables".into(), drawing } +} + +pub(super) fn named_header_reference(key: &str) -> Case { + let mut case = headers(); + case.name = format!("drawing/header-reference/{key}"); + case.drawing.header.set_str( + key, + match key { + "CLAYER" => "Survey_Ä", + "TEXTSTYLE" => "Notes", + _ => panic!("unknown header reference"), + }, + ); + case +} + +pub(super) fn assert_headers(a: &Drawing, b: &Drawing, context: &str) { + for key in HEADER_KEYS { + assert_eq!(b.header.get(key), a.header.get(key), "{context}.header.{key}"); + } +} + +pub(super) fn symbol_tables() -> Case { + let mut drawing = cases::drawing(); + drawing.layers.push(Layer { + name: "UnusedLayer".into(), + color: Color::Index(5), + locked: true, + description: "Unused Ø".into(), + ..Layer::default() + }); + drawing.linetypes.push(Linetype::simple("UnusedDash", "Unused synthetic", &[3.0, -0.5, 0.0, -0.25])); + drawing.text_styles.push(TextStyle { name: "UnusedStyle".into(), font: "SyntheticSans.ttf".into(), width_factor: 1.25, ..TextStyle::default() }); + Case { name: "drawing/unreferenced-tables".into(), drawing } +} + +pub(super) fn assert_symbol_tables(a: &Drawing, b: &Drawing, context: &str) { + for layer in &a.layers { + assert_eq!(b.layer(&layer.name), Some(layer), "{context}.layer[{}]", layer.name); + } + for linetype in &a.linetypes { + assert_eq!(b.linetype(&linetype.name), Some(linetype), "{context}.linetype[{}]", linetype.name); + } + for style in &a.text_styles { + assert_eq!(b.text_style(&style.name), Some(style), "{context}.style[{}]", style.name); + } +} + +pub(super) fn views_and_ucs() -> Case { + let mut drawing = cases::drawing(); + drawing.views.push(NamedView { name: "SurveyView".into(), center: Vec2::new(1.25, -2.5), height: 25.0, width: 40.0, ..NamedView::default() }); + drawing.ucss.push(Ucs { + name: "RotatedUCS".into(), + origin: Vec3::new(3.0, 4.0, 5.0), + x_axis: Vec3::new(0.0, 1.0, 0.0), + y_axis: Vec3::new(-1.0, 0.0, 0.0), + }); + Case { name: "drawing/views-and-ucs".into(), drawing } +} + +pub(super) fn assert_views_and_ucs(a: &Drawing, b: &Drawing, context: &str) { + assert_eq!(b.views, a.views, "{context}.views"); + assert_eq!(b.ucss, a.ucss, "{context}.ucss"); +} + +pub(super) fn vports() -> Case { + let mut drawing = cases::drawing(); + drawing.vports.push(VportConfig { + name: "Split".into(), + tiles: vec![ + VportTile { min: Vec2::ZERO, max: Vec2::new(0.5, 1.0), center: Vec2::new(2.0, 3.0), height: 20.0, aspect: 0.75 }, + VportTile { min: Vec2::new(0.5, 0.0), max: Vec2::new(1.0, 1.0), center: Vec2::new(7.0, 8.0), height: 30.0, aspect: 0.75 }, + ], + }); + Case { name: "drawing/tiled-viewports".into(), drawing } +} + +pub(super) fn assert_vports(a: &Drawing, b: &Drawing, context: &str) { + for viewport in &a.vports { + assert_eq!(b.vports.iter().find(|v| v.name == viewport.name), Some(viewport), "{context}.vport[{}]", viewport.name); + } +} + +pub(super) fn groups() -> Case { + let mut case = cases::common_case("drawing/groups", Common::default()); + let handles: Vec<_> = case.drawing.model.iter().map(|e| e.handle).collect(); + case.drawing.groups.push(Group { + name: "Synthetic".into(), + description: "Ordered overlapping membership Ø".into(), + selectable: true, + members: vec![handles[2], handles[0]], + }); + case.drawing.groups.push(Group { name: "Other".into(), description: String::new(), selectable: false, members: vec![handles[1], handles[2]] }); + case +} + +pub(super) fn assert_groups(a: &Drawing, b: &Drawing, context: &str) { + assert_eq!(b.groups.len(), a.groups.len(), "{context}.groups.len"); + for group in &a.groups { + assert_eq!(b.groups.iter().find(|g| g.name == group.name), Some(group), "{context}.group[{}]", group.name); + } +} + +pub(super) fn layer_states() -> Case { + let mut drawing = cases::drawing(); + let mut layers = drawing.layers.clone(); + for layer in &mut layers { + layer.on = false; + layer.locked = true; + } + drawing.layer_states.push(LayerState { name: "Saved".into(), layers }); + Case { name: "drawing/layer-state".into(), drawing } +} + +pub(super) fn assert_layer_states(a: &Drawing, b: &Drawing, context: &str) { + assert_eq!(b.layer_states, a.layer_states, "{context}.layer_states"); +} + +pub(super) fn layouts() -> Case { + let mut drawing = cases::drawing(); + drawing.layouts = vec![Layout::new("Sheet_A", 1), Layout::new("Sheet_B", 2)]; + for (index, layout) in drawing.layouts.iter_mut().enumerate() { + layout.page.paper_mm = true; + // PageSetup stores portrait dimensions; landscape is a separate orientation flag. + layout.page.width_mm = 297.0; + layout.page.height_mm = 420.0; + layout.page.scale = 0.5; + layout.page.plot_area = "window".into(); + layout.page.plot_window = [1.0, 2.0, 201.0, 142.0]; + layout.view = Some((Vec2::new(10.0, 20.0), 100.0 + index as f64)); + } + drawing.active_layout = Some("Sheet_B".into()); + for name in ["Sheet_A", "Sheet_B"] { + drawing.add(&Space::Paper(name.into()), Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 20.0, 0.0) })).unwrap(); + drawing + .add( + &Space::Paper(name.into()), + Common::default(), + EntityKind::Viewport(Viewport { + center: Vec3::new(50.0, 60.0, 0.0), + width: 80.0, + height: 50.0, + view_center: Vec2::new(5.0, 7.0), + view_height: 25.0, + id: 2, + locked: true, + frozen_layers: vec!["Survey_Ä".into()], + ..Viewport::default() + }), + ) + .unwrap(); + } + Case { name: "drawing/layouts-and-paper-entities".into(), drawing } +} + +#[test] +fn collection_assertions_reject_lost_authored_data() { + type Check = fn(&Drawing, &Drawing, &str); + type Mutate = fn(&mut Drawing); + let cases: [(Case, Check, Mutate); 6] = [ + (headers(), assert_headers, |d| d.header.set_f64("TEXTSIZE", 9.0)), + (symbol_tables(), assert_symbol_tables, |d| d.layers.retain(|l| l.name != "UnusedLayer")), + (views_and_ucs(), assert_views_and_ucs, |d| d.ucss.clear()), + (groups(), assert_groups, |d| d.groups.first_mut().unwrap().members.reverse()), + (layouts(), assert_layouts, |d| d.layouts.first_mut().unwrap().page.scale = 2.0), + (foreign_records(), assert_foreign_records, |d| std::sync::Arc::make_mut(&mut d.foreign).objects.clear()), + ]; + for (case, verify, mutate) in cases { + verify(&case.drawing, &case.drawing, &case.name); + let mut changed = case.drawing.clone(); + mutate(&mut changed); + assert!(std::panic::catch_unwind(|| verify(&case.drawing, &changed, &case.name)).is_err(), "{}: lost data must fail", case.name); + } +} + +pub(super) fn assert_layouts(a: &Drawing, b: &Drawing, context: &str) { + assert_eq!(b.layouts.len(), a.layouts.len(), "{context}.layouts.len"); + assert_eq!(b.active_layout, a.active_layout, "{context}.active_layout"); + for layout in &a.layouts { + let back = b.layouts.iter().find(|l| l.name == layout.name).expect("layout must survive"); + assert_eq!(back.tab_order, layout.tab_order, "{context}.{}.tab_order", layout.name); + assert_eq!(back.page, layout.page, "{context}.{}.page", layout.name); + assert_eq!(back.view, layout.view, "{context}.{}.view", layout.name); + compare::entities(a, b, &layout.entities, &back.entities, &format!("{context}.layout[{}]", layout.name)); + } +} diff --git a/crates/io/tests/it/roundtrip/compare.rs b/crates/io/tests/it/roundtrip/compare.rs new file mode 100644 index 000000000..d4bd1541a --- /dev/null +++ b/crates/io/tests/it/roundtrip/compare.rs @@ -0,0 +1,374 @@ +//! Shared preservation assertions for ordered entities, authored blocks and referenced tables. +//! Every field of the explicitly supported entities is checked; converted angles alone allow +//! floating-point roundoff, never wrapping or geometric approximation. Blocks are visited once +//! as stored definitions, not recursively expanded, so cyclic references remain bounded. +//! Header defaults, generated objects and other drawing collections are outside this slice. + +use std::fmt::Debug; + +use cadcraft_doc::{Arc, Attrib, Block, Circle, Common, Drawing, Entity, EntityKind, EntityStore, Insert, Line, MText, Text}; + +fn equal(expected: &T, actual: &T, context: &str, field: &str) { + assert_eq!(actual, expected, "{context}.{field}"); +} + +fn angle(expected: f64, actual: f64, context: &str, field: &str) { + // Two floating-point unit conversions, not a geometric approximation or angle wrapping. + let tolerance = 8.0 * f64::EPSILON * expected.abs().max(1.0); + assert!( + expected.is_finite() && actual.is_finite() && (actual - expected).abs() <= tolerance, + "{context}.{field}: expected {expected:?}, actual {actual:?}, tolerance {tolerance:e}" + ); +} + +pub(super) fn model(expected: &Drawing, actual: &Drawing, context: &str) { + entities(expected, actual, &expected.model, &actual.model, &format!("{context}.model")); + for (name, block) in &expected.blocks { + let path = format!("{context}.block[{name}]"); + let back = actual.block(name).unwrap_or_else(|| panic!("{path}: missing block")); + let Block { + name, + annotative, + base, + entities: contents, + description, + xref_overlay, + xref_status, + anonymous, + xref_path, + explodable, + units, + array, + } = block.as_ref(); + equal(name, &back.name, &path, "name"); + equal(annotative, &back.annotative, &path, "annotative"); + equal(base, &back.base, &path, "base"); + equal(description, &back.description, &path, "description"); + equal(xref_overlay, &back.xref_overlay, &path, "xref_overlay"); + equal(xref_status, &back.xref_status, &path, "xref_status"); + equal(anonymous, &back.anonymous, &path, "anonymous"); + equal(xref_path, &back.xref_path, &path, "xref_path"); + equal(explodable, &back.explodable, &path, "explodable"); + equal(units, &back.units, &path, "units"); + equal(array, &back.array, &path, "array"); + entities(expected, actual, contents, &back.entities, &path); + } +} + +pub(super) fn entities(expected: &Drawing, actual: &Drawing, source: &EntityStore, back: &EntityStore, context: &str) { + equal(&source.len(), &back.len(), context, "len"); + for (index, (a, b)) in source.iter().zip(back.iter()).enumerate() { + let path = format!("{context}.entity[{index}]"); + entity(a, b, &path); + layer_reference(expected, actual, &a.common.layer, &path); + linetype_reference(expected, actual, &a.common.linetype, &path); + let dimension_style = match &a.kind { + EntityKind::Dimension(d) => Some(d.style.as_str()), + EntityKind::Leader(l) => Some(l.style.as_str()), + EntityKind::Tolerance(t) => Some(t.style.as_str()), + _ => None, + }; + if let Some(name) = dimension_style { + equal(&expected.dim_style(name), &actual.dim_style(name), &path, "referenced_dimension_style"); + if let Some(style) = expected.dim_style(name) { + equal(&expected.text_style(&style.text_style), &actual.text_style(&style.text_style), &path, "dimension_text_style"); + } + } + let style = match &a.kind { + EntityKind::Text(t) => Some(t.style.as_str()), + EntityKind::MText(t) => Some(t.style.as_str()), + EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.style.as_str()), + _ => None, + }; + if let Some(style) = style { + equal(&expected.text_style(style), &actual.text_style(style), &path, "referenced_text_style"); + } + let attributes: &[Attrib] = match &a.kind { + EntityKind::AttDef(a) => std::slice::from_ref(a), + EntityKind::Insert(i) => &i.attribs, + EntityKind::MLeader(m) => m.block.as_ref().map_or(&[], |i| i.attribs.as_slice()), + _ => &[], + }; + for (index, a) in attributes.iter().enumerate() { + let path = format!("{path}.attrib[{index}]"); + if let Some(name) = &a.props.layer { + layer_reference(expected, actual, name, &path); + } + if let Some(name) = &a.props.linetype { + linetype_reference(expected, actual, name, &path); + } + for style in std::iter::once(a.text.style.as_str()).chain(a.multiline.as_ref().map(|m| m.mtext.style.as_str())) { + equal(&expected.text_style(style), &actual.text_style(style), &path, "referenced_text_style"); + } + } + } +} + +fn layer_reference(expected: &Drawing, actual: &Drawing, name: &str, context: &str) { + let layer = expected.layer(name); + equal(&layer, &actual.layer(name), context, "referenced_layer"); + if let Some(layer) = layer { + linetype_reference(expected, actual, &layer.linetype, context); + } +} + +fn linetype_reference(expected: &Drawing, actual: &Drawing, name: &str, context: &str) { + linetype(expected.linetype(name), actual.linetype(name), &format!("{context}.linetype[{name}]")); + if let Some(linetype) = expected.linetype(name) { + for element in &linetype.pattern { + if let Some(style) = &element.style { + equal(&expected.text_style(style), &actual.text_style(style), context, "linetype_text_style"); + } + } + } +} + +fn linetype(expected: Option<&cadcraft_doc::Linetype>, actual: Option<&cadcraft_doc::Linetype>, context: &str) { + let (Some(a), Some(b)) = (expected, actual) else { + equal(&expected, &actual, context, "presence"); + return; + }; + let cadcraft_doc::Linetype { name, description, pattern } = a; + equal(name, &b.name, context, "name"); + equal(description, &b.description, context, "description"); + equal(&pattern.len(), &b.pattern.len(), context, "pattern.len"); + for (index, (a, b)) in pattern.iter().zip(&b.pattern).enumerate() { + let path = format!("{context}.element[{index}]"); + let cadcraft_doc::DashElement { length, text, shape, style, scale, rotation, offset, absolute } = a; + equal(length, &b.length, &path, "length"); + equal(text, &b.text, &path, "text"); + equal(shape, &b.shape, &path, "shape"); + equal(style, &b.style, &path, "style"); + equal(scale, &b.scale, &path, "scale"); + angle(*rotation, b.rotation, &path, "rotation"); + equal(offset, &b.offset, &path, "offset"); + equal(absolute, &b.absolute, &path, "absolute"); + } +} + +fn entity(expected: &Entity, actual: &Entity, context: &str) { + let Entity { handle, common: properties, kind } = expected; + equal(handle, &actual.handle, context, "handle"); + common(properties, &actual.common, &format!("{context}.common")); + match (kind, &actual.kind) { + (EntityKind::Line(Line { a, b }), EntityKind::Line(other)) => { + equal(a, &other.a, context, "line.a"); + equal(b, &other.b, context, "line.b"); + } + (EntityKind::Circle(Circle { center, radius }), EntityKind::Circle(other)) => { + equal(center, &other.center, context, "circle.center"); + equal(radius, &other.radius, context, "circle.radius"); + } + (EntityKind::Text(a), EntityKind::Text(b)) => text(a, b, &format!("{context}.text")), + (EntityKind::Arc(Arc { center, radius, start, end }), EntityKind::Arc(b)) => { + equal(center, &b.center, context, "arc.center"); + equal(radius, &b.radius, context, "arc.radius"); + angle(*start, b.start, context, "arc.start"); + angle(*end, b.end, context, "arc.end"); + } + (EntityKind::MText(a), EntityKind::MText(b)) => mtext(a, b, context), + (EntityKind::AttDef(a), EntityKind::AttDef(b)) => attrib(a, b, context), + (EntityKind::Insert(a), EntityKind::Insert(b)) => insert(a, b, context), + ( + EntityKind::Point(_) + | EntityKind::Ellipse(_) + | EntityKind::LwPolyline(_) + | EntityKind::Polyline3d(_) + | EntityKind::Spline(_) + | EntityKind::Ray(_) + | EntityKind::XLine(_) + | EntityKind::Solid(_) + | EntityKind::Trace(_) + | EntityKind::Face3d(_) + | EntityKind::Leader(_) + | EntityKind::Hatch(_) + | EntityKind::Table(_) + | EntityKind::Image(_) + | EntityKind::Wipeout(_) + | EntityKind::Helix(_) + | EntityKind::MLine(_) + | EntityKind::MLeader(_) + | EntityKind::Region(_) + | EntityKind::Dimension(_) + | EntityKind::Tolerance(_) + | EntityKind::Viewport(_), + _, + ) => equal(kind, &actual.kind, context, "kind"), + _ => panic!("{context}.kind: unsupported or changed type: expected {kind:?}, actual {:?}", actual.kind), + } +} + +fn common(expected: &Common, actual: &Common, context: &str) { + // No `..`: adding a field requires deciding its preservation contract here. + let Common { layer, color, linetype, lineweight, ltscale, transparency, visible, thickness, extrusion, plot_style, anno_scales, xdata } = + expected; + equal(layer, &actual.layer, context, "layer"); + equal(color, &actual.color, context, "color"); + equal(linetype, &actual.linetype, context, "linetype"); + equal(lineweight, &actual.lineweight, context, "lineweight"); + equal(ltscale, &actual.ltscale, context, "ltscale"); + equal(transparency, &actual.transparency, context, "transparency"); + equal(visible, &actual.visible, context, "visible"); + equal(thickness, &actual.thickness, context, "thickness"); + equal(extrusion, &actual.extrusion, context, "extrusion"); + equal(plot_style, &actual.plot_style, context, "plot_style"); + equal(anno_scales, &actual.anno_scales, context, "anno_scales"); + equal(xdata, &actual.xdata, context, "xdata"); +} + +fn text(expected: &Text, actual: &Text, context: &str) { + let Text { insert, align_pt, height, value, rotation, width_factor, oblique, style, halign, valign } = expected; + equal(insert, &actual.insert, context, "insert"); + equal(align_pt, &actual.align_pt, context, "align_pt"); + equal(height, &actual.height, context, "height"); + equal(value, &actual.value, context, "value"); + angle(*rotation, actual.rotation, context, "rotation"); + equal(width_factor, &actual.width_factor, context, "width_factor"); + angle(*oblique, actual.oblique, context, "oblique"); + equal(style, &actual.style, context, "style"); + equal(halign, &actual.halign, context, "halign"); + equal(valign, &actual.valign, context, "valign"); +} + +fn mtext(expected: &MText, actual: &MText, context: &str) { + let MText { insert, height, width, attach, rotation, style, contents, line_spacing, line_spacing_exact, columns } = expected; + equal(insert, &actual.insert, context, "mtext.insert"); + equal(height, &actual.height, context, "mtext.height"); + equal(width, &actual.width, context, "mtext.width"); + equal(attach, &actual.attach, context, "mtext.attach"); + angle(*rotation, actual.rotation, context, "mtext.rotation"); + equal(style, &actual.style, context, "mtext.style"); + equal(contents, &actual.contents, context, "mtext.contents"); + equal(line_spacing, &actual.line_spacing, context, "mtext.line_spacing"); + equal(line_spacing_exact, &actual.line_spacing_exact, context, "mtext.line_spacing_exact"); + equal(columns, &actual.columns, context, "mtext.columns"); +} + +fn attrib(expected: &Attrib, actual: &Attrib, context: &str) { + let Attrib { tag, text: t, invisible, constant, prompt, props, multiline, modes } = expected; + equal(tag, &actual.tag, context, "attrib.tag"); + text(t, &actual.text, context); + equal(invisible, &actual.invisible, context, "attrib.invisible"); + equal(constant, &actual.constant, context, "attrib.constant"); + equal(prompt, &actual.prompt, context, "attrib.prompt"); + equal(props, &actual.props, context, "attrib.props"); + equal(modes, &actual.modes, context, "attrib.modes"); + match (multiline, &actual.multiline) { + (Some(a), Some(b)) => { + equal(&a.read_as, &b.read_as, context, "attrib.read_as"); + mtext(&a.mtext, &b.mtext, context); + } + _ => equal(multiline, &actual.multiline, context, "attrib.multiline"), + } +} + +fn insert(expected: &Insert, actual: &Insert, context: &str) { + let Insert { block, insert, scale, rotation, attribs, cols, rows, col_spacing, row_spacing } = expected; + equal(block, &actual.block, context, "insert.block"); + equal(insert, &actual.insert, context, "insert.insert"); + equal(scale, &actual.scale, context, "insert.scale"); + angle(*rotation, actual.rotation, context, "insert.rotation"); + equal(cols, &actual.cols, context, "insert.cols"); + 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(&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}]")); + } +} + +#[test] +fn comparison_rejects_lost_fields_and_changed_handles() { + use cadcraft_doc::Handle; + use cadcraft_geom::Vec3; + + let original = Entity::new(Handle(0x123), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(2.0, 3.0, 4.0) })); + let mutations: [fn(&mut Entity); 4] = [ + |e| e.handle = Handle(0x456), + |e| e.common.visible = false, + |e| e.common.xdata.push(cadcraft_doc::RawTag { code: 1000, value: "unexpected".into() }), + |e| e.kind = EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 2.0 }), + ]; + for mutate in mutations { + let mut changed = original.clone(); + mutate(&mut changed); + assert!(std::panic::catch_unwind(|| entity(&original, &changed, "comparison self-test")).is_err()); + } +} + +#[test] +fn comparison_rejects_lost_or_changed_referenced_linetypes() { + use cadcraft_doc::{Linetype, Space}; + use cadcraft_geom::Vec3; + + for (name, entity_linetype, layer_linetype) in [ + ("direct", "ReviewDashed", "Continuous"), + ("mixed-case", "reviewdashed", "Continuous"), + ("inherited", "ByLayer", "ReviewDashed"), + ("inherited-mixed-case", "ByLayer", "reviewdashed"), + ] { + let mut original = Drawing::new_metric(); + original.linetypes.push(Linetype::simple("ReviewDashed", "Synthetic", &[2.0, -1.0])); + original.layer_mut("0").unwrap().linetype = layer_linetype.into(); + original + .add( + &Space::Model, + Common { linetype: entity_linetype.into(), ..Common::default() }, + EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 2.0, 3.0) }), + ) + .unwrap(); + let referenced = if entity_linetype == "ByLayer" { layer_linetype } else { entity_linetype }; + assert!(original.linetype(referenced).is_some(), "{name}: valid reference"); + model(&original, &original, name); + let mutations: [fn(&mut Drawing); 2] = [ + |d| d.linetypes.retain(|l| l.name != "ReviewDashed"), + |d| d.linetypes.iter_mut().find(|l| l.name == "ReviewDashed").unwrap().pattern.clear(), + ]; + for (index, mutate) in mutations.into_iter().enumerate() { + let mut changed = original.clone(); + mutate(&mut changed); + assert!(std::panic::catch_unwind(|| model(&original, &changed, name)).is_err(), "{name}: mutation {index} must be rejected"); + } + } +} + +#[test] +fn comparison_rejects_block_and_attribute_dependency_losses() { + use super::cases::{blocks, properties}; + let original = blocks::attributes("overrides").remove(0).drawing; + let mutations: [fn(&mut Drawing); 4] = [ + |d| { + d.blocks.remove("Z_Leaf"); + }, + |d| std::sync::Arc::make_mut(d.blocks.get_mut("Z_Leaf").unwrap()).base.x += 1.0, + |d| d.layer_mut("Survey_Ä").unwrap().color = cadcraft_color::Color::Index(5), + |d| { + let handle = d.model.iter().next().unwrap().handle; + d.model.modify(handle, |e| { + let EntityKind::Insert(i) = &mut e.kind else { panic!("expected INSERT") }; + i.attribs.reverse(); + }); + }, + ]; + model(&original, &original, "unchanged block and attributes"); + for mutate in mutations { + let mut changed = original.clone(); + mutate(&mut changed); + assert!(std::panic::catch_unwind(|| model(&original, &changed, "block dependency self-test")).is_err()); + } + let original = properties::complex_linetypes(false).remove(0).drawing; + let mut changed = original.clone(); + changed.text_styles.retain(|s| s.name != "Notes"); + assert!(std::panic::catch_unwind(|| model(&original, &changed, "linetype style self-test")).is_err()); + let cyclic = blocks::nested(true).remove(0).drawing; + model(&cyclic, &cyclic, "cycles compare without expansion"); +} + +#[test] +fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() { + angle(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle"); + for actual in [0.700001, f64::NAN, f64::INFINITY] { + assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err()); + } +} diff --git a/crates/io/tests/it/roundtrip/dwg/conformance.rs b/crates/io/tests/it/roundtrip/dwg/conformance.rs new file mode 100644 index 000000000..ff58850ce --- /dev/null +++ b/crates/io/tests/it/roundtrip/dwg/conformance.rs @@ -0,0 +1,87 @@ +//! Independent bridge expectations, not an independent DWG codec. Writer checks inspect native +//! objects without CADCraft's reader; reader fixtures originate in native objects without our +//! DXF writer. acadrust still supplies the binary codec in both directions, so these tests do +//! not establish interoperability with another DWG implementation. All fixtures are synthetic. + +use super::super::cases; +use acadrust::types::Vector3; +use acadrust::{CadDocument, DwgReader, DwgWriter, DxfVersion, EntityType}; +use cadcraft_doc::{Circle, Common, EntityKind, Line, Text}; +use cadcraft_geom::Vec3; +use cadcraft_io::{SaveOptions, Version, read, write_with}; +use std::io::Cursor; + +#[test] +fn writer_populates_native_geometry_without_our_reader() { + let source = cases::common_case("native-writer", Common::default()); + for version in Version::ALL { + let bytes = write_with(&source.drawing, "memory.dwg", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let native = DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let entities: Vec<_> = native.entities().collect(); + assert_eq!(entities.len(), 3, "{version}"); + let EntityType::Line(line) = entities[0] else { panic!("expected native LINE") }; + assert_eq!(line.start, Vector3::new(-1.25, 2.5, 3.75), "{version}"); + assert_eq!(line.end, Vector3::new(8.125, -13.5, 21.25), "{version}"); + let EntityType::Circle(circle) = entities[1] else { panic!("expected native CIRCLE") }; + assert_eq!(circle.center, Vector3::new(-7.25, 11.5, 4.75), "{version}"); + assert_eq!(circle.radius, 3.125, "{version}"); + let EntityType::Text(text) = entities[2] else { panic!("expected native TEXT") }; + assert_eq!(text.value, "CAD Ø", "{version}"); + assert_eq!(text.insertion_point, Vector3::new(2.5, -3.75, 4.125), "{version}"); + assert_eq!(text.height, 2.25, "{version}"); + assert_eq!(text.width_factor, 1.0, "{version}"); + assert_eq!(text.rotation, 0.0, "{version}"); + } +} + +#[test] +#[ignore = "Confirmed native DWG mismatch: a pi/2 linetype rotation is stored as pi/2 degrees; DXF unit interpretation needs investigation"] +fn complex_linetype_rotation_is_correct_in_native_objects() { + // Both document APIs specify radians. Do not infer correctness from a DXF round trip: + // reader and writer can share a unit error. Public DXF references disagree about LTYPE + // group 50, so this asserts the end-to-end native angle, not a guessed DXF encoding. + for shape in [false, true] { + for case in cases::properties::complex_linetypes(shape) { + for version in Version::ALL { + let bytes = write_with(&case.drawing, "memory.dwg", &SaveOptions { version: Some(version), binary: false }).unwrap(); + let native = DwgReader::from_stream(Cursor::new(bytes)).read().unwrap(); + let line = native.line_types.iter().find(|l| l.name == "Dash_test").unwrap(); + let elements: Vec<_> = line.elements.iter().filter_map(|e| e.complex.as_ref()).collect(); + assert_eq!(elements.len(), 1, "{} {version}", case.name); + let rotation = elements[0].rotation; + assert!( + (rotation - std::f64::consts::FRAC_PI_2).abs() <= 8.0 * f64::EPSILON, + "{} {version}: native rotation {rotation} radians, expected pi/2", + case.name + ); + } + } + } +} + +#[test] +fn reader_accepts_native_fixtures_without_our_writer() { + for version in [DxfVersion::AC1015, DxfVersion::AC1018, DxfVersion::AC1021, DxfVersion::AC1024, DxfVersion::AC1027, DxfVersion::AC1032] { + let mut native = CadDocument::with_version(version); + let handles = [ + native.add_entity(EntityType::Line(acadrust::entities::Line::from_coords(1.25, -2.5, 3.75, -4.5, 5.25, -6.75))).unwrap(), + native.add_entity(EntityType::Circle(acadrust::entities::Circle::from_coords(7.25, -8.5, 9.75, 2.125))).unwrap(), + native.add_entity(EntityType::Text(acadrust::entities::Text::with_value("Independent Ø", Vector3::new(-3.25, 4.5, 1.75)))).unwrap(), + ]; + let expected = [ + EntityKind::Line(Line { a: Vec3::new(1.25, -2.5, 3.75), b: Vec3::new(-4.5, 5.25, -6.75) }), + EntityKind::Circle(Circle { center: Vec3::new(7.25, -8.5, 9.75), radius: 2.125 }), + EntityKind::Text(Text { insert: Vec3::new(-3.25, 4.5, 1.75), height: 1.0, value: "Independent Ø".into(), ..cases::text() }), + ]; + let bytes = DwgWriter::write_to_vec(&native).unwrap(); + let back = read(&bytes, "native-fixture.dwg").unwrap(); + assert!(back.read_notes.is_empty(), "{:?}", back.read_notes); + assert!(back.skipped_records.is_empty()); + assert_eq!(back.model.len(), expected.len()); + for ((entity, expected), handle) in back.model.iter().zip(&expected).zip(handles) { + assert_eq!(entity.handle.0, u64::from(handle), "{version:?}"); + assert_eq!(&entity.kind, expected, "{version:?}"); + assert_eq!(entity.common, Common::default(), "{version:?}"); + } + } +} diff --git a/crates/io/tests/it/roundtrip/dwg/dimensions.rs b/crates/io/tests/it/roundtrip/dwg/dimensions.rs new file mode 100644 index 000000000..3599d43f5 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dwg/dimensions.rs @@ -0,0 +1,210 @@ +//! DWG anonymous dimension-block suffixes are not persistent identities (#2257). Match blocks +//! through dimensions with preserved entity handles, then compare authored content and properties +//! strictly. Only anonymous *D names may change; missing references and merged blocks fail. +//! This verifier covers the model-space dimension fixtures, not arbitrary drawing graph remapping. +//! +//! Autodesk documents that anonymous block numbers may change between drawing sessions: +//! https://help.autodesk.com/cloudhelp/2022/ENU/AutoCAD-AutoLISP/files/GUID-EB9BFDAA-487A-4586-A556-1F5F84BCF2F3.htm +//! ODA's DWG specification §20.4.52.1 shows a BLOCK_HEADER named *D without a suffix; +//! DIMENSION records reference their block by handle, not by its reconstructed name: +//! https://www.opendesign.com/files/guestdownloads/OpenDesign_Specification_for_.dwg_files.pdf + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use cadcraft_doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, Space}; +use cadcraft_geom::Vec3; +use cadcraft_io::Version; + +use super::super::{ + cases::{self, Case, complex}, + compare, +}; + +pub(super) fn check() { + for case in complex::dimensions().into_iter().chain([paired_dimensions(["*D42", "*D7"])]) { + for version in Version::ALL { + let mut expected = case.drawing.clone(); + // DIMFXL has no native field before R2007 (same limit as other dimension-style cases). + if version < Version::R2007 { + for style in &mut expected.dim_styles { + style.fixed_ext_length = 0.0; + } + } + super::check_version_using(&case.name, &case.drawing, &expected, version, equivalent); + } + } +} + +// Two independent cache blocks with different authored geometry, plus an ordinary named block. +// Names are supplied explicitly so comparator controls do not learn expectations from a save. +fn paired_dimensions(names: [&str; 2]) -> Case { + let mut drawing = cases::drawing(); + for (index, (case, name)) in complex::dimensions().into_iter().zip(names).enumerate() { + let entity = case.drawing.model.iter().next().unwrap(); + let mut kind = entity.kind.clone(); + let EntityKind::Dimension(dim) = &mut kind else { panic!("fixture dimension") }; + dim.block = Some(name.into()); + drawing.add(&Space::Model, entity.common.clone(), kind).unwrap(); + let mut block = Block::new(name); + for entity in case.drawing.block("*D42").unwrap().entities.iter() { + block.entities.push(Entity { handle: drawing.new_handle(), ..entity.as_ref().clone() }); + } + // This circle is authored cache content, not something dimension regeneration produces. + block + .entities + .push(Entity::new(drawing.new_handle(), EntityKind::Circle(Circle { center: Vec3::new(5.0, 3.0, 0.0), radius: 0.25 + index as f64 }))); + drawing.blocks.insert(name.into(), Arc::new(block)); + } + let mut named = Block::new("UserPart"); + named.entities.push(Entity::new(drawing.new_handle(), EntityKind::Circle(Circle { center: Vec3::new(1.0, 2.0, 0.0), radius: 2.0 }))); + drawing.blocks.insert(named.name.clone(), Arc::new(named)); + Case { name: "dimension/distinct-anonymous-caches-and-named-block".into(), drawing } +} + +fn anonymous_dimension_name(name: &str) -> bool { + name.strip_prefix("*D").is_some_and(|suffix| !suffix.is_empty() && suffix.bytes().all(|c| c.is_ascii_digit())) +} + +fn equivalent(expected: &Drawing, actual: &Drawing, context: &str) { + let mut names = BTreeMap::new(); + for entity in expected.model.iter() { + let EntityKind::Dimension(dim) = &entity.kind else { continue }; + let before = dim.block.as_deref().expect("fixture has a dimension block"); + let back = actual.entity(entity.handle).unwrap_or_else(|| panic!("{context}: missing dimension {}", entity.handle.hex())); + let EntityKind::Dimension(dim) = &back.kind else { panic!("{context}: dimension changed type") }; + let after = dim.block.as_deref().unwrap_or_else(|| panic!("{context}: dimension lost its block reference")); + let source = expected.block(before).expect("fixture block exists"); + let target = actual.block(after).unwrap_or_else(|| panic!("{context}: dangling dimension block reference {after}")); + if before != after { + assert!(source.anonymous && target.anonymous, "{context}: only anonymous dimension blocks may be renamed"); + assert!( + anonymous_dimension_name(before) && anonymous_dimension_name(after), + "{context}: unexpected block name mapping {before} -> {after}" + ); + } + if let Some(previous) = names.insert(before.to_string(), after.to_string()) { + assert_eq!(previous, after, "{context}: one dimension block split into different references"); + } + } + assert!(!names.is_empty(), "{context}: fixture must exercise dimension block references"); + assert_eq!(names.values().collect::>().len(), names.len(), "{context}: distinct dimension blocks were merged"); + assert_eq!(actual.blocks.len(), expected.blocks.len(), "{context}: block lost or extra cache generated"); + + // Adapt only the validated names, never content or properties learned from the output. + // Rebuild the map to handle renumberings that reuse another source block's old name. + let mut renamed = expected.clone(); + renamed.blocks.clear(); + for (name, block) in &expected.blocks { + let mapped = names.get(name).unwrap_or(name); + let mut block = block.clone(); + Arc::make_mut(&mut block).name = mapped.clone(); + assert!(renamed.blocks.insert(mapped.clone(), block).is_none(), "{context}: block name collision"); + } + for entity in expected.model.iter() { + if let EntityKind::Dimension(dim) = &entity.kind { + let mapped = names.get(dim.block.as_ref().expect("fixture block")).expect("mapped reference"); + renamed.model.modify(entity.handle, |e| { + let EntityKind::Dimension(dim) = &mut e.kind else { panic!("fixture dimension") }; + dim.block = Some(mapped.clone()); + }); + } + } + compare::model(&renamed, actual, context); +} + +#[test] +fn comparison_accepts_only_anonymous_dimension_renumbering() { + let original = paired_dimensions(["*D42", "*D7"]).drawing; + equivalent(&original, &original, "unchanged"); + for names in [["*D1", "*D2"], ["*D7", "*D42"]] { + let renamed = paired_dimensions(names).drawing; + equivalent(&original, &renamed, "renumbered, including reused source names"); + // The general comparator must still reject renaming outside this DWG-specific check. + assert!(std::panic::catch_unwind(|| compare::model(&original, &renamed, "strict comparison")).is_err()); + } +} + +fn dimension_handles(d: &Drawing) -> Vec { + d.model.iter().filter(|e| matches!(e.kind, EntityKind::Dimension(_))).map(|e| e.handle).collect() +} + +fn set_reference(d: &mut Drawing, handle: Handle, name: Option<&str>) { + assert!(d.model.modify(handle, |e| { + let EntityKind::Dimension(dim) = &mut e.kind else { panic!("fixture dimension") }; + dim.block = name.map(str::to_string); + })); +} + +#[test] +fn comparison_rejects_broken_references_content_and_block_properties() { + let original = paired_dimensions(["*D42", "*D7"]).drawing; + let renamed = paired_dimensions(["*D1", "*D2"]).drawing; + equivalent(&original, &renamed, "valid control"); + let mutations: [fn(&mut Drawing); 14] = [ + |d| set_reference(d, dimension_handles(d)[0], None), + |d| set_reference(d, dimension_handles(d)[0], Some("*D999")), + |d| set_reference(d, dimension_handles(d)[0], Some("*D2")), + |d| { + let hs = dimension_handles(d); + set_reference(d, hs[0], Some("*D2")); + set_reference(d, hs[1], Some("*D1")); + }, + |d| { + d.blocks.remove("*D1"); + }, + |d| Arc::make_mut(d.blocks.get_mut("*D1").unwrap()).entities = Default::default(), + |d| { + let block = Arc::make_mut(d.blocks.get_mut("*D1").unwrap()); + let h = block.entities.iter().next().unwrap().handle; + block.entities.modify(h, |e| e.common.visible = false); + }, + |d| { + let block = Arc::make_mut(d.blocks.get_mut("*D1").unwrap()); + let h = block.entities.iter().last().unwrap().handle; + block.entities.modify(h, |e| { + let EntityKind::Circle(circle) = &mut e.kind else { panic!("fixture circle") }; + circle.radius += 1.0; + }); + }, + |d| { + let block = Arc::make_mut(d.blocks.get_mut("*D1").unwrap()); + let h = block.entities.iter().next().unwrap().handle; + block.entities.modify(h, |e| e.handle = Handle(0xFFFF)); + }, + |d| Arc::make_mut(d.blocks.get_mut("*D1").unwrap()).base.x += 1.0, + |d| Arc::make_mut(d.blocks.get_mut("*D1").unwrap()).anonymous = false, + |d| { + d.blocks.insert("*D999".into(), Arc::new(Block::new("*D999"))); + }, + |d| { + let mut block = d.blocks.remove("UserPart").unwrap(); + Arc::make_mut(&mut block).name = "RenamedPart".into(); + d.blocks.insert("RenamedPart".into(), block); + }, + |d| { + let h = dimension_handles(d)[0]; + d.model.modify(h, |e| { + let EntityKind::Dimension(dim) = &mut e.kind else { panic!("fixture dimension") }; + dim.p14.x += 1.0; + }); + }, + ]; + for (index, mutate) in mutations.into_iter().enumerate() { + let mut changed = renamed.clone(); + mutate(&mut changed); + assert!(std::panic::catch_unwind(|| equivalent(&original, &changed, "mutation")).is_err(), "mutation {index} must fail"); + } +} + +#[test] +fn comparison_rejects_changed_prefixes_and_named_dimension_cache_renaming() { + let original = paired_dimensions(["*D42", "*D7"]).drawing; + for name in ["*U1", "*D", "*Dcustom", "UserCache"] { + let changed = paired_dimensions([name, "*D2"]).drawing; + assert!(std::panic::catch_unwind(|| equivalent(&original, &changed, "wrong name kind")).is_err()); + } + let original = paired_dimensions(["AuthoredCache", "*D7"]).drawing; + let changed = paired_dimensions(["RenamedCache", "*D2"]).drawing; + assert!(std::panic::catch_unwind(|| equivalent(&original, &changed, "named cache")).is_err()); +} diff --git a/crates/io/tests/it/roundtrip/dwg/entities.rs b/crates/io/tests/it/roundtrip/dwg/entities.rs new file mode 100644 index 000000000..58f97d92f --- /dev/null +++ b/crates/io/tests/it/roundtrip/dwg/entities.rs @@ -0,0 +1,171 @@ +//! DWG property families stay separate: a failing escape, plot-style or alignment regression +//! must not disable unrelated TEXT or Common tests. Pending cases assert the original model, +//! never today's lossy output. Only confirmed failures receive an explicit ignore reason. + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::{Common, EntityKind, Transparency}; +use cadcraft_io::Version; + +use super::super::cases; +use super::{check, check_version}; + +#[test] +fn empty_model_and_defaults() { + check(cases::empty_and_defaults()); +} +#[test] +fn line_endpoints_and_circle_centers_radii() { + check(cases::geometry()); +} +#[test] +fn layers() { + check(cases::layers()); +} +#[test] +fn layer_inherited_linetypes() { + check(cases::layer_linetypes()); +} +#[test] +fn colors() { + check(cases::colors()); +} +#[test] +fn linetypes() { + check(cases::linetypes()); +} +#[test] +fn lineweights() { + check(cases::lineweights()); +} +#[test] +fn linetype_scales() { + check(cases::linetype_scales()); +} +#[test] +fn transparencies() { + check(cases::transparencies()); +} +#[test] +fn visibility() { + check(cases::visibility()); +} +#[test] +fn thicknesses() { + check(cases::thicknesses()); +} +#[test] +#[ignore = "Confirmed DWG bridge loss: named plot style Review becomes ByLayer, including R2018"] +fn named_plot_style_is_preserved() { + check(cases::plot_styles()); +} +#[test] +fn foreign_xdata() { + check(cases::foreign_xdata()); +} +#[test] +fn common_property_interactions() { + check(cases::common_interactions("ByLayer")); +} +#[test] +#[ignore = "Confirmed DWG bridge loss: named plot style is lost in combination with other properties"] +fn common_property_interactions_with_named_plot_style() { + check(cases::common_interactions("Review")); +} +#[test] +fn text_values() { + check(cases::text_values()); +} +#[test] +#[ignore = "Confirmed DWG bridge loss: literal Unicode/MIF escape text is decoded again, including R2018"] +fn text_literal_escapes() { + check(cases::text_literal_escapes()); +} +#[test] +fn text_heights() { + check(cases::text_heights()); +} +#[test] +fn text_rotations() { + check(cases::text_rotations()); +} +#[test] +fn text_widths() { + check(cases::text_widths()); +} +#[test] +fn text_obliques() { + check(cases::text_obliques()); +} +#[test] +fn text_styles() { + check(cases::text_styles()); +} +#[test] +fn annotation_scales() { + check(cases::annotation_scales()); +} +#[test] +fn text_alignment_with_points() { + check(cases::coplanar_text_alignment()); +} +#[test] +#[ignore = "Confirmed change: missing justified TEXT align_pt becomes (0,0,elevation), moving text"] +fn text_alignment_without_points() { + check(cases::text_alignment(false)); +} +#[test] +#[ignore = "Confirmed loss on the shared DXF path: ByBlock plot style becomes ByLayer"] +fn plot_style_byblock_is_preserved() { + check(cases::byblock_plot_style()); +} +#[test] +#[ignore = "Confirmed loss on the shared DXF path: non-default extrusion becomes (0,0,1)"] +fn nondefault_extrusion_is_preserved() { + check(cases::extrusions()); +} + +#[test] +fn text_points_share_one_elevation_in_dwg() { + // Public ODA DWG specification, TEXT (1): insertion and alignment points contain XY; + // a single elevation supplies both Z coordinates. This is a representational limit, not + // a bug or a comparison tolerance. DXF's original XYZ cases are still checked unchanged. + // https://www.opendesign.com/files/guestdownloads/OpenDesign_Specification_for_.dwg_files.pdf + let cases = cases::noncoplanar_text_alignment(); + assert!(!cases.is_empty()); + for case in cases { + let mut expected = case.drawing.clone(); + let handles: Vec<_> = expected.model.iter().map(|e| e.handle).collect(); + for handle in handles { + expected.model.modify(handle, |e| { + let EntityKind::Text(t) = &mut e.kind else { panic!("expected TEXT") }; + let point = t.align_pt.as_mut().expect("second point"); + point.z = t.insert.z; + }); + } + for version in Version::ALL { + check_version(&case.name, &case.drawing, &expected, version); + } + } +} + +#[test] +fn r2000_explicit_color_and_transparency_downgrade() { + // R2000 has no true-color/alpha fields. An exact red RGB maps to ACI 1; neither a fixed + // alpha nor transparency ByBlock is representable. Expected values are authored here, + // not learnt from an initial save, and are checked again after the second save. + for transparency in [Transparency::ByBlock, Transparency::Percent(0), Transparency::Percent(40), Transparency::Percent(90)] { + let case = cases::common_case( + &format!("legacy/true-red/transparency={transparency:?}"), + Common { color: Color::True(Rgb(255, 0, 0)), transparency, ..Common::default() }, + ); + let mut expected = case.drawing.clone(); + let handles: Vec<_> = expected.model.iter().map(|e| e.handle).collect(); + for handle in handles { + expected.model.modify(handle, |e| { + e.common.color = Color::Index(1); + e.common.transparency = Transparency::ByLayer; + }); + } + check_version(&case.name, &case.drawing, &expected, Version::R2000); + } +} diff --git a/crates/io/tests/it/roundtrip/dwg/extended.rs b/crates/io/tests/it/roundtrip/dwg/extended.rs new file mode 100644 index 000000000..001712d28 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dwg/extended.rs @@ -0,0 +1,395 @@ +//! Native DWG extensions to the shared preservation matrix. Version limits (native columns, +//! attributes, HELIX/MULTILEADER and table fields) are explicit, as are named-reference +//! resolution and legacy defaults. Other inputs use the full save-version domain. + +use super::super::cases::{Case, blocks, complex, geometry, properties}; +use super::super::collections; +use super::check; +use cadcraft_io::Version; + +// DWG references a table record by handle, not by an independently spelled name. These +// explicit expected spellings test resolution, not a blanket case-folding comparator. +fn canonical_reference(kind: &str, name: &str) { + for case in properties::mixed_case_references(kind) { + let mut expected = case.drawing.clone(); + let handles: Vec<_> = expected.model.iter().map(|e| e.handle).collect(); + for handle in handles { + expected.model.modify(handle, |e| match kind { + "layer" => e.common.layer = name.into(), + "linetype" => e.common.linetype = name.into(), + "style" => { + let cadcraft_doc::EntityKind::Text(t) = &mut e.kind else { panic!("expected TEXT") }; + t.style = name.into(); + } + _ => panic!("unknown reference family"), + }); + } + for version in Version::ALL { + super::check_version(&case.name, &case.drawing, &expected, version); + } + } +} + +#[test] +fn legacy_block_metadata() { + // DWG BLOCK_HEADER gains insertion units and explodability in R2007 (ODA specification). + for case in blocks::metadata() { + let mut expected = case.drawing.clone(); + let block = std::sync::Arc::make_mut(expected.blocks.get_mut("Z_Leaf").unwrap()); + block.explodable = true; + block.units = 0; + for version in [Version::R2000, Version::R2004] { + super::check_version(&case.name, &case.drawing, &expected, version); + } + } +} + +fn since_2007(cases: Vec) { + assert!(!cases.is_empty()); + for case in cases { + for version in Version::ALL.into_iter().filter(|v| *v >= Version::R2007) { + super::check_version(&case.name, &case.drawing, &case.drawing, version); + } + } +} + +#[test] +fn mixed_case_layers() { + canonical_reference("layer", "Survey_Ä"); +} +#[test] +fn mixed_case_linetypes() { + canonical_reference("linetype", "Dash_test"); +} +#[test] +fn mixed_case_styles() { + canonical_reference("style", "Notes"); +} +#[test] +fn layer_flags() { + check(properties::layer_flags()); +} +#[test] +fn layer_appearance() { + check(properties::layer_appearance()); +} +#[test] +#[ignore = "Confirmed DWG loss: named layer plot style Review becomes Normal"] +fn layer_plot_styles() { + check(properties::layer_plot_styles()); +} +#[test] +fn text_style_metrics() { + check(properties::text_style_metrics()); +} +#[test] +fn text_style_flags() { + check(properties::text_style_flags()); +} +#[test] +fn text_style_fonts() { + check(properties::text_style_fonts()); +} +#[test] +fn linetype_text() { + check(properties::complex_linetypes(false)); +} +#[test] +fn linetype_shapes() { + check(properties::complex_linetypes(true)); +} +#[test] +fn xdata_lists() { + check(properties::xdata_lists()); +} +#[test] +fn xdata_points() { + check(properties::xdata_points()); +} +#[test] +fn xdata_handles() { + check(properties::xdata_handles()); +} +#[test] +fn handles_and_order() { + check(properties::handles_and_order()); +} +#[test] +fn handles_near_integer_limits() { + check(properties::handles_near_integer_limits()); +} +#[test] +fn degenerate_lines() { + check(properties::degenerate_geometry()); +} +#[test] +fn layer_inheritance_overrides() { + check(properties::layer_inheritance_overrides()); +} +#[test] +fn alignment_style_interactions() { + check(properties::alignment_style_interactions()); +} +#[test] +fn nested_attributes() { + check(blocks::nested_attributes()); +} +#[test] +fn text_interactions() { + check(properties::text_interactions()); +} +#[test] +fn long_text() { + check(properties::long_text()); +} +#[test] +fn arcs() { + check(geometry::arcs()); +} +#[test] +fn ellipses() { + check(geometry::ellipses()); +} +#[test] +fn polyline_constant_widths() { + check(geometry::polylines(false)); +} +#[test] +fn polyline_variable_widths() { + check(geometry::polylines(true)); +} +#[test] +fn polylines_3d() { + check(geometry::polylines_3d()); +} +#[test] +fn splines() { + check(geometry::splines(false)); +} +#[test] +fn rational_splines() { + check(geometry::splines(true)); +} +#[test] +fn fit_splines() { + check(geometry::spline_fit(false)); +} +#[test] +#[ignore = "Confirmed DWG loss: periodic closed fit spline reopens as an open spline"] +fn closed_fit_splines() { + check(geometry::spline_fit(true)); +} +#[test] +fn points_and_rays() { + check(geometry::points_and_rays()); +} +#[test] +fn faces() { + check(geometry::faces()); +} +#[test] +fn mtext_placement() { + check(geometry::mtext_placement()); +} +#[test] +fn mtext_spacing() { + check(geometry::mtext_spacing()); +} +#[test] +fn mtext_contents() { + check(geometry::mtext_contents()); +} +#[test] +fn mtext_long() { + check(geometry::mtext_long()); +} +#[test] +#[ignore = "Confirmed DWG loss: MTEXT columns disappear"] +fn mtext_columns() { + since_2007(geometry::mtext_columns()); +} +#[test] +fn leaders() { + with_dimension_styles(geometry::leaders(false)); +} +#[test] +fn hatches() { + check(geometry::hatches()); +} +#[test] +fn tables() { + check(geometry::tables()); +} +#[test] +fn images() { + check(geometry::images()); +} +#[test] +fn wipeouts() { + check(geometry::wipeouts(true)); +} +#[test] +fn wipeout_implicit_closure() { + // The format closes the stored boundary explicitly; this is not an extra editable corner. + // Keep grip behavior separate from this serialization contract (#2256). + for (case, expected) in geometry::wipeouts(false).into_iter().zip(geometry::wipeouts(true)) { + for version in Version::ALL { + super::check_version(&case.name, &case.drawing, &expected.drawing, version); + } + } +} +#[test] +#[ignore = "Confirmed shared DXF loss: LEADER vertex Z coordinates become zero"] +fn leaders_3d() { + check(geometry::leaders(true)); +} +#[test] +#[ignore = "Confirmed shared DXF loss: ATTRIB constant flag becomes false"] +fn constant_attributes() { + check(blocks::attributes("constant")); +} +#[test] +#[ignore = "Confirmed DWG loss: a space following an MTEXT caret is consumed"] +fn mtext_carets() { + check(geometry::mtext_carets()); +} +#[test] +fn block_transformations() { + check(blocks::transformations()); +} +#[test] +fn block_arrays() { + check(blocks::arrays()); +} +#[test] +fn block_metadata() { + since_2007(blocks::metadata()); +} +#[test] +fn nested_blocks() { + check(blocks::nested(false)); +} +#[test] +fn cyclic_blocks() { + check(blocks::nested(true)); +} +#[test] +fn unreferenced_blocks() { + check(blocks::unreferenced()); +} +#[test] +fn attribute_flags() { + check(blocks::attributes("flags")); +} +#[test] +fn attribute_modes() { + check(blocks::attributes("modes")); +} +#[test] +fn attribute_lock() { + since_2007(blocks::attributes("lock")); +} +#[test] +fn multiline_attributes() { + for case in blocks::multiline_attributes() { + super::check_version(&case.name, &case.drawing, &case.drawing, Version::R2018); + } +} +#[test] +fn attribute_overrides() { + check(blocks::attributes("overrides")); +} +#[test] +fn helices() { + since_2007(complex::helices()); +} +#[test] +fn mlines() { + check(complex::mlines()); +} +#[test] +fn mleaders() { + since_2007(complex::mleaders()); +} +#[test] +fn regions() { + check(complex::regions()); +} +#[test] +fn tolerances() { + with_dimension_styles(complex::tolerances()); +} +#[test] +fn dimensions() { + super::dimensions::check(); +} + +fn collection(case: Case, verify: fn(&cadcraft_doc::Drawing, &cadcraft_doc::Drawing, &str)) { + for version in Version::ALL { + super::check_version_with(&case.name, &case.drawing, &case.drawing, version, verify); + } +} +#[test] +fn header_variables() { + collection(collections::headers(), collections::assert_headers); +} +#[test] +#[ignore = "Confirmed DWG loss: current layer CLAYER becomes 0"] +fn header_current_layer() { + collection(collections::named_header_reference("CLAYER"), collections::assert_headers); +} +#[test] +fn header_text_style() { + collection(collections::named_header_reference("TEXTSTYLE"), collections::assert_headers); +} +#[test] +fn unreferenced_tables() { + collection(collections::symbol_tables(), collections::assert_symbol_tables); +} +#[test] +fn foreign_dictionary_records() { + collection(collections::foreign_records(), collections::assert_foreign_records); +} +#[test] +#[ignore = "Confirmed DWG data loss: saving an unregistered entity succeeds but drops it instead of preserving it or returning an error"] +fn unknown_entities_are_preserved_or_explicitly_refused() { + for version in Version::ALL { + super::super::unknown::check("memory.dwg", version, false); + } +} +#[test] +fn views_and_ucs() { + collection(collections::views_and_ucs(), collections::assert_views_and_ucs); +} +#[test] +fn tiled_viewports() { + collection(collections::vports(), collections::assert_vports); +} +#[test] +fn groups() { + collection(collections::groups(), collections::assert_groups); +} +#[test] +fn layer_states() { + collection(collections::layer_states(), collections::assert_layer_states); +} +#[test] +fn layouts_and_paperspace() { + collection(collections::layouts(), collections::assert_layouts); +} + +fn with_dimension_styles(cases: Vec) { + // Fixed-length extension lines (DIMFXL) were added in 2007. Older DWG records have no + // slot for the inactive default length, and the bridge supplies zero on read. + for case in cases { + for version in Version::ALL { + let mut expected = case.drawing.clone(); + if version < Version::R2007 { + for style in &mut expected.dim_styles { + style.fixed_ext_length = 0.0; + } + } + super::check_version(&case.name, &case.drawing, &expected, version); + } + } +} diff --git a/crates/io/tests/it/roundtrip/dwg/mod.rs b/crates/io/tests/it/roundtrip/dwg/mod.rs new file mode 100644 index 000000000..6f9c90e1d --- /dev/null +++ b/crates/io/tests/it/roundtrip/dwg/mod.rs @@ -0,0 +1,75 @@ +//! Native DWG Drawing → bytes → Drawing preservation, using the same cases and assertions as +//! DXF. Every representable case runs at all six save versions and through two saves. R2000's +//! lack of true color/transparency is a format limit, tested separately with explicit expected +//! downgrades; it is not a normalization of modern output. TEXT's single elevation is also +//! checked separately for non-coplanar inputs. Extended cases also specify handle-based name +//! resolution, anonymous dimension-block names and legacy block/dimension-style limits +//! explicitly. Other differences fail. +//! Native-object conformance checks bypass one bridge direction, not the underlying codec. +//! +//! Run `cargo test -p cadcraft-io --test it roundtrip::dwg`; add `-- --ignored` to reproduce +//! pending defects. No DWG bytes are imported from another application or kept as fixtures. + +mod conformance; +mod dimensions; +mod entities; +mod extended; + +use cadcraft_color::Color; +use cadcraft_doc::{Drawing, EntityKind, Transparency}; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +use super::{cases, compare}; + +fn check(cases: Vec) { + for case in cases { + assert!( + !case.drawing.model.iter().any(|e| matches!(&e.kind, EntityKind::Text(t) if t.align_pt.is_some_and(|p| p.z != t.insert.z))), + "{}: non-coplanar TEXT belongs in the explicit single-elevation test", + case.name + ); + let mut tested = 0; + for version in Version::ALL { + if version == Version::R2000 && needs_color_or_transparency(&case.drawing) { + continue; + } + check_version(&case.name, &case.drawing, &case.drawing, version); + tested += 1; + } + assert!(tested > 0, "{}: the version domain must not exclude a whole case", case.name); + } +} + +fn needs_color_or_transparency(d: &Drawing) -> bool { + d.model.iter().any(|e| matches!(e.common.color, Color::True(_)) || e.common.transparency != Transparency::ByLayer) + || d.layers.iter().any(|l| matches!(l.color, Color::True(_)) || l.transparency != 0) +} + +fn check_version(case: &str, original: &Drawing, expected: &Drawing, version: Version) { + check_version_with(case, original, expected, version, |_, _, _| {}); +} + +fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, version: Version, extra: impl Fn(&Drawing, &Drawing, &str)) { + check_version_using(case, original, expected, version, |a, b, context| { + compare::model(a, b, context); + extra(a, b, context); + }); +} + +fn check_version_using(case: &str, original: &Drawing, expected: &Drawing, version: Version, verify: impl Fn(&Drawing, &Drawing, &str)) { + let options = SaveOptions { version: Some(version), binary: false }; + let mut current = original.clone(); + for pass in 1..=2 { + let context = format!("{case} · DWG {version} · pass={pass}"); + let bytes = write_with(¤t, "memory.dwg", &options).unwrap_or_else(|e| panic!("{context}: write: {e}")); + assert_eq!(cadcraft_dwg::version(&bytes).as_deref(), Some(version.code()), "{context}: wire version"); + let back = read(&bytes, "memory.dwg").unwrap_or_else(|e| panic!("{context}: read: {e}")); + assert!(back.read_notes.is_empty(), "{context}: read notes: {:?}", back.read_notes); + assert!(back.skipped_records.is_empty(), "{context}: skipped records: {:?}", back.skipped_records); + verify(expected, &back, &context); + if pass == 2 { + verify(¤t, &back, &format!("{context} · resave stability")); + } + current = back; + } +} diff --git a/crates/io/tests/it/roundtrip/dxf/attributes.rs b/crates/io/tests/it/roundtrip/dxf/attributes.rs new file mode 100644 index 000000000..0962f7bc9 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/attributes.rs @@ -0,0 +1,163 @@ +//! Check multiline ATTRIB values, embedded geometry and legacy placement independently. +//! Unchanged MTEXT rendering does not excuse corrupted attribute values or fallback TEXT +//! justification (#2255). Full field preservation remains in `extended::multiline_attributes`; +//! the legacy-placement test must reach its geometry assertion even while that check fails. +//! ODA's DWG specification §20.4.4 maps the R2018+ embedded object to DXF group 101. + +use super::super::cases::blocks; +use cadcraft_doc::{Attrib, Drawing, EntityKind, Space}; +use cadcraft_io::{SaveOptions, Version}; +use cadcraft_render::{DisplayList, Options, build}; + +const EDITED_VALUE: &str = "edited {value}\nthird line"; +const EDITED_CONTENTS: &str = "edited \\{value\\}\\Pthird line"; + +/// The fixture's primary attribute, not its unrelated single-line control or its ATTDEF. +fn primary(drawing: &Drawing) -> &Attrib { + let mut attributes = drawing + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Insert(i) => Some(i.attribs.iter()), + _ => None, + }) + .flatten() + .filter(|a| a.tag == "ID"); + let attribute = attributes.next().expect("primary ATTRIB must survive"); + assert!(attributes.next().is_none(), "primary ATTRIB must not be duplicated"); + attribute +} + +fn edit_primary(drawing: &mut Drawing, edit: impl Fn(&mut Attrib)) { + let handles: Vec<_> = drawing.model.iter().map(|e| e.handle).collect(); + let mut changed = 0; + for handle in handles { + drawing.model.modify(handle, |e| { + if let EntityKind::Insert(i) = &mut e.kind { + for a in i.attribs.iter_mut().filter(|a| a.tag == "ID") { + edit(a); + changed += 1; + } + } + }); + } + assert_eq!(changed, 1, "edit exactly the primary ATTRIB"); +} + +fn reopen(drawing: &Drawing, version: Version, binary: bool, context: &str) -> Drawing { + let options = SaveOptions { version: Some(version), binary }; + let bytes = cadcraft_io::write_with(drawing, "attributes.dxf", &options).unwrap_or_else(|e| panic!("{context}: write: {e}")); + assert_eq!(cadcraft_dxf::is_binary(&bytes), binary, "{context}: encoding"); + let back = cadcraft_io::read(&bytes, "attributes.dxf").unwrap_or_else(|e| panic!("{context}: read: {e}")); + assert_eq!(cadcraft_io::save_version(&back), version, "{context}: version"); + assert!(back.read_notes.is_empty(), "{context}: {:?}", back.read_notes); + assert!(back.skipped_records.is_empty(), "{context}: {:?}", back.skipped_records); + back +} + +fn geometry(drawing: &Drawing) -> DisplayList { + build(drawing, &Space::Model, &Options::default()) +} + +fn same_geometry(expected: &DisplayList, actual: &DisplayList, context: &str) { + assert!(!expected.prims.is_empty(), "{context}: nonempty fixture"); + assert_eq!(expected.prims.len(), actual.prims.len(), "{context}: primitive count"); + for (a, b) in expected.prims.iter().zip(&actual.prims) { + assert_eq!(a.kind, b.kind, "{context}: primitive kind"); + assert_eq!(expected.points(a), actual.points(b), "{context}: world-space geometry"); + } +} + +/// Check saved data, not only the effective text drawn by `multiline_text()`. That method can +/// hide a corrupt value/read_as pair or replace stale embedded contents from the plain value. +fn saved_text(drawing: &Drawing, value: &str, contents: &str, context: &str) { + let a = primary(drawing); + assert_eq!(a.text.value, value, "{context}: attribute value"); + let m = a.multiline.as_ref().expect("embedded MTEXT must survive"); + assert_eq!(m.read_as, value, "{context}: read_as"); + assert_eq!(m.mtext.contents, contents, "{context}: raw embedded contents"); +} + +#[test] +fn multiline_geometry_and_value_edits_survive_two_saves() { + for case in blocks::multiline_attributes() { + let expected = geometry(&case.drawing); + let mut edited = case.drawing.clone(); + edit_primary(&mut edited, |a| a.text.value = EDITED_VALUE.into()); + let edited_expected = geometry(&edited); + assert_ne!(expected.verts, edited_expected.verts, "value edit must actually change the drawn text"); + for binary in [false, true] { + let mut current = case.drawing.clone(); + for pass in 1..=2 { + let context = format!("{} · R2018 · binary={binary} · pass={pass}", case.name); + current = reopen(¤t, Version::R2018, binary, &context); + saved_text(¤t, "first\nsecond", "first\\Psecond", &context); + same_geometry(&expected, &geometry(¤t), &context); + let mut edited = current.clone(); + edit_primary(&mut edited, |a| a.text.value = EDITED_VALUE.into()); + same_geometry(&edited_expected, &geometry(&edited), &format!("{context} · edit after reopening")); + let context = format!("{context} · save after editing"); + let back = reopen(&edited, Version::R2018, binary, &context); + saved_text(&back, EDITED_VALUE, EDITED_CONTENTS, &context); + same_geometry(&edited_expected, &geometry(&back), &context); + } + } + } +} + +#[test] +fn saved_text_checks_reject_corruption_hidden_by_rendering() { + let mut source = blocks::multiline_attributes().remove(0).drawing; + edit_primary(&mut source, |a| a.text.value = EDITED_VALUE.into()); + let back = reopen(&source, Version::R2018, true, "mutation control"); + saved_text(&back, EDITED_VALUE, EDITED_CONTENTS, "mutation control"); + for field in ["value", "read_as", "contents", "value-and-read_as"] { + let mut corrupt = back.clone(); + edit_primary(&mut corrupt, |a| { + let m = a.multiline.as_mut().unwrap(); + match field { + "value" => a.text.value = "CORRUPTED VALUE".into(), + "read_as" => m.read_as = "CORRUPTED VALUE".into(), + "contents" => m.mtext.contents = "CORRUPTED CONTENTS".into(), + "value-and-read_as" => { + a.text.value = "CORRUPTED VALUE".into(); + m.read_as.clone_from(&a.text.value); + } + _ => unreachable!(), + } + }); + if field == "value-and-read_as" { + same_geometry(&geometry(&back), &geometry(&corrupt), "corruption invisible to geometry"); + } + assert!(std::panic::catch_unwind(|| saved_text(&corrupt, EDITED_VALUE, EDITED_CONTENTS, field)).is_err(), "must reject {field}"); + } +} + +#[test] +#[ignore = "Confirmed DXF placement loss (#2255): R2018 save changes subsequent legacy ATTRIB placement; existing reader fix #1942"] +fn legacy_placement_is_independent_of_an_intermediate_modern_save() { + for case in blocks::multiline_attributes() { + for version in [Version::R2000, Version::R2004] { + for binary in [false, true] { + let legacy_context = format!("{} · legacy={version} · binary={binary}", case.name); + let direct = reopen(&case.drawing, version, binary, &legacy_context); + let a = primary(&direct); + assert!(a.multiline.is_none(), "{legacy_context}: single-line fallback required"); + assert_eq!(a.text.value, "first second", "{legacy_context}: fallback value"); + let expected = geometry(&direct); + for modern_binary in [false, true] { + let mut current = case.drawing.clone(); + for pass in 1..=2 { + let context = format!("{legacy_context} · intermediate=R2018 · binary={modern_binary} · pass={pass}"); + current = reopen(¤t, Version::R2018, modern_binary, &context); + let indirect = reopen(¤t, version, binary, &context); + let a = primary(&indirect); + assert!(a.multiline.is_none(), "{context}: single-line fallback required"); + assert_eq!(a.text.value, "first second", "{context}: fallback value"); + same_geometry(&expected, &geometry(&indirect), &context); + } + } + } + } + } +} diff --git a/crates/io/tests/it/roundtrip/dxf/common.rs b/crates/io/tests/it/roundtrip/dxf/common.rs new file mode 100644 index 000000000..6e40977c9 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/common.rs @@ -0,0 +1,197 @@ +//! Independent input and output contracts for common LINE/CIRCLE/TEXT properties. Read fixtures +//! are handwritten DXF, never writer output; write expectations are literal groups, never a +//! reread Drawing. Absence, explicit zero and inheritance are distinct. Pending tests localize +//! the existing extrusion and ByBlock plot-style losses without accepting them as correct. +//! References: https://ezdxf.readthedocs.io/en/stable/dxfentities/dxfgfx.html +//! https://ezdxf.readthedocs.io/en/stable/concepts/true_color.html +//! https://ezdxf.readthedocs.io/en/stable/concepts/transparency.html + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::{Common, Drawing, EntityKind, Layer, Lineweight, Transparency}; +use cadcraft_dxf::{Tag, records, sections}; +use cadcraft_geom::Vec3; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +fn fixture(properties: &str) -> Drawing { + let records = [ + ("LINE", "AcDbLine", "10\n1\n20\n2\n30\n3\n11\n4\n21\n5\n31\n6\n"), + ("CIRCLE", "AcDbCircle", "10\n7\n20\n8\n30\n9\n40\n2.5\n"), + ("TEXT", "AcDbText", "10\n3\n20\n4\n40\n2.5\n1\nfixture\n"), + ]; + let mut bytes = String::from("0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"); + for (kind, subclass, geometry) in records { + bytes.push_str(&format!("0\n{kind}\n100\nAcDbEntity\n{properties}100\n{subclass}\n{geometry}")); + } + bytes.push_str("0\nENDSEC\n0\nEOF\n"); + read(bytes.as_bytes(), "fixture.dxf").unwrap() +} + +fn assert_read(properties: &str, expected: &Common) { + let drawing = fixture(properties); + assert_eq!(drawing.model.len(), 3); + assert!(drawing.skipped_records.is_empty()); + for entity in drawing.model.iter() { + assert_eq!(&entity.common, expected, "{} with groups {properties:?}", entity.kind.type_name()); + } +} + +fn output(common: &Common, version: Version, binary: bool) -> Vec<(String, Vec)> { + let mut drawing = super::conformance::model(); + if drawing.layer(&common.layer).is_none() { + drawing.layers.push(Layer::new(&common.layer)); + } + let handles: Vec<_> = drawing.model.iter().map(|e| e.handle).collect(); + for handle in handles { + drawing.model.modify(handle, |e| e.common = common.clone()); + } + let bytes = write_with(&drawing, "memory.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + let tags = cadcraft_dxf::parse(&bytes).unwrap(); + let sections = sections(&tags); + let entities = records(§ions.iter().find(|s| s.name == "ENTITIES").unwrap().tags); + assert_eq!(entities.iter().map(|(kind, _)| kind.as_str()).collect::>(), ["LINE", "CIRCLE", "TEXT"]); + entities +} + +fn assert_write(common: Common, present: &[Tag], absent: &[i32]) { + for version in Version::ALL { + for binary in [false, true] { + for (kind, groups) in output(&common, version, binary) { + let context = format!("{version} binary={binary} {kind} {common:?}"); + for tag in present { + assert_eq!(groups.iter().filter(|t| t.code == tag.code).collect::>(), [tag], "{context}: group {}", tag.code); + } + for code in absent { + assert!(!groups.iter().any(|t| t.code == *code), "{context}: group {code} should be omitted"); + } + } + } + } +} + +#[test] +fn missing_optional_groups_and_explicit_defaults() { + assert_read("", &Common::default()); + assert_read("8\n0\n6\nByLayer\n62\n256\n370\n-1\n48\n1\n60\n0\n39\n0\n210\n0\n220\n0\n230\n1\n", &Common::default()); + // Omission is this writer's convention, not a requirement that other DXF writers omit them. + assert_write(Common::default(), &[Tag::s(8, "0")], &[6, 62, 370, 48, 60, 39, 420, 440, 210, 220, 230]); +} + +#[test] +fn layer_linetype_scale_visibility_and_thickness_have_independent_groups() { + let common = + Common { layer: "Fixture".into(), linetype: "Continuous".into(), ltscale: 2.75, visible: false, thickness: -1.25, ..Common::default() }; + assert_read("8\nFixture\n6\nContinuous\n48\n2.75\n60\n1\n39\n-1.25\n", &common); + assert_write(common, &[Tag::s(8, "Fixture"), Tag::s(6, "Continuous"), Tag::f(48, 2.75), Tag::i(60, 1), Tag::f(39, -1.25)], &[62, 420, 440]); + assert_read("6\nByBlock\n", &Common { linetype: "ByBlock".into(), ..Common::default() }); + assert_write(Common { linetype: "ByBlock".into(), ..Common::default() }, &[Tag::s(6, "ByBlock")], &[]); +} + +#[test] +fn lineweight_distinguishes_logical_modes_and_explicit_zero() { + for (value, lineweight) in [ + (-1, Lineweight::ByLayer), + (-2, Lineweight::ByBlock), + (-3, Lineweight::Default), + (0, Lineweight::Mm100(0)), + (53, Lineweight::Mm100(53)), + (211, Lineweight::Mm100(211)), + ] { + let common = Common { lineweight, ..Common::default() }; + assert_read(&format!("370\n{value}\n"), &common); + if value == -1 { + assert_write(common, &[], &[370]); + } else { + assert_write(common, &[Tag::i(370, value)], &[]); + } + } +} + +#[test] +fn aci_color_distinguishes_inheritance_and_explicit_color() { + for (value, color) in + [(256, Color::ByLayer), (0, Color::ByBlock)].into_iter().chain((1..=255).map(|index| (i64::from(index), Color::Index(index)))) + { + let common = Common { color, ..Common::default() }; + assert_read(&format!("62\n{value}\n"), &common); + if value == 256 { + assert_write(common, &[], &[62, 420]); + } else { + assert_write(common, &[Tag::i(62, value)], &[420]); + } + } +} + +#[test] +fn true_color_overrides_aci_in_either_tag_order_including_black() { + // 0x12_34_56 = 1,193,046. The black value 0 must not be mistaken for an absent group. + for (value, rgb) in [(1_193_046, Rgb(0x12, 0x34, 0x56)), (0, Rgb(0, 0, 0))] { + let common = Common { color: Color::True(rgb), ..Common::default() }; + for aci in [0, 1, 256] { + assert_read(&format!("62\n{aci}\n420\n{value}\n"), &common); + assert_read(&format!("420\n{value}\n62\n{aci}\n"), &common); + } + assert_write(common, &[Tag::i(420, value)], &[]); + } +} + +#[test] +fn transparency_distinguishes_inheritance_and_explicit_opacity() { + assert_read("", &Common::default()); + assert_write(Common::default(), &[], &[440]); + // High byte: 01 = ByBlock, 02 = explicit alpha. Low byte: opacity, not transparency. + // Independent integer oracle: floor(255 * (1 - p/100)) = 255 - ceil(255*p/100). + // No production alpha conversion is used. Check every supported integer percentage. + for (raw, transparency) in std::iter::once((0x0100_0000, Transparency::ByBlock)).chain((0..=90).map(|percent| { + let opacity = 255 - (255 * i64::from(percent) + 99) / 100; + (0x0200_0000 + opacity, Transparency::Percent(percent)) + })) { + let common = Common { transparency, ..Common::default() }; + assert_read(&format!("440\n{raw}\n"), &common); + assert_write(common, &[Tag::i(440, raw)], &[]); + } + // Another writer may round up instead; both neighboring alpha values map to the same + // integer percentage. This is a read expectation, not normalization of writer output. + assert_read("440\n33554560\n", &Common { transparency: Transparency::Percent(50), ..Common::default() }); + assert_read("440\n33554458\n", &Common { transparency: Transparency::Percent(90), ..Common::default() }); +} + +#[test] +fn reads_line_extrusion_without_changing_world_space_endpoints() { + for (groups, expected) in [("210\n0\n220\n0\n230\n-1\n", Vec3::new(0.0, 0.0, -1.0)), ("220\n1\n230\n0\n", Vec3::new(0.0, 1.0, 0.0))] { + let drawing = fixture(groups); + let line = drawing.model.iter().next().unwrap(); + assert_eq!(line.common.extrusion, expected); + let EntityKind::Line(geometry) = &line.kind else { panic!("expected LINE") }; + assert_eq!(geometry.a, Vec3::new(1.0, 2.0, 3.0)); + assert_eq!(geometry.b, Vec3::new(4.0, 5.0, 6.0)); + } +} + +#[test] +#[ignore = "Known writer loss: a non-default extrusion is omitted; the independent LINE read test passes"] +fn writes_nondefault_extrusion_groups() { + // X/Y may be omitted at zero, but Z=-1 must not disappear into the default Z=1. + assert_write(Common { extrusion: Vec3::new(0.0, 0.0, -1.0), ..Common::default() }, &[Tag::f(230, -1.0)], &[]); +} + +#[test] +#[ignore = "Known writer loss: ByLayer and ByBlock plot styles produce identical files"] +fn writer_must_distinguish_bylayer_from_byblock_plot_style() { + // The available group-380 HEADER enum is not sufficient evidence for a universal entity + // encoding; do not prescribe an unverified tag here. Identical complete outputs prove the + // loss is already in the writer, independently of any reader or representation choice. + let by_layer = super::conformance::model(); + let mut by_block = by_layer.clone(); + let handles: Vec<_> = by_block.model.iter().map(|e| e.handle).collect(); + for handle in handles { + by_block.model.modify(handle, |e| e.common.plot_style = "ByBlock".into()); + } + for version in Version::ALL { + for binary in [false, true] { + let options = SaveOptions { version: Some(version), binary }; + let a = write_with(&by_layer, "memory.dxf", &options).unwrap(); + let b = write_with(&by_block, "memory.dxf", &options).unwrap(); + assert!(a != b, "{version} binary={binary}: plot style is not encoded anywhere in the file"); + } + } +} diff --git a/crates/io/tests/it/roundtrip/dxf/conformance.rs b/crates/io/tests/it/roundtrip/dxf/conformance.rs new file mode 100644 index 000000000..3f036be2c --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/conformance.rs @@ -0,0 +1,185 @@ +//! Independent synthetic entity records prevent matching reader/writer mistakes from passing +//! the round-trip suite. Only public DXF group meanings are used; no reference-app files or assets. +//! Entity semantics: https://ezdxf.readthedocs.io/en/stable/dxfentities/text.html +//! and https://ezdxf.readthedocs.io/en/stable/dxfentities/line.html + +use cadcraft_color::Color; +use cadcraft_doc::{Circle, Common, Drawing, Entity, EntityKind, HAlign, Handle, Line, Space, Text, VAlign}; +use cadcraft_dxf::{Tag, records, sections}; +use cadcraft_geom::Vec3; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +use super::compare; + +const ENTITIES: &[u8] = b"0\nSECTION\n2\nENTITIES\n\ +0\nLINE\n5\n100\n8\n0\n62\n3\n60\n1\n39\n-2.5\n10\n1.25\n20\n-2.5\n30\n3.75\n11\n-4.5\n21\n5.25\n31\n-6.75\n\ +0\nCIRCLE\n5\n101\n8\n0\n10\n7.25\n20\n-8.5\n30\n9.75\n40\n2.125\n\ +0\nTEXT\n5\n102\n8\n0\n10\n-3.25\n20\n4.5\n30\n1.75\n40\n2.5\n1\nfixture text\n50\n30\n41\n1.25\n51\n-15\n7\nStandard\n\ +0\nENDSEC\n0\nEOF\n"; + +pub(super) fn model() -> Drawing { + let mut d = Drawing::new_metric(); + d.add( + &Space::Model, + Common { color: Color::Index(3), visible: false, thickness: -2.5, ..Common::default() }, + EntityKind::Line(Line { a: Vec3::new(1.25, -2.5, 3.75), b: Vec3::new(-4.5, 5.25, -6.75) }), + ) + .unwrap(); + d.add(&Space::Model, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(7.25, -8.5, 9.75), radius: 2.125 })).unwrap(); + d.add( + &Space::Model, + Common::default(), + EntityKind::Text(Text { + insert: Vec3::new(-3.25, 4.5, 1.75), + align_pt: None, + height: 2.5, + value: "fixture text".into(), + rotation: 30_f64.to_radians(), + width_factor: 1.25, + oblique: -15_f64.to_radians(), + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + }), + ) + .unwrap(); + d +} + +#[test] +fn reads_independent_line_circle_and_text_records() { + let back = read(ENTITIES, "fixture.dxf").unwrap(); + compare::model(&model(), &back, "independent entity fixture"); +} + +#[test] +fn writes_standard_entity_groups_not_just_self_readable_data() { + let expected = [ + ( + "LINE", + vec![ + Tag::s(5, "100"), + Tag::i(62, 3), + Tag::i(60, 1), + Tag::f(39, -2.5), + Tag::f(10, 1.25), + Tag::f(20, -2.5), + Tag::f(30, 3.75), + Tag::f(11, -4.5), + Tag::f(21, 5.25), + Tag::f(31, -6.75), + ], + ), + ("CIRCLE", vec![Tag::s(5, "101"), Tag::f(10, 7.25), Tag::f(20, -8.5), Tag::f(30, 9.75), Tag::f(40, 2.125)]), + ( + "TEXT", + vec![ + Tag::s(5, "102"), + Tag::f(10, -3.25), + Tag::f(20, 4.5), + Tag::f(30, 1.75), + Tag::f(40, 2.5), + Tag::s(1, "fixture text"), + Tag::f(41, 1.25), + Tag::s(7, "Standard"), + ], + ), + ]; + for version in Version::ALL { + for binary in [false, true] { + let bytes = write_with(&model(), "memory.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + let tags = cadcraft_dxf::parse(&bytes).unwrap(); + let sections = sections(&tags); + let entities = records(§ions.iter().find(|s| s.name == "ENTITIES").unwrap().tags); + assert_eq!(entities.len(), expected.len()); + for ((kind, groups), (expected_kind, expected_groups)) in entities.iter().zip(&expected) { + let context = format!("{version} binary={binary} {expected_kind}"); + assert_eq!(kind, expected_kind, "{context}"); + for tag in expected_groups { + let values: Vec<_> = groups.iter().filter(|t| t.code == tag.code).collect(); + assert_eq!(values, [tag], "{context}: group {}", tag.code); + } + if kind == "TEXT" { + for (code, degrees) in [(50, 30.0), (51, -15.0)] { + let values: Vec<_> = groups.iter().filter(|t| t.code == code).collect(); + assert_eq!(values.len(), 1, "{context}: group {code}"); + assert!((values[0].f64() - degrees).abs() < 1e-13, "{context}: group {code} is in degrees"); + } + } + } + } + } +} + +#[test] +fn reads_text_alignment_codes_independently_of_the_writer() { + let horizontal = [(0, HAlign::Left), (1, HAlign::Center), (2, HAlign::Right), (3, HAlign::Aligned), (4, HAlign::Middle), (5, HAlign::Fit)]; + let vertical = [(0, VAlign::Baseline), (1, VAlign::Bottom), (2, VAlign::Middle), (3, VAlign::Top)]; + for (hcode, halign) in horizontal { + for (vcode, valign) in vertical { + if hcode >= 3 && vcode != 0 { + continue; + } + let bytes = format!( + "0\nSECTION\n2\nENTITIES\n0\nTEXT\n10\n3\n20\n4\n30\n5\n40\n2.5\n1\nA\n72\n{hcode}\n73\n{vcode}\n11\n6\n21\n7\n31\n8\n0\nENDSEC\n0\nEOF\n" + ); + let back = read(bytes.as_bytes(), "fixture.dxf").unwrap(); + let EntityKind::Text(text) = &back.model.iter().next().unwrap().kind else { panic!("expected TEXT") }; + assert_eq!((text.halign, text.valign), (halign, valign), "72={hcode}, 73={vcode}"); + assert_eq!(text.insert, Vec3::new(3.0, 4.0, 5.0)); + let expected_point = if hcode == 0 && vcode == 0 { None } else { Some(Vec3::new(6.0, 7.0, 8.0)) }; + assert_eq!(text.align_pt, expected_point, "72={hcode}, 73={vcode}"); + } + } +} + +// Odd values above 2^53, above i64::MAX and near u64::MAX expose floating-point coercion, +// signed conversion and truncation. Literal hex and numeric values are independent expectations. +const LARGE_HANDLES: [(u64, &str); 3] = + [(9_007_199_254_740_993, "20000000000001"), (9_223_372_036_854_775_809, "8000000000000001"), (18_446_744_073_709_486_081, "FFFFFFFFFFFF0001")]; + +#[test] +fn reads_large_literal_hex_handles_without_numeric_coercion() { + let mut fixture = String::from("0\nSECTION\n2\nENTITIES\n"); + for (_, hex) in LARGE_HANDLES { + fixture.push_str(&format!("0\nLINE\n5\n{hex}\n8\n0\n10\n0\n20\n0\n11\n1\n21\n2\n")); + } + fixture.push_str("0\nENDSEC\n0\nEOF\n"); + let back = read(fixture.as_bytes(), "fixture.dxf").unwrap(); + assert!(back.read_notes.is_empty()); + assert!(back.skipped_records.is_empty()); + assert_eq!(back.model.iter().map(|e| e.handle.0).collect::>(), LARGE_HANDLES.map(|(numeric, _)| numeric)); +} + +#[test] +fn writes_large_handles_as_exact_hex_groups() { + let mut drawing = Drawing::new_metric(); + for (numeric, _) in LARGE_HANDLES { + drawing.model.push(Entity::new(Handle(numeric), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 2.0, 0.0) }))); + } + drawing.handseed = 0xffff_ffff_ffff_1000; + for version in Version::ALL { + for binary in [false, true] { + let bytes = write_with(&drawing, "memory.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + let tags = cadcraft_dxf::parse(&bytes).unwrap(); + let sections = sections(&tags); + let entities = records(§ions.iter().find(|s| s.name == "ENTITIES").unwrap().tags); + assert_eq!(entities.len(), LARGE_HANDLES.len()); + for ((kind, groups), (_, hex)) in entities.iter().zip(LARGE_HANDLES) { + assert_eq!(kind, "LINE"); + assert_eq!(groups.iter().filter(|t| t.code == 5).collect::>(), [&Tag::s(5, hex)], "{version} binary={binary} handle={hex}"); + } + } + } +} + +#[test] +fn left_baseline_text_ignores_the_unused_second_alignment_point() { + // DXF TEXT groups 11/21/31 are meaningful only when 72 or 73 is nonzero. The model + // intentionally represents the unused point as None, not Some(Vec3::ZERO). + let bytes = b"0\nSECTION\n2\nENTITIES\n0\nTEXT\n10\n3\n20\n4\n40\n2.5\n1\nA\n72\n0\n73\n0\n11\n0\n21\n0\n31\n0\n0\nENDSEC\n0\nEOF\n"; + let back = read(bytes, "fixture.dxf").unwrap(); + let EntityKind::Text(text) = &back.model.iter().next().unwrap().kind else { panic!("expected TEXT") }; + assert_eq!(text.align_pt, None); + assert_eq!(text.insert, Vec3::new(3.0, 4.0, 0.0)); +} diff --git a/crates/io/tests/it/roundtrip/dxf/entities.rs b/crates/io/tests/it/roundtrip/dxf/entities.rs new file mode 100644 index 000000000..5816d5017 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/entities.rs @@ -0,0 +1,121 @@ +//! DXF runs every shared input family in both encodings and all writable versions. Keep known +//! failures isolated from other property sweeps; the comparison contract is never weakened. + +use super::super::cases; + +fn check(cases: Vec) { + for case in cases { + super::check(&case.name, &case.drawing); + } +} + +#[test] +fn empty_model_and_defaults() { + check(cases::empty_and_defaults()); +} +#[test] +fn line_endpoints_and_circle_centers_radii() { + check(cases::geometry()); +} +#[test] +fn layers() { + check(cases::layers()); +} +#[test] +fn layer_inherited_linetypes() { + check(cases::layer_linetypes()); +} +#[test] +fn colors() { + check(cases::colors()); +} +#[test] +fn linetypes() { + check(cases::linetypes()); +} +#[test] +fn lineweights() { + check(cases::lineweights()); +} +#[test] +fn linetype_scales() { + check(cases::linetype_scales()); +} +#[test] +fn transparencies() { + check(cases::transparencies()); +} +#[test] +fn visibility() { + check(cases::visibility()); +} +#[test] +fn thicknesses() { + check(cases::thicknesses()); +} +#[test] +fn plot_styles() { + check(cases::plot_styles()); +} +#[test] +fn foreign_xdata() { + check(cases::foreign_xdata()); +} +#[test] +fn common_property_interactions() { + check(cases::common_interactions("ByLayer")); + check(cases::common_interactions("Review")); +} +#[test] +fn text_values() { + check(cases::text_values()); +} +#[test] +fn text_literal_escapes() { + check(cases::text_literal_escapes()); +} +#[test] +fn text_heights() { + check(cases::text_heights()); +} +#[test] +fn text_rotations() { + check(cases::text_rotations()); +} +#[test] +fn text_widths() { + check(cases::text_widths()); +} +#[test] +fn text_obliques() { + check(cases::text_obliques()); +} +#[test] +fn text_styles() { + check(cases::text_styles()); +} +#[test] +fn annotation_scales() { + check(cases::annotation_scales()); +} +#[test] +fn text_alignment_with_points() { + check(cases::coplanar_text_alignment()); + check(cases::noncoplanar_text_alignment()); +} +#[test] +fn text_alignment_without_points() { + check(cases::text_alignment(false)); +} + +#[test] +#[ignore = "Known writer loss: ByBlock plot style becomes ByLayer on the first R2000 ASCII save"] +fn plot_style_byblock_is_preserved() { + check(cases::byblock_plot_style()); +} + +#[test] +#[ignore = "Known writer loss: groups 210/220/230 are omitted; a LINE's normal becomes (0,0,1)"] +fn nondefault_extrusion_is_preserved() { + check(cases::extrusions()); +} diff --git a/crates/io/tests/it/roundtrip/dxf/extended.rs b/crates/io/tests/it/roundtrip/dxf/extended.rs new file mode 100644 index 000000000..4e8415337 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/extended.rs @@ -0,0 +1,334 @@ +//! Extended DXF property families. Pending losses stay separate from passing families; +//! version domains are explicit for Lock position, HELIX/MULTILEADER (2007) and the native +//! multiline-attribute representation (2018). + +use super::super::cases::{Case, blocks, complex, geometry, properties}; +use super::super::collections; +use cadcraft_io::Version; + +fn check(cases: Vec) { + assert!(!cases.is_empty()); + for case in cases { + super::check(&case.name, &case.drawing); + } +} +fn since_2007(cases: Vec) { + assert!(!cases.is_empty()); + for case in cases { + for version in Version::ALL.into_iter().filter(|v| *v >= Version::R2007) { + super::check_version(&case.name, &case.drawing, &case.drawing, version); + } + } +} + +#[test] +fn mixed_case_layers() { + check(properties::mixed_case_references("layer")); +} +#[test] +fn mixed_case_linetypes() { + check(properties::mixed_case_references("linetype")); +} +#[test] +fn mixed_case_styles() { + check(properties::mixed_case_references("style")); +} +#[test] +fn layer_flags() { + check(properties::layer_flags()); +} +#[test] +fn layer_appearance() { + check(properties::layer_appearance()); +} +#[test] +fn layer_plot_styles() { + check(properties::layer_plot_styles()); +} +#[test] +fn text_style_metrics() { + check(properties::text_style_metrics()); +} +#[test] +fn text_style_flags() { + check(properties::text_style_flags()); +} +#[test] +fn text_style_fonts() { + check(properties::text_style_fonts()); +} +#[test] +fn linetype_text() { + check(properties::complex_linetypes(false)); +} +#[test] +fn linetype_shapes() { + check(properties::complex_linetypes(true)); +} +#[test] +fn xdata_lists() { + check(properties::xdata_lists()); +} +#[test] +fn xdata_points() { + check(properties::xdata_points()); +} +#[test] +fn xdata_handles() { + check(properties::xdata_handles()); +} +#[test] +fn handles_and_order() { + check(properties::handles_and_order()); +} +#[test] +fn handles_near_integer_limits() { + check(properties::handles_near_integer_limits()); +} +#[test] +fn degenerate_lines() { + check(properties::degenerate_geometry()); +} +#[test] +fn layer_inheritance_overrides() { + check(properties::layer_inheritance_overrides()); +} +#[test] +fn alignment_style_interactions() { + check(properties::alignment_style_interactions()); +} +#[test] +fn nested_attributes() { + check(blocks::nested_attributes()); +} +#[test] +fn text_interactions() { + check(properties::text_interactions()); +} +#[test] +fn long_text() { + check(properties::long_text()); +} +#[test] +fn arcs() { + check(geometry::arcs()); +} +#[test] +fn ellipses() { + check(geometry::ellipses()); +} +#[test] +fn polyline_constant_widths() { + check(geometry::polylines(false)); +} +#[test] +fn polyline_variable_widths() { + check(geometry::polylines(true)); +} +#[test] +fn polylines_3d() { + check(geometry::polylines_3d()); +} +#[test] +fn splines() { + check(geometry::splines(false)); +} +#[test] +fn rational_splines() { + check(geometry::splines(true)); +} +#[test] +fn fit_splines() { + check(geometry::spline_fit(false)); + check(geometry::spline_fit(true)); +} +#[test] +fn points_and_rays() { + check(geometry::points_and_rays()); +} +#[test] +fn faces() { + check(geometry::faces()); +} +#[test] +fn mtext_placement() { + check(geometry::mtext_placement()); +} +#[test] +fn mtext_spacing() { + check(geometry::mtext_spacing()); +} +#[test] +fn mtext_contents() { + check(geometry::mtext_contents()); + check(geometry::mtext_carets()); +} +#[test] +fn mtext_long() { + check(geometry::mtext_long()); +} +#[test] +#[ignore = "Confirmed DXF loss: MTEXT column group 48 is also read as Common.ltscale"] +fn mtext_columns() { + check(geometry::mtext_columns()); +} +#[test] +fn leaders() { + check(geometry::leaders(false)); +} +#[test] +fn hatches() { + check(geometry::hatches()); +} +#[test] +fn tables() { + check(geometry::tables()); +} +#[test] +fn images() { + check(geometry::images()); +} +#[test] +fn wipeouts() { + check(geometry::wipeouts(true)); +} +#[test] +fn wipeout_implicit_closure() { + // The format closes the stored boundary explicitly; this is not an extra editable corner. + // Keep grip behavior separate from this serialization contract (#2256). + for (case, expected) in geometry::wipeouts(false).into_iter().zip(geometry::wipeouts(true)) { + for version in Version::ALL { + super::check_version(&case.name, &case.drawing, &expected.drawing, version); + } + } +} +#[test] +#[ignore = "Confirmed DXF loss: LEADER vertex Z coordinates become zero"] +fn leaders_3d() { + check(geometry::leaders(true)); +} +#[test] +#[ignore = "Confirmed DXF loss: ATTRIB constant flag becomes false"] +fn constant_attributes() { + check(blocks::attributes("constant")); +} +#[test] +fn block_transformations() { + check(blocks::transformations()); +} +#[test] +fn block_arrays() { + check(blocks::arrays()); +} +#[test] +fn block_metadata() { + check(blocks::metadata()); +} +#[test] +fn nested_blocks() { + check(blocks::nested(false)); +} +#[test] +fn cyclic_blocks() { + check(blocks::nested(true)); +} +#[test] +fn unreferenced_blocks() { + check(blocks::unreferenced()); +} +#[test] +fn attribute_flags() { + check(blocks::attributes("flags")); +} +#[test] +fn attribute_modes() { + check(blocks::attributes("modes")); +} +#[test] +fn attribute_lock() { + since_2007(blocks::attributes("lock")); +} +#[test] +#[ignore = "Confirmed DXF read loss (#2255): multiline header changes Left to Center and synthesizes align_pt; existing fix #1942"] +fn multiline_attributes() { + for case in blocks::multiline_attributes() { + super::check_version(&case.name, &case.drawing, &case.drawing, Version::R2018); + } +} +#[test] +fn attribute_overrides() { + check(blocks::attributes("overrides")); +} +#[test] +fn helices() { + since_2007(complex::helices()); +} +#[test] +fn mlines() { + check(complex::mlines()); +} +#[test] +fn mleaders() { + since_2007(complex::mleaders()); +} +#[test] +fn regions() { + check(complex::regions()); +} +#[test] +fn tolerances() { + check(complex::tolerances()); +} +#[test] +fn dimensions() { + check(complex::dimensions()); +} + +fn collection(case: Case, verify: fn(&cadcraft_doc::Drawing, &cadcraft_doc::Drawing, &str)) { + for version in Version::ALL { + super::check_version_with(&case.name, &case.drawing, &case.drawing, version, verify); + } +} +#[test] +fn header_variables() { + collection(collections::headers(), collections::assert_headers); + for key in ["CLAYER", "TEXTSTYLE"] { + collection(collections::named_header_reference(key), collections::assert_headers); + } +} +#[test] +fn unreferenced_tables() { + collection(collections::symbol_tables(), collections::assert_symbol_tables); +} +#[test] +fn foreign_dictionary_records() { + collection(collections::foreign_records(), collections::assert_foreign_records); +} +#[test] +fn unknown_entity_payload_and_references() { + for version in Version::ALL { + for binary in [false, true] { + super::super::unknown::check("memory.dxf", version, binary); + } + } +} +#[test] +fn views_and_ucs() { + collection(collections::views_and_ucs(), collections::assert_views_and_ucs); +} +#[test] +fn tiled_viewports() { + collection(collections::vports(), collections::assert_vports); +} +#[test] +fn groups() { + collection(collections::groups(), collections::assert_groups); +} +#[test] +fn layer_states() { + collection(collections::layer_states(), collections::assert_layer_states); +} +#[test] +fn layouts_and_paperspace() { + collection(collections::layouts(), collections::assert_layouts); +} diff --git a/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs new file mode 100644 index 000000000..b447638eb --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/geometry_groups.rs @@ -0,0 +1,138 @@ +//! Independent synthetic DXF records for the extended geometry slice. Literal group streams +//! specify both reader input and writer expectations; neither side obtains its oracle from +//! the other. Group meanings: https://ezdxf.readthedocs.io/en/stable/dxfentities/index.html + +use super::super::{cases, compare}; +use cadcraft_doc::{Arc, Common, Ellipse, EntityKind, LwPolyline, MText, Point, RayLine}; +use cadcraft_dxf::{Tag, records, sections}; +use cadcraft_geom::{PolyVertex, Vec2, Vec3}; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +struct Fixture { + wire_type: &'static str, + kind: EntityKind, + groups: &'static str, + output: Vec, +} + +fn fixtures() -> Vec { + vec![ + Fixture { + wire_type: "ARC", + kind: EntityKind::Arc(Arc { center: Vec3::new(1.25, -2.5, 3.75), radius: 2.5, start: 0.0, end: std::f64::consts::FRAC_PI_2 }), + groups: "10\n1.25\n20\n-2.5\n30\n3.75\n40\n2.5\n50\n0\n51\n90\n", + output: vec![Tag::f(10, 1.25), Tag::f(20, -2.5), Tag::f(30, 3.75), Tag::f(40, 2.5), Tag::f(50, 0.0), Tag::f(51, 90.0)], + }, + Fixture { + wire_type: "ELLIPSE", + kind: EntityKind::Ellipse(Ellipse { + center: Vec3::new(1.0, 2.0, 3.0), + major: Vec3::new(3.0, 4.0, 0.0), + ratio: 0.5, + start: 0.0, + end: std::f64::consts::TAU, + }), + groups: "10\n1\n20\n2\n30\n3\n11\n3\n21\n4\n31\n0\n40\n0.5\n41\n0\n42\n6.283185307179586\n", + output: vec![Tag::f(11, 3.0), Tag::f(21, 4.0), Tag::f(31, 0.0), Tag::f(40, 0.5), Tag::f(41, 0.0), Tag::f(42, std::f64::consts::TAU)], + }, + Fixture { + wire_type: "LWPOLYLINE", + kind: EntityKind::LwPolyline(LwPolyline { + vertices: vec![ + PolyVertex { p: Vec2::new(1.25, -2.5), bulge: 0.5, start_width: 0.125, end_width: 0.75 }, + PolyVertex::new(Vec2::new(5.0, 3.0)), + ], + closed: true, + plinegen: true, + const_width: 0.0, + elevation: -3.75, + }), + groups: "90\n2\n70\n129\n38\n-3.75\n10\n1.25\n20\n-2.5\n40\n0.125\n41\n0.75\n42\n0.5\n10\n5\n20\n3\n", + output: vec![ + Tag::i(90, 2), + Tag::i(70, 129), + Tag::f(38, -3.75), + Tag::f(10, 1.25), + Tag::f(10, 5.0), + Tag::f(20, -2.5), + Tag::f(20, 3.0), + Tag::f(40, 0.125), + Tag::f(41, 0.75), + Tag::f(42, 0.5), + ], + }, + Fixture { + wire_type: "MTEXT", + kind: EntityKind::MText(MText { + insert: Vec3::new(1.25, -2.5, 3.75), + height: 2.25, + width: 12.5, + attach: 5, + rotation: std::f64::consts::FRAC_PI_2, + style: "Standard".into(), + contents: "first\\Psecond".into(), + line_spacing: 1.75, + line_spacing_exact: true, + columns: None, + }), + groups: "10\n1.25\n20\n-2.5\n30\n3.75\n40\n2.25\n41\n12.5\n71\n5\n50\n90\n7\nStandard\n1\nfirst\\Psecond\n73\n2\n44\n1.75\n", + output: vec![ + Tag::f(40, 2.25), + Tag::f(41, 12.5), + Tag::i(71, 5), + Tag::f(50, 90.0), + Tag::s(7, "Standard"), + Tag::s(1, "first\\Psecond"), + Tag::i(73, 2), + Tag::f(44, 1.75), + ], + }, + Fixture { + wire_type: "POINT", + kind: EntityKind::Point(Point { p: Vec3::new(1.0, 2.0, 3.0), angle: 0.0 }), + groups: "10\n1\n20\n2\n30\n3\n", + output: vec![Tag::f(10, 1.0), Tag::f(20, 2.0), Tag::f(30, 3.0)], + }, + Fixture { + wire_type: "RAY", + kind: EntityKind::Ray(RayLine { base: Vec3::new(1.0, 2.0, 3.0), dir: Vec3::new(0.0, 1.0, 0.0) }), + groups: "10\n1\n20\n2\n30\n3\n11\n0\n21\n1\n31\n0\n", + output: vec![Tag::f(11, 0.0), Tag::f(21, 1.0), Tag::f(31, 0.0)], + }, + ] +} + +#[test] +fn reads_extended_entities_from_independent_groups() { + for fixture in fixtures() { + let name = fixture.wire_type; + let bytes = format!("0\nSECTION\n2\nENTITIES\n0\n{name}\n5\n100\n{}0\nENDSEC\n0\nEOF\n", fixture.groups); + let expected = cases::entity_case(name, Common::default(), fixture.kind.clone()); + let back = read(bytes.as_bytes(), "fixture.dxf").unwrap(); + compare::model(&expected.drawing, &back, name); + } +} + +#[test] +fn writes_extended_entities_with_independent_groups() { + for fixture in fixtures() { + let name = fixture.wire_type; + let source = cases::entity_case(name, Common::default(), fixture.kind.clone()); + for version in Version::ALL { + for binary in [false, true] { + let bytes = write_with(&source.drawing, "memory.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + let tags = cadcraft_dxf::parse(&bytes).unwrap(); + let sections = sections(&tags); + let records = records(§ions.iter().find(|s| s.name == "ENTITIES").unwrap().tags); + assert_eq!(records.len(), 1); + let (kind, groups) = &records[0]; + assert_eq!(kind, name); + for code in fixture.output.iter().map(|t| t.code) { + let expected: Vec<_> = fixture.output.iter().filter(|t| t.code == code).collect(); + let actual: Vec<_> = groups.iter().filter(|t| t.code == code).collect(); + assert_eq!(actual, expected, "{name} {version} binary={binary} group={code}"); + } + } + } + } +} diff --git a/crates/io/tests/it/roundtrip/dxf/mod.rs b/crates/io/tests/it/roundtrip/dxf/mod.rs new file mode 100644 index 000000000..929c1a483 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/mod.rs @@ -0,0 +1,56 @@ +//! DXF preservation through public Drawing → bytes → Drawing APIs, without disk or UI. +//! Covers modeled entity families, stored block graphs, references and selected drawing +//! collections, not whole-drawing/session equivalence. Each case runs in ASCII and binary, +//! twice, at every representable save version; expectations never come from writer output. +//! WIPEOUT's explicit closing marker is an authored format expectation, not a new corner. +//! +//! Run: `cargo test -p cadcraft-io --test it roundtrip::dxf`. +//! Add `-- --ignored` to reproduce the pending preservation cases. Those tests +//! assert desired preservation, not today's wrong result; remove `ignore` when fixing them. +//! Independent fixtures cover the core entity groups; deep compound-entity interoperability +//! still needs separate format checks beyond the self-round-trip matrix. + +mod attributes; +mod common; +mod conformance; +mod entities; +mod extended; +mod geometry_groups; +mod table_flags; + +use super::compare; +use cadcraft_doc::Drawing; +use cadcraft_io::{SaveOptions, Version, read, save_version, write_with}; + +fn check(case: &str, original: &Drawing) { + for version in Version::ALL { + check_version(case, original, original, version); + } +} + +fn check_version(case: &str, original: &Drawing, expected: &Drawing, version: Version) { + check_version_with(case, original, expected, version, |_, _, _| {}); +} + +fn check_version_with(case: &str, original: &Drawing, expected: &Drawing, version: Version, extra: impl Fn(&Drawing, &Drawing, &str)) { + for binary in [false, true] { + let options = SaveOptions { version: Some(version), binary }; + let mut current = original.clone(); + for pass in 1..=2 { + let context = format!("{case} · {version} · binary={binary} · pass={pass}"); + let bytes = write_with(¤t, "memory.dxf", &options).unwrap_or_else(|e| panic!("{context}: write: {e}")); + assert_eq!(cadcraft_dxf::is_binary(&bytes), binary, "{context}: encoding"); + let back = read(&bytes, "memory.dxf").unwrap_or_else(|e| panic!("{context}: read: {e}")); + assert_eq!(save_version(&back), version, "{context}: version"); + assert!(back.read_notes.is_empty(), "{context}: read notes: {:?}", back.read_notes); + assert!(back.skipped_records.is_empty(), "{context}: skipped records: {:?}", back.skipped_records); + compare::model(expected, &back, &context); + extra(expected, &back, &context); + if pass == 2 { + compare::model(¤t, &back, &format!("{context} · resave stability")); + extra(¤t, &back, &format!("{context} · resave stability")); + } + current = back; + } + } +} diff --git a/crates/io/tests/it/roundtrip/dxf/table_flags.rs b/crates/io/tests/it/roundtrip/dxf/table_flags.rs new file mode 100644 index 000000000..cefc28bb1 --- /dev/null +++ b/crates/io/tests/it/roundtrip/dxf/table_flags.rs @@ -0,0 +1,128 @@ +//! Independent standard LAYER/STYLE flag contracts. Literal wire-to-field mappings cover the +//! small modeled flag domains, including off-vs-frozen and vertical-vs-mirrored distinctions. +//! Reader fixtures are handwritten records; writer checks inspect tags, not our Drawing reader. +//! Annotative STYLE xdata is covered separately by the round-trip tests, not this native-bit test. +//! References: Autodesk DXF Reference, LAYER and STYLE symbol table entries. + +use cadcraft_color::Color; +use cadcraft_doc::{Drawing, Layer, TextStyle}; +use cadcraft_dxf::{Tag, Value, records, sections}; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +fn layers() -> Vec<(Layer, i64)> { + let mut cases = Vec::new(); + // (group 70, frozen, frozen in new viewports, locked). Off is the sign of 62, + // not another flag; plot is group 290 and must not accidentally change any of these. + for (flags, frozen, vp_freeze_new, locked) in [ + (0, false, false, false), + (1, true, false, false), + (2, false, true, false), + (3, true, true, false), + (4, false, false, true), + (5, true, false, true), + (6, false, true, true), + (7, true, true, true), + ] { + for on in [false, true] { + for plot in [false, true] { + cases.push(( + Layer { name: "Flags".into(), color: Color::Index(3), frozen, vp_freeze_new, locked, on, plot, ..Layer::default() }, + flags, + )); + } + } + } + cases +} + +fn styles() -> Vec<(TextStyle, i64, i64)> { + let mut cases = Vec::new(); + for (generation, backwards, upside_down) in [(0, false, false), (2, true, false), (4, false, true), (6, true, true)] { + for (flags, vertical) in [(0, false), (4, true)] { + cases.push(( + TextStyle { name: "Flags".into(), font: "Synthetic.ttf".into(), backwards, upside_down, vertical, ..TextStyle::default() }, + flags, + generation, + )); + } + } + cases +} + +fn fixture(table: &str, body: &str) -> Drawing { + let bytes = format!("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\n{table}\n70\n1\n0\n{table}\n2\nFlags\n{body}0\nENDTAB\n0\nENDSEC\n0\nEOF\n"); + let drawing = read(bytes.as_bytes(), "fixture.dxf").unwrap(); + assert!(drawing.read_notes.is_empty(), "{:?}", drawing.read_notes); + assert!(drawing.skipped_records.is_empty()); + drawing +} + +fn output(drawing: &Drawing, table: &str, version: Version, binary: bool) -> Vec { + let bytes = write_with(drawing, "memory.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + let tags = cadcraft_dxf::parse(&bytes).unwrap(); + let sections = sections(&tags); + let tables = records(§ions.iter().find(|s| s.name == "TABLES").unwrap().tags); + let matching: Vec<_> = tables.into_iter().filter(|(kind, groups)| kind == table && groups.contains(&Tag::s(2, "Flags"))).collect(); + assert_eq!(matching.len(), 1, "{version} binary={binary} {table}"); + matching.into_iter().next().unwrap().1 +} + +fn group(tags: &[Tag], expected: Tag, context: &str) { + assert_eq!(tags.iter().filter(|t| t.code == expected.code).collect::>(), [&expected], "{context}"); +} + +#[test] +fn reads_all_layer_flag_combinations() { + for (expected, flags) in layers() { + let aci = if expected.on { 3 } else { -3 }; + let plot = i64::from(expected.plot); + let drawing = fixture("LAYER", &format!("70\n{flags}\n62\n{aci}\n6\nContinuous\n290\n{plot}\n")); + assert_eq!(drawing.layer("Flags"), Some(&expected), "70={flags} 62={aci} 290={plot}"); + } +} + +#[test] +fn writes_all_layer_flag_combinations() { + for (layer, flags) in layers() { + let mut drawing = Drawing::new_metric(); + drawing.layers.push(layer.clone()); + for version in Version::ALL { + for binary in [false, true] { + let tags = output(&drawing, "LAYER", version, binary); + let context = format!("{version} binary={binary} {layer:?}"); + group(&tags, Tag::i(70, flags), &context); + group(&tags, Tag::i(62, if layer.on { 3 } else { -3 }), &context); + if layer.plot { + // This writer omits the default true; the fixture above tests explicit true. + assert!(!tags.iter().any(|t| t.code == 290), "{context}"); + } else { + group(&tags, Tag::new(290, Value::Bool(false)), &context); + } + } + } + } +} + +#[test] +fn reads_all_native_text_style_flags() { + for (expected, flags, generation) in styles() { + let drawing = fixture("STYLE", &format!("70\n{flags}\n71\n{generation}\n40\n0\n41\n1\n50\n0\n3\nSynthetic.ttf\n4\n\n")); + assert_eq!(drawing.text_style("Flags"), Some(&expected), "70={flags} 71={generation}"); + } +} + +#[test] +fn writes_all_native_text_style_flags() { + for (style, flags, generation) in styles() { + let mut drawing = Drawing::new_metric(); + drawing.text_styles.push(style.clone()); + for version in Version::ALL { + for binary in [false, true] { + let tags = output(&drawing, "STYLE", version, binary); + let context = format!("{version} binary={binary} {style:?}"); + group(&tags, Tag::i(70, flags), &context); + group(&tags, Tag::i(71, generation), &context); + } + } + } +} diff --git a/crates/io/tests/it/roundtrip/handle_limits.rs b/crates/io/tests/it/roundtrip/handle_limits.rs new file mode 100644 index 000000000..3cff2b3e4 --- /dev/null +++ b/crates/io/tests/it/roundtrip/handle_limits.rs @@ -0,0 +1,40 @@ +//! Exhausting generated-handle space may be refused, but must not silently lose authored +//! entities. This is separate from the preservation matrix's large handles with free capacity. +//! Neither a particular allocator strategy nor a successful save is required at exhaustion. + +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +use super::{cases::properties, compare}; + +fn preserves_or_refuses(path: &str, binary: bool) { + let original = properties::exhausted_handles().drawing; + for version in Version::ALL { + let options = SaveOptions { version: Some(version), binary }; + let mut current = original.clone(); + for pass in 1..=2 { + let context = format!("exhausted handles · {path} {version} binary={binary} pass={pass}"); + let Ok(bytes) = write_with(¤t, path, &options) else { + break; // An explicit save error is safe; a nominal success must preserve the data. + }; + let back = read(&bytes, path).unwrap_or_else(|e| panic!("{context}: successful save is unreadable: {e}")); + assert!(back.read_notes.is_empty(), "{context}: {:?}", back.read_notes); + assert!(back.skipped_records.is_empty(), "{context}: {:?}", back.skipped_records); + compare::model(&original, &back, &context); + current = back; + } + } +} + +#[test] +#[ignore = "Confirmed DXF data loss: exhausted generated handles produce a successful save that reopens with no model entities"] +fn dxf_exhausted_handles_are_preserved_or_refused() { + for binary in [false, true] { + preserves_or_refuses("memory.dxf", binary); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn dwg_exhausted_handles_are_preserved_or_refused() { + preserves_or_refuses("memory.dwg", false); +} diff --git a/crates/io/tests/it/roundtrip/mod.rs b/crates/io/tests/it/roundtrip/mod.rs new file mode 100644 index 000000000..d38f84eb1 --- /dev/null +++ b/crates/io/tests/it/roundtrip/mod.rs @@ -0,0 +1,11 @@ +//! In-memory preservation tests grouped by file format. DXF and DWG use the same drawing cases +//! and strict assertions; each format owns its version domain and explicitly pending regressions. + +mod cases; +mod collections; +mod compare; +#[cfg(not(target_arch = "wasm32"))] +mod dwg; +mod dxf; +mod handle_limits; +mod unknown; diff --git a/crates/io/tests/it/roundtrip/unknown.rs b/crates/io/tests/it/roundtrip/unknown.rs new file mode 100644 index 000000000..5883a078c --- /dev/null +++ b/crates/io/tests/it/roundtrip/unknown.rs @@ -0,0 +1,106 @@ +//! Unknown-entity preservation is payload- and reference-aware: the entity's handle, Common +//! fields, model-space membership and every application payload tag must survive. Transport +//! owner handles may be reallocated, but the DXF owner must still resolve to model space. +//! DWG may explicitly refuse an unregistered class; a successful save must not silently drop it. + +use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Line, RawTag, Unknown}; +use cadcraft_dxf::{records, sections}; +use cadcraft_geom::Vec3; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +fn drawing() -> Drawing { + let mut d = super::cases::drawing(); + let handle = d.new_handle(); + let target = d.new_handle(); + let tags = vec![ + RawTag { code: 5, value: handle.hex() }, + // The store supplies the owner when saved, as it does for every modeled entity. + RawTag { code: 330, value: "0".into() }, + RawTag { code: 100, value: "AcDbEntity".into() }, + RawTag { code: 8, value: "0".into() }, + RawTag { code: 100, value: "SyntheticWidget".into() }, + RawTag { code: 1, value: "Original Ø payload".into() }, + RawTag { code: 90, value: "-7".into() }, + RawTag { code: 310, value: "00FF80".into() }, + RawTag { code: 10, value: "1.25".into() }, + RawTag { code: 20, value: "-2.5".into() }, + RawTag { code: 30, value: "3.75".into() }, + RawTag { code: 330, value: target.hex() }, + ]; + d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags }))); + d.model.push(Entity::new(target, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) }))); + d +} + +fn payload(tags: &[RawTag]) -> &[RawTag] { + let start = tags.iter().position(|t| t.code == 100 && t.value == "SyntheticWidget").expect("application subclass must survive"); + &tags[start..] +} + +fn preserved(original: &Drawing, back: &Drawing, context: &str) { + assert!(back.read_notes.is_empty(), "{context}: {:?}", back.read_notes); + assert!(back.skipped_records.is_empty(), "{context}: {:?}", back.skipped_records); + assert_eq!(back.model.len(), original.model.len(), "{context}: entity count"); + for (a, b) in original.model.iter().zip(back.model.iter()) { + assert_eq!(b.handle, a.handle, "{context}: handle"); + assert_eq!(b.common, a.common, "{context}: Common"); + match (&a.kind, &b.kind) { + (EntityKind::Unknown(a), EntityKind::Unknown(b)) => { + assert_eq!(b.dxf_type, a.dxf_type, "{context}: application entity type"); + assert_eq!(payload(&b.tags), payload(&a.tags), "{context}: full payload including handle reference"); + } + _ => assert_eq!(b.kind, a.kind, "{context}: geometry"), + } + } +} + +fn dxf_owner(bytes: &[u8]) { + let tags = cadcraft_dxf::parse(bytes).unwrap(); + let sections = sections(&tags); + let tables = records(§ions.iter().find(|s| s.name == "TABLES").unwrap().tags); + let (_, model) = tables + .iter() + .find(|(kind, tags)| kind == "BLOCK_RECORD" && tags.iter().any(|t| t.code == 2 && t.str().eq_ignore_ascii_case("*Model_Space"))) + .unwrap(); + let model_handle = model.iter().find(|t| t.code == 5).unwrap().str(); + let entities = records(§ions.iter().find(|s| s.name == "ENTITIES").unwrap().tags); + let (_, widget) = entities.iter().find(|(kind, _)| kind == "SYNTHETIC_WIDGET").unwrap(); + assert_eq!(widget.iter().find(|t| t.code == 330).unwrap().str(), model_handle, "unknown entity belongs to the model-space block"); +} + +pub(super) fn check(path: &str, version: Version, binary: bool) { + let original = drawing(); + let mut current = original.clone(); + for pass in 1..=2 { + let context = format!("unknown entity {path} {version} binary={binary} pass={pass}"); + let bytes = match write_with(¤t, path, &SaveOptions { version: Some(version), binary }) { + Ok(bytes) => bytes, + Err(_) if path.ends_with(".dwg") && pass == 1 => return, + Err(error) => panic!("{context}: {error}"), + }; + if path.ends_with(".dxf") { + assert_eq!(cadcraft_dxf::is_binary(&bytes), binary, "{context}: encoding"); + dxf_owner(&bytes); + } else { + assert_eq!(cadcraft_dwg::version(&bytes).as_deref(), Some(version.code()), "{context}: wire version"); + } + let back = read(&bytes, path).unwrap(); + preserved(&original, &back, &context); + preserved(¤t, &back, &context); + current = back; + } +} + +#[test] +fn unknown_payload_assertion_rejects_lost_references() { + let original = drawing(); + preserved(&original, &original, "unchanged unknown entity"); + let mut changed = original.clone(); + let handle = changed.model.iter().next().unwrap().handle; + changed.model.modify(handle, |e| { + let EntityKind::Unknown(u) = &mut e.kind else { panic!("expected unknown entity") }; + u.tags.pop(); + }); + assert_eq!(original.model.iter().next().unwrap().common, Common::default()); + assert!(std::panic::catch_unwind(|| preserved(&original, &changed, "missing application reference")).is_err()); +} From f0c1b4ff290d15d259b2a61c2eb8ddfdca641e6b Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:20:48 +1100 Subject: [PATCH 256/900] -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 257/900] 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 822f61b73a1b51ea4549675a5973bc1b56fa604f Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Fri, 30 Oct 2026 23:22:50 -0400 Subject: [PATCH 258/900] Release 0.15.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 32 ++++++++++++++++---------------- Cargo.toml | 2 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 51693203d..0541ed60d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -643,7 +643,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -659,14 +659,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.14.0" +version = "0.15.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -676,7 +676,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -687,14 +687,14 @@ dependencies = [ [[package]] name = "cadcraft-dwg" -version = "0.14.0" +version = "0.15.0" dependencies = [ "acadrust", ] [[package]] name = "cadcraft-dxf" -version = "0.14.0" +version = "0.15.0" dependencies = [ "encoding_rs", "log", @@ -703,7 +703,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -724,7 +724,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-geom", "harfrust 0.14.0", @@ -734,14 +734,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.14.0" +version = "0.15.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.14.0" +version = "0.15.0" dependencies = [ "acadrust", "cadcraft-color", @@ -762,7 +762,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -775,7 +775,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -789,7 +789,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -815,7 +815,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.14.0" +version = "0.15.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -5894,7 +5894,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.14.0" +version = "0.15.0" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index da6bca3b4..2e2e45f5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.14.0" +version = "0.15.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 4caf26ee60346262fedfe269b62e56f21754edd5 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:27:48 +1100 Subject: [PATCH 259/900] 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 260/900] 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 d4eab70e63f45db03159d1ae0dd781772ba0416f Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Fri, 30 Oct 2026 23:46:09 -0400 Subject: [PATCH 261/900] DWG bridge: build without acadrust on FreeBSD aarch64, where 0.6.6 doesn't compile Co-Authored-By: Claude Opus 5.5 --- crates/dwg/Cargo.toml | 5 +++- crates/dwg/build.rs | 12 +++++++++ crates/dwg/src/lib.rs | 60 +++++++++++++++++++++++-------------------- 3 files changed, 48 insertions(+), 29 deletions(-) create mode 100644 crates/dwg/build.rs diff --git a/crates/dwg/Cargo.toml b/crates/dwg/Cargo.toml index a409e5b90..0be9fdf40 100644 --- a/crates/dwg/Cargo.toml +++ b/crates/dwg/Cargo.toml @@ -8,6 +8,9 @@ license.workspace = true [lints] workspace = true -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The same targets as build.rs's `no_dwg_bridge` leave acadrust out: wasm32, and FreeBSD aarch64, +# where acadrust 0.6.6 passes a `*const c_char` (u8 there) to its own `*const i8` sysctlbyname. +# 0.6.7 and 0.6.8 fix that but read some damaged DWGs as empty with no note (tests.rs, #800). +[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.5" diff --git a/crates/dwg/build.rs b/crates/dwg/build.rs new file mode 100644 index 000000000..e97782ab4 --- /dev/null +++ b/crates/dwg/build.rs @@ -0,0 +1,12 @@ +//! Sets `no_dwg_bridge` on the targets built without acadrust (see Cargo.toml): the DWG functions +//! there return an error that says to use DXF. + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo::rustc-check-cfg=cfg(no_dwg_bridge)"); + let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); + let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + if arch == "wasm32" || (os == "freebsd" && arch == "aarch64") { + println!("cargo::rustc-cfg=no_dwg_bridge"); + } +} diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index f7bf13dd6..037aa26b5 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -58,13 +58,13 @@ impl Limits { } /// A byte count in megabytes for messages ("9.9 MB", "1024 MB"). -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +#[cfg_attr(no_dwg_bridge, allow(dead_code))] fn mb(n: u64) -> String { let m = n as f64 / f64::from(1u32 << 20); if m >= 100.0 { format!("{m:.0} MB") } else { format!("{m:.1} MB") } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(no_dwg_bridge))] mod native { use std::io::{Cursor, Write}; use std::panic::AssertUnwindSafe; @@ -741,18 +741,18 @@ mod native { } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(no_dwg_bridge))] pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as}; // Test-only: the stage ("post_process" or "convert") whose guard the current test checks. The // stage then panics on entry, so a test through the public API shows whether it is guarded. -#[cfg(all(test, not(target_arch = "wasm32")))] +#[cfg(all(test, not(no_dwg_bridge)))] thread_local! { static PANIC_IN: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// Panics when a test asked for `stage` to fail (see [`PANIC_IN`]); does nothing otherwise. -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(no_dwg_bridge))] #[allow(clippy::panic)] fn fail_in_test(_stage: &str) { #[cfg(test)] @@ -762,31 +762,35 @@ fn fail_in_test(_stage: &str) { } /// The error for a DWG version CADCraft can't write. -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +#[cfg_attr(no_dwg_bridge, allow(dead_code))] fn unsupported(version: &str) -> String { let list: Vec<&str> = VERSIONS.iter().map(|(_, year)| *year).collect(); format!("DWG version `{version}` can't be written (CADCraft writes {})", list.join(", ")) } -#[cfg(target_arch = "wasm32")] +/// Which build has no DWG bridge, for the stubs' errors. +#[cfg(no_dwg_bridge)] +const NO_BRIDGE_BUILD: &str = if cfg!(target_arch = "wasm32") { "web" } else { "FreeBSD aarch64" }; + +#[cfg(no_dwg_bridge)] pub fn dwg_to_dxf(_bytes: &[u8]) -> Result, String> { - Err("DWG files can't be opened in the web build yet; save as DXF".into()) + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } -#[cfg(target_arch = "wasm32")] +#[cfg(no_dwg_bridge)] pub fn dwg_to_dxf_noted(_bytes: &[u8], _limits: Limits) -> Result<(Vec, Vec), String> { - Err("DWG files can't be opened in the web build yet; save as DXF".into()) + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } -#[cfg(target_arch = "wasm32")] +#[cfg(no_dwg_bridge)] pub fn dwg_to_dxf_with(_bytes: &[u8], _limits: Limits) -> Result, String> { - Err("DWG files can't be opened in the web build yet; save as DXF".into()) + Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } -#[cfg(target_arch = "wasm32")] +#[cfg(no_dwg_bridge)] pub fn dxf_to_dwg(_dxf: &[u8]) -> Result, String> { - Err("DWG files can't be written in the web build yet; save as DXF".into()) + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } -#[cfg(target_arch = "wasm32")] +#[cfg(no_dwg_bridge)] 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()) + Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF")) } #[cfg(test)] @@ -794,14 +798,14 @@ mod tests { use super::*; /// The DXF of an empty drawing, enough for the bridge to make a small DWG. - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] const MINIMAL_DXF: &str = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nEOF\n"; /// Makes `stage` panic on the current thread until dropped. - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] struct PanicIn; - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] impl PanicIn { fn at(stage: &'static str) -> Self { PANIC_IN.with(|p| p.set(Some(stage))); @@ -809,7 +813,7 @@ mod tests { } } - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] impl Drop for PanicIn { fn drop(&mut self) { PANIC_IN.with(|p| p.set(None)); @@ -818,7 +822,7 @@ mod tests { /// The public read reports a panic in the post-read fix-ups as an error: this fails if the /// `guarded` call around `post_process` is taken out (#2402). - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] #[test] fn reading_a_dwg_survives_a_panic_in_post_processing() { let dwg = dxf_to_dwg(MINIMAL_DXF.as_bytes()).unwrap(); @@ -829,7 +833,7 @@ mod tests { } /// The DXF to DWG conversion reports a panic in its fix-ups as an error, not a crash (#2402). - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] #[test] fn converting_to_dwg_survives_a_panic_in_the_fix_ups() { let _panic = PanicIn::at("convert"); @@ -846,7 +850,7 @@ mod tests { /// A DXF with ROMANS as `$TEXTSTYLE` gives a DWG whose current text style is ROMANS, not /// Standard: the DXF names the style, and the handle read with it was Standard's (#1650). - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] #[test] fn current_text_style_reaches_the_dwg() { let header = " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 9\n$TEXTSTYLE\n 7\nROMANS\n 0\nENDSEC\n"; @@ -866,7 +870,7 @@ mod tests { assert!(dwg_to_dxf(b"").is_err()); } - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] #[test] fn dxf_to_dwg_rejects_garbage_without_crashing() { // The DXF→DWG path runs the third-party reader inside catch_unwind and reports failures @@ -876,7 +880,7 @@ mod tests { } /// A DXF with one DIMENSION per (text, group 70, subclass, points) row. - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] fn dims_dxf(dims: &[(&str, i64, &str, &[(i32, [f64; 2])])]) -> String { let mut s = String::from(" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1032\n 0\nENDSEC\n 0\nSECTION\n 2\nENTITIES\n"); for (text, flags, sub, pts) in dims { @@ -893,7 +897,7 @@ mod tests { /// the text is at its default position), and bit 32 in bit 1 (ODA DWG specification, common /// dimension data). The bytes are read back raw, so a reader that inverts bit 0 the same way /// as the writer can't hide a wrong byte. - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] #[test] fn dimension_text_position_flags_reach_the_dwg_as_autocad_reads_them() { let linear: &[(i32, [f64; 2])] = &[(13, [0.0, 0.0]), (14, [100.0, 0.0])]; @@ -940,7 +944,7 @@ mod tests { } /// The handles a DXF text refers to or gives its records (groups 5, 105 and 330–369). - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] fn dxf_handles(dxf: &str) -> std::collections::HashSet { let lines: Vec<&str> = dxf.lines().collect(); lines @@ -957,7 +961,7 @@ mod tests { /// 1.2 GB DXF rendition over the limit, so it didn't open). They're left out with a note, and /// their dictionary entries with them; the definition and every component it reaches — /// through compound and point components, around a cycle — are kept. - #[cfg(not(target_arch = "wasm32"))] + #[cfg(not(no_dwg_bridge))] #[test] fn orphaned_dgn_line_style_components_are_left_out() { use acadrust::objects::*; From 660e15c9f494ce647e87de10adbb01a8786e0901 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Fri, 30 Oct 2026 23:46:11 -0400 Subject: [PATCH 262/900] Release 0.15.1 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 32 ++++++++++++++++---------------- Cargo.toml | 2 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0541ed60d..1d51978e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -643,7 +643,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -659,14 +659,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.15.0" +version = "0.15.1" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -676,7 +676,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -687,14 +687,14 @@ dependencies = [ [[package]] name = "cadcraft-dwg" -version = "0.15.0" +version = "0.15.1" dependencies = [ "acadrust", ] [[package]] name = "cadcraft-dxf" -version = "0.15.0" +version = "0.15.1" dependencies = [ "encoding_rs", "log", @@ -703,7 +703,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -724,7 +724,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-geom", "harfrust 0.14.0", @@ -734,14 +734,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.15.0" +version = "0.15.1" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.15.0" +version = "0.15.1" dependencies = [ "acadrust", "cadcraft-color", @@ -762,7 +762,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -775,7 +775,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -789,7 +789,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -815,7 +815,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.15.0" +version = "0.15.1" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -5894,7 +5894,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.15.0" +version = "0.15.1" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 2e2e45f5e..ee2dc2fae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.15.0" +version = "0.15.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 74ddfb377fb2f2b1c093b58d9589b820e32d66be Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:49:13 +1100 Subject: [PATCH 263/900] 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 264/900] 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 ee715f4636c4588741cfa3474d23239d5ff60f69 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 31 Oct 2026 04:17:25 +0000 Subject: [PATCH 265/900] docs: tidy agent, contributor and asset docs --- AGENTS.md | 13 ++++--------- ATTRIBUTION.md | 16 ++++++++-------- CLAUDE.md | 6 ++---- ROADMAP.md | 4 ++-- contributors/people.toml | 7 ++----- crates/ui-egui/build.rs | 7 +++---- crates/ui-egui/src/credits.rs | 2 +- docs/contributors.md | 25 ++++--------------------- docs/localization-parity.md | 2 +- docs/releasing.md | 2 +- docs/roadmap.md | 3 +-- docs/target-app-parity.md | 2 +- 12 files changed, 30 insertions(+), 59 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f805cdddd..309f3f0ce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,8 +2,6 @@ CADCraft is a clean-room, open-source, pure-Rust computer-aided design and drafting application targeting Autodesk AutoCAD parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop-class), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). -Standards and learnings shared across the crafting apps live in `../../craftrules` (or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code. - ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/autocad/*` (`01-observed-ui.md` holds measured observations of the running reference app; `04-menu-tree.txt` the menu tree by name). 2. Library decisions: `plan/adr/0001-geometry-libraries.md` (what we may depend on, what is rejected for licence reasons). @@ -12,7 +10,7 @@ Standards and learnings shared across the crafting apps live in `../../craftrule `plan/` is gitignored (local only). ## Never crash -People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). +People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). - **Errors are `Result`** through the crate's error type and `?`. An unfinished feature returns an error or reports "not available yet"; it never panics. - **Input-derived numbers are hostile** (DXF/DWG files, command-line text, MCP/control params): `get()` not `[i]`, checked arithmetic, no NaN casts, cap input-sized allocations and loop counts. @@ -47,25 +45,22 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. It follows craftrules' `standards/progress-docs.md`: the assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. PRs don't edit these docs: name the affected rows in the PR description, and maintainers update the rows, status lines and revision history in batches, which keeps open PRs from conflicting. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. +`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. The assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. PRs don't edit these docs: name the affected rows in the PR description, and maintainers update the rows, status lines and revision history in batches, which keeps open PRs from conflicting. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. ## Contributor credits (About window) - About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json` - (commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for + (commit stats; never hand-edit) and `contributors/people.toml` (names people chose for themselves). See `docs/contributors.md`. - **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once whether they want to be credited by more than their username: a real name, a display name, and/or their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry - (copy the template at the top of the file, or run - `python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`) + (copy the template at the top of the file) and include it in their PR, committed as them. If no, change nothing: they are credited as `@username` anyway. - Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or GitHub profiles). Never hand-edit `contributors.json`. -- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also - re-verifies who wrote each `people.toml` entry; `--check` only verifies). ## CI workflows - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 31ea4b474..20b3dcc6e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -48,14 +48,14 @@ Generated-in-code assets are original and have no file to list: | `docs/images/ui-apartment.png` | CADCraft contributors | screenshot of CADCraft itself (examples/apartment.dxf) | MIT OR Apache-2.0 | Original; no Autodesk UI | | `docs/images/ui-layout.png` | CADCraft contributors | screenshot of CADCraft itself (a layout of examples/apartment.dxf) | MIT OR Apache-2.0 | Original; no Autodesk UI | | `docs/images/ui-bracket.png` | CADCraft contributors | screenshot of CADCraft itself (sample drawing generated in code) | MIT OR Apache-2.0 | Original; no Autodesk UI | -| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-logo.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-logo.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-mark.png` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | -| `docs/brand/artcraft-mark.svg` | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-logo.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-logo.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-mark.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | +| `docs/brand/artcraft-mark.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source | ## Interface translations diff --git a/CLAUDE.md b/CLAUDE.md index f5036db11..659cc8c2b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,8 +2,6 @@ CADCraft is a clean-room, open-source, pure-Rust computer-aided design and drafting application targeting Autodesk AutoCAD parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows, Linux and FreeBSD, and on the web via WASM. Siblings with the same conventions: `../photocraft` (Photoshop-class), `../vectorcraft` (Illustrator), `../filmcraft` (Premiere), `../lightcraft` (Lightroom), `../pdfcraft` (Acrobat), `../effectcraft` (After Effects), `../designcraft` (InDesign). -Standards and learnings shared across the crafting apps live in `../../craftrules` (or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its standards, and contribute reusable learnings back there. Never code: repos don't share code. - ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/autocad/*` (`01-observed-ui.md` holds measured observations of the running reference app; `04-menu-tree.txt` the menu tree by name). 2. Library decisions: `plan/adr/0001-geometry-libraries.md` (what we may depend on, what is rejected for licence reasons). @@ -12,7 +10,7 @@ Standards and learnings shared across the crafting apps live in `../../craftrule `plan/` is gitignored (local only). ## Never crash -People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** Standard: [`craftrules/standards/never-crash.md`](https://github.com/storytold/craftrules/blob/main/standards/never-crash.md). +People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** - **No panics in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`; no `unsafe` (`unsafe_code = "forbid"`). - **Errors are `Result`** through the crate's error type and `?`. An unfinished feature returns an error or reports "not available yet"; it never panics. - **Input-derived numbers are hostile** (DXF/DWG files, command-line text, MCP/control params): `get()` not `[i]`, checked arithmetic, no NaN casts, cap input-sized allocations and loop counts. @@ -46,7 +44,7 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; delete your target dir when done (disk). ## Roadmap -`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. It follows craftrules' `standards/progress-docs.md`: the assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. PRs don't edit these docs: name the affected rows in the PR description, and maintainers update the rows, status lines and revision history in batches, which keeps open PRs from conflicting. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. +`ROADMAP.md` (committed) is the one-page summary: stage, parity numbers, estimates. The assessment is `docs/target-app-parity.md`, the work list `docs/gaps.md` (pick work from its top rows), milestones `docs/roadmap.md`, deep checklists `docs/geometry-parity.md`, `docs/ui-parity.md`, `docs/file-format-parity.md`, `docs/hardware-parity.md`, `docs/localization-parity.md`. PRs don't edit these docs: name the affected rows in the PR description, and maintainers update the rows, status lines and revision history in batches, which keeps open PRs from conflicting. `cargo xtask parity` regenerates the menu-breadth checklist in `docs/parity-checklist.md`. ## CI workflows - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. diff --git a/ROADMAP.md b/ROADMAP.md index 239e10ac7..12c6983bb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -125,8 +125,8 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md) | 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. | | 2026-10-10 | Added mainstream practitioner (≈ 27%) and essentials user (≈ 45%) numbers; ready for real work unchanged at ≈ 37%. User evidence: 2 praise comments, 0 "switched from AutoCAD" reports, 27 of 37 open issues on the core path. | -| 2026-10-10 | Stage re-normalized from alpha to **pre-alpha** under the craftrules core-workflow gate: drafting with tracking, blocks, plotting and lossless DWG save fail; dimensioning passes. Alpha is ≈ 125–190 h away. | -| 2026-10-10 | Full re-measure against AutoCAD 2027 for Mac in the craftrules progress-docs format: menu breadth 245/491 (50%), ready for real work ≈ 37%, stage alpha. Remaining estimates rose (≈ 570 h → 1,300–2,100 h) on new evidence: behaviour audits found tracking/extension/parallel snaps and dynamic input are not real, saves drop unmodelled content, DWG saves as R2000, and the old estimate had no localization, ecosystem, stability, platform or AI rows. New docs: target-app-parity, gaps, roadmap, architecture, localization, file-format, hardware, UI and geometry parity; `docs/parity.md` became `docs/parity-checklist.md`. | +| 2026-10-10 | Stage re-normalized from alpha to **pre-alpha** under the core-workflow gate: drafting with tracking, blocks, plotting and lossless DWG save fail; dimensioning passes. Alpha is ≈ 125–190 h away. | +| 2026-10-10 | Full re-measure against AutoCAD 2027 for Mac in the progress-docs format: menu breadth 245/491 (50%), ready for real work ≈ 37%, stage alpha. Remaining estimates rose (≈ 570 h → 1,300–2,100 h) on new evidence: behaviour audits found tracking/extension/parallel snaps and dynamic input are not real, saves drop unmodelled content, DWG saves as R2000, and the old estimate had no localization, ecosystem, stability, platform or AI rows. New docs: target-app-parity, gaps, roadmap, architecture, localization, file-format, hardware, UI and geometry parity; `docs/parity.md` became `docs/parity-checklist.md`. | | 2026-10-10 | About 60 community PRs merged in a day: DXF fidelity (transparency, LWPOLYLINE elevation, frozen VP layers, dimension text rotation, arc-length dims, non-ASCII escapes), CJK font fallback, Save/Don't Save on close, Light/System themes, F2 history, trackpad pan, Linux XWayland drag-and-drop, correctness fixes across draw/modify/constraints. Release v0.4.0. | | 2026-10-08 | Releases v0.1.0–v0.3.0: Flatpak, AppImage updates, signed macOS universal, Windows x64/x86/arm64, Linux, FreeBSD and web builds. | | 2026-10-07 | Old assessment: menu breadth 233/491 (47%), ≈ 29% weighted parity, 2D drafting ≈ 55%, ≈ 570 h remaining; milestones as reported then: M1 ~85%, M2 ~65%, M3 ~75%, M4 ~50%, M5 ~35%, M6 ~55%, M7 ~55%, M8 ~20%, M9 ~60%, M10 ~70%, M11 0%, M12 ~25%, M13 ~10%. | diff --git a/contributors/people.toml b/contributors/people.toml index 28564415e..cd1925e36 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -1,13 +1,10 @@ -# Contributor names for the About window (craftrules standards/contributors.md). +# Contributor names for the About window. # # Everyone who contributes is credited by GitHub username automatically. Anything more is up to # you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a # maintainer may add a person only when that person asked, recording where in consent_source. # -# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \ -# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name] -# -# Or copy this block, replacing your-github-username (every field is optional): +# Copy this block, replacing your-github-username (every field is optional): # # [people.your-github-username] # real_name = "Your Name" # shown when the viewer picks "Real name" diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index f40007fb2..3116b01db 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -1,8 +1,7 @@ -//! Bake the contributor credits into the binary as static Rust tables (craftrules -//! standards/contributors.md). Nothing is read at run time. +//! Bake the contributor credits into the binary as static Rust tables. Nothing is read at run time. //! -//! - contributors/contributors.json: commit stats per GitHub username, generated by craftrules -//! scripts/contributors.py, which also marks whose people.toml entry it verified. +//! - contributors/contributors.json: commit stats per GitHub username, with a mark for whose people.toml +//! entry is verified. //! - contributors/people.toml: the names people chose for themselves. A name is used only when the //! JSON says the entry was verified (`people_entry`). //! diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index 28d08269a..6ebcb362e 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -1,6 +1,6 @@ //! The About window's credits: every contributor (GitHub login always; display and real names only //! with recorded consent) and the AI models that helped. The tables are baked into the binary by -//! build.rs from contributors/contributors.json (craftrules standards/contributors.md); nothing is +//! build.rs from contributors/contributors.json; nothing is //! read at run time. use std::cmp::Ordering; diff --git a/docs/contributors.md b/docs/contributors.md index acda57b24..13f693149 100644 --- a/docs/contributors.md +++ b/docs/contributors.md @@ -1,16 +1,14 @@ # Contributors in the About window **About ▸ Contributors** credits everyone who contributed to CADCraft, and **About ▸ Models** credits -the AI models named in `Co-Authored-By` trailers. This follows the shared craftrules standard -[`standards/contributors.md`](https://github.com/storytold/craftrules/blob/main/standards/contributors.md); -this page is the local copy of the decision. +the AI models named in `Co-Authored-By` trailers. ## Decision - Two files, both **compiled into the binary** by the UI crate's `build.rs` (nothing is read from disk or the network at run time; the web build has them too): - [`contributors/contributors.json`](../contributors/contributors.json): commit stats per GitHub - username. **Generated** by `craftrules/scripts/contributors.py`; never hand-edit. + username. - [`contributors/people.toml`](../contributors/people.toml): the names people chose for themselves. **Each contributor adds only their own entry**, in their own PR. - Each contributor gets one line: GitHub username (always), display name (opt-in, or their synced @@ -32,20 +30,5 @@ display_name = "Nickname" sync_github_name = true # use the name on your public GitHub profile as display name ``` -or, with craftrules checked out next to `craft-apps/`: - -```sh -python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "Your Name" --sync-github-name -``` - -Names show after the next refresh: the script checks that each entry was committed by its own -user (or by a maintainer with a `consent_source`). Delete your entry to remove your names. - -## Refreshing (maintainers) - -```sh -python3 ../../craftrules/scripts/contributors.py . # regenerate + verify; needs git, Python 3.11+, gh -python3 ../../craftrules/scripts/contributors.py --check . # verify people.toml only -``` - -Commit the updated `contributors/contributors.json`. Git author names and emails are never recorded. +Names show for entries committed by their own user (or by a maintainer with a `consent_source`). +Delete your entry to remove your names. Git author names and emails are never recorded. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index a6bcb5079..c6f43ee4a 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -46,7 +46,7 @@ shaping and right-to-left text through TrueType, vertical SHX text styles. ## Languages -Order and columns from craftrules' progress-docs standard. Every UI percentage is **measured** +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, plus native review by a human; extending the catalog to the remaining English-only strings diff --git a/docs/releasing.md b/docs/releasing.md index 85c7c7cbd..3595c6b68 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,6 +1,6 @@ # Releasing CADCraft -The canonical recipe is craftrules' [`release/playbook.md`](https://github.com/storytold/craftrules/blob/main/release/playbook.md); this file covers only what's CADCraft-specific. +This file describes how CADCraft is released. - **Version:** `[workspace.package] version` in the root `Cargo.toml` is the single source. `cargo xtask version` prints it; `cargo xtask version set X.Y.Z[-pre]` changes it. The app shows it in About, `cadcraft --version` and `cadcraft-cli --version`; release builds also embed the commit (`CADCRAFT_BUILD_SHA`). - **Cut a release:** bump the version on `main`, then push `main` to `release` (`git push origin main:release`). Every push to `release` runs `.github/workflows/release.yml` and creates or updates the draft GitHub Release `CADCraft v`. A `workflow_dispatch` run with `version: X.Y.Z-rc.N` makes a test build. A dispatch on any other branch is a dry run: the unsigned jobs (version, Linux, Linux riscv64, Flatpak, FreeBSD, web) build, the `release` environment refuses the signing jobs (macOS, Windows), and no release is drafted. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3d46be9df..025a43f54 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -26,8 +26,7 @@ Items 2–5 and 7 are the [alpha gate](#alpha-gate) rows. ## Alpha gate -The core workflows a typical AutoCAD professional does every day (craftrules progress-docs -standard). CADCraft is **pre-alpha** because four of the five fail the gate; the failing rows are +The core workflows a typical AutoCAD professional does every day. CADCraft is **pre-alpha** because four of the five fail the gate; the failing rows are the alpha checklist. Main platform: macOS. | Core workflow | Works end to end? | Evidence | Hours to pass | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6b5407d60..a981d0c62 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -215,7 +215,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Feature breadth | Weighted parity | Remaining | Note | |---|---|---|---|---| | 2026-10-10 (merge) | unchanged (233/491 re-scanned) | ready ≈ 38% (37.7%), mainstream ≈ 28%, essentials ≈ 46% | unchanged within rounding | main landed dynamic input pointer boxes (#60), the Ukrainian catalog (#36), WIPEOUT/gradient DXF fixes (#147, #162): UI/UX 40% → 43%, localization 3% → 5% | -| 2026-10-10 (later) | unchanged | ready for real work ≈ 37% (unchanged: already built from the written dimension weights, no hidden judgement); mainstream practitioner ≈ 27%; essentials user ≈ 45% | unchanged | mainstream and essentials numbers added (craftrules standard) | +| 2026-10-10 (later) | unchanged | ready for real work ≈ 37% (unchanged: already built from the written dimension weights, no hidden judgement); mainstream practitioner ≈ 27%; essentials user ≈ 45% | unchanged | mainstream and essentials numbers added | | 2026-10-10 | 245/491 (50%), engine-only 233/491 | features ≈ 41%, ready for real work ≈ 37% | 1,300–2,100 h | full re-measure in this format (this file) | | 2026-10-07 | 233/491 (47%) | ≈ 29% overall, 2D ≈ 55% | ≈ 570 h | old ROADMAP: milestone percentages reported by the building agents | From 9b32882065070cf7671873b809eafeba29c3944f Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 31 Oct 2026 04:25:44 +0000 Subject: [PATCH 266/900] docs: tidy wording --- ROADMAP.md | 4 ++-- docs/gaps.md | 2 +- docs/target-app-parity.md | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 12c6983bb..48bd33032 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -126,7 +126,7 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md) | 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. | | 2026-10-10 | Added mainstream practitioner (≈ 27%) and essentials user (≈ 45%) numbers; ready for real work unchanged at ≈ 37%. User evidence: 2 praise comments, 0 "switched from AutoCAD" reports, 27 of 37 open issues on the core path. | | 2026-10-10 | Stage re-normalized from alpha to **pre-alpha** under the core-workflow gate: drafting with tracking, blocks, plotting and lossless DWG save fail; dimensioning passes. Alpha is ≈ 125–190 h away. | -| 2026-10-10 | Full re-measure against AutoCAD 2027 for Mac in the progress-docs format: menu breadth 245/491 (50%), ready for real work ≈ 37%, stage alpha. Remaining estimates rose (≈ 570 h → 1,300–2,100 h) on new evidence: behaviour audits found tracking/extension/parallel snaps and dynamic input are not real, saves drop unmodelled content, DWG saves as R2000, and the old estimate had no localization, ecosystem, stability, platform or AI rows. New docs: target-app-parity, gaps, roadmap, architecture, localization, file-format, hardware, UI and geometry parity; `docs/parity.md` became `docs/parity-checklist.md`. | +| 2026-10-10 | Full re-measure against AutoCAD 2027 for Mac: menu breadth 245/491 (50%), ready for real work ≈ 37%, stage alpha. Remaining estimates rose (≈ 570 h → 1,300–2,100 h) on new evidence: behaviour audits found tracking/extension/parallel snaps and dynamic input are not real, saves drop unmodelled content, DWG saves as R2000, and the old estimate had no localization, ecosystem, stability, platform or AI rows. New docs: target-app-parity, gaps, roadmap, architecture, localization, file-format, hardware, UI and geometry parity; `docs/parity.md` became `docs/parity-checklist.md`. | | 2026-10-10 | About 60 community PRs merged in a day: DXF fidelity (transparency, LWPOLYLINE elevation, frozen VP layers, dimension text rotation, arc-length dims, non-ASCII escapes), CJK font fallback, Save/Don't Save on close, Light/System themes, F2 history, trackpad pan, Linux XWayland drag-and-drop, correctness fixes across draw/modify/constraints. Release v0.4.0. | | 2026-10-08 | Releases v0.1.0–v0.3.0: Flatpak, AppImage updates, signed macOS universal, Windows x64/x86/arm64, Linux, FreeBSD and web builds. | | 2026-10-07 | Old assessment: menu breadth 233/491 (47%), ≈ 29% weighted parity, 2D drafting ≈ 55%, ≈ 570 h remaining; milestones as reported then: M1 ~85%, M2 ~65%, M3 ~75%, M4 ~50%, M5 ~35%, M6 ~55%, M7 ~55%, M8 ~20%, M9 ~60%, M10 ~70%, M11 0%, M12 ~25%, M13 ~10%. | @@ -144,7 +144,7 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md) | 2026-10-10 | minor | Readiness-by-audience table with hours to ~95% for each number | | 2026-10-10 | minor | Mainstream practitioner and essentials user headline numbers | | 2026-10-10 | minor | Stage alpha → pre-alpha under the core-workflow gate; banner, why, headline row | -| 2026-10-10 | major | Restructured to the progress-docs standard (stage, two numbers, dimensions, features, languages, upcoming, log); full re-measure; milestone detail moved to docs/roadmap.md, parity assessment to docs/target-app-parity.md | +| 2026-10-10 | major | Progress docs restructured (stage, two numbers, dimensions, features, languages, upcoming, log); full re-measure; milestone detail moved to docs/roadmap.md, parity assessment to docs/target-app-parity.md | | 2026-10-07 | major | Alpha checklist, milestone table, ≈ 29% weighted parity estimate | ## Shared UI workspace integration diff --git a/docs/gaps.md b/docs/gaps.md index a7548c4d2..f8ddac941 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -107,7 +107,7 @@ 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 | +| 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 | 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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a981d0c62..fc36dea7d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -65,8 +65,7 @@ mainstream and essentials numbers use multiplicative discounts. ## Mainstream practitioner The typical AutoCAD professional is a 2D drafter or detailer: draw, modify, dimension, use -blocks, manage layers, plot sheets, and exchange DWGs with colleagues, every week. Excluded per -the standard: 3D, AutoLISP and plug-ins, cloud/AI (Autodesk Assistant, Smart Blocks, Traces, +blocks, manage layers, plot sheets, and exchange DWGs with colleagues, every week. Excluded: 3D, AutoLISP and plug-ins, cloud/AI (Autodesk Assistant, Smart Blocks, Traces, Share), Sheet Set Manager administration, specialist hardware, languages other than English. | Area (weekly use) | Weight | Depth | Weighted | From 11ce7eb52c6a72e81fd809b48ce734facfdab31e Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 31 Oct 2026 04:42:07 +0000 Subject: [PATCH 267/900] updates: show check results with craft-update's CheckResultDialog --- Cargo.lock | 18 ++++++++-------- Cargo.toml | 2 +- crates/ui-egui/src/updates_ui.rs | 35 +++++++++++++++++++++++++++++--- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1d51978e1..c45ba071c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -268,7 +268,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.59.0", + "windows-sys 0.61.2", "wl-clipboard-rs", "x11rb", ] @@ -1191,7 +1191,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=04aa1703b32d299e54f78fcde4182f2b393a9116#04aa1703b32d299e54f78fcde4182f2b393a9116" +source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" dependencies = [ "chrono", "dunce", @@ -1643,7 +1643,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3435,7 +3435,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4030,7 +4030,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4087,7 +4087,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4562,10 +4562,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -5471,7 +5471,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ee2dc2fae..8e16721a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,7 +66,7 @@ egui-wgpu = "0.37" # Monotonic time on native and web (performance.now on wasm). web-time = "1.1" # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "04aa1703b32d299e54f78fcde4182f2b393a9116", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } rfd = "0.17" arboard = { version = "3.6", default-features = false } diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index ffc625767..ce8f53a3f 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -3,6 +3,7 @@ //! `craft_update::updater::Updater`. use craft_update::updater::{Action, Status, Updater}; +use craft_update::{CheckResultDialog, CheckResultResponse}; use crate::CadApp; @@ -16,11 +17,15 @@ pub struct Runtime { enabled: bool, /// Help ▸ Check for Updates… was chosen; the next frame's `tick` starts it with the context. check_requested: bool, + /// The check-result dialog is open (from a requested check until it is closed). + result_open: bool, + /// The current result was already written to the command history. + result_echoed: bool, } impl Default for Runtime { fn default() -> Self { - Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false } + Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false, result_open: false, result_echoed: false } } } @@ -31,9 +36,11 @@ impl CadApp { } } -/// Help ▸ Check for Updates…: check now, and say so when there is nothing newer. +/// Help ▸ Check for Updates…: check now, and show the result when there is nothing newer. pub fn check_now(app: &mut CadApp) { app.updates_rt.check_requested = true; + app.updates_rt.result_open = true; + app.updates_rt.result_echoed = false; } /// Start the checks and collect the answers. @@ -50,8 +57,16 @@ pub fn tick(app: &mut CadApp, ctx: &egui::Context) { Status::Failed(_) => Some(crate::tl!("Could not check for updates.")), Status::Idle | Status::Checking => None, }; - if let Some(message) = outcome { + let Some(message) = outcome else { + // A check that found an update leaves `Idle`; the prompt takes over from the dialog. + if rt.result_open && matches!(rt.updater.status(), Status::Idle) { + rt.result_open = false; + } + return; + }; + if !rt.result_open { rt.updater.dismiss_status(); + } else if !std::mem::replace(&mut rt.result_echoed, true) { app.session.echo(message); } } @@ -60,6 +75,20 @@ pub fn tick(app: &mut CadApp, ctx: &egui::Context) { pub fn show(app: &mut CadApp, ctx: &egui::Context) { // The restart helper is scheduled before the app closes, so no update starts over unsaved work. let clean = !app.session.docs.iter().any(|d| d.is_dirty()); + let rt = &mut app.updates_rt; + if rt.result_open { + match CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status()) { + CheckResultResponse::Close => { + rt.result_open = false; + rt.updater.dismiss_status(); + } + CheckResultResponse::CheckAgain => { + rt.result_echoed = false; + rt.check_requested = true; + } + CheckResultResponse::None => {} + } + } match app.updates_rt.updater.show_if(ctx, clean) { Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), // The guarded close path asks about unsaved changes; the restart helper relaunches once the From c6e49b177cd6bc103a0042eadfa5dee96a59aed1 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sat, 31 Oct 2026 00:44:27 -0400 Subject: [PATCH 268/900] test(autosave): fix a flake: wait for the background write to finish, not just for its file Since #2518 the write syncs the folder after the rename, so the autosave file exists while the write is still running. Until it finishes the drawing is busy and the next change isn't planned, so the test's tick() returned None. Autosaver::writing() says whether a write is still running. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/autosave.rs | 7 +++++++ crates/engine/tests/autosave.rs | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index c6b41cce4..9ff7eab0b 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -416,6 +416,13 @@ mod native { writes } + /// Whether a background write hasn't finished yet. Its file can exist before it finishes + /// (the folder is synced after the rename), and until [`Autosaver::reap`] takes it in, the + /// drawing is left out of planning. + pub fn writing(&self) -> bool { + self.running.iter().any(|(_, h)| !h.is_finished()) + } + /// Take in the writes that have finished ([`Autosaver::tick`] does this first). A drawing /// whose write failed is no longer counted as autosaved: the next plan restarts its clock, /// so it is tried again SAVETIME later even if it doesn't change. diff --git a/crates/engine/tests/autosave.rs b/crates/engine/tests/autosave.rs index da03c0d7d..f44be5231 100644 --- a/crates/engine/tests/autosave.rs +++ b/crates/engine/tests/autosave.rs @@ -185,6 +185,14 @@ fn autosave_files_are_written_in_the_background_and_removed_on_exit() { std::thread::sleep(Duration::from_millis(10)); } assert!(std::fs::read(&path).unwrap().ends_with(b"EOF\n")); + // The file exists before the write finishes (the folder sync comes after the rename); until + // it has, the drawing is busy and the change drawn below would not be planned. + for _ in 0..500 { + if !a.writing() { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } // While the app runs, its lock keeps its files out of recovery. SAVETIME and SAVEFILEPATH // are system variables (process-wide, so set in this test only). assert_eq!(cadcraft_engine::sysvars::get(&s, "SAVETIME"), Some(json!(10))); From b35f00847a76485b271956dc17685fbc88c58760 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:45:52 +0100 Subject: [PATCH 269/900] Validate new linetype names in the rename command (#2519) * Validate new linetype names in the rename command Found while testing crates/engine/src/cmd/props.rs:1154-1200 (run_rename, "linetype" branch) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 * rename: a linetype's new name is stored trimmed, as -RENAME types it (CodeRabbit) --------- Co-authored-by: Claude Haiku 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/props.rs | 18 ++++++++++++++++++ crates/engine/src/cmd/props/rename.rs | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index daf963f67..43f2aca38 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1181,6 +1181,11 @@ fn run_rename(s: &mut Session, p: &Value) -> Result { run_dimstyle_rename(s, &json!({ "from": from, "to": to }))?; } "linetype" | "ltype" => { + // Stored trimmed, as -RENAME types it: lookups compare names untrimmed. + let to = to.trim().to_string(); + if !rename::valid_name(&to) { + return Err(bad("rename", format!("`{to}` is not a valid linetype name"))); + } let d = s.doc_mut()?; if ["ByBlock", "ByLayer", "Continuous"].iter().any(|n| from.eq_ignore_ascii_case(n)) { return Err(bad("rename", format!("the {from} linetype cannot be renamed"))); @@ -1246,6 +1251,19 @@ mod tests { assert_eq!(col(&s), Color::ByBlock); } + #[test] + fn rename_linetype_rejects_invalid_names() { + let mut s = Session::new(); + s.execute("linetype", &json!({ "load": "DASHED" })).unwrap(); + for to in ["", " ", "A;B", "A|B", "*X"] { + let r = s.execute("rename", &json!({ "table": "linetype", "from": "DASHED", "to": to })); + assert!(r.is_err(), "renamed DASHED to {to:?}: {r:?}"); + assert!(s.doc().unwrap().linetype("DASHED").is_some()); + } + s.execute("rename", &json!({ "table": "linetype", "from": "DASHED", "to": " DASH2 " })).unwrap(); + assert!(s.doc().unwrap().linetype("DASH2").is_some()); + } + #[test] fn properties_set_rejects_unloaded_linetype() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/props/rename.rs b/crates/engine/src/cmd/props/rename.rs index fe2e289ce..3513c1254 100644 --- a/crates/engine/src/cmd/props/rename.rs +++ b/crates/engine/src/cmd/props/rename.rs @@ -8,7 +8,7 @@ use serde_json::json; use super::super::bad; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; -fn valid_name(n: &str) -> bool { +pub(super) fn valid_name(n: &str) -> bool { !n.trim().is_empty() && n.len() <= 255 && !n.starts_with('*') && !n.chars().any(|c| "<>/\\\":;?*|,=`".contains(c)) } From 42be8540a98d3046206d3f7be90a999dd861adde Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 31 Oct 2026 00:26:50 -0700 Subject: [PATCH 270/900] Backups of drawings sharing a name no longer overwrite each other (#2537) plan.dwg and plan.dxf in one folder shared plan.bak. A DWG keeps .bak, as AutoCAD names it, and any other drawing appends .bak. The naming comes from #1006. Co-authored-by: Filippo Reimer <49290121+filforce95@users.noreply.github.com> --- crates/engine/src/cmd/file.rs | 15 +++++++++++++-- crates/engine/tests/save_backup.rs | 14 ++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 9aaff4631..1c3fbd5c8 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -446,9 +446,20 @@ fn store(path: &str, bytes: &[u8]) -> Result<()> { } } -/// The backup of the drawing file `path`: `.bak` beside it, as AutoCAD names it. +/// The backup of the drawing file `path`, beside it. A DWG's is `.bak`, as AutoCAD names it, +/// in the extension's letter case (`plan.DWG` to `plan.BAK`); any other drawing appends `.bak` +/// (`plan.dxf.bak`), so `plan.dwg` and `plan.dxf` in one folder never overwrite each other's backup. pub fn backup_path(path: &std::path::Path) -> std::path::PathBuf { - path.with_extension("bak") + match path.extension().map(|e| e.to_string_lossy()) { + Some(e) if e.eq_ignore_ascii_case("dwg") => path.with_extension( + e.chars().zip("bak".chars()).map(|(d, b)| if d.is_ascii_uppercase() { b.to_ascii_uppercase() } else { b }).collect::(), + ), + _ => { + let mut name = path.as_os_str().to_os_string(); + name.push(".bak"); + name.into() + } + } } /// Whether `bytes` read as a DWG or a DXF (ASCII or binary) by their start: what a save keeps as diff --git a/crates/engine/tests/save_backup.rs b/crates/engine/tests/save_backup.rs index afa5a14cb..d84aaedd3 100644 --- a/crates/engine/tests/save_backup.rs +++ b/crates/engine/tests/save_backup.rs @@ -72,7 +72,7 @@ fn each_save_keeps_the_previous_file_as_bak() { add_circle(&mut s, 5.0); s.execute("qsave", &json!({})).unwrap(); - assert_eq!(files(&dir), ["Plan.bak", "Plan.dxf"]); + assert_eq!(files(&dir), ["Plan.dxf", "Plan.dxf.bak"]); assert_eq!((circles(&path), circles(&backup_path(&path))), (2, 1), "the .bak is the previous save"); add_circle(&mut s, 10.0); @@ -118,7 +118,7 @@ fn a_damaged_file_never_replaces_a_good_backup_and_isavebak_0_keeps_none() { add_circle(&mut s, 15.0); s.execute("qsave", &json!({})).unwrap(); assert_eq!((circles(&path), circles(&backup_path(&path))), (6, 1)); - assert_eq!(files(&dir), ["Plan.bak", "Plan.dxf"]); + assert_eq!(files(&dir), ["Plan.dxf", "Plan.dxf.bak"]); let _ = std::fs::remove_dir_all(&dir); } @@ -294,3 +294,13 @@ fn the_backup_a_save_promises_is_the_one_it_writes() { assert!(!save_keeps_current(&path), "backups off"); let _ = std::fs::remove_dir_all(&dir); } + +/// `plan.dwg` and `plan.dxf` in one folder keep their own backups, in the DWG's letter case. +#[test] +fn drawings_sharing_a_name_keep_their_own_backups() { + let name = |p: &str| backup_path(std::path::Path::new(p)).to_string_lossy().into_owned(); + assert_eq!(name("x/plan.dwg"), "x/plan.bak"); + assert_eq!(name("x/plan.DWG"), "x/plan.BAK"); + assert_eq!(name("x/plan.dxf"), "x/plan.dxf.bak"); + assert_eq!(name("x/plan.dwt"), "x/plan.dwt.bak"); +} From e60d546ce4907d126981c38b544043977e7cd1b2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Sat, 31 Oct 2026 00:34:14 -0700 Subject: [PATCH 271/900] Picking after an edit no longer ends the app on an rstar panic (#2539) rstar 0.13 can panic when inserting after removals in a bulk-loaded tree, and picking runs outside the command guard. The patch now runs on a copy under catch_unwind and falls back to a bulk load. The web build can't catch a panic, so it always bulk-loads. Diagnosis, reproduction and fix from #2468. Fixes #2468 Co-authored-by: octopoulpos <32617732+octopoulpos@users.noreply.github.com> --- crates/engine/src/spatial.rs | 78 ++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index ca15bd4c4..dd2e0d593 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -94,6 +94,28 @@ fn hidden_layers(d: &Drawing) -> impl Iterator { d.layers.iter().filter(|l| !l.visible()).map(|l| l.name.as_str()) } +/// A copy of `tree` with `removed` taken out and `inserted` added, or `None` when the caller must +/// bulk-load instead. rstar 0.13 can panic ("This is a bug in rstar.") when inserting after removals +/// in a bulk-loaded tree (#2468), and picking is outside the command guard, so that panic would end +/// the app. The web build can't catch a panic, so it always bulk-loads. +fn patch_tree(tree: &RTree, removed: impl Iterator, inserted: impl Iterator) -> Option> { + if cfg!(target_arch = "wasm32") { + return None; + } + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut tree = tree.clone(); + for it in removed { + tree.remove(&it); + } + for it in inserted { + tree.insert(it); + } + tree + })) + .map_err(|_| log::warn!("spatial index: rstar failed to patch the tree; rebuilding it")) + .ok() +} + impl SpatialIndex { /// Build an index over a store (no caching). pub fn build(d: &Drawing, store: &EntityStore) -> SpatialIndex { @@ -127,23 +149,11 @@ impl SpatialIndex { offset = offset.saturating_add(n); } // Patch the previous tree when most of it survives; otherwise bulk-load. - let tree = match prev { - Some(p) if kept.len() * 2 >= chunks.len().max(1) => { - let mut tree = p.tree.clone(); - for (_, c) in p.chunks.iter().filter(|(_, c)| !kept.contains(&c.serial)) { - for it in c.items() { - tree.remove(&it); - } - } - for c in &fresh { - for it in c.items() { - tree.insert(it); - } - } - tree - } - _ => RTree::bulk_load(chunks.iter().flat_map(|(_, c)| c.items()).collect()), - }; + let patched = prev.filter(|_| kept.len() * 2 >= chunks.len().max(1)).and_then(|p| { + let removed = p.chunks.iter().filter(|(_, c)| !kept.contains(&c.serial)).flat_map(|(_, c)| c.items()); + patch_tree(&p.tree, removed, fresh.iter().flat_map(|c| c.items())) + }); + let tree = patched.unwrap_or_else(|| RTree::bulk_load(chunks.iter().flat_map(|(_, c)| c.items()).collect())); let offsets = chunks.iter().map(|(off, c)| (c.serial, *off)).collect(); let infinite = chunks.iter().flat_map(|(off, c)| c.infinite.iter().map(move |i| off + i)).collect(); SpatialIndex { @@ -367,6 +377,40 @@ mod tests { Some(Arc::new(SpatialIndex::build(d, &d.model))) } + /// The edits of #2468, on rstar alone: its insert panics for seed 8. A failed patch falls back + /// to a bulk load, and every tree holds exactly the live items. + #[test] + fn rstar_patch_failures_fall_back_to_a_rebuild() { + fn item(r: &mut Rng, s: u32, i: u32) -> Item { + let (x, y, w, h) = (r.f() * 1000.0, r.f() * 1000.0, r.f() * 50.0, r.f() * 50.0); + GeomWithData::new(Rectangle::from_corners([x, y], [x + w, y + h]), (s, i)) + } + for seed in 1..=10u64 { + let mut r = Rng(seed * 7919); + let n_chunks = 4 + (r.f() * 20.0) as u32; + let mut chunks: Vec> = (0..n_chunks) + .map(|s| { + let n = 1 + (r.f() * 60.0) as u32; + (0..n).map(|i| item(&mut r, s, i)).collect() + }) + .collect(); + let mut tree = RTree::bulk_load(chunks.iter().flatten().cloned().collect()); + for serial in (n_chunks..).take(300) { + let c = (r.f() * chunks.len() as f64) as usize; + let n = (chunks[c].len() as i64 + if r.f() < 0.5 { -1 } else { 1 }).max(0) as u32; + let fresh: Vec = (0..n).map(|i| item(&mut r, serial, i)).collect(); + let patched = patch_tree(&tree, chunks[c].iter().cloned(), fresh.iter().cloned()); + chunks[c] = fresh; + tree = patched.unwrap_or_else(|| RTree::bulk_load(chunks.iter().flatten().cloned().collect())); + let mut held: Vec<(u32, u32)> = tree.iter().map(|it| it.data).collect(); + let mut live: Vec<(u32, u32)> = chunks.iter().flatten().map(|it| it.data).collect(); + held.sort_unstable(); + live.sort_unstable(); + assert_eq!(held, live, "seed {seed}, serial {serial}"); + } + } + } + #[test] fn pick_parity_with_scan() { for seed in [3, 11, 97] { From 4552b3568895a890c5c164027aba56c0f5a50b47 Mon Sep 17 00:00:00 2001 From: austin62jake Date: Sat, 31 Oct 2026 02:34:18 -0500 Subject: [PATCH 272/900] fix(ui): dash only the visible part of a highlight, so zooming far in doesn't freeze (#2299) (#2454) * fix(ui): dash only the visible part of a highlight, so zooming far in doesn't freeze (#2299) With the pointer on an object, its rollover highlight is dashed, and draw_highlight dashed the object's whole outline in screen space, off-screen parts included: one shape per 10 points of it. Zoomed far in, a short line is billions of points long, so the app froze and then ran out of memory, which is the freeze and crash #2299 reports. Wheel-zooming a circle and two lines with the pointer on them reached 7.9 million shapes in one frame at a view height of 0.001 before a 1 GB allocation failed. The highlight now clips each outline to the view, plus a margin, in world coordinates first (precise when zoomed far in), and dashes only what is left. Each visible piece starts its dash pattern at its distance along the whole outline, so dashes don't crawl along a line that runs off screen while the view pans. The two dashed rectangles drawn in screen space, a layout's printable area and the crossing window, clip each edge to the painter's clip rect for the same reason. The same zoom now stays under 1,300 shapes per frame down to the zoom limit. Co-Authored-By: Claude Opus 5.5 * fix(ui): a clipped rectangle edge keeps its dashes where the whole edge puts them dashed_rect clipped each edge to the screen and then started its dashes at the clip boundary, so a printable area or crossing window running off screen had its dashes move with the view, and its bottom and left edges were drawn in reverse. Each edge now keeps its direction and its dashes start at their distance along the whole edge, as the highlight's outlines do. The zoomed-far-in app test also checks that the line really is hovered, so it can't pass with no highlight drawn. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 8 +- crates/ui-egui/src/canvas/draw.rs | 201 ++++++++++++++++++++++- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/zoomed_far_in.rs | 40 +++++ 4 files changed, 240 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/tests/it/zoomed_far_in.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fcc464be3..39040c366 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -26,7 +26,7 @@ mod widgets; use cursor::{draw_crosshair, draw_snap_marker, draw_tracking, effective_point, override_cursor}; use cycle::{CycleList, cycle_badge, cycle_click, cycle_list, over_canvas_menu, shift_space_cycle}; pub(crate) use draw::{Look, draw_highlight, draw_list}; -use draw::{draw_drag_gpu, draw_highlight_gpu, draw_list_gpu, list_mesh_key, selection_area_fill}; +use draw::{dashed_rect, draw_drag_gpu, draw_highlight_gpu, draw_list_gpu, list_mesh_key, selection_area_fill}; use dyn_boxes::dynamic_input; pub(crate) use dyn_boxes::length_units; use grid::draw_grid; @@ -982,8 +982,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) { xf_paper.to_screen(Vec2::new(sh.printable.min.x, sh.printable.max.y)), xf_paper.to_screen(Vec2::new(sh.printable.max.x, sh.printable.min.y)), ); - let pts = [pa.left_top(), pa.right_top(), pa.right_bottom(), pa.left_bottom(), pa.left_top()]; - painter.extend(Shape::dashed_line(&pts, Stroke::new(1.0, Color32::from_gray(150)), 4.0, 4.0)); + painter.extend(dashed_rect(painter.clip_rect(), pa, Stroke::new(1.0, Color32::from_gray(150)), 4.0, 4.0)); (Rgb(t.paper.r(), t.paper.g(), t.paper.b()), Some(paper)) } None => { @@ -1112,8 +1111,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) { } let st = Stroke::new(1.0, if crossing { t.crossing_stroke } else { t.window_stroke }); if crossing { - let pts = vec![r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()]; - painter.extend(Shape::dashed_line(&pts, st, 5.0, 3.0)); + painter.extend(dashed_rect(painter.clip_rect(), r, st, 5.0, 3.0)); } else { painter.rect_stroke(r, 0.0, st, egui::StrokeKind::Middle); } diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index 9ca1d9314..146466b24 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -19,6 +19,64 @@ fn clip_infinite(xf: &Xf, base: Vec2, dir: Vec2, ray: bool) -> Option<[Pos2; 2]> Some([xf.to_screen(a), xf.to_screen(b)]) } +/// Points past the view's edge that a dashed outline is still drawn to: more than one dash +/// period, so a dash cut at the clip edge never shows. +const CLIP_MARGIN: f32 = 16.0; + +/// The parts of a world-space polyline within `xf`'s view, as screen points, each with how far +/// along the whole polyline it starts (in points). Clipped in world coordinates, so an outline far +/// larger than the screen costs only what can show, and its points stay precise when zoomed far +/// in: dashing a whole line made billions of dashes (#2299). +fn visible_runs(xf: &Xf, pts: &[Vec2]) -> Vec<(Vec, f64)> { + let vis = xf.world_bounds().expand(f64::from(CLIP_MARGIN) / xf.scale); + let mut runs: Vec<(Vec, f64)> = Vec::new(); + // World length before the current segment; whether the last run reaches its start. + let (mut along, mut open) = (0.0, false); + for w in pts.windows(2) { + let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue }; + match cadcraft_render::clip::clip_segment(a, b, &vis) { + Some((p, q)) => { + match runs.last_mut() { + Some((run, _)) if open && p == a => run.push(xf.to_screen(q)), + _ => runs.push((vec![xf.to_screen(p), xf.to_screen(q)], (along + a.dist(p)) * xf.scale)), + } + open = q == b; + } + None => open = false, + } + along += a.dist(b); + } + runs +} + +/// Dashes along a screen polyline that starts `along` points into the outline it is part of, so +/// they sit where they would on the whole outline. +fn dashes(run: &[Pos2], along: f64, stroke: Stroke, dash: f32, gap: f32, out: &mut Vec) { + let period = f64::from(dash + gap); + let offset = (period - along.rem_euclid(period)) % period; + out.extend(Shape::dashed_line_with_offset(run, stroke, &[dash], &[gap], offset as f32)); +} + +/// A dashed rectangle outline, each edge clipped to `clip` first: a rectangle zoomed far larger +/// than the screen (a layout's printable area, a selection window) gets only the dashes that can +/// show (#2299). Each edge keeps its direction and its dashes start where they would on the whole +/// edge, so they don't crawl as the rectangle or the view moves. +pub(super) fn dashed_rect(clip: Rect, r: Rect, stroke: Stroke, dash: f32, gap: f32) -> Vec { + let v = |p: Pos2| Vec2::new(f64::from(p.x), f64::from(p.y)); + let c = clip.expand(CLIP_MARGIN); + let c = Bounds2::new(v(c.min), v(c.max)); + let mut out = Vec::new(); + let edges = + [(r.left_top(), r.right_top()), (r.right_top(), r.right_bottom()), (r.right_bottom(), r.left_bottom()), (r.left_bottom(), r.left_top())]; + for (a, b) in edges { + if let Some((p, q)) = cadcraft_render::clip::clip_segment(v(a), v(b), &c) { + let pos = |w: Vec2| Pos2::new(w.x as f32, w.y as f32); + dashes(&[pos(p), pos(q)], v(a).dist(p), stroke, dash, gap, &mut out); + } + } + out +} + /// Draw a display list. pub(crate) fn draw_list(p: &egui::Painter, xf: &Xf, list: &DisplayList, bg: Rgb, lwdisplay: bool) { let vis = xf.world_bounds(); @@ -279,25 +337,31 @@ impl Look { /// outlined, since filling it would hide the drawing under it. pub(crate) fn draw_highlight(p: &egui::Painter, xf: &Xf, list: &DisplayList, prims: &[usize], color: Color32, look: Look) { let stroke = Stroke::new(look.width, color); - let line = |pts: Vec, out: &mut Vec| { + let screen_line = |pts: Vec, along: f64, out: &mut Vec| { if look.dashed { - out.extend(Shape::dashed_line(&pts, stroke, 6.0, 4.0)); + dashes(&pts, along, stroke, 6.0, 4.0, out); } else { out.push(Shape::line(pts, stroke)); } }; + // Only the part of an outline in view (#2299). + let line = |pts: &[Vec2], out: &mut Vec| { + for (run, along) in visible_runs(xf, pts) { + screen_line(run, along, out); + } + }; let mut shapes = Vec::new(); let mut fill = egui::Mesh::default(); let fill_color = color.gamma_multiply(crate::gpu::HIGHLIGHT_FILL_ALPHA); for prim in prims.iter().filter_map(|&i| list.prims.get(i)) { let pts = list.points(prim); match prim.kind { - Kind::Polyline => line(pts.iter().map(|q| xf.to_screen(*q)).collect(), &mut shapes), + Kind::Polyline => line(pts, &mut shapes), Kind::Infinite { ray } => { if let (Some(b), Some(d)) = (pts.first(), pts.get(1)) && let Some(seg) = clip_infinite(xf, *b, *d, ray) { - line(seg.to_vec(), &mut shapes); + screen_line(seg.to_vec(), 0.0, &mut shapes); } } Kind::Point => { @@ -314,7 +378,7 @@ pub(crate) fn draw_highlight(p: &egui::Painter, xf: &Xf, list: &DisplayList, pri } Kind::Tris | Kind::Mask => { for outline in list.fill_outlines(prim) { - line(outline.iter().map(|q| xf.to_screen(*q)).collect(), &mut shapes); + line(&outline, &mut shapes); } } } @@ -422,3 +486,130 @@ mod highlight_stability_tests { } } } + +#[cfg(test)] +mod zoomed_highlight_tests { + use super::*; + use egui::pos2; + + /// A one-segment polyline from `a` to `b`. + fn line(a: Vec2, b: Vec2) -> DisplayList { + let mut list = DisplayList { verts: vec![a, b], ..Default::default() }; + list.prims.push(cadcraft_render::DPrim { + handle: Handle(256), + color: Rgb(255, 255, 255), + aci7: true, + lw: 0.0, + transparency: 0, + kind: Kind::Polyline, + start: 0, + len: 2, + }); + list + } + + const SCREEN: Rect = Rect { min: Pos2::ZERO, max: Pos2 { x: 600.0, y: 400.0 } }; + + /// The dash segments `draw_highlight` makes for `list` in `xf`. + fn dashes_of(list: &DisplayList, xf: &Xf) -> Vec<[Pos2; 2]> { + let ctx = egui::Context::default(); + let input = egui::RawInput { screen_rect: Some(SCREEN), ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| draw_highlight(ui.painter(), xf, list, &[0], Color32::LIGHT_BLUE, Look { width: 1.0, dashed: true })); + output.textures_delta.clear(); + output + .shapes + .iter() + .filter_map(|s| match &s.shape { + Shape::LineSegment { points, .. } => Some(*points), + _ => None, + }) + .collect() + } + + /// Zoomed far in on a line, the highlight dashes only what shows. Dashing the whole line made + /// one shape per 10 points of it: billions at the zoom limit, so the app froze and then ran out + /// of memory (#2299). + #[test] + fn a_zoomed_in_highlight_dashes_only_what_shows() { + let list = line(Vec2::new(-1000.0, 0.0), Vec2::new(1000.0, 0.0)); + // The smaller zoom first, so a regression fails here instead of filling memory at 1e9. + for scale in [1e3, 1e9] { + let n = dashes_of(&list, &Xf { rect: SCREEN, center: Vec2::new(0.3, 0.0), scale }).len(); + assert!((50..=70).contains(&n), "scale {scale}: {n} dashes for 600 points of line"); + } + } + + /// A line running off screen keeps its dashes where they are on the whole line, so they don't + /// crawl along it when the view pans. + #[test] + fn clipped_dashes_stay_where_the_whole_line_puts_them() { + let list = line(Vec2::new(0.0, 0.0), Vec2::new(1000.0, 0.0)); + for x in [500.3, 512.9, 731.0] { + let xf = Xf { rect: SCREEN, center: Vec2::new(x, 0.0), scale: 1.0 }; + let whole = Shape::dashed_line( + &[xf.to_screen(Vec2::ZERO), xf.to_screen(Vec2::new(1000.0, 0.0))], + Stroke::new(1.0, Color32::LIGHT_BLUE), + 6.0, + 4.0, + ); + let on_screen = |p: &[Pos2; 2]| p.iter().all(|q| SCREEN.contains(*q)); + let expected: Vec<[Pos2; 2]> = whole + .iter() + .filter_map(|s| match s { + Shape::LineSegment { points, .. } => Some(*points).filter(on_screen), + _ => None, + }) + .collect(); + let got: Vec<[Pos2; 2]> = dashes_of(&list, &xf).into_iter().filter(on_screen).collect(); + assert!(!expected.is_empty()); + assert_eq!(got.len(), expected.len(), "centre {x}"); + for (g, e) in got.iter().zip(&expected) { + assert!(g.iter().zip(e).all(|(a, b)| a.distance(*b) < 1e-3), "centre {x}: {g:?} vs {e:?}"); + } + } + } + + /// A rectangle edge running off screen keeps its dashes where they are on the whole edge. + #[test] + fn clipped_rectangle_edges_keep_their_dashes() { + let stroke = Stroke::new(1.0, Color32::GRAY); + let segments = |shapes: Vec| -> Vec<[Pos2; 2]> { + shapes + .into_iter() + .filter_map(|s| match s { + // The top edge's dashes that are wholly on screen. + Shape::LineSegment { points, .. } if points.iter().all(|q| SCREEN.contains(*q) && q.y == 100.0) => Some(points), + _ => None, + }) + .collect() + }; + for left in [-500.3, -517.9, -1200.0] { + let r = Rect::from_min_max(pos2(left, 100.0), pos2(400.0, 300.0)); + let expected = segments(Shape::dashed_line(&[r.left_top(), r.right_top()], stroke, 4.0, 4.0)); + let got = segments(dashed_rect(SCREEN, r, stroke, 4.0, 4.0)); + assert!(!expected.is_empty()); + assert_eq!(got.len(), expected.len(), "left edge at {left}"); + for (g, e) in got.iter().zip(&expected) { + assert!(g.iter().zip(e).all(|(a, b)| a.distance(*b) < 1e-3), "left edge at {left}: {g:?} vs {e:?}"); + } + } + } + + /// A dashed rectangle far larger than the screen gets dashes only along the edges that show. + #[test] + fn a_huge_dashed_rectangle_dashes_only_what_shows() { + let stroke = Stroke::new(1.0, Color32::GRAY); + // Its left edge runs through the screen; the other three are far off it. The smaller one + // first, so a regression fails here instead of filling memory with the larger one. + for far in [1e6, 1e9] { + let huge = Rect::from_min_max(pos2(300.0, -far), pos2(far, far)); + let n = dashed_rect(SCREEN, huge, stroke, 4.0, 4.0).len(); + assert!((50..=60).contains(&n), "{far}: {n} dashes along 432 points of edge"); + } + // A rectangle inside the screen keeps all four edges. + let small = Rect::from_min_max(pos2(100.0, 100.0), pos2(180.0, 140.0)); + assert_eq!(dashed_rect(SCREEN, small, stroke, 4.0, 4.0).len(), 10 + 5 + 10 + 5); + // Off screen, nothing. + assert!(dashed_rect(SCREEN, small.translate(egui::vec2(5000.0, 0.0)), stroke, 4.0, 4.0).is_empty()); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c32012e1a..b80614182 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -37,3 +37,4 @@ mod toolsets_gear; mod toolsets_parametric; mod viewport_double_click_selection; mod workspace_focus; +mod zoomed_far_in; diff --git a/crates/ui-egui/tests/it/zoomed_far_in.rs b/crates/ui-egui/tests/it/zoomed_far_in.rs new file mode 100644 index 000000000..5f6a73a21 --- /dev/null +++ b/crates/ui-egui/tests/it/zoomed_far_in.rs @@ -0,0 +1,40 @@ +//! Zooming far in with the pointer on an object (#2299): its rollover highlight is dashed, and +//! dashing the whole object made one shape per 10 points of it on screen. Zoomed to the limit +//! that was billions of shapes, so the app froze and then ran out of memory. + +use cadcraft_engine::Session; +use cadcraft_ui_egui::{CadApp, Services}; +use serde_json::json; + +/// One frame of the app; the number of shapes it painted. +fn frame(app: &mut CadApp, ctx: &egui::Context, events: Vec) -> usize { + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 800.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + out.shapes.len() +} + +#[test] +fn zooming_far_in_on_a_hovered_line_paints_what_shows() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.run("circle", json!({"center": [50, 50], "radius": 20})).unwrap(); + app.run("line", json!({"points": [[0, 0], [100, 100]]})).unwrap(); + app.run("line", json!({"points": [[0, 100], [100, 0]]})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, Vec::new()); + let over = app.canvas.rect.unwrap().center(); + // The smaller zoom first, so a regression fails there instead of filling memory at the limit. + for height in [1e-2, 1e-9] { + // Centred on a point of the first line, which the pointer, at the canvas centre, hovers. + app.run("view.set", json!({"center": [25, 25], "height": height})).unwrap(); + let shapes = (0..3).map(|_| frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)])).max().unwrap_or(0); + // Without a hovered object there is no dashed highlight, and the count says nothing. + assert!(app.canvas.hover.is_some(), "view height {height}: the line is hovered"); + assert!(shapes < 5_000, "view height {height}: {shapes} shapes painted"); + assert_eq!(app.session.state().unwrap().view().height, height); + } +} From a83af92eb26bfc6dad969531a4f1384bac260295 Mon Sep 17 00:00:00 2001 From: Capri <96988330+SusieeTheLinuxUser@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:34:23 +0100 Subject: [PATCH 273/900] wblock: write the source drawing's $INSUNITS and $MEASUREMENT (#2002) (#2023) * wblock: write the source drawing's $INSUNITS and $MEASUREMENT run_wblock built the written drawing from Drawing::new_imperial() and never copied the source's units, so every WBLOCK file declared inches ($INSUNITS 1) and imperial measurement ($MEASUREMENT 0) whatever the source: a block written from a metric drawing came back at 0.0254 of its size in any program that honours $INSUNITS on insert. The written drawing now takes the source's values for both variables, as AutoCAD's -WBLOCK does. A unitless source ($INSUNITS 0, kept by the reader per #1209) writes unitless. Co-Authored-By: GLM-5.3 * wblock: start from the source drawing's header and styles Clone the source header (resetting $INSBASE as before) and copy the multileader, table and multiline styles and the annotation scale list along with the other tables, so a block written from a metric drawing keeps its text size, current dimension style, limits and scales, not the imperial template's (review on #2023). Co-Authored-By: Claude Opus 5.5 * wblock_units: each WBLOCK call writes into its own TempDir The two tests shared one temp path and raced when cargo ran them in parallel (review on #2023). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: GLM-5.3 Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks.rs | 8 +++ crates/engine/tests/wblock_units.rs | 87 +++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 crates/engine/tests/wblock_units.rs diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 8cc248685..760b6921c 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -365,10 +365,18 @@ fn run_wblock(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string(); let src = s.doc()?; let mut d = cadcraft_doc::Drawing::new_imperial(); + // The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its + // units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches + // and scaled on insert, and its defaults (text size, current styles, annotation scales). + d.header = src.header.clone(); d.layers = src.layers.clone(); d.linetypes = src.linetypes.clone(); d.text_styles = src.text_styles.clone(); d.dim_styles = src.dim_styles.clone(); + d.mleader_styles = src.mleader_styles.clone(); + d.table_styles = src.table_styles.clone(); + d.mline_styles = src.mline_styles.clone(); + d.scales = src.scales.clone(); d.blocks = src.blocks.clone(); // The base point becomes the written drawing's origin, its insertion base: by default 0,0 for // objects and the block's base point for a block (`base` is then in block coordinates). diff --git a/crates/engine/tests/wblock_units.rs b/crates/engine/tests/wblock_units.rs new file mode 100644 index 000000000..8ba2dffad --- /dev/null +++ b/crates/engine/tests/wblock_units.rs @@ -0,0 +1,87 @@ +//! WBLOCK writes the source drawing's units: `$INSUNITS` and `$MEASUREMENT` of the written file +//! are the source's, for selected objects and for a block, as AutoCAD's `-WBLOCK` does. So are its +//! other settings and styles: a metric drawing's text size, dimension style and scale list. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::Drawing; +use serde_json::json; + +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +/// Writes "INSUNITS;MEASUREMENT" and, on a second line, the settings a metric drawing changes, so +/// the test can read them from the file that would be saved. +fn write(d: &Drawing, _path: &str) -> Result, String> { + Ok(format!("{};{}\n{}", d.header.i64("INSUNITS", -1), d.header.i64("MEASUREMENT", -1), settings(d)).into_bytes()) +} + +fn settings(d: &Drawing) -> String { + let mleader = d.mleader_styles.first().map(|m| format!("{m:?}")).unwrap_or_default(); + let table = d.table_styles.first().map(|t| format!("{t:?}")).unwrap_or_default(); + let limmax = d.header.point("LIMMAX"); + format!("{} {} {limmax:?} {} {mleader} {table}", d.header.str("DIMSTYLE", ""), d.header.f64("TEXTSIZE", -1.0), d.scales.len()) +} + +/// The file WBLOCK would save: line `n` of what [`write`] wrote. Each call writes into a folder +/// of its own, so tests running in parallel never read or delete each other's file. +fn wblock(s: &mut Session, p: serde_json::Value, n: usize) -> String { + let dir = TempDir::new("wblock-units"); + let path = dir.path_str("out.dxf"); + let mut p = p; + p["path"] = json!(path); + s.execute("wblock", &p).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + text.lines().nth(n).unwrap_or("").to_string() +} + +fn written(s: &mut Session, p: serde_json::Value) -> String { + wblock(s, p, 0) +} + +fn written_settings(s: &mut Session, p: serde_json::Value) -> String { + wblock(s, p, 1) +} + +fn line(s: &mut Session) -> String { + s.execute("line", &json!({ "points": [[0, 0], [2, 0]] })).unwrap()["handles"][0].as_str().unwrap().to_string() +} + +#[test] +fn wblock_keeps_the_source_drawing_units() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write, plot: None }); + let mut s = Session::new(); + // A metric drawing in metres, like the issue's metres.dxf (`--metric` then `insunits 6`). + s.new_drawing(true); + s.execute("units", &json!({ "insunits": 6 })).unwrap(); + let b = line(&mut s); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [b], "keep": "delete" })).unwrap(); + let c = line(&mut s); + + // Selected objects and a block by name both keep the source's units, not inches. + assert_eq!(written(&mut s, json!({ "handles": [c] })), "6;1"); + assert_eq!(written(&mut s, json!({ "name": "B" })), "6;1"); + + // The metric default (millimetres) and an imperial drawing keep their units too. + s.new_drawing(true); + let m = line(&mut s); + assert_eq!(written(&mut s, json!({ "handles": [m] })), "4;1"); + s.new_drawing(false); + let i = line(&mut s); + assert_eq!(written(&mut s, json!({ "handles": [i] })), "1;0"); +} + +#[test] +fn wblock_keeps_the_source_drawing_settings_and_styles() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write, plot: None }); + let mut s = Session::new(); + // A metric drawing: ISO-25, 2.5 mm text, A3 limits, metric multileader/table styles and scales. + s.new_drawing(true); + let source = settings(s.doc().unwrap()); + let l = line(&mut s); + assert_eq!(written_settings(&mut s, json!({ "handles": [l] })), source); + s.new_drawing(false); + assert_ne!(settings(s.doc().unwrap()), source, "the imperial template differs, so the check means something"); +} From 7cee28580d1a459856b8b65c1e8890514ac35243 Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Sat, 31 Oct 2026 15:34:27 +0800 Subject: [PATCH 274/900] fix(dxf): preserve 3D LEADER vertex elevations (#2245) (#2397) Co-authored-by: Zaxaerith <189452125+Zaxaerith@users.noreply.github.com> --- crates/io/src/dxf_read/entities.rs | 12 +- crates/io/tests/it/leader_vertex_elevation.rs | 106 ++++++++++++++++++ crates/io/tests/it/main.rs | 1 + 3 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 crates/io/tests/it/leader_vertex_elevation.rs diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index fc55fe335..12abae7da 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -201,7 +201,17 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef }) } "LEADER" => EntityKind::Leader(Leader { - vertices: t.pts(10).into_iter().map(|p| p.to3(0.0)).collect(), + // Each group 10 starts a vertex. Scope Y/Z to it so an omitted Z cannot + // shift a later vertex's elevation onto this one. + vertices: t + .all_f(10) + .into_iter() + .zip(tags.split(|tag| tag.code == 10).skip(1)) + .map(|(x, vertex)| { + let v = T(vertex); + Vec3::new(x, v.fd(20, 0.0), v.fd(30, 0.0)) + }) + .collect(), arrow: t.i(71).unwrap_or(1) != 0, spline: t.i(72).unwrap_or(0) != 0, style: t.s(3).unwrap_or_else(|| "Standard".into()), diff --git a/crates/io/tests/it/leader_vertex_elevation.rs b/crates/io/tests/it/leader_vertex_elevation.rs new file mode 100644 index 000000000..2566a861b --- /dev/null +++ b/crates/io/tests/it/leader_vertex_elevation.rs @@ -0,0 +1,106 @@ +//! LEADER vertex elevations survive the shared DXF read path and DWG bridge (#2245). + +use cadcraft_color::Color; +use cadcraft_doc::{Common, DimStyle, Drawing, EntityKind, Handle, Leader, Lineweight, Space}; +use cadcraft_dxf::Tag; +use cadcraft_geom::Vec3; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +type TestResult = Result>; + +fn drawing() -> TestResult { + let mut d = Drawing::new_metric(); + d.dim_styles.push(DimStyle { name: "Elevation".into(), ..DimStyle::default() }); + let common = Common { color: Color::Index(3), lineweight: Lineweight::Mm100(25), ltscale: 2.5, visible: false, ..Common::default() }; + for vertices in [ + vec![Vec3::new(1.0, 2.0, 4.0), Vec3::new(5.0, 6.0, 7.0), Vec3::new(9.0, 10.0, -3.0)], + vec![Vec3::new(1.0, 2.0, 0.0), Vec3::new(5.0, 6.0, 0.0), Vec3::new(9.0, 10.0, 0.0)], + ] { + for arrow in [false, true] { + for spline in [false, true] { + let leader = Leader { vertices: vertices.clone(), arrow, spline, style: "Elevation".into() }; + d.add(&Space::Model, common.clone(), EntityKind::Leader(leader))?; + } + } + } + Ok(d) +} + +fn check_round_trips(name: &str, binary: bool) -> TestResult { + let original = drawing()?; + for version in Version::ALL { + let mut d = original.clone(); + for pass in 1..=2 { + let bytes = write_with(&d, name, &SaveOptions { version: Some(version), binary })?; + d = read(&bytes, name)?; + assert_eq!(d.model.len(), original.model.len(), "{name} {version:?}, pass={pass}"); + for expected in original.model.iter() { + let actual = d.entity(expected.handle).ok_or("LEADER handle lost")?; + let (EntityKind::Leader(want), EntityKind::Leader(got)) = (&expected.kind, &actual.kind) else { + return Err("LEADER entity type changed".into()); + }; + assert_eq!(got.vertices, want.vertices, "XYZ/order: {name} {version:?}, pass={pass}, {:?}", expected.handle); + assert_eq!((got.arrow, got.spline, &got.style), (want.arrow, want.spline, &want.style), "LEADER properties"); + assert_eq!(actual.common, expected.common, "Common properties: {name} {version:?}, pass={pass}"); + } + } + } + Ok(()) +} + +#[test] +fn dxf_preserves_leader_vertex_elevations() -> TestResult { + for binary in [false, true] { + check_round_trips("leader.dxf", binary)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dwg_preserves_leader_vertex_elevations() -> TestResult { + check_round_trips("leader.dwg", false) +} + +#[test] +fn missing_z_defaults_only_the_corresponding_vertex() -> TestResult { + let vertices = [Vec3::new(1.0, 2.0, 4.0), Vec3::new(5.0, 6.0, 7.0), Vec3::new(9.0, 10.0, -3.0)]; + // All eight presence patterns include wholly 2D input and omitted first/middle/last Zs. + // Author the groups directly, independently of CADCraft's entity writer. + for z_mask in 0..8 { + let mut tags = vec![ + Tag::s(0, "SECTION"), + Tag::s(2, "ENTITIES"), + Tag::s(0, "LEADER"), + Tag::s(5, "10"), + Tag::s(100, "AcDbEntity"), + Tag::s(8, "0"), + Tag::s(100, "AcDbLeader"), + Tag::s(3, "Standard"), + Tag::i(71, 0), + Tag::i(72, 1), + Tag::i(76, 3), + ]; + let mut expected = Vec::new(); + for (i, p) in vertices.iter().enumerate() { + tags.push(Tag::f(10, p.x)); + let has_z = z_mask & (1 << i) != 0; + if has_z { + // Y and Z can appear in either order within this vertex. + tags.push(Tag::f(30, p.z)); + } + tags.push(Tag::f(20, p.y)); + expected.push(Vec3::new(p.x, p.y, if has_z { p.z } else { 0.0 })); + } + tags.extend([Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")]); + let dxf = cadcraft_dxf::write_ascii(&tags); + let d = read(dxf.as_bytes(), "missing-z.dxf")?; + let e = d.entity(Handle(0x10)).ok_or("LEADER missing")?; + let EntityKind::Leader(l) = &e.kind else { return Err("expected LEADER".into()) }; + assert_eq!(l.vertices, expected, "Z presence mask {z_mask:03b}"); + assert!(!l.arrow && l.spline); + assert_eq!(l.style, "Standard"); + assert_eq!(e.common, Common::default()); + } + Ok(()) +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 7f6ad8f20..52f37068a 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -33,6 +33,7 @@ mod hatch_pattern_def; mod helix_roundtrip; mod layout_paper_units; mod layout_plot_window; +mod leader_vertex_elevation; #[cfg(not(target_arch = "wasm32"))] mod low_handseed; mod mleader_content; 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 275/900] 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 276/900] 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 277/900] 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 278/900] 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 279/900] 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 280/900] 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 281/900] 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 282/900] 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 b0b2aba23e0244819715ae91ce804a71aa6abdee Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:32:24 +0100 Subject: [PATCH 283/900] Reject non-finite arguments in CAL min() and max() (#2547) Found while testing crates/engine/src/cmd/utility/calc.rs:~355-360 (call, "min" | "max" branch using f64::min/f64::max) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd/utility/calc.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/engine/src/cmd/utility/calc.rs b/crates/engine/src/cmd/utility/calc.rs index 05c6fc52e..0c0d29b32 100644 --- a/crates/engine/src/cmd/utility/calc.rs +++ b/crates/engine/src/cmd/utility/calc.rs @@ -333,6 +333,9 @@ fn call(name: &str, args: &[Val]) -> Result { "min" | "max" => { arity(1, MAX_ARGS)?; let vs = (0..args.len()).map(n).collect::, _>>()?; + if vs.iter().any(|v| !v.is_finite()) { + return Err("result is not a finite number".into()); + } let f = if name == "min" { f64::min } else { f64::max }; Ok(Val::Num(vs.into_iter().reduce(f).unwrap_or(0.0))) } @@ -597,6 +600,10 @@ mod tests { assert!(ev("[1").is_err()); assert!(ev(&"[".repeat(5000)).is_err()); assert_eq!(ev("min(3,1,2)"), Ok(Val::Num(1.0))); + assert!(ev("min(sqrt(-1), 5)").is_err()); + assert!(ev("max(5, ln(-1))").is_err()); + assert!(ev("min(exp(1000), 5)").is_err()); + assert!(ev("max(exp(1000), 5)").is_err()); assert_eq!(ev("1e-3*2"), Ok(Val::Num(0.002))); assert!(ev("max(1,2,3,4,5,6,7,8,9)").is_err()); } From c254c51474e859377b2ab1e0ae2376c67ca12b47 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:32:28 +0100 Subject: [PATCH 284/900] Reject nan and inf text values in SETVAR for real variables (#2546) Found while testing crates/engine/src/sysvars.rs:~404-425 (generic fallthrough in set: String branch, then the `Some(HVal::Real(_))` arm) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/sysvars.rs | 2 +- crates/engine/src/tests.rs | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index b532f66dd..60af821d7 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -424,7 +424,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { // Keep the header type stable for known numeric vars. match d.header.get(&n) { Some(cadcraft_doc::HVal::Real(_)) => { - d.header.set_f64(&n, val.as_f64().ok_or_else(bad)?); + d.header.set_f64(&n, val.as_f64().filter(|f| f.is_finite()).ok_or_else(bad)?); return Ok(()); } Some(cadcraft_doc::HVal::Int(_)) => { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1f3d0e8e1..75cfd468e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1465,3 +1465,16 @@ fn array_counts_reject_invalid_values() { } s.execute("arraypolar", &json!({"center": [0, 0], "count": 1, "associative": false})).unwrap(); } + +#[test] +fn setvar_rejects_non_finite_text_for_real_variables() { + let mut s = Session::new(); + for name in ["LTSCALE", "TEXTSIZE", "SNAPANG"] { + let before = s.execute("getvar", &json!({"name": name})).unwrap(); + for text in ["nan", "inf", "-inf"] { + let r = s.execute("setvar", &json!({"name": name, "value": text})); + assert!(r.is_err(), "SETVAR {name} {text} was accepted"); + assert_eq!(s.execute("getvar", &json!({"name": name})).unwrap(), before); + } + } +} From add1fd3528aa7b31651e5815b72f0ea4308d10e1 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:32:32 +0100 Subject: [PATCH 285/900] Fix LISP atof returning a wrong value for out-of-range exponents (#2533) Found while testing crates/engine/src/lisp/builtins/strings.rs:64-72 (atof) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/lisp/builtins/strings.rs | 45 ++++++++++++++++------ crates/engine/src/lisp/tests.rs | 9 +++++ 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/lisp/builtins/strings.rs b/crates/engine/src/lisp/builtins/strings.rs index 46d985bf1..853e0656f 100644 --- a/crates/engine/src/lisp/builtins/strings.rs +++ b/crates/engine/src/lisp/builtins/strings.rs @@ -60,20 +60,43 @@ pub(super) fn atoi(a: &[Value]) -> R { Ok(Value::Int(t.get(..end).and_then(|n| n.parse::().ok()).map(|n| n as i32).unwrap_or(0))) } -/// C's `atof`: the longest number at the start; 0.0 when there is none. +/// C's `atof`: the number token at the start; 0.0 when there is none. +/// An overflowing token clamps to the largest finite value of its sign. pub(super) fn atof(a: &[Value]) -> R { arity(a, 1, 1)?; let s = string(&a[0])?; - // The longest prefix (of the first 64 characters) that reads as a finite number. - let t: String = s.trim_start().chars().take(64).collect(); - let ends: Vec = t.char_indices().map(|(i, _)| i).skip(1).chain(std::iter::once(t.len())).collect(); - let v = ends.iter().rev().find_map(|&e| t.get(..e).and_then(|p| p.parse::().ok()).filter(|v| v.is_finite() && !p_is_word(&t[..e]))); - Ok(Value::Real(v.unwrap_or(0.0))) -} - -/// Words Rust reads as numbers that C's `atof` doesn't ("inf", "nan", "infinity"). -fn p_is_word(p: &str) -> bool { - p.chars().any(|c| c.is_ascii_alphabetic() && !matches!(c, 'e' | 'E')) + let b = s.trim_start().as_bytes(); + let digits = |mut i: usize| { + while b.get(i).is_some_and(u8::is_ascii_digit) { + i += 1; + } + i + }; + let mut i = usize::from(matches!(b.first(), Some(b'-' | b'+'))); + let int_end = digits(i); + let mut end = int_end; + let mut mantissa = int_end > i; + if b.get(end) == Some(&b'.') { + let frac_end = digits(end + 1); + if mantissa || frac_end > end + 1 { + mantissa = true; + end = frac_end; + } + } + if mantissa && matches!(b.get(end), Some(b'e' | b'E')) { + i = end + 1 + usize::from(matches!(b.get(end + 1), Some(b'-' | b'+'))); + let exp_end = digits(i); + if exp_end > i { + end = exp_end; + } + } + let v = if mantissa { b.get(..end).and_then(|t| std::str::from_utf8(t).ok()).and_then(|t| t.parse::().ok()) } else { None }; + let v = match v { + Some(v) if v.is_finite() => v, + Some(v) if v.is_infinite() => f64::MAX.copysign(v), + _ => 0.0, + }; + Ok(Value::Real(v)) } pub(super) fn chr(a: &[Value]) -> R { diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 0cb31f395..0ed4b22fd 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -1039,3 +1039,12 @@ fn a_lisp_value_at_a_prompt_is_not_evaluated_again() { }); assert_eq!(r, Some(4.0)); } + +#[test] +fn atof_out_of_range_exponent_reads_whole_token() { + let mut s = Session::new(); + // Overflow must not fall back to a shorter prefix such as "1e40". + assert_eq!(ok(&mut s, "(> (atof \"1e400\") 1e300)"), "T"); + assert_eq!(ok(&mut s, "(< (atof \"-1e400\") -1e300)"), "T"); + assert_eq!(ok(&mut s, "(= (atof \"1e-400\") 0.0)"), "T"); +} From e28ed2018ad46cbe0c5ff6440efbd515df3d6e9a Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:32:35 +0100 Subject: [PATCH 286/900] Clamp Bounds2 width/height instead of overflowing to infinity (#2532) Found while testing crates/geom/src/bounds.rs:49-54 (width, height) Co-authored-by: Claude Haiku 5.5 --- crates/geom/src/bounds.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/geom/src/bounds.rs b/crates/geom/src/bounds.rs index c52efdef6..ba5b7175d 100644 --- a/crates/geom/src/bounds.rs +++ b/crates/geom/src/bounds.rs @@ -9,6 +9,12 @@ pub struct Bounds2 { pub max: Vec2, } +/// `max - min`, clamped to `f64::MAX` when finite endpoints make it overflow. +fn span(min: f64, max: f64) -> f64 { + let d = max - min; + if d.is_infinite() && min.is_finite() && max.is_finite() { f64::MAX } else { d } +} + impl Default for Bounds2 { fn default() -> Self { Bounds2::EMPTY @@ -47,10 +53,10 @@ impl Bounds2 { Bounds2 { min: self.min.min(o.min), max: self.max.max(o.max) } } pub fn width(&self) -> f64 { - if self.is_empty() { 0.0 } else { self.max.x - self.min.x } + if self.is_empty() { 0.0 } else { span(self.min.x, self.max.x) } } pub fn height(&self) -> f64 { - if self.is_empty() { 0.0 } else { self.max.y - self.min.y } + if self.is_empty() { 0.0 } else { span(self.min.y, self.max.y) } } pub fn center(&self) -> Vec2 { if self.is_empty() { @@ -98,4 +104,14 @@ mod tests { assert_eq!(b.center().y, 5.0); assert_eq!(Bounds2::EMPTY.center(), Vec2::ZERO); } + + #[test] + fn width_and_height_stay_finite_for_opposite_large_coordinates() { + let b = Bounds2::new(Vec2::new(-1e308, -1e308), Vec2::new(1e308, 1e308)); + assert_eq!(b.width(), f64::MAX); + assert_eq!(b.height(), f64::MAX); + let b = Bounds2::new(Vec2::new(1e308, 0.0), Vec2::new(1.6e308, 10.0)); + assert!((b.width() / 1e308 - 0.6).abs() < 1e-12); + assert_eq!(b.height(), 10.0); + } } From 0575a7629157568e71f0370e8f5e2c5e685261fa Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:32:39 +0100 Subject: [PATCH 287/900] Reject out-of-range OSMODE values in SETVAR instead of wrapping (#2531) Found while testing crates/engine/src/sysvars.rs:282 (set, "OSMODE" branch) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/sysvars.rs | 4 +++- crates/engine/src/tests.rs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 60af821d7..930a9bad1 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -281,7 +281,9 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") }; let st = &mut s.settings; match n.as_str() { - "OSMODE" => st.osmode = v.as_u64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())).ok_or_else(bad)? as u32 & 0x7fff, + "OSMODE" => { + st.osmode = v.as_u64().or_else(|| v.as_str().and_then(|s| s.trim().parse().ok())).filter(|x| *x <= 0x7fff).ok_or_else(bad)? as u32 + } // The `color` command's input: ByLayer, ByBlock, a name, an index or a true colour. "CECOLOR" => crate::cmd::set_current_color_value(s, v).ok_or_else(bad)?, "OSNAPHATCH" => st.osnaphatch = as_bool(v).ok_or_else(bad)?, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 75cfd468e..fec3fbb18 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -653,6 +653,18 @@ fn setvar_rejects_out_of_range_units() { assert_ne!(s.doc().unwrap().header.i64("LUNITS", 2), 9); } +#[test] +fn setvar_rejects_out_of_range_osmode() { + let mut s = Session::new(); + s.execute("setvar", &json!({"name": "OSMODE", "value": 4133})).unwrap(); + for v in [4294967296u64, 65536, 32768] { + assert!(s.execute("setvar", &json!({"name": "OSMODE", "value": v})).is_err(), "{v}"); + assert_eq!(sysvars::get(&s, "OSMODE"), Some(json!(4133)), "{v}"); + } + s.execute("setvar", &json!({"name": "OSMODE", "value": 0x7fff})).unwrap(); + assert_eq!(sysvars::get(&s, "OSMODE"), Some(json!(0x7fff))); +} + #[test] fn dynamic_input_pointer_settings() { let mut s = Session::new(); From fc9d0565762d59b64a327590d15bc0b4a3303e39 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 31 Oct 2026 15:32:42 +0100 Subject: [PATCH 288/900] Refuse mirror lines whose points are closer than the geometry EPS (#2555) * Refuse mirror lines whose points are closer than the geometry EPS Found while testing crates/engine/src/cmd/modify/transform.rs:run_mirror (coincidence check `a.near(b, 1e-12)`), with crates/geom/src/mat.rs:43-47 (Mat3::mirror) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 * mirror: the interactive prompt also refuses points closer than the geometry EPS Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Haiku 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/modify/select_then.rs | 2 +- crates/engine/src/cmd/modify/transform.rs | 2 +- crates/engine/tests/it/main.rs | 1 + .../engine/tests/it/mirror_degenerate_line.rs | 17 +++++++++++++++++ 4 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 crates/engine/tests/it/mirror_degenerate_line.rs diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 10bf08399..f9a970ebd 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -445,7 +445,7 @@ impl Interactive for SelectThen { Ok(Step::Done) } (Op::Mirror, 1, Input::Point(p)) => { - if p.near(self.pts[0], 1e-12) { + if p.near(self.pts[0], cadcraft_geom::EPS) { return Err(EngineError::Other("Mirror line points must differ.".into())); } self.pts.push(p); diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 5a86d9e07..18ff4866c 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -100,7 +100,7 @@ pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let a = point_req("mirror", p, "p1")?; let b = point_req("mirror", p, "p2")?; - if a.near(b, 1e-12) { + if a.near(b, cadcraft_geom::EPS) { return Err(bad("mirror", "mirror line points coincide")); } let erase_src = bool_or(p, "erase", false); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 5c0a37f45..8009cf4d3 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -71,6 +71,7 @@ mod malformed_handles; mod matchprop; mod measure_distance_snapping; mod metric_linetypes; +mod mirror_degenerate_line; mod mleader_content; mod mleader_remember; mod mline; diff --git a/crates/engine/tests/it/mirror_degenerate_line.rs b/crates/engine/tests/it/mirror_degenerate_line.rs new file mode 100644 index 000000000..afa7a32a1 --- /dev/null +++ b/crates/engine/tests/it/mirror_degenerate_line.rs @@ -0,0 +1,17 @@ +//! MIRROR refuses a mirror line whose points are closer than the geometry tolerance. + +use cadcraft_engine::Session; +use serde_json::json; + +#[test] +fn nearly_coincident_mirror_points_are_refused() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 5], [10, 5]] })).unwrap(); + let before = s.doc().unwrap().model.iter().count(); + for erase in [false, true] { + let r = s.execute("mirror", &json!({ "handles": ["100"], "p1": [0, 0], "p2": [5e-10, 0], "erase": erase })); + let err = r.expect_err("mirror line is degenerate").to_string(); + assert!(err.contains("mirror line points coincide"), "{err}"); + } + assert_eq!(s.doc().unwrap().model.iter().count(), before); +} From f18cdcbcac29627f25cf4bd7797358896f000089 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:32:46 +0700 Subject: [PATCH 289/900] Add -UNITS; show due surveyor bearings as one letter (#2562) * Add -UNITS; show due surveyor bearings as one letter -UNITS asks for the length format and precision, the angle format and precision, the direction of angle 0 and whether angles turn clockwise, with AutoCAD 2024's prompts, listings, defaults and messages. As in AutoCAD, each answer is kept as it is given, and choosing another format resets its precision to 4. The direction is typed in the chosen angle format and turns as ANGDIR says. Surveyor's units show a bearing that is due north, south, east or west as that letter ("E"), except to whole degrees ("N 90d E"), as AutoCAD's ANGTOS does. Co-Authored-By: Claude Opus 5.5 * units: read a due bearing typed as one letter (E, N, W, S) in surveyor's units Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/props.rs | 2 + crates/engine/src/cmd/props/dash_units.rs | 220 +++++++++++++++++++++ crates/engine/src/units.rs | 60 +++++- crates/engine/tests/it/dash_units.rs | 223 ++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 5 files changed, 505 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/props/dash_units.rs create mode 100644 crates/engine/tests/it/dash_units.rs diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 43f2aca38..45199b12c 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -2,6 +2,7 @@ //! RENAME. mod chprop; +mod dash_units; mod matchprop; mod rename; @@ -38,6 +39,7 @@ pub fn specs() -> Vec { CommandSpec::new("lweight", "Lineweight...", run_lweight).menu(&["Format", "Lineweight..."]).alias(&["lw", "lineweight"]).params("{lineweight: mm | ByLayer}"), CommandSpec::new("ltscale", "Linetype Scale", run_ltscale).alias(&["lts"]).params("{scale}").interactive(|_| Ok(Box::new(LtscaleM))), CommandSpec::new("units", "Units...", run_units).menu(&["Format", "Units..."]).alias(&["un"]).params("{lunits?: 1..5, luprec?: 0..8, aunits?: 0..4, auprec?: 0..8, insunits?}"), + CommandSpec::new("-units", "Units", run_units).alias(&["-un"]).params("(as UNITS)").interactive(|_| Ok(Box::new(dash_units::DashUnits::default()))), CommandSpec::new("thickness", "Thickness", run_thickness) .menu(&["Format", "Thickness"]) .params("{thickness} (THICKNESS: the 3D thickness given to new lines, arcs, circles, points and polylines; may be negative) → {thickness}") diff --git a/crates/engine/src/cmd/props/dash_units.rs b/crates/engine/src/cmd/props/dash_units.rs new file mode 100644 index 000000000..a10153f56 --- /dev/null +++ b/crates/engine/src/cmd/props/dash_units.rs @@ -0,0 +1,220 @@ +//! -UNITS: the drawing's units at the command line, with AutoCAD 2024's prompts and listings. + +use std::f64::consts::TAU; + +use crate::units::{AngleSettings, format_angle}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +const REPORT_FORMATS: [&str; 10] = [ + "Report formats: (Examples)", + " 1. Scientific 1.55E+01", + " 2. Decimal 15.50", + " 3. Engineering 1'-3.50\"", + " 4. Architectural 1'-3 1/2\"", + " 5. Fractional 15 1/2", + "With the exception of Engineering and Architectural formats,", + "these formats can be used with any basic unit of measurement.", + "For example, Decimal mode is perfect for metric units as well", + "as decimal English units.", +]; + +const ANGLE_SYSTEMS: [&str; 6] = [ + "Systems of angle measure: (Examples)", + " 1. Decimal degrees 45.0000", + " 2. Degrees/minutes/seconds 45d0'0\"", + " 3. Grads 50.0000g", + " 4. Radians 0.7854r", + " 5. Surveyor's units N 45d0'0\" E", +]; + +const DENOMINATOR: &str = "Enter denominator of smallest fraction to display"; + +/// The drawing's units, as -UNITS shows and asks them. +struct Units { + lunits: i64, + luprec: i64, + aunits: i64, + auprec: i64, + angbase: f64, + clockwise: bool, +} + +impl Units { + fn of(s: &Session) -> Units { + let Ok(d) = s.doc() else { return Units { lunits: 2, luprec: 4, aunits: 0, auprec: 0, angbase: 0.0, clockwise: false } }; + let h = &d.header; + let angbase = h.f64("ANGBASE", 0.0); + Units { + lunits: h.i64("LUNITS", 2).clamp(1, 5), + luprec: h.i64("LUPREC", 4).clamp(0, 8), + aunits: h.i64("AUNITS", 0).clamp(0, 4), + auprec: h.i64("AUPREC", 0).clamp(0, 8), + angbase: if angbase.is_finite() { angbase } else { 0.0 }, + clockwise: h.i64("ANGDIR", 0) != 0, + } + } + + /// Architectural and fractional units give their precision as a fraction's denominator. + fn fractional(&self) -> bool { + matches!(self.lunits, 4 | 5) + } + + /// Direction `a` (radians counterclockwise from +X) in the angle format, measured as the + /// drawing measures angles but from +X: -UNITS shows north as 270 when angles turn clockwise. + fn direction_text(&self, a: f64) -> String { + format_angle(if self.clockwise { -a } else { a }, self.aunits, self.auprec) + } + + /// A typed direction of angle 0, in radians counterclockwise from +X: an amount in the angle + /// format, or with its own unit (`45d`, `0.5r`, `100g`, a bearing `N45dE`, and in surveyor's + /// units N, E, S or W), measured from +X as the drawing measures angles. + fn direction(&self, t: &str) -> Option { + let cardinal = match t.trim().to_ascii_lowercase().as_str() { + "e" if self.aunits == 4 => Some(0.0), + "n" if self.aunits == 4 => Some(90f64.to_radians()), + "w" if self.aunits == 4 => Some(180f64.to_radians()), + "s" if self.aunits == 4 => Some(270f64.to_radians()), + _ => None, + }; + let a = cardinal.or_else(|| AngleSettings { aunits: self.aunits, ..AngleSettings::default() }.amount(t))?; + let a = if self.clockwise { -a } else { a }; + a.is_finite().then(|| a.rem_euclid(TAU)) + } +} + +/// An integer answer in `lo..=hi`, or AutoCAD's message for one that isn't. +fn integer(t: &str, lo: i64, hi: i64) -> Result { + let v = t.trim().parse::().map_err(|_| EngineError::Other("Requires an integer value.".into()))?; + if (lo..=hi).contains(&v) { Ok(v) } else { Err(EngineError::Other(format!("Requires an integer between {lo} and {hi}."))) } +} + +#[derive(Clone, Copy, Default)] +enum Ask { + #[default] + LengthFormat, + LengthPrecision, + AngleFormat, + AnglePrecision, + Direction, + Clockwise, +} + +/// -UNITS: the length format and precision, the angle format and precision, the direction of +/// angle 0 and whether angles turn clockwise, asked in that order. As in AutoCAD, each answer is +/// kept as it is given (Esc keeps the ones before it), and choosing another format resets its +/// precision to 4, the precision then offered. +#[derive(Default)] +pub(super) struct DashUnits { + ask: Ask, +} + +impl Interactive for DashUnits { + fn name(&self) -> &'static str { + "-UNITS" + } + + fn begin(&mut self, s: &mut Session) -> Result { + for l in REPORT_FORMATS { + s.echo(l); + } + Ok(Step::Continue) + } + + fn prompt(&self, s: &Session) -> Prompt { + let u = Units::of(s); + match self.ask { + Ask::LengthFormat => Prompt::new("Enter choice, 1 to 5", Accept::NUMBER).default(u.lunits.to_string()), + Ask::LengthPrecision if u.fractional() => { + Prompt::new("(1, 2, 4, 8, 16, 32, 64, 128, or 256)", Accept::NUMBER).default((1_i64 << u.luprec).to_string()) + } + Ask::LengthPrecision => { + Prompt::new("Enter number of digits to right of decimal point (0 to 8)", Accept::NUMBER).default(u.luprec.to_string()) + } + Ask::AngleFormat => Prompt::new("Enter choice, 1 to 5", Accept::NUMBER).default((u.aunits + 1).to_string()), + Ask::AnglePrecision => { + Prompt::new("Enter number of fractional places for display of angles (0 to 8)", Accept::NUMBER).default(u.auprec.to_string()) + } + Ask::Direction => { + Prompt::new(format!("Enter direction for angle {}", u.direction_text(0.0)), Accept::TEXT).default(u.direction_text(u.angbase)) + } + Ask::Clockwise => Prompt::new("Measure angles clockwise?", Accept::TEXT).kw(&["Yes", "No"]).default(if u.clockwise { "Y" } else { "N" }), + } + } + + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let u = Units::of(s); + let text = match &i { + Input::Text(t) => Some(t.as_str()), + Input::Enter => None, + Input::Keyword(k) => Some(k.as_str()), + _ => return Ok(Step::Continue), + }; + let h = &mut s.doc_mut()?.header; + match self.ask { + Ask::LengthFormat => { + let l = text.map_or(Ok(u.lunits), |t| integer(t, 1, 5))?; + if l != u.lunits { + h.set_i64("LUNITS", l); + h.set_i64("LUPREC", 4); + } + self.ask = Ask::LengthPrecision; + if matches!(l, 4 | 5) { + s.echo(DENOMINATOR); + } + } + Ask::LengthPrecision => { + let prec = if u.fractional() { + let den = text.map_or(Some(1 << u.luprec), |t| t.trim().parse::().ok()); + let Some(p) = den.and_then(|d| (0..=8).find(|p| 1_i64 << p == d)) else { + s.echo("Invalid choice."); + s.echo(DENOMINATOR); + return Ok(Step::Continue); + }; + p + } else { + text.map_or(Ok(u.luprec), |t| integer(t, 0, 8))? + }; + h.set_i64("LUPREC", prec); + self.ask = Ask::AngleFormat; + for l in ANGLE_SYSTEMS { + s.echo(l); + } + } + Ask::AngleFormat => { + let a = text.map_or(Ok(u.aunits + 1), |t| integer(t, 1, 5))? - 1; + if a != u.aunits { + h.set_i64("AUNITS", a); + h.set_i64("AUPREC", 4); + } + self.ask = Ask::AnglePrecision; + } + Ask::AnglePrecision => { + h.set_i64("AUPREC", text.map_or(Ok(u.auprec), |t| integer(t, 0, 8))?); + self.ask = Ask::Direction; + let u = Units::of(s); + s.echo(format!("Direction for angle {}:", u.direction_text(0.0))); + for (name, deg) in [("East 3", 0.0), ("North 12", 90.0), ("West 9", 180.0), ("South 6", 270.0)] { + s.echo(format!(" {name} o'clock = {}", u.direction_text(f64::to_radians(deg)))); + } + } + Ask::Direction => { + if let Some(t) = text { + let a = u.direction(t).ok_or_else(|| EngineError::Other("Requires valid numeric angle or two points.".into()))?; + h.set_f64("ANGBASE", a); + } + self.ask = Ask::Clockwise; + } + Ask::Clockwise => { + let clockwise = match text.map(|t| t.trim().trim_start_matches('_').to_ascii_lowercase()) { + None => u.clockwise, + Some(t) if t == "y" || t == "yes" => true, + Some(t) if t == "n" || t == "no" => false, + Some(_) => return Err(EngineError::Other("Invalid option keyword.".into())), + }; + h.set_i64("ANGDIR", i64::from(clockwise)); + return Ok(Step::Done); + } + } + Ok(Step::Continue) + } +} diff --git a/crates/engine/src/units.rs b/crates/engine/src/units.rs index 3c6f3456e..560551f1c 100644 --- a/crates/engine/src/units.rs +++ b/crates/engine/src/units.rs @@ -172,7 +172,16 @@ pub fn format_angle(a: f64, aunits: i64, auprec: i64) -> String { } else { ("S", "E", deg - 270.0) }; - format!("{ns} {} {ew}", format_dms(ang, prec)) + // A bearing shown as due north, south, east or west is that letter, as AutoCAD 2024 + // shows it ("E" for 0), except to whole degrees ("N 90d E"). + let dms = format_dms(ang, prec); + if prec > 0 && dms == format_dms(0.0, prec) { + ns.to_string() + } else if prec > 0 && dms == format_dms(90.0, prec) { + ew.to_string() + } else { + format!("{ns} {dms} {ew}") + } } _ => format!("{:.*}", prec, wrap_full_turn(deg, 360.0, prec)), } @@ -332,6 +341,9 @@ fn parse_units(s: &str, aunits: i64) -> Option<(f64, bool)> { ((num(g)? * 0.9).to_radians(), false) } else if let Some(b) = bearing(&t) { (b, true) + } else if let Some(b) = (aunits == 4).then(|| cardinal(&t)).flatten() { + // A due bearing as surveyor's units show it: one letter. + (b, true) } else if let Some(v) = num(&t) { let a = match aunits { 2 => (v * 0.9).to_radians(), @@ -345,6 +357,17 @@ fn parse_units(s: &str, aunits: i64) -> Option<(f64, bool)> { v.0.is_finite().then_some(v) } +/// A due bearing (`n`, `e`, `s`, `w`, lower case) as radians counterclockwise from +X. +fn cardinal(t: &str) -> Option { + match t { + "e" => Some(0.0), + "n" => Some(PI / 2.0), + "w" => Some(PI), + "s" => Some(1.5 * PI), + _ => None, + } +} + /// A surveyor's bearing (`n45d30'e`, lower case) as radians counterclockwise from +X. fn bearing(t: &str) -> Option { let north = t.starts_with('n'); @@ -542,6 +565,41 @@ mod tests { } } + #[test] + fn surveyors_units_read_a_due_bearing_typed_as_one_letter() { + // What surveyor's units show for a due bearing can be typed back, e.g. `@10 Session { + let mut s = Session::new(); + let h = &mut s.doc_mut().unwrap().header; + h.set_i64("LUNITS", u.0); + h.set_i64("LUPREC", u.1); + h.set_i64("AUNITS", u.2); + h.set_i64("AUPREC", u.3); + h.set_f64("ANGBASE", u.4); + h.set_i64("ANGDIR", u.5); + s +} + +fn units(s: &Session) -> Units { + let h = &s.doc().unwrap().header; + (h.i64("LUNITS", 2), h.i64("LUPREC", 4), h.i64("AUNITS", 0), h.i64("AUPREC", 0), h.f64("ANGBASE", 0.0), h.i64("ANGDIR", 0)) +} + +fn same(a: Units, b: Units) -> bool { + (a.0, a.1, a.2, a.3, a.5) == (b.0, b.1, b.2, b.3, b.5) && (a.4 - b.4).abs() <= 1e-12 +} + +fn run(s: &mut Session, answers: &str) { + s.cmdline(&format!("(command \"_.-UNITS\" {answers})")).unwrap(); + assert!(s.running.is_none(), "{answers}: {}", s.prompt_text()); +} + +#[test] +fn the_measured_scripts_set_the_units() { + let cases: [(Units, &str, Units); 21] = [ + (DEFAULT, "4 16 1 0 0 \"_N\"", (4, 4, 0, 0, 0.0, 0)), + (DEFAULT, "3 2 2 4 90 \"_Y\"", (3, 2, 1, 4, FRAC_PI_2, 1)), + (DEFAULT, "2 3 3 2 100 \"_N\"", (2, 3, 2, 2, FRAC_PI_2, 0)), + (DEFAULT, "5 8 5 2 \"N\" \"_N\"", (5, 3, 4, 2, FRAC_PI_2, 0)), + ((4, 3, 1, 2, 0.5, 1), "\"\" \"\" \"\" \"\" \"\" \"\"", (4, 3, 1, 2, 0.5, 1)), + ((2, 4, 0, 0, FRAC_PI_2, 1), "2 4 1 0 45 \"_N\"", (2, 4, 0, 0, 5.497787143782137, 0)), + (DEFAULT, "1 2 4 3 30 \"_N\"", (1, 2, 3, 3, 4.867258771281656, 0)), + ((2, 2, 0, 2, 0.0, 0), "3 \"\" 2 \"\" \"\" \"\"", (3, 4, 1, 4, 0.0, 0)), + ((2, 2, 0, 2, 0.0, 0), "2 \"\" 1 \"\" \"\" \"\"", (2, 2, 0, 2, 0.0, 0)), + (DEFAULT, "4 3 \"\" \"\" \"\" \"\" \"\"", (4, 4, 0, 0, 0.0, 0)), + ((2, 4, 0, 0, 0.0, 1), "2 4 5 4 \"N45dE\" \"\"", (2, 4, 4, 4, 5.497787143782137, 1)), + (DEFAULT, "6 \"\" \"\" \"\" \"\" \"\" \"\"", (2, 4, 0, 0, 0.0, 0)), + ((2, 2, 0, 0, 0.0, 0), "4 \"\" \"\" \"\" \"\" \"\"", (4, 4, 0, 0, 0.0, 0)), + ((5, 6, 0, 0, 0.0, 0), "\"\" \"\" \"\" \"\" \"\" \"\"", (5, 6, 0, 0, 0.0, 0)), + ((2, 4, 0, 0, 0.0, 1), "\"\" \"\" 5 \"\" \"N\" \"\"", (2, 4, 4, 4, 4.712388980384689, 1)), + ((2, 4, 3, 4, 0.0, 0), "\"\" \"\" \"\" \"\" \"45d\" \"\"", (2, 4, 3, 4, 0.7853981633974482, 0)), + (DEFAULT, "5 1 \"\" \"\" \"\" \"\"", (5, 0, 0, 0, 0.0, 0)), + ((1, 7, 0, 7, 0.0, 0), "3 \"\" 1 \"\" \"\" \"\"", (3, 4, 0, 7, 0.0, 0)), + (DEFAULT, "\"\" \"\" \"\" \"\" \"\" \"Yes\"", (2, 4, 0, 0, 0.0, 1)), + ((2, 4, 2, 6, 0.0, 0), "\"\" \"\" \"\" \"\" \"\" \"\"", (2, 4, 2, 6, 0.0, 0)), + ((2, 4, 4, 2, 0.0, 1), "\"\" \"\" \"\" \"\" \"S45dE\" \"\"", (2, 4, 4, 2, 0.7853981633974482, 1)), + ]; + for (from, answers, to) in cases { + let mut s = session(from); + run(&mut s, answers); + assert!(same(units(&s), to), "{answers}: {:?}, AutoCAD {to:?}", units(&s)); + } +} + +/// The prompt, after the command's name. +fn asks(s: &Session) -> String { + let p = s.prompt_text(); + p.strip_prefix("-UNITS ").unwrap_or(&p).to_string() +} + +fn ends_with(s: &Session, lines: &[&str]) -> bool { + s.log.len() >= lines.len() && s.log[s.log.len() - lines.len()..].iter().zip(lines).all(|(a, b)| a == b) +} + +#[test] +fn prompts_and_listings_show_the_drawings_units() { + // Architectural to 1/8, degrees/minutes/seconds to 2 places, angle 0 at 0.5 radians, clockwise. + let mut s = session((4, 3, 1, 2, 0.5, 1)); + s.cmdline("-units").unwrap(); + assert!(s.log.iter().any(|l| l == " 4. Architectural 1'-3 1/2\""), "{:?}", s.log); + assert_eq!(asks(&s), "Enter choice, 1 to 5 <4>:"); + s.cmdline("").unwrap(); + assert!(ends_with(&s, &["Enter denominator of smallest fraction to display"]), "{:?}", s.log); + assert_eq!(asks(&s), "(1, 2, 4, 8, 16, 32, 64, 128, or 256) <8>:"); + s.cmdline("").unwrap(); + assert!(ends_with(&s, &[" 4. Radians 0.7854r", " 5. Surveyor's units N 45d0'0\" E"]), "{:?}", s.log); + assert_eq!(asks(&s), "Enter choice, 1 to 5 <2>:"); + s.cmdline("").unwrap(); + assert_eq!(asks(&s), "Enter number of fractional places for display of angles (0 to 8) <2>:"); + s.cmdline("").unwrap(); + let directions = [ + "Direction for angle 0d0':", + " East 3 o'clock = 0d0'", + " North 12 o'clock = 270d0'", + " West 9 o'clock = 180d0'", + " South 6 o'clock = 90d0'", + ]; + assert!(ends_with(&s, &directions), "{:?}", s.log); + assert_eq!(asks(&s), "Enter direction for angle 0d0' <331d21'>:"); + s.cmdline("").unwrap(); + assert_eq!(asks(&s), "Measure angles clockwise? [Yes/No] :"); + s.cmdline("").unwrap(); + assert!(s.running.is_none()); + assert!(same(units(&s), (4, 3, 1, 2, 0.5, 1)), "{:?}", units(&s)); + + // Surveyor's units, clockwise: north is listed as S, as AutoCAD lists it. + let mut s = session((2, 4, 0, 0, 0.0, 1)); + s.script( + "-units + + +5 + +", + ) + .unwrap(); + let directions = [ + "Direction for angle E:", + " East 3 o'clock = E", + " North 12 o'clock = S", + " West 9 o'clock = W", + " South 6 o'clock = N", + ]; + assert!(ends_with(&s, &directions), "{:?}", s.log); + assert_eq!(asks(&s), "Enter direction for angle E :"); + + // The listing shows directions to the precision just given. + let mut s = session(DEFAULT); + s.script( + "-units + + +2 +2 +", + ) + .unwrap(); + let directions = [ + "Direction for angle 0d0':", + " East 3 o'clock = 0d0'", + " North 12 o'clock = 90d0'", + " West 9 o'clock = 180d0'", + " South 6 o'clock = 270d0'", + ]; + assert!(ends_with(&s, &directions), "{:?}", s.log); + assert_eq!(asks(&s), "Enter direction for angle 0d0' <0d0'>:"); +} + +#[test] +fn a_rejected_answer_is_asked_again() { + let mut s = session(DEFAULT); + s.cmdline("-units").unwrap(); + s.cmdline("6").unwrap(); + assert!(ends_with(&s, &["Requires an integer between 1 and 5."]), "{:?}", s.log); + s.cmdline("2.5").unwrap(); + assert!(ends_with(&s, &["Requires an integer value."]), "{:?}", s.log); + assert_eq!(asks(&s), "Enter choice, 1 to 5 <2>:"); + s.cmdline("4").unwrap(); + s.cmdline("3").unwrap(); + assert!(ends_with(&s, &["Invalid choice.", "Enter denominator of smallest fraction to display"]), "{:?}", s.log); + assert_eq!(asks(&s), "(1, 2, 4, 8, 16, 32, 64, 128, or 256) <16>:"); + s.script( + " + +9 +", + ) + .unwrap(); + assert!(ends_with(&s, &["Requires an integer between 0 and 8."]), "{:?}", s.log); + s.script( + " +abc +", + ) + .unwrap(); + assert!(ends_with(&s, &["Requires valid numeric angle or two points."]), "{:?}", s.log); + s.script( + " + +", + ) + .unwrap(); + assert!(s.running.is_none()); + assert!(same(units(&s), (4, 4, 0, 0, 0.0, 0)), "{:?}", units(&s)); +} + +#[test] +fn each_answer_is_kept_as_it_is_given() { + // Esc after the angle format: the answers before it are kept, and the new angle format's + // precision is reset to 4. + let mut s = session(DEFAULT); + s.script( + "-units +4 +16 +2 +", + ) + .unwrap(); + s.cancel(); + assert!(s.running.is_none()); + assert!(same(units(&s), (4, 4, 1, 4, 0.0, 0)), "{:?}", units(&s)); + let mut s = session(DEFAULT); + s.script( + "-units +3 +2 +3 +5 +90 +", + ) + .unwrap(); + s.cancel(); + assert!(same(units(&s), (3, 2, 2, 5, 1.413716694115407, 0)), "{:?}", units(&s)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 8009cf4d3..ee06666c5 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -26,6 +26,7 @@ mod constraint_infer; mod copy_count; mod count; mod dash_block; +mod dash_units; mod data_extraction; mod dim_baseline_spacing; mod dim_chain; From 81e93f2caf0bb7fbd7ae3f00c58e01492213d01b Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:32:49 +0700 Subject: [PATCH 290/900] Scale heights with SCALE and keep them with OFFSET (#2558) AutoCAD 2024's SCALE is a uniform 3D scale about the base point: every Z and elevation scales about the base point's Z (the current ELEVATION for a point given without one) and every thickness by the factor. cadcraft scaled X and Y only. The JSON form also takes a Z with the base point. OFFSET's copy now keeps the source's height: a line's end Zs, a circle's or arc's centre Z, a polyline's elevation. A circle's or arc's copy has no thickness and a polyline's keeps it, as AutoCAD makes them. Grip scaling, ALIGN's scale option and MOCORO stay 2D: their base point is often a grip or snapped point whose Z cadcraft doesn't keep. Co-authored-by: Claude Opus 5.5 --- crates/doc/src/entity.rs | 85 +++++++++ crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/offset.rs | 27 ++- crates/engine/src/cmd/modify/select_then.rs | 6 +- crates/engine/src/cmd/modify/transform.rs | 36 +++- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/scale_offset_z.rs | 184 ++++++++++++++++++++ 7 files changed, 332 insertions(+), 9 deletions(-) create mode 100644 crates/engine/tests/it/scale_offset_z.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index d13b82722..b19d10961 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -465,6 +465,91 @@ impl EntityKind { } } + /// Scale every height of the object by `f` about the height `base_z`: the Z of its points, + /// its elevation. With [`EntityKind::transform`] scaling about the base point's XY this is a + /// uniform 3D scale about the base point, as AutoCAD 2024's SCALE makes it. Sizes `transform` + /// already scales (text and helix heights, an insert's Z scale) are left alone; splines, + /// regions and wipeouts lie in the XY plane. + pub fn scale_heights(&mut self, base_z: f64, f: f64) { + let scale = |h: &mut f64| *h = base_z + (*h - base_z) * f; + let z = |p: &mut Vec3| scale(&mut p.z); + let text_z = |t: &mut Text| { + z(&mut t.insert); + if let Some(a) = &mut t.align_pt { + z(a); + } + }; + let attribs_z = |attribs: &mut Vec| { + for a in attribs { + text_z(&mut a.text); + if let Some(ml) = &mut a.multiline { + z(&mut ml.mtext.insert); + } + } + }; + match self { + EntityKind::Line(l) => { + z(&mut l.a); + z(&mut l.b); + } + EntityKind::Point(p) => z(&mut p.p), + EntityKind::Circle(c) => z(&mut c.center), + EntityKind::Arc(a) => z(&mut a.center), + EntityKind::Ellipse(e) => z(&mut e.center), + EntityKind::LwPolyline(p) => scale(&mut p.elevation), + EntityKind::Polyline3d(p) => p.points.iter_mut().for_each(z), + EntityKind::Helix(h) => z(&mut h.center), + EntityKind::Ray(r) | EntityKind::XLine(r) => z(&mut r.base), + EntityKind::Text(t) => text_z(t), + EntityKind::AttDef(a) => { + text_z(&mut a.text); + if let Some(ml) = &mut a.multiline { + z(&mut ml.mtext.insert); + } + } + EntityKind::MText(t) => z(&mut t.insert), + EntityKind::Insert(i) => { + z(&mut i.insert); + attribs_z(&mut i.attribs); + } + EntityKind::Dimension(d) => { + for p in [&mut d.defpt, &mut d.text_mid, &mut d.p13, &mut d.p14, &mut d.p15, &mut d.p16] { + z(p); + } + if let Some(j) = &mut d.marks.jog_line { + z(j); + } + if let Some(j) = &mut d.marks.jogged { + z(&mut j.center); + z(&mut j.jog); + } + d.marks.breaks.iter_mut().for_each(|b| z(&mut b.at)); + d.block = None; + } + EntityKind::MLine(ml) => ml.vertices.iter_mut().for_each(|v| z(&mut v.p)), + EntityKind::Leader(l) => l.vertices.iter_mut().for_each(z), + EntityKind::MLeader(ml) => { + ml.leaders.iter_mut().flatten().for_each(z); + z(&mut ml.landing); + if let Some(t) = &mut ml.text { + z(&mut t.insert); + } + if let Some(b) = &mut ml.block { + z(&mut b.insert); + attribs_z(&mut b.attribs); + } + } + EntityKind::Hatch(h) => scale(&mut h.elevation), + EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(z), + EntityKind::Face3d(fc) => fc.corners.iter_mut().for_each(z), + EntityKind::Viewport(v) => z(&mut v.center), + EntityKind::Image(i) => z(&mut i.insert), + EntityKind::Table(t) => z(&mut t.insert), + EntityKind::Tolerance(t) => z(&mut t.insert), + EntityKind::Spline(_) | EntityKind::Region(_) | EntityKind::Wipeout(_) | EntityKind::Unknown(_) => {} + } + } + /// Grip points (editable defining points), in display order. pub fn grips(&self) -> Vec { // A broken table has a grip for each part. diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index bbcd25267..22126f900 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { CommandSpec::new("scale", "Scale", run_scale) .menu(&["Modify", "Scale"]) .alias(&["sc"]) - .params("{handles?, base: [x,y], factor, copy?: bool}") + .params("{handles?, base: [x,y] or [x,y,z] (default Z: ELEVATION), factor, copy?: bool}") .interactive(|_| Ok(Box::new(SelectThen::new(Op::Scale)))), CommandSpec::new("mirror", "Mirror", run_mirror) .menu(&["Modify", "Mirror"]) diff --git a/crates/engine/src/cmd/modify/offset.rs b/crates/engine/src/cmd/modify/offset.rs index 17cd15b09..74dc0fb79 100644 --- a/crates/engine/src/cmd/modify/offset.rs +++ b/crates/engine/src/cmd/modify/offset.rs @@ -212,12 +212,35 @@ pub(super) fn run_offset(s: &mut Session, p: &Value) -> Result { Ok(json!({ "handle": nh.hex() })) } +/// The copy at the source's height, as AutoCAD 2024's OFFSET makes it: a line's end Zs, an arc's +/// or circle's centre Z, a polyline's elevation (an ellipse's offset, a polyline, at its centre Z). +fn keep_z(src: &EntityKind, k: &mut EntityKind) { + match (src, k) { + (EntityKind::Line(s), EntityKind::Line(l)) => { + l.a.z = s.a.z; + l.b.z = s.b.z; + } + (EntityKind::Circle(s), EntityKind::Circle(c)) => c.center.z = s.center.z, + (EntityKind::Arc(s), EntityKind::Arc(a)) => a.center.z = s.center.z, + (EntityKind::LwPolyline(s), EntityKind::LwPolyline(p)) => p.elevation = s.elevation, + (EntityKind::Ellipse(s), EntityKind::LwPolyline(p)) => p.elevation = s.center.z, + (EntityKind::Ray(s) | EntityKind::XLine(s), EntityKind::Ray(r) | EntityKind::XLine(r)) => r.base.z = s.base.z, + _ => {} + } +} + /// Add the offset copy `k` of `src` (on the current layer instead of the source's when -/// `current_layer`), then erase the source when `erase` and its layer is not locked. -fn add_offset(s: &mut Session, src: &Entity, k: EntityKind, current_layer: bool, erase: bool) -> Result { +/// `current_layer`), then erase the source when `erase` and its layer is not locked. The copy is +/// at the source's height ([`keep_z`]); a circle's or arc's copy has no thickness, a polyline's +/// keeps it, as AutoCAD 2024 makes them. +fn add_offset(s: &mut Session, src: &Entity, mut k: EntityKind, current_layer: bool, erase: bool) -> Result { + keep_z(&src.kind, &mut k); let space = s.space(); let d = s.doc_mut()?; let mut common = src.common.clone(); + if matches!(k, EntityKind::Circle(_) | EntityKind::Arc(_)) { + common.thickness = 0.0; + } if current_layer { common.layer = d.header.str("CLAYER", "0"); } diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index f9a970ebd..009a95281 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -1,6 +1,6 @@ use super::break_join::join; use super::explode::explode; -use super::transform::{erase, transform_entities}; +use super::transform::{at_elevation, erase, scale_entities, transform_entities}; use super::{ Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line, number, }; @@ -242,7 +242,7 @@ impl SelectThen { let f = require_length(Some(f))?; // The next SCALE offers this factor. s.last_used.scale_factor = f; - transform_entities(s, &self.objs, &Mat3::scale_about(base, f), self.copy_mode)?; + scale_entities(s, &self.objs, at_elevation(s, base), f, self.copy_mode)?; s.set_selection(Vec::new()); Ok(Step::Done) } @@ -439,7 +439,7 @@ impl Interactive for SelectThen { }; if f > 1e-12 && f.is_finite() { s.last_used.scale_factor = f; - transform_entities(s, &self.objs, &Mat3::scale_about(self.pts[0], f), self.copy_mode)?; + scale_entities(s, &self.objs, at_elevation(s, self.pts[0]), f, self.copy_mode)?; } s.set_selection(Vec::new()); Ok(Step::Done) diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 18ff4866c..9adc54ec1 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -1,8 +1,33 @@ +use cadcraft_geom::Vec3; + use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, f64_req, json, point_param, point_req, targets}; // ---------------- core operations ---------------- pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { + edit_entities(s, hs, copy, |e| e.kind.transform(m)) +} + +/// Scale `hs` by `f` about `base` in 3D, as AutoCAD 2024's SCALE does: about the base point's XY, +/// 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); + edit_entities(s, hs, copy, |e| { + e.kind.transform(&m); + e.kind.scale_heights(base.z, f); + e.common.thickness *= f; + }) +} + +/// `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()); + Vec3::new(p.x, p.y, z.unwrap_or(0.0)) +} + +/// Apply `edit` to each of `hs` still in the drawing, or to a copy of each when `copy`; an object +/// 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()?; let mut out = Vec::new(); for h in hs { @@ -11,7 +36,7 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: let Some(e) = d.entity(*h).map(|e| (**e).clone()) else { continue }; let nh = d.new_handle(); let mut ne = Entity { handle: nh, ..e }; - ne.kind.transform(m); + edit(&mut ne); if let Some(st) = d.space_mut(&sp) { st.push(ne); out.push(nh); @@ -21,7 +46,7 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: if locked { continue; } - d.modify_entity(*h, |e| e.kind.transform(m))?; + d.modify_entity(*h, &edit)?; out.push(*h); } } @@ -92,7 +117,12 @@ pub(super) fn run_scale(s: &mut Session, p: &Value) -> Result { if f <= 0.0 { return Err(bad("scale", "factor must be positive")); } - let r = transform_entities(s, &hs, &Mat3::scale_about(base, f), bool_or(p, "copy", false))?; + // A Z given with the base point, as AutoCAD takes one; without one, the current elevation. + let base = match p.get("base").and_then(|b| b.get(2)) { + Some(z) => z.as_f64().map(|z| Vec3::new(base.x, base.y, z)).ok_or_else(|| bad("scale", "`base` Z must be a number"))?, + None => at_elevation(s, base), + }; + let r = scale_entities(s, &hs, base, f, bool_or(p, "copy", false))?; 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 ee06666c5..137e423a7 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -113,6 +113,7 @@ mod refedit; mod region; mod rename_cmdline; mod rotate_reference; +mod scale_offset_z; mod select_keywords; mod select_similar; mod select_underscore_keywords; diff --git a/crates/engine/tests/it/scale_offset_z.rs b/crates/engine/tests/it/scale_offset_z.rs new file mode 100644 index 000000000..a32cea081 --- /dev/null +++ b/crates/engine/tests/it/scale_offset_z.rs @@ -0,0 +1,184 @@ +//! SCALE scales heights too and OFFSET keeps them, as AutoCAD 2024 does (measured with +//! accoreconsole, running these scripts on these drawings): SCALE scales every Z and elevation +//! about the base point's Z (the current elevation for a point given without one) and every +//! thickness by the factor; OFFSET's copy is at the source's height, and a circle's or arc's copy +//! has no thickness while a polyline's keeps it. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Arc, Circle, Common, EntityKind, Handle, Line, LwPolyline, Point}; +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(); + s.doc_mut().unwrap().add(&space, Common { thickness, ..Common::default() }, kind).unwrap() +} + +fn lisp(s: &mut Session, expr: &str) { + s.cmdline(expr).unwrap(); + assert!(s.running.is_none(), "{expr}: {}", s.prompt_text()); +} + +fn get(s: &Session, h: Handle) -> (EntityKind, f64) { + let e = s.doc().unwrap().entity(h).unwrap().clone(); + (e.kind.clone(), e.common.thickness) +} + +fn last(s: &Session) -> (EntityKind, f64) { + let e = s.doc().unwrap().model.iter().last().unwrap().clone(); + (e.kind.clone(), e.common.thickness) +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-9 * (1.0 + b.abs()) +} + +fn near3(a: Vec3, b: Vec3) -> bool { + close(a.x, b.x) && close(a.y, b.y) && close(a.z, b.z) +} + +fn scale(s: &mut Session, h: Handle, base: &str) { + lisp(s, &format!("(command \"_.SCALE\" (handent \"{}\") \"\" '({base}) 1.7)", h.hex())); +} + +#[test] +fn scale_scales_a_lines_z() { + let mut s = Session::new(); + let h = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 7.0), b: Vec3::new(40.0, 0.0, 7.0) }), 0.0); + scale(&mut s, h, "2.0 3.0"); + let EntityKind::Line(l) = get(&s, h).0 else { panic!() }; + assert!(near3(l.a, Vec3::new(-1.4, -2.1, 11.9)) && near3(l.b, Vec3::new(66.6, -2.1, 11.9)), "{l:?}"); + // A sloped line at survey coordinates. + let mut s = Session::new(); + let h = add(&mut s, EntityKind::Line(Line { a: Vec3::new(612345.678, 2398765.432, 3.0), b: Vec3::new(612375.678, 2398775.432, 8.0) }), 0.0); + scale(&mut s, h, "612347.678 2398768.432"); + let EntityKind::Line(l) = get(&s, h).0 else { panic!() }; + assert!(near3(l.a, Vec3::new(612344.278, 2398763.332, 5.1)) && near3(l.b, Vec3::new(612395.278, 2398780.332, 13.6)), "{l:?}"); +} + +#[test] +fn scale_scales_the_centre_z_and_thickness_of_circles_and_arcs() { + let mut s = Session::new(); + let c = add(&mut s, EntityKind::Circle(Circle { center: Vec3::new(0.5, 0.25, 0.005), radius: 0.01 }), 0.002); + scale(&mut s, c, "0.502 0.253"); + let (EntityKind::Circle(k), t) = get(&s, c) else { panic!() }; + assert!(near3(k.center, Vec3::new(0.4986, 0.2479, 0.0085)) && close(k.radius, 0.017) && close(t, 0.0034), "{k:?} {t}"); + let mut s = Session::new(); + let arc = Arc { center: Vec3::new(0.0, 0.0, 4.5), radius: 10.0, start: 30f64.to_radians(), end: 200f64.to_radians() }; + let a = add(&mut s, EntityKind::Arc(arc), 1.5); + scale(&mut s, a, "2.0 3.0"); + let (EntityKind::Arc(k), t) = get(&s, a) else { panic!() }; + assert!(near3(k.center, Vec3::new(-1.4, -2.1, 7.65)) && close(k.radius, 17.0) && close(t, 2.55), "{k:?} {t}"); +} + +#[test] +fn scale_scales_a_polylines_elevation_and_thickness_and_a_points_z() { + let mut s = Session::new(); + let vs = [(612345.678, 2398765.432, 0.0), (612365.678, 2398765.432, 0.4), (612375.678, 2398780.432, 0.0), (612350.678, 2398785.432, 0.0)]; + let vertices = vs.iter().map(|&(x, y, b)| PolyVertex { bulge: b, ..PolyVertex::new(Vec2::new(x, y)) }).collect(); + let p = add(&mut s, EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 12.5, plinegen: false }), 1.0); + scale(&mut s, p, "612347.678 2398768.432"); + let (EntityKind::LwPolyline(k), t) = get(&s, p) else { panic!() }; + assert!(close(k.elevation, 21.25) && close(t, 1.7), "{} {t}", k.elevation); + let first = k.vertices.first().unwrap().p; + assert!(close(first.x, 612344.278) && close(first.y, 2398763.332), "{first:?}"); + let pt = add(&mut s, EntityKind::Point(Point { p: Vec3::new(5.0, 5.0, 6.0), angle: 0.0 }), 0.0); + scale(&mut s, pt, "2.0 3.0"); + let EntityKind::Point(k) = get(&s, pt).0 else { panic!() }; + assert!(near3(k.p, Vec3::new(7.1, 6.4, 10.2)), "{k:?}"); +} + +#[test] +fn scale_scales_heights_about_the_current_elevation() { + // ELEVATION 5: the base point, given without a Z, is at Z = 5. + let mut s = Session::new(); + s.doc_mut().unwrap().header.set_f64("ELEVATION", 5.0); + let h = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 7.0), b: Vec3::new(40.0, 0.0, 7.0) }), 0.0); + scale(&mut s, h, "2.0 3.0"); + let EntityKind::Line(l) = get(&s, h).0 else { panic!() }; + assert!(near3(l.a, Vec3::new(-1.4, -2.1, 8.4)) && near3(l.b, Vec3::new(66.6, -2.1, 8.4)), "{l:?}"); + let c = add(&mut s, EntityKind::Circle(Circle { center: Vec3::new(0.0, 0.0, 4.5), radius: 10.0 }), 1.5); + scale(&mut s, c, "2.0 3.0"); + let (EntityKind::Circle(k), t) = get(&s, c) else { panic!() }; + assert!(near3(k.center, Vec3::new(-1.4, -2.1, 4.15)) && close(k.radius, 17.0) && close(t, 2.55), "{k:?} {t}"); + let vs = [(0.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0)]; + let vertices = vs.iter().map(|&(x, y, b)| PolyVertex { bulge: b, ..PolyVertex::new(Vec2::new(x, y)) }).collect(); + let p = add(&mut s, EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 12.5, plinegen: false }), 1.0); + scale(&mut s, p, "2.0 3.0"); + let (EntityKind::LwPolyline(k), t) = get(&s, p) else { panic!() }; + assert!(close(k.elevation, 17.75) && close(t, 1.7), "{} {t}", k.elevation); + let last = k.vertices.last().unwrap().p; + assert!(close(last.x, 49.6) && close(last.y, 23.4), "{last:?}"); +} + +#[test] +fn json_scale_takes_the_base_points_z() { + let line = || EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 7.0), b: Vec3::new(40.0, 0.0, 7.0) }); + let z = |s: &Session, h: Handle| { + let EntityKind::Line(l) = get(s, h).0 else { panic!() }; + (l.a.z, l.b.z) + }; + let mut s = Session::new(); + let h = add(&mut s, line(), 0.0); + s.execute("scale", &json!({ "handles": [h.hex()], "base": [2.0, 3.0, 1.0], "factor": 1.7 })).unwrap(); + let (a, b) = z(&s, h); + assert!(close(a, 11.2) && close(b, 11.2), "{a} {b}"); + // Without one, the current elevation (not measured through JSON: the same base point as the + // command line's). + let mut s = Session::new(); + s.doc_mut().unwrap().header.set_f64("ELEVATION", 5.0); + let h = add(&mut s, line(), 0.0); + s.execute("scale", &json!({ "handles": [h.hex()], "base": [2.0, 3.0], "factor": 1.7 })).unwrap(); + let (a, b) = z(&s, h); + assert!(close(a, 8.4) && close(b, 8.4), "{a} {b}"); + // A Z that isn't a number is refused, the drawing left as it was. + assert!(s.execute("scale", &json!({ "handles": [h.hex()], "base": [2.0, 3.0, "1"], "factor": 1.7 })).is_err()); + assert_eq!(z(&s, h), (a, b)); +} + +#[test] +fn move_and_rotate_leave_heights_alone() { + let mut s = Session::new(); + let h = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 7.0), b: Vec3::new(40.0, 0.0, 7.0) }), 2.0); + lisp(&mut s, &format!("(command \"_.ROTATE\" (handent \"{}\") \"\" '(0.0 0.0) 90)", h.hex())); + lisp(&mut s, &format!("(command \"_.MOVE\" (handent \"{}\") \"\" '(0.0 0.0) '(5.0 5.0))", h.hex())); + let (EntityKind::Line(l), t) = get(&s, h) else { panic!() }; + assert!(close(l.a.z, 7.0) && close(l.b.z, 7.0) && close(t, 2.0), "{l:?} {t}"); +} + +#[test] +fn offset_keeps_a_lines_z() { + let mut s = Session::new(); + let h = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 7.0), b: Vec3::new(40.0, 0.0, 7.0) }), 0.0); + lisp(&mut s, &format!("(command \"_.OFFSET\" 3.0 (list (handent \"{}\") '(20.0 0.0)) '(10.0 5.0) \"\")", h.hex())); + let EntityKind::Line(l) = last(&s).0 else { panic!() }; + assert!(near3(l.a, Vec3::new(0.0, 3.0, 7.0)) && near3(l.b, Vec3::new(40.0, 3.0, 7.0)), "{l:?}"); +} + +#[test] +fn offset_keeps_the_centre_z_of_circles_and_arcs_but_not_their_thickness() { + 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); + lisp(&mut s, &format!("(command \"_.OFFSET\" 3.0 (list (handent \"{}\") '(612355.678 2398765.432)) '(612345.678 2398780.432) \"\")", c.hex())); + let (EntityKind::Circle(k), t) = last(&s) else { panic!() }; + assert!(close(k.center.z, 5.0) && close(k.radius, 13.0) && t == 0.0, "{k:?} {t}"); + let mut s = Session::new(); + let arc = Arc { center: Vec3::new(-35000.0, 81000.0, 225.0), radius: 500.0, start: 30f64.to_radians(), end: 200f64.to_radians() }; + let a = add(&mut s, EntityKind::Arc(arc), 75.0); + lisp(&mut s, &format!("(command \"_.OFFSET\" 150.0 (list (handent \"{}\") '(-35000.0 81500.0)) '(-35000.0 81750.0) \"\")", a.hex())); + let (EntityKind::Arc(k), t) = last(&s) else { panic!() }; + assert!(close(k.center.z, 225.0) && close(k.radius, 650.0) && t == 0.0, "{k:?} {t}"); +} + +#[test] +fn offset_keeps_a_polylines_elevation_and_thickness() { + let mut s = Session::new(); + let vs = [(0.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)]; + let vertices = vs.iter().map(|&(x, y, b)| PolyVertex { bulge: b, ..PolyVertex::new(Vec2::new(x, y)) }).collect(); + let p = add(&mut s, EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 12.5, plinegen: false }), 1.0); + lisp(&mut s, &format!("(command \"_.OFFSET\" 3.0 (list (handent \"{}\") '(10.0 0.0)) '(12.0 6.0) \"\")", p.hex())); + let (EntityKind::LwPolyline(k), t) = last(&s) else { panic!() }; + assert!(close(k.elevation, 12.5) && close(t, 1.0), "{} {t}", k.elevation); + let first = k.vertices.first().unwrap().p; + assert!(close(first.x, 0.0) && close(first.y, 3.0), "{first:?}"); +} From a626b7128466074ce60989d24e948b0809967179 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:32:53 +0700 Subject: [PATCH 291/900] fix(draw): RECTANG and POLYGON vertices in AutoCAD's order; RECTANG remembers its modes (#2554) RECTANG's polyline now starts at the first corner and runs along X to the other corner, as AutoCAD 2024 draws it; each chamfer cuts the edge into its corner by the first distance and the edge out by the second, and fillet arcs start on the edge into their corner (clockwise outlines get negative bulges). RECTANG keeps its chamfer, fillet, width, elevation, thickness and rotation for the next rectangle, lists them as "Current rectangle modes:" and offers the rotation as "<50.50>"; chamfer and fillet clear each other. A circumscribed POLYGON starts at the end of the picked edge counter-clockwise from its midpoint. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/draw2/rect.rs | 78 ++++++- crates/engine/src/cmd/draw2/tests.rs | 3 +- crates/engine/src/cmd/helpers.rs | 62 +++-- crates/engine/src/last_used.rs | 17 ++ crates/engine/tests/it/main.rs | 1 + .../engine/tests/it/rectang_polygon_order.rs | 215 ++++++++++++++++++ 6 files changed, 335 insertions(+), 41 deletions(-) create mode 100644 crates/engine/tests/it/rectang_polygon_order.rs diff --git a/crates/engine/src/cmd/draw2/rect.rs b/crates/engine/src/cmd/draw2/rect.rs index 4b19dc703..245ef24f8 100644 --- a/crates/engine/src/cmd/draw2/rect.rs +++ b/crates/engine/src/cmd/draw2/rect.rs @@ -2,6 +2,7 @@ use super::{ Accept, EntityKind, Input, Interactive, PolyVertex, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, f64_or, lwpoly, number, other, point_param, point_req, rect_with_corners, size_param, }; +use crate::last_used::RectangModes; // ===================================================================================== // RECTANG with Area / Dimensions / Rotation / Width / Elevation / Thickness @@ -115,11 +116,58 @@ pub(crate) struct RectM2 { asking: Option, } +/// A rectangle's rotation as AutoCAD 2024 shows it: degrees from 0 to 360, two decimals. +fn rotation_text(rotation: f64) -> String { + let t = format!("{:.2}", rotation.to_degrees().rem_euclid(360.0)); + if t == "360.00" { "0.00".into() } else { t } +} + +/// AutoCAD 2024's line listing the RECTANG modes that are set, `None` when none is ("Current +/// rectangle modes: Chamfer=2.2518 x 3.7663 Rotation=50.50"): distances in the drawing's +/// units, the rotation as [`rotation_text`] shows it. +fn modes_line(s: &Session, m: &RectangModes) -> Option { + let (u, p) = s.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4)); + let d = |v: f64| crate::units::format_distance(v, u, p); + let mut parts = Vec::new(); + if m.chamfer.0 > 0.0 || m.chamfer.1 > 0.0 { + parts.push(format!("Chamfer={} x {}", d(m.chamfer.0), d(m.chamfer.1))); + } + if m.fillet > 0.0 { + parts.push(format!("Fillet={}", d(m.fillet))); + } + if m.elevation != 0.0 { + parts.push(format!("Elevation={}", d(m.elevation))); + } + if m.thickness != 0.0 { + parts.push(format!("Thickness={}", d(m.thickness))); + } + if m.width > 0.0 { + parts.push(format!("Width={}", d(m.width))); + } + let rot = rotation_text(m.rotation); + if rot != "0.00" { + parts.push(format!("Rotation={rot}")); + } + (!parts.is_empty()).then(|| format!("Current rectangle modes: {}", parts.join(" "))) +} + impl RectM2 { + /// The modes the next rectangle starts from. + fn modes(&self) -> RectangModes { + RectangModes { + chamfer: self.chamfer, + fillet: self.fillet, + width: self.width, + elevation: self.elevation, + thickness: self.thickness, + rotation: self.rotation, + } + } /// Adds the rectangle of full size `w` × `h` with the collected options, drawing it from /// the centre when centre mode is on, then applies the requested thickness. fn make(&self, s: &mut Session, w: f64, h: f64) -> Result { let Some(a) = self.first else { return Ok(Step::Cancel) }; + s.last_used.rectang = self.modes(); if w.abs() < 1e-12 || h.abs() < 1e-12 { return Err(other("The rectangle has no area.")); } @@ -155,6 +203,20 @@ impl Interactive for RectM2 { fn name(&self) -> &'static str { "RECTANG" } + /// Starts from the modes the last rectangle left, and lists the ones that are set. + fn begin(&mut self, s: &mut Session) -> Result { + let m = s.last_used.rectang; + self.chamfer = m.chamfer; + self.fillet = m.fillet; + self.width = m.width; + self.elevation = m.elevation; + self.thickness = m.thickness; + self.rotation = m.rotation; + if let Some(line) = modes_line(s, &m) { + s.echo(line); + } + Ok(Step::Continue) + } /// Asks for the pending option's value, or for the first and second points; in centre mode /// the first prompt asks for the centre instead of a corner. fn prompt(&self, _s: &Session) -> Prompt { @@ -173,9 +235,9 @@ impl Interactive for RectM2 { RAsk::AreaWidth => num("Enter rectangle width", 10.0), RAsk::DimL => num("Specify length for rectangles", self.dims.map(|d| d.0).unwrap_or(10.0)), RAsk::DimW => num("Specify width for rectangles", self.dims.map(|d| d.1).unwrap_or(10.0)), - RAsk::Rotation => Prompt::new("Specify rotation angle or", Accept::POINT_OR_NUMBER) + RAsk::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER) .kw(&["Pick points"]) - .default(format!("{:.0}", self.rotation.to_degrees())) + .default(rotation_text(self.rotation)) .base_opt(self.first), RAsk::RotPick1 => Prompt::new("Specify first point", Accept::POINT), RAsk::RotPick2(b) => Prompt::new("Specify second point", Accept::POINT).base(b), @@ -207,8 +269,14 @@ impl Interactive for RectM2 { self.chamfer.1 = self.chamfer.0; self.asking = Some(RAsk::Chamfer2); } - RAsk::Chamfer2 => self.chamfer.1 = val(&i, self.chamfer.1)?.max(0.0), - RAsk::Fillet => self.fillet = val(&i, self.fillet)?.max(0.0), + RAsk::Chamfer2 => { + self.chamfer.1 = val(&i, self.chamfer.1)?.max(0.0); + self.fillet = 0.0; + } + RAsk::Fillet => { + self.fillet = val(&i, self.fillet)?.max(0.0); + self.chamfer = (0.0, 0.0); + } RAsk::Width => self.width = val(&i, self.width)?.max(0.0), RAsk::Elevation => self.elevation = val(&i, self.elevation)?, RAsk::Thickness => self.thickness = val(&i, self.thickness)?, @@ -260,6 +328,8 @@ impl Interactive for RectM2 { } } } + // A mode is kept as soon as it is set, even if no rectangle follows. + s.last_used.rectang = self.modes(); return Ok(Step::Continue); } match i { diff --git a/crates/engine/src/cmd/draw2/tests.rs b/crates/engine/src/cmd/draw2/tests.rs index 8eedd3772..efad025ca 100644 --- a/crates/engine/src/cmd/draw2/tests.rs +++ b/crates/engine/src/cmd/draw2/tests.rs @@ -996,7 +996,8 @@ fn rectang_options_command_line() { s.cmdline("rectang 0,0 r p 0,0 1,1 d 2 2 5,5").unwrap(); let pts = rect_pts(&s); assert!(pts.iter().any(|p| near(*p, 0.0, 8f64.sqrt())), "{pts:?}"); - s.cmdline("rectang w 0.5 c 0.5 0.5 0,0 4,4").unwrap(); + // RECTANG keeps the rotation of the rectangle before (45 degrees), as AutoCAD does: back to 0. + s.cmdline("rectang w 0.5 c 0.5 0.5 0,0 r 0 4,4").unwrap(); match last(&s) { EntityKind::LwPolyline(p) => assert!(p.const_width == 0.5 && p.vertices.len() == 8), k => panic!("{k:?}"), diff --git a/crates/engine/src/cmd/helpers.rs b/crates/engine/src/cmd/helpers.rs index 54c5ffdaf..ed5891203 100644 --- a/crates/engine/src/cmd/helpers.rs +++ b/crates/engine/src/cmd/helpers.rs @@ -34,7 +34,9 @@ pub fn polygon_vertices(center: Vec2, sides: usize, radius_pt: Vec2, inscribed: let r = d.len(); let a0 = d.angle(); let step = cadcraft_geom::TAU / n as f64; - let (r, a0) = if inscribed { (r, a0) } else { (r / (step / 2.0).cos(), a0 - step / 2.0) }; + // Circumscribed: the picked point is an edge's midpoint and the first vertex is the end of + // that edge counter-clockwise from it, as AutoCAD 2024 numbers them. + let (r, a0) = if inscribed { (r, a0) } else { (r / (step / 2.0).cos(), a0 + step / 2.0) }; (0..n).map(|i| PolyVertex::new(Vec2::polar(center, r, a0 + step * i as f64))).collect() } @@ -62,43 +64,31 @@ pub fn polygon_from_edge(p1: Vec2, p2: Vec2, sides: usize) -> Vec { pts.into_iter().map(PolyVertex::new).collect() } -/// Rectangle vertices with fillet radius or chamfer distances at every corner. +/// Rectangle vertices from corner `a` to the opposite corner `b`, with a fillet radius or +/// chamfer distances at every corner, in AutoCAD 2024's order: from `a` along X to `b`'s X, then +/// `b`, then back along Y. A chamfer cuts the edge into each corner by its first distance and the +/// edge out of it by its second; each fillet arc starts on the edge into its corner. A fillet or +/// chamfer that doesn't fit leaves the corners square. pub fn rect_with_corners(a: Vec2, b: Vec2, fillet: f64, chamfer: (f64, f64)) -> Vec { - let (x0, x1) = (a.x.min(b.x), a.x.max(b.x)); - let (y0, y1) = (a.y.min(b.y), a.y.max(b.y)); - let w = x1 - x0; - let h = y1 - y0; - if fillet > 0.0 && fillet * 2.0 <= w.min(h) + 1e-12 { - let r = fillet; - let bul = cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2); - return vec![ - PolyVertex::new(Vec2::new(x0 + r, y0)), - PolyVertex::with_bulge(Vec2::new(x1 - r, y0), bul), - PolyVertex::new(Vec2::new(x1, y0 + r)), - PolyVertex::with_bulge(Vec2::new(x1, y1 - r), bul), - PolyVertex::new(Vec2::new(x1 - r, y1)), - PolyVertex::with_bulge(Vec2::new(x0 + r, y1), bul), - PolyVertex::new(Vec2::new(x0, y1 - r)), - PolyVertex::with_bulge(Vec2::new(x0, y0 + r), bul), - ]; + let corners = [a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y)]; + let short = (b.x - a.x).abs().min((b.y - a.y).abs()); + let (d_in, d_out, bulge) = if fillet > 0.0 && fillet * 2.0 <= short + 1e-12 { + // Counter-clockwise round the corners (a positive bulge) when `b` is up and right of `a`, or + // down and left. + let sign = if (b.x - a.x) * (b.y - a.y) >= 0.0 { 1.0 } else { -1.0 }; + (fillet, fillet, sign * cadcraft_geom::arc_to_bulge(std::f64::consts::FRAC_PI_2)) + } else if chamfer.0 > 0.0 && chamfer.1 > 0.0 && chamfer.0 + chamfer.1 <= short + 1e-12 { + (chamfer.0, chamfer.1, 0.0) + } else { + return corners.into_iter().map(PolyVertex::new).collect(); + }; + let mut out = Vec::with_capacity(8); + for (i, cur) in corners.iter().enumerate() { + let (Some(prev), Some(next)) = (corners.get((i + 3) % 4), corners.get((i + 1) % 4)) else { continue }; + out.push(PolyVertex::with_bulge(*cur + (*prev - *cur).normalized() * d_in, bulge)); + out.push(PolyVertex::new(*cur + (*next - *cur).normalized() * d_out)); } - let (c1, c2) = chamfer; - if c1 > 0.0 && c2 > 0.0 && c1 + c1 <= w + 1e-12 && c2 + c2 <= h + 1e-12 { - return [ - Vec2::new(x0 + c1, y0), - Vec2::new(x1 - c1, y0), - Vec2::new(x1, y0 + c2), - Vec2::new(x1, y1 - c2), - Vec2::new(x1 - c1, y1), - Vec2::new(x0 + c1, y1), - Vec2::new(x0, y1 - c2), - Vec2::new(x0, y0 + c2), - ] - .into_iter() - .map(PolyVertex::new) - .collect(); - } - rect_vertices(Vec2::new(x0, y0), Vec2::new(x1, y1)) + out } // ---------- the user's support files ---------- diff --git a/crates/engine/src/last_used.rs b/crates/engine/src/last_used.rs index 73c610329..88a1d4f59 100644 --- a/crates/engine/src/last_used.rs +++ b/crates/engine/src/last_used.rs @@ -25,6 +25,8 @@ pub struct LastUsed { pub mleader_block: String, /// BREAKLINE's Block, Size and Extension. pub breakline: cmd::BreaklineOptions, + /// RECTANG's chamfer, fillet, width, elevation, thickness and rotation. + pub rectang: RectangModes, } impl Default for LastUsed { @@ -39,10 +41,25 @@ impl Default for LastUsed { mleader: MLeaderOptions::default(), mleader_block: String::new(), breakline: cmd::BreaklineOptions::default(), + rectang: RectangModes::default(), } } } +/// The modes RECTANG keeps from one rectangle to the next, as AutoCAD 2024 does. Chamfer and +/// fillet exclude each other: setting one clears the other. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct RectangModes { + /// First and second chamfer distances. + pub chamfer: (f64, f64), + pub fillet: f64, + pub width: f64, + pub elevation: f64, + pub thickness: f64, + /// Radians. + pub rotation: f64, +} + /// Which part of a multileader MLEADER places first. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum LeaderOrder { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 137e423a7..e36e30b35 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -109,6 +109,7 @@ mod query_entities; mod quickcalc; mod recent_commands; mod rectang_ortho; +mod rectang_polygon_order; mod refedit; mod region; mod rename_cmdline; diff --git a/crates/engine/tests/it/rectang_polygon_order.rs b/crates/engine/tests/it/rectang_polygon_order.rs new file mode 100644 index 000000000..e58f0a6e9 --- /dev/null +++ b/crates/engine/tests/it/rectang_polygon_order.rs @@ -0,0 +1,215 @@ +//! RECTANG and POLYGON vertices in AutoCAD 2024's order, and the RECTANG modes it remembers from +//! one rectangle to the next. The scripts and numbers were measured with accoreconsole; the +//! RECTANG scripts reset Chamfer, Fillet, Width, Elevation and Thickness first, but not Rotation. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +type Vertex = (f64, f64, f64); + +const RESET: &str = "\"_C\" 0 0 \"_F\" 0 \"_W\" 0 \"_E\" 0 \"_T\" 0"; + +/// The last polyline's vertices (x, y, bulge). +fn last_polyline(s: &Session) -> Vec { + let d = s.doc().unwrap(); + match &d.model.iter().last().unwrap().kind { + EntityKind::LwPolyline(p) => p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect(), + k => panic!("not a polyline: {k:?}"), + } +} + +fn expect(got: &[Vertex], want: &[Vertex]) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + let tol = 1e-9 * (1.0 + w.0.abs().max(w.1.abs())); + assert!((g.0 - w.0).abs() < tol && (g.1 - w.1).abs() < tol && (g.2 - w.2).abs() < 1e-9, "{got:?}\n!= {want:?}"); + } +} + +fn lisp(s: &mut Session, expr: &str) { + s.cmdline(expr).unwrap(); + assert!(s.running.is_none(), "{expr}: {}", s.prompt_text()); +} + +fn rectang(s: &mut Session, rest: &str) { + lisp(s, &format!("(command \"_.RECTANG\" {RESET} {rest})")); +} + +#[test] +fn a_rectangle_starts_at_its_first_corner_and_runs_along_x_first() { + let mut s = Session::new(); + rectang(&mut s, "'(-2.2557479240466947 -9.488221049171962) '(-31.36203661716106 -47.886714708394166)"); + expect( + &last_polyline(&s), + &[ + (-2.255747924046694, -9.488221049171962, 0.0), + (-31.36203661716105, -9.488221049171962, 0.0), + (-31.36203661716105, -47.88671470839417, 0.0), + (-2.255747924046694, -47.88671470839417, 0.0), + ], + ); +} + +#[test] +fn chamfers_cut_the_edge_into_each_corner_by_the_first_distance() { + let mut s = Session::new(); + rectang(&mut s, "\"_C\" 2.2518104656366162 3.766337568886034 '(4.8089419289768 29.66648885915597) '(28.114797694689763 43.85884965263156)"); + expect( + &last_polyline(&s), + &[ + (4.8089419289768, 31.91829932479258, 0.0), + (8.575279497862834, 29.66648885915597, 0.0), + (25.86298722905314, 29.66648885915597, 0.0), + (28.11479769468976, 33.432826428042, 0.0), + (28.11479769468976, 41.60703918699494, 0.0), + (24.34846012580373, 43.85884965263156, 0.0), + (7.060752394613416, 43.85884965263156, 0.0), + (4.8089419289768, 40.09251208374553, 0.0), + ], + ); +} + +#[test] +fn fillet_arcs_start_on_the_edge_into_each_corner() { + let mut s = Session::new(); + rectang(&mut s, "\"_F\" 0.6042729201106594 '(-13.457476758444333 -29.884431038180395) '(14.673991980287038 27.14695046607133)"); + let b = 0.414213562373095; + expect( + &last_polyline(&s), + &[ + (-13.45747675844433, -29.28015811806973, b), + (-12.85320383833367, -29.88443103818039, 0.0), + (14.06971906017638, -29.88443103818039, b), + (14.67399198028703, -29.28015811806973, 0.0), + (14.67399198028703, 26.54267754596067, b), + (14.06971906017638, 27.14695046607133, 0.0), + (-12.85320383833367, 27.14695046607133, b), + (-13.45747675844433, 26.54267754596067, 0.0), + ], + ); +} + +#[test] +fn fillet_arcs_turn_clockwise_when_the_second_corner_is_below_the_first() { + // The second corner down and right: the outline runs clockwise and the bulges are negative + // (AutoCAD gave -0.414213562373095 for such a rectangle, there also rotated). + let mut s = Session::new(); + rectang(&mut s, "\"_F\" 1.0 '(0.0 0.0) '(10.0 -5.0)"); + let b = -0.414213562373095; + expect( + &last_polyline(&s), + &[(0.0, -1.0, b), (1.0, 0.0, 0.0), (9.0, 0.0, b), (10.0, -1.0, 0.0), (10.0, -4.0, b), (9.0, -5.0, 0.0), (1.0, -5.0, b), (0.0, -4.0, 0.0)], + ); +} + +#[test] +fn the_next_rectangle_keeps_the_rotation_and_lists_the_modes() { + let mut s = Session::new(); + rectang(&mut s, "'(27.647422687394844 28.925709913163516) \"_R\" 50.50299224048081 '(46.86449612780332 4.979921576806525)"); + expect( + &last_polyline(&s), + &[ + (27.64742268739484, 28.92570991316351, 0.0), + (23.66889931823719, 24.09886156025833, 0.0), + (46.86449612780331, 4.979921576806525, 0.0), + (50.84301949696097, 9.80676992971171, 0.0), + ], + ); + // No Rotation option this time: the rectangle still turns by 50.50 degrees. + rectang(&mut s, "'(14.3947813348612 23.649728466870016) \"_D\" 19.35761675393126 49.775239210761946 '(-4.9628354190700605 -26.12551074389193)"); + assert!(s.log.iter().any(|l| l == "Current rectangle modes: Rotation=50.50"), "{:?}", s.log); + // The next Rotation prompt offers it as its default, as AutoCAD shows it. + s.cmdline("RECTANG 0,0 R").unwrap(); + assert!(s.prompt_text().ends_with("Specify rotation angle or [Pick points] <50.50>:"), "{}", s.prompt_text()); + s.cancel(); + expect( + &last_polyline(&s), + &[ + (14.3947813348612, 23.64972846687001, 0.0), + (2.082603004810238, 8.712272486646885, 0.0), + (40.4920546468795, -22.94666721518322, 0.0), + (52.80423297693047, -8.009211234960095, 0.0), + ], + ); +} + +#[test] +fn elevation_thickness_and_a_picked_rotation_carry_over_together() { + let mut s = Session::new(); + rectang( + &mut s, + "\"_E\" 7.5 \"_T\" 2.25 '(-18.42481827666694 -20.50343704206707) \"_R\" \"_P\" '(0.0 0.0) '(10.0 6.0) '(10.197290578707722 25.5222006119985)", + ); + expect( + &last_polyline(&s), + &[ + (-18.42481827666694, -20.50343704206706, 0.0), + (22.92627837613747, 4.307220949615576, 0.0), + (10.19729057870772, 25.5222006119985, 0.0), + (-31.15380607409669, 0.7115426203158534, 0.0), + ], + ); + let d = s.doc().unwrap(); + let e = d.model.iter().last().unwrap(); + let EntityKind::LwPolyline(p) = &e.kind else { panic!("not a polyline") }; + assert_eq!((p.elevation, e.common.thickness), (7.5, 2.25)); + s.cmdline("RECTANG").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Current rectangle modes: Elevation=7.5000 Thickness=2.2500 Rotation=30.96")); + s.cancel(); +} + +#[test] +fn chamfer_and_fillet_are_remembered_one_at_a_time() { + let mut s = Session::new(); + rectang(&mut s, "\"_C\" 2.2518104656366162 3.766337568886034 '(0.0 0.0) '(40.0 30.0)"); + rectang(&mut s, "\"_F\" 0.6042729201106594 '(0.0 0.0) '(40.0 30.0)"); + let logs: Vec<&String> = s.log.iter().filter(|l| l.starts_with("Current rectangle modes:")).collect(); + assert_eq!(logs, ["Current rectangle modes: Chamfer=2.2518 x 3.7663"]); + s.cmdline("RECTANG").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Current rectangle modes: Fillet=0.6043")); + s.cancel(); +} + +#[test] +fn setting_a_fillet_clears_the_chamfer_and_back() { + // A chamfer set after a fillet makes a chamfered rectangle, and the other way round. + let mut s = Session::new(); + s.script("RECTANG F 1 C 2 3 0,0 40,30\n").unwrap(); + assert!(last_polyline(&s).iter().all(|v| v.2 == 0.0), "{:?}", last_polyline(&s)); + assert_eq!(last_polyline(&s).first().map(|v| (v.0, v.1)), Some((0.0, 2.0))); + s.script("RECTANG C 2 3 F 1 0,0 40,30\n").unwrap(); + assert!(s.log.iter().any(|l| l == "Current rectangle modes: Chamfer=2.0000 x 3.0000"), "{:?}", s.log); + expect(&last_polyline(&s)[..1], &[(0.0, 1.0, 0.414213562373095)]); + s.cmdline("RECTANG").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Current rectangle modes: Fillet=1.0000")); + s.cancel(); +} + +#[test] +fn the_json_form_ignores_the_remembered_modes() { + let mut s = Session::new(); + rectang(&mut s, "'(0.0 0.0) \"_R\" 30 '(10.0 10.0)"); + s.execute("rectang", &json!({ "p1": [100, 0], "p2": [110, 10] })).unwrap(); + expect(&last_polyline(&s), &[(100.0, 0.0, 0.0), (110.0, 0.0, 0.0), (110.0, 10.0, 0.0), (100.0, 10.0, 0.0)]); +} + +#[test] +fn a_circumscribed_polygon_starts_counter_clockwise_from_the_picked_edge() { + let mut s = Session::new(); + lisp(&mut s, "(command \"_.POLYGON\" 4 '(-13.660465775726184 6.051830973104977) \"_C\" '(-33.469717497592136 8.913096552751803))"); + expect( + &last_polyline(&s), + &[ + (-36.33098307723896, -10.89615516911414, 0.0), + (3.287520366492948, -16.61868632840779, 0.0), + (9.01005152578659, 22.9998171153241, 0.0), + (-30.60845191794531, 28.72234827461775, 0.0), + ], + ); + lisp(&mut s, "(command \"_.POLYGON\" 3 '(-4.866064513702604 -0.5675999154110016) \"_C\" '(-33.004110114447 14.119144448101377))"); + expect( + &last_polyline(&s), + &[(-58.44229754982628, -34.61738015807783, 0.0), (51.41002668778618, -29.94108864243579, 0.0), (-7.565922679067647, 62.85566905428061, 0.0)], + ); +} From ac886483d194b182c19a8c5455ddaa549bc576e9 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:32:56 +0700 Subject: [PATCH 292/900] -INSERT: ATTREQ, Preset and Verify attributes as AutoCAD asks them (#2535) * -INSERT: ATTREQ, Preset and Verify attributes as AutoCAD asks them ATTREQ 0 inserts blocks with their attributes' default values without asking (a session setting, as AutoCAD keeps it in the registry). Preset attributes are never asked for, "Enter attribute values" heads the questions, and Verify attributes are asked again after "Verify attribute values", each with the value typed. Co-Authored-By: Claude Opus 5.5 * -INSERT: a click doesn't answer a Verify attribute Only typed text or Enter answers "Verify attribute values"; anything else asks again (CodeRabbit). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks.rs | 53 ++++++++++-- crates/engine/src/settings.rs | 4 + crates/engine/src/sysvars.rs | 1 + crates/engine/src/sysvars/table.rs | 7 +- .../tests/it/insert_attribute_prompts.rs | 82 +++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 6 files changed, 140 insertions(+), 8 deletions(-) create mode 100644 crates/engine/tests/it/insert_attribute_prompts.rs diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 760b6921c..19543141e 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -603,6 +603,8 @@ enum InsStage { ZScale, Rotation, Attribs, + /// A Verify attribute asked again. + Verify, } #[derive(Default)] @@ -623,8 +625,11 @@ struct InsertM { /// Where the block was dropped to pick a Basepoint on it. dropped: Option, rotation: Option, - attdefs: Vec<(String, String, String)>, + /// The attributes asked for: tag, prompt, default value, and Verify (asked again). + attdefs: Vec<(String, String, String, bool)>, values: serde_json::Map, + /// Verify attributes asked again so far. + verified: usize, /// `*name`: insert the block's objects (one uniform scale factor, no attribute values). explode: bool, /// The file waiting for the Redefine answer. @@ -641,6 +646,17 @@ impl InsertM { } else { InsStage::Attribs }; + if self.stage == InsStage::Attribs && self.values.is_empty() && !self.attdefs.is_empty() { + s.echo("Enter attribute values"); + } + // Then the Verify attributes are asked again, with the values typed. + if self.stage == InsStage::Attribs && self.values.len() >= self.attdefs.len() && self.verified < self.verifying().len() { + if self.verified == 0 { + s.echo("Verify attribute values"); + } + self.stage = InsStage::Verify; + return Ok(Step::Continue); + } if self.stage == InsStage::Attribs && self.values.len() >= self.attdefs.len() && let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation) @@ -654,20 +670,26 @@ impl InsertM { Ok(Step::Continue) } - /// Block `name` chosen: collect its attribute prompts and ask for the insertion point. + /// The Verify attributes asked for. + fn verifying(&self) -> Vec<&(String, String, String, bool)> { + self.attdefs.iter().filter(|a| a.3).collect() + } + + /// Block `name` chosen: collect its attribute prompts and ask for the insertion point. Constant + /// and Preset attributes take their values without asking, and so do all of them with ATTREQ 0. fn choose(&mut self, s: &mut Session, name: &str) -> Result<()> { let Some(b) = s.doc()?.block(name).cloned() else { s.echo(format!("Block \"{name}\" not found.")); return Ok(()); }; - self.attdefs = if self.explode { + self.attdefs = if self.explode || !s.settings.attreq { Vec::new() } else { b.entities .iter() .filter_map(|e| { if let EntityKind::AttDef(a) = &e.kind { - (!a.constant).then(|| (a.tag.clone(), a.prompt.clone(), a.text.value.clone())) + (!a.constant && !a.modes.preset).then(|| (a.tag.clone(), a.prompt.clone(), a.text.value.clone(), a.modes.verify)) } else { None } @@ -752,9 +774,14 @@ impl Interactive for InsertM { InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"), InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at), InsStage::Attribs => { - let (_, prompt, default) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); + let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT).default(default) } + InsStage::Verify => { + let (tag, prompt) = self.verifying().get(self.verified).map(|a| (a.0.clone(), a.1.clone())).unwrap_or_default(); + let typed = self.values.get(&tag).and_then(Value::as_str).unwrap_or_default().to_string(); + Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT).default(typed) + } } } fn input(&mut self, s: &mut Session, i: Input) -> Result { @@ -913,7 +940,7 @@ impl Interactive for InsertM { return self.advance(s); } InsStage::Attribs => { - let (tag, _, default) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); + let (tag, _, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); let v = match i { Input::Text(t) => t, _ => default, @@ -921,6 +948,20 @@ impl Interactive for InsertM { self.values.insert(tag, Value::String(v)); return self.advance(s); } + // Enter keeps the value typed. + InsStage::Verify => { + let tag = self.verifying().get(self.verified).map(|a| a.0.clone()).unwrap_or_default(); + match i { + Input::Text(t) => { + self.values.insert(tag, Value::String(t)); + } + Input::Enter => {} + // A click or anything else is no answer: the value is asked for again. + _ => return Ok(Step::Continue), + } + self.verified += 1; + return self.advance(s); + } } Ok(Step::Continue) } diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 32507162f..736cec91c 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -127,6 +127,9 @@ pub struct Settings { pub polardist: f64, /// AUDITCTL: 1 creates an audit report (.adt) file when AUDIT is run (default: 0). pub auditctl: bool, + /// ATTREQ: 0 inserts blocks with their attributes' default values instead of asking for them + /// (default: 1). + pub attreq: bool, } impl Default for Settings { @@ -191,6 +194,7 @@ impl Default for Settings { polarsnap: false, polardist: 0.0, auditctl: false, + attreq: true, } } } diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 930a9bad1..3fe47c052 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -8,6 +8,7 @@ mod table; const SESSION_VARS: &[&str] = &[ "AUDITCTL", + "ATTREQ", "OSMODE", "OSNAPHATCH", "ANNOAUTOSCALE", diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index fa319d3f1..910068f5c 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -81,8 +81,11 @@ const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, /// On/off session settings: name, read, write. type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool)); -const SETTINGS: &[Toggle] = - &[("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v), ("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v)]; +const SETTINGS: &[Toggle] = &[ + ("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v), + ("ATTREQ", |s| s.attreq, |s, v| s.attreq = v), + ("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v), +]; fn header_var(name: &str) -> Option<&'static (&'static str, Kind, Def)> { HEADER.iter().find(|(n, _, _)| *n == name) diff --git a/crates/engine/tests/it/insert_attribute_prompts.rs b/crates/engine/tests/it/insert_attribute_prompts.rs new file mode 100644 index 000000000..97df80386 --- /dev/null +++ b/crates/engine/tests/it/insert_attribute_prompts.rs @@ -0,0 +1,82 @@ +//! INSERT's attribute questions as AutoCAD 2024 asks them from AutoLISP's `command` (accoreconsole, +//! the attributes read back with `entget`). + +use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec}; +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session}; + +/// A session with block K: a circle and attributes (tag, DXF flags, default value), each with the +/// prompt "P" + tag. +fn with_block(defs: &[(&str, i32, &str)]) -> Session { + // `entmake` goes through the DXF codec, as in the app. + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + let mut s = Session::new(); + let mut code = + String::from("(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0)))"); + for (i, (tag, flags, default)) in defs.iter().enumerate() { + let y = 5.0 + 3.0 * i as f64; + code += &format!( + " (entmake '((0 . \"ATTDEF\") (10 0.0 {y:.1} 0.0) (40 . 2.5) (1 . \"{default}\") (3 . \"P{tag}\") (2 . \"{tag}\") (70 . {flags})))" + ); + } + code += " (entmake '((0 . \"ENDBLK\")))"; + s.cmdline(&format!("(progn {code})")).unwrap(); + s.log.clear(); + s +} + +/// The attribute values of the last block reference, by tag. +fn values(s: &Session) -> Vec<(String, String)> { + let d = s.doc().unwrap(); + let Some(EntityKind::Insert(i)) = d.model.iter().last().map(|e| &e.kind) else { panic!("no block reference") }; + i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect() +} + +fn said(s: &Session, line: &str) -> usize { + s.log.iter().filter(|l| l.as_str() == line).count() +} + +fn pair(tag: &str, value: &str) -> (String, String) { + (tag.to_string(), value.to_string()) +} + +#[test] +fn attreq_0_inserts_the_default_values_without_asking() { + let mut s = with_block(&[("T1", 0, "V1"), ("T2", 0, "V2")]); + s.cmdline("(progn (setvar \"ATTREQ\" 0) (command \"_.-INSERT\" \"K\" '(100.0 0.0) \"\" \"\" 0))").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), [pair("T1", "V1"), pair("T2", "V2")]); + assert_eq!(said(&s, "Enter attribute values"), 0, "{:?}", s.log); + s.cmdline("(setvar \"ATTREQ\" 1)").unwrap(); + s.cmdline("(princ (getvar \"ATTREQ\"))").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("1"), "{:?}", s.log); +} + +#[test] +fn a_preset_attribute_is_not_asked() { + let mut s = with_block(&[("T1", 8, "V1"), ("T2", 0, "V2")]); + s.cmdline("(command \"_.-INSERT\" \"K\" '(200.0 0.0) \"\" \"\" 0 \"X\")").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), [pair("T1", "V1"), pair("T2", "X")]); + assert_eq!(said(&s, "Enter attribute values"), 1, "{:?}", s.log); +} + +#[test] +fn a_verify_attribute_is_asked_again_with_the_value_typed() { + let mut s = with_block(&[("T1", 4, "V1")]); + s.cmdline("(command \"_.-INSERT\" \"K\" '(300.0 0.0) \"\" \"\" 0 \"X\")").unwrap(); + assert_eq!(said(&s, "Verify attribute values"), 1, "{:?}", s.log); + assert!(s.prompt_text().contains("PT1 "), "{}", s.prompt_text()); + // A click is no answer. + s.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap(); + assert!(s.prompt_text().contains("PT1 "), "{}", s.prompt_text()); + // Typed at the prompt, the whole line is the value. + s.cmdline("Y").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), [pair("T1", "Y")]); + // Enter keeps the value typed. + let mut s = with_block(&[("T1", 4, "V1")]); + s.cmdline("(command \"_.-INSERT\" \"K\" '(300.0 0.0) \"\" \"\" 0 \"X\" \"\")").unwrap(); + assert_eq!(values(&s), [pair("T1", "X")]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e36e30b35..2e60c9df1 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -58,6 +58,7 @@ mod hatch_options; mod helix; mod inquiry_keywords; mod inquiry_z; +mod insert_attribute_prompts; mod insert_prompts; mod isometric; mod join_close; From 87f8ce22f6307b30440037c071daeb7fc1e09eb0 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:33:00 +0700 Subject: [PATCH 293/900] CHANGE: change objects by a change point or their properties, as AutoCAD does (#2534) * Add CHANGE, changing objects by a change point or their properties as AutoCAD does A change point moves each line's nearer end to it (level or plumb under ORTHOMODE), passes a circle through it, and places a text, attribute definition or block reference by it when that is the one object selected; otherwise "Change point ignored" and the object's questions follow, in selection order. Properties is CHPROP's loop with Elev, applied as the command ends. Objects on locked layers are left out, through selection helpers now shared with CHPROP. Co-Authored-By: Claude Opus 5.5 * CHANGE: refuse a JSON call without a readable point or elevation A `point` or `elevation` that can't be read is an error, and so is a call with neither, instead of changing nothing. Co-Authored-By: Claude Opus 5.5 * CHANGE: Elev on every kind AutoCAD sets it for; Aligned and Fit text; rotation default Measured in AutoCAD 2024: Elev also sets the z of ellipses, multiline texts, solids and flat 3D polylines (a 3D polyline between heights keeps them), and of hatches, which stop being associative ("Hatch boundary associativity removed."). Aligned text isn't asked its height or rotation and Fit text its rotation, their two points setting them. The rotation default shows as the drawing measures angles (ANGBASE 90 shows a text at 0 as 270.00). Shared z is compared to rounding, and the radius and height prompts say what they need. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/hatch.rs | 1 + crates/engine/src/cmd/hatch/assoc.rs | 2 +- crates/engine/src/cmd/props.rs | 5 + crates/engine/src/cmd/props/change.rs | 544 +++++++++++++++++++++++ crates/engine/src/cmd/props/chprop.rs | 104 +++-- crates/engine/tests/it/change_command.rs | 321 +++++++++++++ crates/engine/tests/it/main.rs | 1 + 7 files changed, 952 insertions(+), 26 deletions(-) create mode 100644 crates/engine/src/cmd/props/change.rs create mode 100644 crates/engine/tests/it/change_command.rs diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index ca7defed8..a362a3502 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -15,6 +15,7 @@ use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_p use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step}; mod assoc; +pub(crate) use assoc::detach; mod edit; mod pick; use super::has_doc; diff --git a/crates/engine/src/cmd/hatch/assoc.rs b/crates/engine/src/cmd/hatch/assoc.rs index b653aa451..e67782938 100644 --- a/crates/engine/src/cmd/hatch/assoc.rs +++ b/crates/engine/src/cmd/hatch/assoc.rs @@ -121,7 +121,7 @@ pub(super) fn same_shape(a: &[PolyVertex], b: &[PolyVertex]) -> bool { ba.min.dist(bb.min) <= eps && ba.max.dist(bb.max) <= eps && (shoelace(&pa).abs() - shoelace(&pb).abs()).abs() <= eps * (1.0 + size) } -pub(super) fn detach(h: &mut Hatch) { +pub(crate) fn detach(h: &mut Hatch) { h.associative = false; h.loops.iter_mut().for_each(|l| l.sources.clear()); } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 45199b12c..8afaddb3d 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1,6 +1,7 @@ //! Properties: per-object property edits, current properties, CHPROP, MATCHPROP, linetypes, units, //! RENAME. +mod change; mod chprop; mod dash_units; mod matchprop; @@ -24,6 +25,10 @@ pub fn specs() -> Vec { CommandSpec::new("chprop", "Change Properties", chprop::run_chprop) .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) + .alias(&["-ch"]) + .params("{handles?, point?: [x, y], elevation?} → {changed, ignored, differingZ, detachedHatches, locked}: the point moves the nearer end of each line to it (level or plumb with the other end under ORTHOMODE) and, when it is the one object, passes a circle through it or places a text, attribute definition or block reference at it (`ignored` otherwise); `elevation` sets the z of objects whose points share one (`differingZ` otherwise); objects on locked layers are left out (the command line asks Specify change point or [Properties], then about each circle, text, attribute definition and block reference in turn)") + .interactive(|_| Ok(Box::new(change::ChangeM::new()))), CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) diff --git a/crates/engine/src/cmd/props/change.rs b/crates/engine/src/cmd/props/change.rs new file mode 100644 index 000000000..64ff4b1ac --- /dev/null +++ b/crates/engine/src/cmd/props/change.rs @@ -0,0 +1,544 @@ +//! CHANGE: change objects by a change point, or change their properties, as AutoCAD 2024 does. +//! +//! "Specify change point or [Properties]" follows "Select objects", which leaves objects on locked +//! layers out as CHPROP does. Properties is CHPROP's loop with Elev added: the elevation is set +//! when the command ends, and objects whose points differ in z keep theirs ("Cannot change +//! elevation of objects with differing Z coordinates."). A change point, or Enter, goes through the +//! objects in the order they were selected. Measured from AutoLISP's `command` (accoreconsole, +//! every object read back with `entget`): +//! - each line moves its end nearer the point to it: (0,0)–(50,0) with (60,10) gives +//! (0,0)–(60,10), with (−5,5) gives (−5,5)–(50,0). Under ORTHOMODE the moved end stays level or +//! plumb with the other one ((60,0)). Enter leaves lines alone; +//! - a circle passes through the point (centre (100,0) and (115,0): radius 15), or asks "Specify +//! new circle radius "; +//! - a text is placed by the point (the alignment point of justified text), or asks "Specify new +//! text insertion point "; then "Enter new text style", "Specify new height" (not +//! with a style of fixed height, nor for Aligned text), "Specify new rotation angle" (not for +//! Aligned or Fit text, whose two points set it) and "Enter new text". An +//! attribute definition asks "Enter new tag", "Enter new prompt" and "Enter new default value" in +//! place of the text. A style that does not exist is refused: `Style "5" not defined - use STYLE +//! command.`; +//! - a block reference is placed by the point, its attributes moving and turning with it, or asks +//! "Specify new block insertion point "; then "Specify new block rotation angle"; +//! - the point places a circle, text or block reference only when it is the one object selected: +//! with others, "Change point ignored" comes before that object's questions, which are asked as +//! for Enter; +//! - other objects (arcs, polylines…) are left alone, and with nothing to change it says "No +//! changeable object selected". +//! +//! Elev sets the z of lines, 3D polylines and solids whose points share one, and of points, +//! circles, arcs, ellipses, polylines, hatches (no longer associative: "Hatch boundary +//! associativity removed."), texts, multiline texts and block references. + +use std::collections::{HashSet, VecDeque}; + +use cadcraft_doc::{Attrib, EntityKind, HAlign, Handle, Text}; +use cadcraft_geom::{Mat3, Vec2, Vec3}; +use serde_json::{Value, json}; + +use super::super::machines::{SelOutcome, SelectPhase, number}; +use super::super::{bad, f64_req, point_req, targets}; +use super::chprop::{ChpropM, begin_unlocked, feed_unlocked, locked}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +/// A question CHANGE asks about one object. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Ask { + /// Not a question: "Change point ignored" as the object comes up. + Ignored, + Radius, + TextPoint, + Style, + Height, + Rotation, + Value, + Tag, + AttPrompt, + Default, + BlockPoint, + BlockRotation, +} + +enum Stage { + Select, + Point, + Properties(Box), + /// The questions left, in order, each about one object. + Asking(VecDeque<(Handle, Ask)>), +} + +pub(super) struct ChangeM { + select: SelectPhase, + handles: Vec, + stage: Stage, +} + +impl ChangeM { + pub(super) fn new() -> Self { + ChangeM { select: SelectPhase::default(), handles: Vec::new(), stage: Stage::Select } + } + + /// Apply the change point `p` (`None`: Enter) and line up the questions it leaves. + fn change_point(&mut self, s: &mut Session, p: Option) -> Result { + let alone = self.handles.len() == 1; + let ortho = s.drafting_settings().orthomode; + let mut asks = VecDeque::new(); + let mut changeable = false; + for &h in &self.handles { + let Some(kind) = s.doc()?.entity(h).map(|e| e.kind.clone()) else { continue }; + if matches!(kind, EntityKind::Line(_)) { + if let Some(p) = p { + move_end(s, h, p, ortho)?; + changeable = true; + } + continue; + } + let Some(questions) = questions(&kind) else { continue }; + changeable = true; + let placed = p.filter(|_| alone); + if p.is_some() && !alone { + asks.push_back((h, Ask::Ignored)); + } + if let Some(q) = placed { + place(s, h, q)?; + } + // The point answers the first question: the radius or the insertion point. + asks.extend(questions.iter().skip(usize::from(placed.is_some())).map(|a| (h, *a))); + } + if !changeable { + s.echo("No changeable object selected"); + return Ok(Step::Done); + } + self.stage = Stage::Asking(asks); + self.advance(s) + } + + /// Pass over what needs no answer: say "Change point ignored", and skip what [`skipped`] + /// says isn't asked. Done when nothing is left to ask. + fn advance(&mut self, s: &mut Session) -> Result { + let Stage::Asking(asks) = &mut self.stage else { return Ok(Step::Continue) }; + while let Some(&(h, ask)) = asks.front() { + match ask { + Ask::Ignored => s.echo("Change point ignored"), + a if skipped(s, h, a) => {} + _ => return Ok(Step::Continue), + } + asks.pop_front(); + } + s.set_selection(Vec::new()); + Ok(Step::Done) + } +} + +/// The questions about an object of `kind`, the first answered by the change point when it is +/// the one object; `None` when the change point leaves it alone. +fn questions(kind: &EntityKind) -> Option<&'static [Ask]> { + Some(match kind { + EntityKind::Circle(_) => &[Ask::Radius], + EntityKind::Text(_) => &[Ask::TextPoint, Ask::Style, Ask::Height, Ask::Rotation, Ask::Value], + EntityKind::AttDef(_) => &[Ask::TextPoint, Ask::Style, Ask::Height, Ask::Rotation, Ask::Tag, Ask::AttPrompt, Ask::Default], + EntityKind::Insert(_) => &[Ask::BlockPoint, Ask::BlockRotation], + _ => return None, + }) +} + +fn text_of(kind: &EntityKind) -> Option<&Text> { + match kind { + EntityKind::Text(t) | EntityKind::AttDef(Attrib { text: t, .. }) => Some(t), + _ => None, + } +} + +fn text_of_mut(kind: &mut EntityKind) -> Option<&mut Text> { + match kind { + EntityKind::Text(t) | EntityKind::AttDef(Attrib { text: t, .. }) => Some(t), + _ => None, + } +} + +/// Where a circle, text or block reference is measured from: its centre, the point it is placed by +/// (the alignment point of justified text) or its insertion point. +fn anchor(kind: &EntityKind) -> Option { + match kind { + EntityKind::Circle(c) => Some(c.center.xy()), + EntityKind::Insert(i) => Some(i.insert.xy()), + k => text_of(k).map(Text::justify_point), + } +} + +/// Whether CHANGE passes over `ask` for text `h`: the height of a text whose style has a fixed +/// one or that is Aligned, and the rotation of Aligned or Fit text (their two points set it). +fn skipped(s: &Session, h: Handle, ask: Ask) -> bool { + let Ok(d) = s.doc() else { return false }; + let Some(t) = d.entity(h).and_then(|e| text_of(&e.kind)) else { return false }; + match ask { + Ask::Height => t.halign == HAlign::Aligned || d.text_style(&t.style).is_some_and(|st| st.height > 0.0), + Ask::Rotation => matches!(t.halign, HAlign::Aligned | HAlign::Fit), + _ => false, + } +} + +/// Move the end of line `h` nearer `p` to it; under ortho, level or plumb with the other end. +fn move_end(s: &mut Session, h: Handle, p: Vec2, ortho: bool) -> Result<()> { + let settings = s.drafting_settings(); + s.doc_mut()?.modify_entity(h, |e| { + if let EntityKind::Line(l) = &mut e.kind { + let (end, other) = if l.a.xy().dist(p) <= l.b.xy().dist(p) { (&mut l.a, l.b) } else { (&mut l.b, l.a) }; + let q = if ortho { crate::snap::iso::constrain(&settings, other.xy(), p) } else { p }; + end.x = q.x; + end.y = q.y; + } + })?; + Ok(()) +} + +/// Place circle, text or block reference `h` by `q`: a circle passes through it, a text or block +/// reference moves there (with its attributes). +fn place(s: &mut Session, h: Handle, q: Vec2) -> Result<()> { + s.doc_mut()?.modify_entity(h, |e| { + if let EntityKind::Circle(c) = &mut e.kind { + let r = c.center.xy().dist(q); + if r > 0.0 && r.is_finite() { + c.radius = r; + } + } else if let Some(at) = anchor(&e.kind) { + e.kind.transform(&Mat3::translate(q - at)); + } + })?; + Ok(()) +} + +/// Set a circle's radius or a text's height. +fn set_length(s: &mut Session, h: Handle, v: f64) -> Result<()> { + s.doc_mut()?.modify_entity(h, |e| match &mut e.kind { + EntityKind::Circle(c) => c.radius = v, + k => { + if let Some(t) = text_of_mut(k) { + t.height = v; + } + } + })?; + Ok(()) +} + +/// Set a text's rotation, or turn a block reference (and its attributes) to `angle` about its +/// insertion point. +fn set_rotation(s: &mut Session, h: Handle, angle: f64) -> Result<()> { + s.doc_mut()?.modify_entity(h, |e| { + if let EntityKind::Insert(i) = &e.kind { + let m = Mat3::rotate_about(i.insert.xy(), angle - i.rotation); + e.kind.transform(&m); + } else if let Some(t) = text_of_mut(&mut e.kind) { + t.rotation = cadcraft_geom::norm_angle(angle); + } + })?; + Ok(()) +} + +/// Take an answer to `ask` about `h`; `false` when it was refused (the question comes again). +fn answer(s: &mut Session, h: Handle, ask: Ask, i: Input) -> Result { + let at = s.doc()?.entity(h).and_then(|e| anchor(&e.kind)).unwrap_or(Vec2::ZERO); + match (ask, i.clone()) { + // Enter keeps what there is. + (_, Input::Enter) => {} + (Ask::TextPoint | Ask::BlockPoint, Input::Point(q)) => place(s, h, q)?, + (Ask::TextPoint | Ask::BlockPoint, _) => return Err(EngineError::Other("Point or option keyword required.".into())), + (Ask::Radius | Ask::Height, Input::Point(_) | Input::Text(_)) => { + let v = match &i { + Input::Point(q) => q.dist(at), + Input::Text(t) => number(t).ok_or_else(|| EngineError::Other("Requires numeric distance or second point.".into()))?, + _ => 0.0, + }; + if !(v > 0.0 && v.is_finite()) { + return Err(EngineError::Other("Value must be positive and nonzero.".into())); + } + set_length(s, h, v)?; + } + (Ask::Rotation | Ask::BlockRotation, Input::Point(q)) => set_rotation(s, h, at.angle_to(q))?, + (Ask::Rotation | Ask::BlockRotation, Input::Text(t)) => { + let a = s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?; + set_rotation(s, h, a)?; + } + (Ask::Style, Input::Text(t) | Input::Keyword(t)) => { + let name = t.trim(); + let Some(style) = s.doc()?.text_style(name).map(|st| st.name.clone()) else { + s.echo(format!("Style \"{name}\" not defined - use STYLE command.")); + return Ok(false); + }; + s.doc_mut()?.modify_entity(h, |e| { + if let Some(t) = text_of_mut(&mut e.kind) { + t.style = style; + } + })?; + } + (Ask::Value | Ask::Tag | Ask::AttPrompt | Ask::Default, Input::Text(t) | Input::Keyword(t)) => { + s.doc_mut()?.modify_entity(h, |e| match (&mut e.kind, ask) { + (EntityKind::AttDef(a), Ask::Tag) => a.tag = t, + (EntityKind::AttDef(a), Ask::AttPrompt) => a.prompt = t, + (k, _) => { + if let Some(x) = text_of_mut(k) { + x.value = t; + } + } + })?; + } + _ => return Ok(false), + } + Ok(true) +} + +/// The question `ask` about `h`. +fn ask_prompt(s: &Session, h: Handle, ask: Ask) -> Prompt { + let d = s.doc().ok(); + let kind = d.and_then(|d| d.entity(h)).map(|e| &e.kind); + let at = kind.and_then(anchor); + let text = kind.and_then(text_of); + // As the drawing shows directions: from ANGBASE in the ANGDIR sense (ANGBASE 90° shows a text + // at 0° as 270.00). + let deg = |a: f64| format!("{:.2}", s.angle_settings().shown(a).to_degrees()); + match ask { + Ask::Radius => Prompt::new("Specify new circle radius", Accept::POINT_OR_NUMBER).default("no change").base_opt(at).distance(), + Ask::TextPoint => Prompt::new("Specify new text insertion point", Accept::POINT).default("no change"), + Ask::BlockPoint => Prompt::new("Specify new block insertion point", Accept::POINT).default("no change"), + Ask::Style => Prompt::new("Enter new text style", Accept::TEXT).default(text.map(|t| t.style.clone()).unwrap_or_default()), + Ask::Height => Prompt::new("Specify new height", Accept::POINT_OR_NUMBER) + .default(format!("{:.4}", text.map_or(0.0, |t| t.height))) + .base_opt(at) + .distance(), + Ask::Rotation => { + Prompt::new("Specify new rotation angle", Accept::POINT_OR_NUMBER).default(deg(text.map_or(0.0, |t| t.rotation))).base_opt(at) + } + Ask::BlockRotation => { + let r = match kind { + Some(EntityKind::Insert(i)) => i.rotation, + _ => 0.0, + }; + Prompt::new("Specify new block rotation angle", Accept::POINT_OR_NUMBER).default(deg(r)).base_opt(at) + } + Ask::Value => Prompt::new("Enter new text", Accept::TEXT).default(text.map(|t| t.value.clone()).unwrap_or_default()), + Ask::Default => Prompt::new("Enter new default value", Accept::TEXT).default(text.map(|t| t.value.clone()).unwrap_or_default()), + Ask::Tag | Ask::AttPrompt => { + let (msg, v) = match (kind, ask) { + (Some(EntityKind::AttDef(a)), Ask::Tag) => ("Enter new tag", a.tag.clone()), + (Some(EntityKind::AttDef(a)), _) => ("Enter new prompt", a.prompt.clone()), + (_, Ask::Tag) => ("Enter new tag", String::new()), + _ => ("Enter new prompt", String::new()), + }; + Prompt::new(msg, Accept::TEXT).default(v) + } + Ask::Ignored => Prompt::new("", Accept::TEXT), + } +} + +/// The one z of `zs`, to rounding; `None` when they differ. +fn shared_z(zs: impl IntoIterator) -> Option { + let mut zs = zs.into_iter(); + let first = zs.next().unwrap_or(0.0); + zs.all(|z| (z - first).abs() <= 1e-9 * (1.0 + first.abs())).then_some(first) +} + +/// The elevation of an object Elev sets: `Some(None)` when its points differ in z (a line between +/// two heights), `None` for the kinds Elev leaves alone. +pub(super) fn elevation_of(kind: &EntityKind) -> Option> { + match kind { + EntityKind::Line(l) => Some(shared_z([l.a.z, l.b.z])), + EntityKind::Polyline3d(p) => Some(shared_z(p.points.iter().map(|q| q.z))), + EntityKind::Solid(so) | EntityKind::Trace(so) => Some(shared_z(so.corners.iter().map(|c| c.z))), + EntityKind::Point(p) => Some(Some(p.p.z)), + EntityKind::Circle(c) => Some(Some(c.center.z)), + EntityKind::Arc(a) => Some(Some(a.center.z)), + EntityKind::Ellipse(e) => Some(Some(e.center.z)), + EntityKind::LwPolyline(p) => Some(Some(p.elevation)), + EntityKind::Hatch(h) => Some(Some(h.elevation)), + EntityKind::MText(t) => Some(Some(t.insert.z)), + EntityKind::Insert(i) => Some(Some(i.insert.z)), + k => text_of(k).map(|t| Some(t.insert.z)), + } +} + +/// Move `text` up by `dz`. +fn raise_text(text: &mut Text, dz: f64) { + for p in std::iter::once(&mut text.insert).chain(text.align_pt.as_mut()) { + p.z += dz; + } +} + +fn set_elevation(kind: &mut EntityKind, z: f64) { + let set = |p: &mut Vec3| p.z = z; + match kind { + EntityKind::Line(l) => { + set(&mut l.a); + set(&mut l.b); + } + EntityKind::Polyline3d(p) => p.points.iter_mut().for_each(set), + EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(set), + EntityKind::Point(p) => set(&mut p.p), + EntityKind::Circle(c) => set(&mut c.center), + EntityKind::Arc(a) => set(&mut a.center), + EntityKind::Ellipse(e) => set(&mut e.center), + EntityKind::LwPolyline(p) => p.elevation = z, + EntityKind::Hatch(h) => { + h.elevation = z; + crate::cmd::hatch::detach(h); + } + EntityKind::MText(t) => set(&mut t.insert), + // A block reference's attributes go up with it. + EntityKind::Insert(i) => { + let dz = z - i.insert.z; + set(&mut i.insert); + for a in &mut i.attribs { + raise_text(&mut a.text, dz); + if let Some(ml) = &mut a.multiline { + ml.mtext.insert.z += dz; + } + } + } + k => { + if let Some(t) = text_of_mut(k) { + let dz = z - t.insert.z; + raise_text(t, dz); + } + } + } +} + +/// What [`elevate`] did. +pub(super) struct Elevated { + /// The objects whose elevation was set. + pub(super) set: Vec, + /// Objects whose points differ in z, which keep theirs. + pub(super) differing: usize, + /// Associative hatches, which no longer are. + pub(super) detached: usize, +} + +/// Set the elevation of the objects among `hs` whose points share one. +pub(super) fn elevate(s: &mut Session, hs: &[Handle], z: f64) -> Result { + let d = s.doc_mut()?; + let mut r = Elevated { set: Vec::new(), differing: 0, detached: 0 }; + for &h in hs { + let Some(e) = d.entity(h) else { continue }; + match elevation_of(&e.kind) { + Some(Some(_)) => { + r.detached += usize::from(matches!(&e.kind, EntityKind::Hatch(hatch) if hatch.associative)); + d.modify_entity(h, |e| set_elevation(&mut e.kind, z))?; + r.set.push(h); + } + Some(None) => r.differing += 1, + None => {} + } + } + Ok(r) +} + +/// Properties ▸ Elev as the command ends: set the elevation, and say what was left alone or +/// changed besides. +pub(super) fn elevate_and_say(s: &mut Session, hs: &[Handle], z: f64) -> Result<()> { + let r = elevate(s, hs, z)?; + if r.differing > 0 { + s.echo("Cannot change elevation of objects with differing Z coordinates."); + } + if r.detached > 0 { + s.echo("Hatch boundary associativity removed."); + } + Ok(()) +} + +/// CHANGE's JSON form: `point` changes the objects as the change point does (`ignored`: circles, +/// texts and block references it leaves alone because others were selected too), `elevation` as +/// Properties ▸ Elev does (`differingZ`: objects whose points differ in z; `detachedHatches`: +/// associative hatches that no longer are); objects on locked layers are left out (`locked`). +pub(super) fn run_change(s: &mut Session, p: &Value) -> Result { + // A point or an elevation that can't be read is refused, and so is a call with neither. + let point = p.get("point").map(|_| point_req("change", p, "point")).transpose()?; + let elevation = p.get("elevation").map(|_| f64_req("change", p, "elevation")).transpose()?; + if point.is_none() && elevation.is_none() { + return Err(bad("change", "`point` or `elevation` is required")); + } + let hs = targets(s, p)?; + let locked = locked(s, &hs); + let free: Vec = hs.into_iter().filter(|h| !locked.contains(h)).collect(); + let (mut changed, mut ignored, mut differing, mut detached) = (HashSet::new(), 0, 0, 0); + if let Some(q) = point { + let ortho = s.drafting_settings().orthomode; + for &h in &free { + let Some(kind) = s.doc()?.entity(h).map(|e| e.kind.clone()) else { continue }; + if matches!(kind, EntityKind::Line(_)) { + move_end(s, h, q, ortho)?; + changed.insert(h); + } else if questions(&kind).is_some() { + if free.len() == 1 { + place(s, h, q)?; + changed.insert(h); + } else { + ignored += 1; + } + } + } + } + if let Some(z) = elevation { + let r = elevate(s, &free, z)?; + changed.extend(r.set); + (differing, detached) = (r.differing, r.detached); + } + Ok(json!({ "changed": changed.len(), "ignored": ignored, "differingZ": differing, "detachedHatches": detached, "locked": locked.len() })) +} + +impl Interactive for ChangeM { + fn name(&self) -> &'static str { + "CHANGE" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.select = begin_unlocked(s); + if self.select.done { + self.handles = self.select.picked.clone(); + self.stage = Stage::Point; + } + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + match &self.stage { + Stage::Select => self.select.prompt(), + Stage::Point => Prompt::new("Specify change point", Accept::POINT).kw(&["Properties"]), + Stage::Properties(m) => m.prompt(s), + Stage::Asking(asks) => asks.front().map_or_else(|| Prompt::new("", Accept::TEXT), |&(h, ask)| ask_prompt(s, h, ask)), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match &mut self.stage { + Stage::Select => { + return Ok(match feed_unlocked(&mut self.select, s, i)? { + SelOutcome::More => Step::Continue, + SelOutcome::Done(hs) => { + self.handles = hs; + self.stage = Stage::Point; + Step::Continue + } + SelOutcome::Empty => { + s.set_selection(Vec::new()); + Step::Done + } + }); + } + Stage::Properties(m) => return m.input(s, i), + Stage::Asking(asks) => { + let Some(&(h, ask)) = asks.front() else { return Ok(Step::Done) }; + if !answer(s, h, ask, i)? { + return Ok(Step::Continue); + } + asks.pop_front(); + return self.advance(s); + } + Stage::Point => {} + } + match i { + Input::Keyword(k) if k == "Properties" => { + self.stage = Stage::Properties(Box::new(ChpropM::change_properties(self.handles.clone()))); + Ok(Step::Continue) + } + Input::Point(p) => self.change_point(s, Some(p)), + Input::Enter => self.change_point(s, None), + _ => Err(EngineError::Other("Point or option keyword required.".into())), + } + } +} diff --git a/crates/engine/src/cmd/props/chprop.rs b/crates/engine/src/cmd/props/chprop.rs index 0949abee9..fac500ecd 100644 --- a/crates/engine/src/cmd/props/chprop.rs +++ b/crates/engine/src/cmd/props/chprop.rs @@ -28,6 +28,9 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; const PROPERTIES: [&str; 7] = ["Color", "LAyer", "LType", "ltScale", "LWeight", "Thickness", "TRansparency"]; +/// CHANGE's Properties: CHPROP's list with Elev. +const CHANGE_PROPERTIES: [&str; 8] = ["Color", "Elev", "LAyer", "LType", "ltScale", "LWeight", "Thickness", "TRansparency"]; + /// What CHPROP asks for. #[derive(Clone, Copy, Debug, PartialEq)] enum Ask { @@ -40,6 +43,7 @@ enum Ask { Lineweight, Thickness, Transparency, + Elevation, } pub(super) struct ChpropM { @@ -47,11 +51,35 @@ pub(super) struct ChpropM { handles: Vec, /// `None` while objects are selected. ask: Option, + /// CHANGE's Properties: Elev is on the list. + change: bool, + /// The elevation typed at Elev, set when the command ends. + elevation: Option, } impl ChpropM { pub(super) fn new() -> Self { - ChpropM { select: SelectPhase::default(), handles: Vec::new(), ask: None } + ChpropM { select: SelectPhase::default(), handles: Vec::new(), ask: None, change: false, elevation: None } + } + + /// CHANGE's Properties option on `handles`. + pub(super) fn change_properties(handles: Vec) -> Self { + ChpropM { select: SelectPhase::default(), handles, ask: Some(Ask::Property), change: true, elevation: None } + } + + fn keywords(&self) -> &'static [&'static str] { + if self.change { &CHANGE_PROPERTIES } else { &PROPERTIES } + } + + /// The selection's common elevation, or "varies" (as a line between two heights does alone). + fn common_elevation(&self, s: &Session) -> String { + let Ok(d) = s.doc() else { return String::new() }; + let zs: Vec> = self.handles.iter().filter_map(|h| d.entity(*h)).filter_map(|e| super::change::elevation_of(&e.kind)).collect(); + match zs.first() { + None => format!("{:.4}", 0.0), + Some(Some(z)) if zs.iter().all(|o| *o == Some(*z)) => format!("{z:.4}"), + Some(_) => "varies".into(), + } } /// The selection's common value of a property, or "varies". @@ -151,6 +179,13 @@ impl ChpropM { return Ok(false); } } + Ask::Elevation => match number(word).filter(|v| v.is_finite()) { + Some(z) => self.elevation = Some(z), + None => { + s.echo("Requires a number."); + return Ok(false); + } + }, Ask::Property => {} } Ok(true) @@ -158,7 +193,7 @@ impl ChpropM { } /// The objects among `hs` on locked layers. -fn locked(s: &Session, hs: &[Handle]) -> HashSet { +pub(super) fn locked(s: &Session, hs: &[Handle]) -> HashSet { hs.iter().copied().filter(|h| is_locked(s, *h)).collect() } @@ -170,6 +205,38 @@ fn say_locked(s: &mut Session, n: usize) { } } +/// Start selecting objects, leaving those on locked layers out of the pickfirst selection (and +/// saying how many); `done` when some of it is left. +pub(super) fn begin_unlocked(s: &mut Session) -> SelectPhase { + let mut select = SelectPhase::begin(s); + if select.done { + let locked = locked(s, &select.picked); + if !locked.is_empty() { + select.picked.retain(|h| !locked.contains(h)); + say_locked(s, locked.len()); + s.set_selection(select.picked.clone()); + // Nothing left of the pickfirst selection: ask for objects instead. + select.done = !select.picked.is_empty(); + } + } + select +} + +/// Feed `i` to `select`, leaving picked objects on locked layers out and saying how many after +/// what was found. +pub(super) fn feed_unlocked(select: &mut SelectPhase, s: &mut Session, i: Input) -> Result { + let (i, n) = match i { + Input::Pick(hs) if !select.removing => { + let locked = locked(s, &hs); + (Input::Pick(hs.into_iter().filter(|h| !locked.contains(h)).collect()), locked.len()) + } + i => (i, 0), + }; + let outcome = select.feed(s, &i)?; + say_locked(s, n); + 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 { @@ -242,17 +309,7 @@ impl Interactive for ChpropM { "CHPROP" } fn begin(&mut self, s: &mut Session) -> Result { - self.select = SelectPhase::begin(s); - if self.select.done { - let locked = locked(s, &self.select.picked); - if !locked.is_empty() { - self.select.picked.retain(|h| !locked.contains(h)); - say_locked(s, locked.len()); - s.set_selection(self.select.picked.clone()); - // Nothing left of the pickfirst selection: ask for objects instead. - self.select.done = !self.select.picked.is_empty(); - } - } + self.select = begin_unlocked(s); if self.select.done { self.handles = self.select.picked.clone(); self.ask = Some(Ask::Property); @@ -262,7 +319,7 @@ impl Interactive for ChpropM { fn prompt(&self, s: &Session) -> Prompt { let Some(ask) = self.ask else { return self.select.prompt() }; match ask { - Ask::Property => Prompt::new("Enter property to change", Accept::TEXT).kw(&PROPERTIES), + Ask::Property => Prompt::new("Enter property to change", Accept::TEXT).kw(self.keywords()), Ask::Color => { Prompt::new("New color", Accept::TEXT).kw(&["Truecolor"]).default(self.current(s, |e| e.common.color.name().to_ascii_uppercase())) } @@ -275,21 +332,13 @@ impl Interactive for ChpropM { Ask::Lineweight => Prompt::new("Enter new lineweight", Accept::TEXT).default(self.current(s, |e| lineweight_name(e.common.lineweight))), Ask::Thickness => Prompt::new("Specify new thickness", Accept::NUMBER).default(self.current(s, |e| format!("{:.4}", e.common.thickness))), Ask::Transparency => Prompt::new("Enter transparency value", KW).default(self.current(s, |e| e.common.transparency.name())), + Ask::Elevation => Prompt::new("Specify new elevation", Accept::NUMBER).default(self.common_elevation(s)), } } fn input(&mut self, s: &mut Session, i: Input) -> Result { let Some(ask) = self.ask else { // Objects on locked layers are left out, and said after what was found. - let (i, n) = match i { - Input::Pick(hs) if !self.select.removing => { - let locked = locked(s, &hs); - (Input::Pick(hs.into_iter().filter(|h| !locked.contains(h)).collect()), locked.len()) - } - i => (i, 0), - }; - let outcome = self.select.feed(s, &i)?; - say_locked(s, n); - return Ok(match outcome { + return Ok(match feed_unlocked(&mut self.select, s, i)? { SelOutcome::More => Step::Continue, SelOutcome::Done(hs) => { self.handles = hs; @@ -304,6 +353,10 @@ impl Interactive for ChpropM { }; match (ask, i) { (Ask::Property, Input::Enter) => { + // CHANGE sets the elevation as it ends. + if let Some(z) = self.elevation { + super::change::elevate_and_say(s, &self.handles, z)?; + } s.set_selection(Vec::new()); return Ok(Step::Done); } @@ -315,12 +368,13 @@ impl Interactive for ChpropM { "ltScale" => Ask::LtScale, "LWeight" => Ask::Lineweight, "Thickness" => Ask::Thickness, + "Elev" => Ask::Elevation, _ => Ask::Transparency, }); } (Ask::Property, Input::Text(t)) => { let t = t.trim().trim_start_matches('_').to_ascii_lowercase(); - let n = PROPERTIES.iter().filter(|k| k.to_ascii_lowercase().starts_with(&t)).count(); + let n = self.keywords().iter().filter(|k| k.to_ascii_lowercase().starts_with(&t)).count(); s.echo(if n > 1 { "Ambiguous response, please clarify..." } else { "Invalid option keyword." }); } (Ask::Color, Input::Keyword(k)) if k == "Truecolor" => self.ask = Some(Ask::TrueColor), diff --git a/crates/engine/tests/it/change_command.rs b/crates/engine/tests/it/change_command.rs new file mode 100644 index 000000000..f497112c5 --- /dev/null +++ b/crates/engine/tests/it/change_command.rs @@ -0,0 +1,321 @@ +//! CHANGE as AutoCAD 2024 runs it from AutoLISP's `command` (accoreconsole, every object read back +//! with `entget`). + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec}; +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::doc::color::Color; +use serde_json::json; + +/// The measured drawing, its objects named in LISP: lines `a` (0,0)–(50,0) and `b` (0,20)–(50,30) +/// on layer L1, circle `c` (centre (100,0), radius 10), text `t` "ABC" at (0,50) 2.5 high, circle +/// `e` ((200,0), 3), arc `r` ((150,0), 10, 0°–90°) and polyline `p` (0,100)–(50,100)–(50,120); then +/// `code`. +fn run(code: &str) -> Session { + // `entmake` and `entget` go through the DXF codec, as in the app. + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + let mut s = Session::new(); + s.doc_mut().unwrap().ensure_layer("L1"); + for (v, made) in [ + ("a", "(0 . \"LINE\") (10 0.0 0.0 0.0) (11 50.0 0.0 0.0)"), + ("b", "(0 . \"LINE\") (8 . \"L1\") (10 0.0 20.0 0.0) (11 50.0 30.0 0.0)"), + ("c", "(0 . \"CIRCLE\") (10 100.0 0.0 0.0) (40 . 10.0)"), + ("t", "(0 . \"TEXT\") (10 0.0 50.0 0.0) (40 . 2.5) (1 . \"ABC\")"), + ("e", "(0 . \"CIRCLE\") (10 200.0 0.0 0.0) (40 . 3.0)"), + ("r", "(0 . \"ARC\") (10 150.0 0.0 0.0) (40 . 10.0) (50 . 0.0) (51 . 1.5707963267948966)"), + ("p", "(0 . \"LWPOLYLINE\") (90 . 3) (70 . 0) (10 0.0 100.0) (10 50.0 100.0) (10 50.0 120.0)"), + ] { + s.cmdline(&format!("(setq {v} (progn (entmake '({made})) (entlast)))")).unwrap(); + } + s.log.clear(); + s.cmdline(&format!("(progn {code})")).unwrap(); + s +} + +/// The `i`th object drawn. +fn kind(s: &Session, i: usize) -> EntityKind { + s.doc().unwrap().model.iter().nth(i).unwrap().kind.clone() +} + +fn line(s: &Session, i: usize) -> [[f64; 3]; 2] { + let EntityKind::Line(l) = kind(s, i) else { panic!("not a line") }; + [[l.a.x, l.a.y, l.a.z], [l.b.x, l.b.y, l.b.z]] +} + +fn radius(s: &Session, i: usize) -> f64 { + let EntityKind::Circle(c) = kind(s, i) else { panic!("not a circle") }; + c.radius +} + +fn text(s: &Session, i: usize) -> cadcraft_engine::doc::Text { + match kind(s, i) { + EntityKind::Text(t) => t, + EntityKind::AttDef(a) => a.text, + _ => panic!("not a text"), + } +} + +fn said(s: &Session, line: &str) -> usize { + s.log.iter().filter(|l| l.as_str() == line).count() +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn the_change_point_moves_the_nearer_end_of_each_line() { + let s = run("(command \"_.CHANGE\" a \"\" '(60.0 10.0))"); + assert_eq!(line(&s, 0), [[0.0, 0.0, 0.0], [60.0, 10.0, 0.0]]); + let s = run("(command \"_.CHANGE\" a \"\" '(-5.0 5.0))"); + assert_eq!(line(&s, 0), [[-5.0, 5.0, 0.0], [50.0, 0.0, 0.0]]); + let s = run("(command \"_.CHANGE\" a b \"\" '(60.0 10.0))"); + assert_eq!((line(&s, 0)[1], line(&s, 1)), ([60.0, 10.0, 0.0], [[0.0, 20.0, 0.0], [60.0, 10.0, 0.0]])); + // Under ortho the moved end stays level or plumb with the other one. + let s = run("(setvar \"ORTHOMODE\" 1) (command \"_.CHANGE\" a b \"\" '(60.0 10.0))"); + assert_eq!((line(&s, 0)[1], line(&s, 1)[1]), ([60.0, 0.0, 0.0], [60.0, 20.0, 0.0])); + // Arcs and polylines are left alone: with a line the point still moves it, without one there + // is nothing to change. Enter leaves lines alone too. + let s = run("(command \"_.CHANGE\" a r p \"\" '(60.0 10.0))"); + assert_eq!(line(&s, 0)[1], [60.0, 10.0, 0.0]); + assert_eq!(said(&s, "No changeable object selected"), 0, "{:?}", s.log); + for code in ["(command \"_.CHANGE\" r \"\" '(160.0 10.0))", "(command \"_.CHANGE\" p \"\" '(60.0 130.0))", "(command \"_.CHANGE\" a \"\" \"\")"] { + let s = run(code); + assert_eq!(said(&s, "No changeable object selected"), 1, "{code}: {:?}", s.log); + assert!(s.running.is_none(), "{code}"); + assert_eq!(line(&s, 0)[1], [50.0, 0.0, 0.0], "{code}"); + } +} + +#[test] +fn a_circle_passes_through_the_point_or_takes_a_radius() { + let s = run("(command \"_.CHANGE\" c \"\" '(115.0 0.0))"); + assert!(near(radius(&s, 2), 15.0)); + let s = run("(command \"_.CHANGE\" c \"\" \"\" 20.0)"); + assert!(near(radius(&s, 2), 20.0)); + // With other objects the point is ignored, said as each circle comes up. + let s = run("(command \"_.CHANGE\" c e \"\" '(110.0 10.0) 8.0)"); + assert_eq!((radius(&s, 2), radius(&s, 4)), (8.0, 3.0)); + assert_eq!(said(&s, "Change point ignored"), 2, "{:?}", s.log); + assert!(s.prompt_text().contains("Specify new circle radius "), "{}", s.prompt_text()); + let s = run("(command \"_.CHANGE\" a c \"\" '(60.0 10.0) 12.0)"); + assert_eq!((line(&s, 0)[1], radius(&s, 2)), ([60.0, 10.0, 0.0], 12.0)); + assert_eq!(said(&s, "Change point ignored"), 1, "{:?}", s.log); +} + +#[test] +fn a_text_is_placed_by_the_point_then_asked_the_rest() { + let s = run("(command \"_.CHANGE\" t \"\" '(10.0 60.0) \"\" 4.0 \"\" \"\")"); + let t = text(&s, 3); + assert_eq!((t.insert.x, t.insert.y, t.height, t.value.as_str()), (10.0, 60.0, 4.0, "ABC")); + // Enter asks for the insertion point first. + let s = run("(command \"_.CHANGE\" t \"\" \"\" \"\" \"\" 5.0 30 \"XYZ\")"); + let t = text(&s, 3); + assert_eq!((t.insert.x, t.insert.y, t.height, t.value.as_str()), (0.0, 50.0, 5.0, "XYZ")); + assert!(near(t.rotation.to_degrees(), 30.0)); + // A style that does not exist is refused, and asked for again. + let s = run("(command \"_.CHANGE\" t \"\" \"\" \"\" \"5\")"); + assert_eq!(said(&s, "Style \"5\" not defined - use STYLE command."), 1, "{:?}", s.log); + assert!(s.prompt_text().contains("Enter new text style "), "{}", s.prompt_text()); + // Justified text is placed by its alignment point, with the point or after Enter. + for (justify, code) in [("(72 . 1) (73 . 2)", "'(10.0 60.0) \"\" \"\" \"\" \"\""), ("(72 . 2)", "\"\" '(10.0 60.0) \"\" \"\" \"\" \"\"")] { + let s = run(&format!( + "(entmake '((0 . \"TEXT\") (10 0.0 50.0 0.0) (40 . 2.5) (1 . \"ABC\") {justify} (11 0.0 50.0 0.0))) (command \"_.CHANGE\" (entlast) \"\" {code})" + )); + let at = text(&s, 7).align_pt.unwrap(); + assert_eq!((at.x, at.y), (10.0, 60.0), "{justify}"); + } +} + +#[test] +fn a_style_of_fixed_height_is_not_asked_for_a_height() { + let mut s = run(""); + s.execute("style", &json!({ "name": "FIXH", "height": 5.0 })).unwrap(); + s.cmdline("(entmake '((0 . \"TEXT\") (10 0.0 80.0 0.0) (40 . 5.0) (1 . \"FIX\") (7 . \"FIXH\")))").unwrap(); + s.cmdline("(command \"_.CHANGE\" (entlast) \"\" \"\" \"\" \"\" 30 \"Q\")").unwrap(); + let t = text(&s, 7); + assert_eq!((t.height, t.value.as_str()), (5.0, "Q")); + assert!(near(t.rotation.to_degrees(), 30.0)); + assert!(s.running.is_none()); +} + +#[test] +fn objects_are_asked_about_in_the_order_selected() { + let s = run( + "(setq d (progn (entmake '((0 . \"TEXT\") (10 0.0 70.0 0.0) (40 . 2.5) (1 . \"DEF\"))) (entlast))) (command \"_.CHANGE\" t d \"\" \"\" \"\" \"\" \"\" \"\" \"X1\" \"\" \"\" \"\" \"\" \"X2\")", + ); + assert_eq!((text(&s, 3).value.as_str(), text(&s, 7).value.as_str()), ("X1", "X2")); + let s = run("(command \"_.CHANGE\" t c \"\" \"\" \"\" \"\" \"\" \"\" \"TT\" 7.0)"); + assert_eq!((text(&s, 3).value.as_str(), radius(&s, 2)), ("TT", 7.0)); + let s = run("(command \"_.CHANGE\" c t \"\" \"\" 7.0 \"\" \"\" \"\" \"\" \"TT\")"); + assert_eq!((text(&s, 3).value.as_str(), radius(&s, 2)), ("TT", 7.0)); +} + +/// Block K: a circle and attribute TAG1 (default V) 5 above its base point, inserted at (200,0) +/// with the default value. +const BLOCK: &str = "(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0))) (entmake '((0 . \"ATTDEF\") (10 0.0 5.0 0.0) (40 . 2.5) (1 . \"V\") (3 . \"P\") (2 . \"TAG1\") (70 . 0))) (entmake '((0 . \"ENDBLK\"))) (command \"_.-INSERT\" \"K\" '(200.0 0.0) \"\" \"\" 0 \"\")"; + +#[test] +fn a_block_reference_is_placed_and_turned_with_its_attributes() { + let s = run(&format!("{BLOCK} (command \"_.CHANGE\" (entlast) \"\" '(250.0 50.0) 90)")); + let EntityKind::Insert(i) = kind(&s, 7) else { panic!("not a block reference") }; + assert_eq!((i.insert.x, i.insert.y), (250.0, 50.0)); + assert!(near(i.rotation.to_degrees(), 90.0)); + let a = &i.attribs.first().expect("the attribute").text; + assert!(near(a.insert.x, 245.0) && near(a.insert.y, 50.0), "{:?}", a.insert); + assert!(near(a.rotation.to_degrees(), 90.0)); + let s = run(&format!("{BLOCK} (command \"_.CHANGE\" (entlast) \"\" \"\" '(220.0 30.0) 90)")); + let EntityKind::Insert(i) = kind(&s, 7) else { panic!("not a block reference") }; + assert_eq!((i.insert.x, i.insert.y), (220.0, 30.0)); + assert!(near(i.rotation.to_degrees(), 90.0)); +} + +#[test] +fn an_attribute_definition_is_asked_its_tag_prompt_and_default() { + let s = run( + "(entmake '((0 . \"ATTDEF\") (10 300.0 0.0 0.0) (40 . 2.5) (1 . \"V\") (3 . \"P\") (2 . \"TAG1\") (70 . 0))) (command \"_.CHANGE\" (entlast) \"\" '(310.0 10.0) \"\" \"\" \"\" \"T2\" \"P2\" \"V2\")", + ); + let EntityKind::AttDef(a) = kind(&s, 7) else { panic!("not an attribute definition") }; + assert_eq!((a.text.insert.x, a.text.insert.y), (310.0, 10.0)); + assert_eq!((a.tag.as_str(), a.prompt.as_str(), a.text.value.as_str()), ("T2", "P2", "V2")); +} + +#[test] +fn objects_on_locked_layers_are_left_out() { + let s = run("(command \"_.-LAYER\" \"_LO\" \"L1\" \"\") (command \"_.CHANGE\" a b \"\" '(60.0 10.0))"); + assert_eq!((line(&s, 0)[1], line(&s, 1)[1]), ([60.0, 10.0, 0.0], [50.0, 30.0, 0.0])); + assert_eq!(said(&s, "1 was on a locked layer."), 1, "{:?}", s.log); +} + +#[test] +fn properties_add_elev_which_is_set_as_the_command_ends() { + let s = run("(command \"_.CHANGE\" a \"\" \"_P\" \"_C\" 2 \"_E\" 10.0 \"\")"); + let d = s.doc().unwrap(); + assert_eq!(d.model.iter().next().unwrap().common.color, Color::Index(2)); + assert_eq!(line(&s, 0), [[0.0, 0.0, 10.0], [50.0, 0.0, 10.0]]); + let s = run("(command \"_.CHANGE\" a c \"\" \"_P\" \"_LA\" \"L1\" \"_T\" 3.0 \"\")"); + for e in s.doc().unwrap().model.iter().take(3).step_by(2) { + assert_eq!((e.common.layer.as_str(), e.common.thickness), ("L1", 3.0)); + } + let s = run("(command \"_.CHANGE\" c t r p \"\" \"_P\" \"_E\" 5.0 \"\")"); + let EntityKind::Circle(c) = kind(&s, 2) else { panic!() }; + let EntityKind::Arc(r) = kind(&s, 5) else { panic!() }; + let EntityKind::LwPolyline(p) = kind(&s, 6) else { panic!() }; + assert_eq!((c.center.z, text(&s, 3).insert.z, r.center.z, p.elevation), (5.0, 5.0, 5.0, 5.0)); + // A line between two heights keeps them, said as the command ends; the elevation asked shows + // it varies. + let mut s = run( + "(setq l (progn (entmake '((0 . \"LINE\") (10 0.0 200.0 0.0) (11 50.0 200.0 10.0))) (entlast))) (command \"_.CHANGE\" l \"\" \"_P\" \"_E\")", + ); + assert!(s.prompt_text().contains("Specify new elevation "), "{}", s.prompt_text()); + s.cmdline("(command 5.0 \"\")").unwrap(); + assert_eq!(line(&s, 7), [[0.0, 200.0, 0.0], [50.0, 200.0, 10.0]]); + assert_eq!(said(&s, "Cannot change elevation of objects with differing Z coordinates."), 1, "{:?}", s.log); +} + +#[test] +fn change_by_json() { + let mut s = run(""); + let h: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + let r = s.execute("change", &json!({ "handles": [h[0], h[2]], "point": [60, 10] })).unwrap(); + assert_eq!((r["changed"].as_u64(), r["ignored"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!((line(&s, 0)[1], radius(&s, 2)), ([60.0, 10.0, 0.0], 10.0)); + s.execute("change", &json!({ "handles": [h[2]], "point": [115, 0] })).unwrap(); + assert!(near(radius(&s, 2), 15.0)); + s.execute("layer.set", &json!({ "name": "L1", "locked": true })).unwrap(); + let r = s.execute("change", &json!({ "handles": [h[0], h[1]], "elevation": 4.0 })).unwrap(); + assert_eq!((r["changed"].as_u64(), r["locked"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!((line(&s, 0)[0][2], line(&s, 1)[0][2]), (4.0, 0.0)); + // Neither a point nor an elevation, or one that can't be read, is refused. + for bad in [json!({ "handles": [h[0]] }), json!({ "handles": [h[0]], "point": "nowhere" }), json!({ "handles": [h[0]], "elevation": "high" })] { + assert!(s.execute("change", &bad).is_err(), "{bad}"); + } + assert_eq!(line(&s, 0), [[0.0, 0.0, 4.0], [60.0, 10.0, 4.0]]); +} + +/// Elev on the other kinds AutoCAD 2024 sets it for, each alone: the z of a point, a block +/// reference with its attributes, a multiline text, an ellipse, a solid and a flat 3D polyline; +/// a 3D polyline between heights keeps them, and a hatch loses its associativity. +#[test] +fn elev_sets_the_z_of_every_kind_with_one() { + let elev = |made: &str| { + let mut s = run(made); + s.log.clear(); + s.cmdline("(command \"_.CHANGE\" (entlast) \"\" \"_P\" \"_E\" 4.0 \"\")").unwrap(); + let k = s.doc().unwrap().model.iter().last().unwrap().kind.clone(); + (k, s) + }; + let (k, _) = elev("(entmake '((0 . \"POINT\") (10 5.0 5.0 0.0)))"); + assert!(matches!(k, EntityKind::Point(p) if p.p.z == 4.0)); + let (k, _) = elev("(entmake '((0 . \"MTEXT\") (10 0.0 150.0 0.0) (40 . 2.5) (1 . \"AB\")))"); + assert!(matches!(k, EntityKind::MText(t) if t.insert.z == 4.0)); + let (k, _) = elev("(entmake '((0 . \"ELLIPSE\") (10 50.0 150.0 0.0) (11 20.0 0.0 0.0) (40 . 0.5) (41 . 0.0) (42 . 6.283185307179586)))"); + assert!(matches!(k, EntityKind::Ellipse(e) if e.center.z == 4.0)); + let (k, _) = elev("(entmake '((0 . \"SOLID\") (10 0.0 170.0 0.0) (11 10.0 170.0 0.0) (12 0.0 180.0 0.0) (13 10.0 180.0 0.0)))"); + assert!(matches!(k, EntityKind::Solid(so) if so.corners.iter().all(|c| c.z == 4.0))); + // 3D polylines (made with their z, which a point given to a command doesn't carry). + let poly3d = |pts: serde_json::Value| { + let mut s = run(""); + s.execute("3dpoly", &json!({ "points": pts })).unwrap(); + s.log.clear(); + s.cmdline("(command \"_.CHANGE\" (entlast) \"\" \"_P\" \"_E\" 4.0 \"\")").unwrap(); + let EntityKind::Polyline3d(p) = s.doc().unwrap().model.iter().last().unwrap().kind.clone() else { panic!("not a 3D polyline") }; + (p.points.iter().map(|q| q.z).collect::>(), s) + }; + let (zs, _) = poly3d(json!([[0, 220, 2], [10, 220, 2], [20, 230, 2]])); + assert_eq!(zs, [4.0, 4.0, 4.0]); + let (zs, s) = poly3d(json!([[0, 200, 0], [10, 200, 5], [20, 210, 0]])); + assert_eq!(zs, [0.0, 5.0, 0.0]); + assert_eq!(said(&s, "Cannot change elevation of objects with differing Z coordinates."), 1, "{:?}", s.log); + let (k, _) = elev(&format!("{BLOCK} (command \"_.-INSERT\" \"K\" '(200.0 0.0) \"\" \"\" 0 \"\")")); + let EntityKind::Insert(i) = k else { panic!("not a block reference") }; + assert_eq!((i.insert.z, i.attribs[0].text.insert.z), (4.0, 4.0)); + // A hatch: its elevation, and no longer associative. + let mut s = run("(entmake '((0 . \"LWPOLYLINE\") (90 . 4) (70 . 1) (10 100.0 150.0) (10 120.0 150.0) (10 120.0 170.0) (10 100.0 170.0)))"); + let poly = s.doc().unwrap().model.iter().last().unwrap().handle.hex(); + s.execute("hatch", &json!({ "handles": [poly], "associative": true })).unwrap(); + // The hatch is drawn behind its boundary, so it isn't the last object in the list. + let hatch = |s: &Session| { + let d = s.doc().unwrap(); + d.model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).map(|e| (e.handle.hex(), e.kind.clone())).expect("a hatch") + }; + let (hex, k) = hatch(&s); + assert!(matches!(&k, EntityKind::Hatch(h) if h.associative)); + s.log.clear(); + s.cmdline(&format!("(command \"_.CHANGE\" (handent \"{hex}\") \"\" \"_P\" \"_E\" 4.0 \"\")")).unwrap(); + let (_, EntityKind::Hatch(h)) = hatch(&s) else { panic!("not a hatch") }; + assert_eq!((h.elevation, h.associative), (4.0, false)); + assert_eq!(said(&s, "Hatch boundary associativity removed."), 1, "{:?}", s.log); +} + +#[test] +fn the_rotation_asked_shows_as_the_drawing_measures_angles() { + // ANGBASE 90°: a text at 0° shows as 270.00. + let s = run("(setvar \"ANGBASE\" (/ pi 2)) (command \"_.CHANGE\" t \"\" \"\" \"\" \"\" \"\")"); + assert!(s.prompt_text().contains("Specify new rotation angle <270.00>"), "{}", s.prompt_text()); +} + +#[test] +fn aligned_and_fit_texts_are_set_by_their_two_points() { + // Aligned: neither height nor rotation is asked; Fit: no rotation. + let s = run( + "(entmake '((0 . \"TEXT\") (10 0.0 300.0 0.0) (11 40.0 300.0 0.0) (40 . 2.5) (1 . \"AL\") (72 . 3))) (command \"_.CHANGE\" (entlast) \"\" \"\" \"\" \"\" \"NEW\")", + ); + let t = text(&s, 7); + assert_eq!((t.height, t.rotation, t.value.as_str()), (2.5, 0.0, "NEW")); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let s = run( + "(entmake '((0 . \"TEXT\") (10 0.0 320.0 0.0) (11 40.0 320.0 0.0) (40 . 2.5) (1 . \"FI\") (72 . 5))) (command \"_.CHANGE\" (entlast) \"\" \"\" \"\" \"\" 5.0 \"FN\")", + ); + let t = text(&s, 7); + assert_eq!((t.height, t.rotation, t.value.as_str()), (5.0, 0.0, "FN")); + assert!(s.running.is_none(), "{}", s.prompt_text()); +} + +#[test] +fn the_json_point_follows_ortho() { + let mut s = run("(setvar \"ORTHOMODE\" 1)"); + let a = s.doc().unwrap().model.iter().next().unwrap().handle.hex(); + s.execute("change", &json!({ "handles": [a], "point": [60, 10] })).unwrap(); + assert_eq!(line(&s, 0)[1], [60.0, 0.0, 0.0]); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2e60c9df1..9b0907e24 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 burst; +mod change_command; mod chprop_command; mod compare_export; mod constraint_geometry; From fa060b0998d174eca9529bd3d0332f0678deee9c Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:33:03 +0700 Subject: [PATCH 294/900] Add Vietnamese (vi) to the interface languages (#2541) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add Vietnamese (vi) to the interface languages vi.tsv covers every key of the other catalogs and the three strings none of them has yet, with one plural form. Its tone-marked letters (U+1EA0-U+1EF9) aren't in egui's bundled faces, so the Vietnamese interface takes the first system interface font that has them (Segoe UI, Arial, SF, DejaVu Sans, Noto Sans) and otherwise stays English and says why, as Korean does without Hangul. AI-assisted; native-speaker review pending. Co-Authored-By: Claude Opus 5.5 * Vietnamese: the terminology Vietnamese AutoCAD users speak Polyline, Pan, Offset, Spline and Grip stay in English as they are said in the office; Modify is Hiệu chỉnh, LINE draws an Đoạn thẳng, Explode is Phân rã, Linetype Loại nét, the plot style table Bảng nét in, Polar and Object Snap Tracking Dò theo góc / Dò theo điểm bắt, Settings Cài đặt; the snap modes Endpoint, Midpoint and Nearest are Đầu mút, Điểm giữa and Điểm gần nhất. Co-Authored-By: Claude Opus 5.5 * Vietnamese: name the language by the font loaded; Arabic's own message The picker writes Tiếng Việt only when the interface's loaded system font has its letters (another interface loads the first installed candidate, which may lack them). The font choice is one function with a unit test, gated off wasm with its callers. Choosing Arabic without an Arabic font no longer gets the Chinese message. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ATTRIBUTION.md | 1 + crates/ui-egui/src/i18n.rs | 23 +- crates/ui-egui/src/i18n/tests.rs | 27 +- crates/ui-egui/src/i18n/vi.tsv | 1453 ++++++++++++++++++++++++++++++ crates/ui-egui/src/menus.rs | 13 +- crates/ui-egui/src/options.rs | 2 +- crates/ui-egui/src/theme.rs | 110 ++- 7 files changed, 1605 insertions(+), 24 deletions(-) create mode 100644 crates/ui-egui/src/i18n/vi.tsv diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 20b3dcc6e..22550ffaf 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -77,3 +77,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/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending | diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 7bb00ec17..af289ff56 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -47,10 +47,12 @@ pub enum Preference { Turkish, #[serde(rename = "bs")] Bosnian, + #[serde(rename = "vi")] + Vietnamese, } impl Preference { - pub const ALL: [Self; 18] = [ + pub const ALL: [Self; 19] = [ Self::Auto, Self::English, Self::Greek, @@ -69,6 +71,7 @@ impl Preference { Self::Hungarian, Self::Turkish, Self::Bosnian, + Self::Vietnamese, ]; /// Every preference in the order the Interface Language dialog lists them: Auto, then English @@ -117,6 +120,7 @@ impl Preference { Self::Hungarian => "hu", Self::Turkish => "tr", Self::Bosnian => "bs", + Self::Vietnamese => "vi", } } @@ -146,6 +150,14 @@ impl Preference { Self::Hungarian => "Magyar", Self::Turkish => "Türkçe", Self::Bosnian => "Bosanski", + // Its letters need a font egui doesn't bundle ([`crate::theme::vietnamese_font`]). + Self::Vietnamese => { + if crate::theme::shows_vietnamese(CURRENT.with(Cell::get)) { + "Tiếng Việt" + } else { + "Vietnamese" + } + } } } @@ -177,6 +189,7 @@ impl Preference { Self::Hungarian => "hu", Self::Turkish => "tr", Self::Bosnian => "bs", + Self::Vietnamese => "vi", Self::Auto => locales.iter().find_map(|s| locale_language(s)).unwrap_or("en"), } } @@ -193,7 +206,7 @@ pub struct Language { catalog: OnceLock>, } -pub static LANGUAGES: [Language; 17] = [ +pub static LANGUAGES: [Language; 18] = [ 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 { @@ -243,6 +256,10 @@ pub static LANGUAGES: [Language; 17] = [ // Bosnian (Latin script, Ijekavian): one (1, 21), few (2–4, 22–24, not 12–14), other — the // Ukrainian rule for integer counts. Language { code: "bs", name: "Bosanski", source: include_str!("i18n/bs.tsv"), plural: plural_uk, plural_forms: 3, catalog: OnceLock::new() }, + // Vietnamese doesn't inflect a noun for number ("3 commit"), so like Korean it has one form. + Language { + code: "vi", name: "Tiếng Việt", source: include_str!("i18n/vi.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`. @@ -447,6 +464,8 @@ mod picker_order_tests { assert!(pos(Preference::Italian) < pos(Preference::Hungarian), "Magyar sorts under M"); assert!(pos(Preference::Turkish) < pos(Preference::Greek), "Latin names come before Greek"); assert!(pos(Preference::Bosnian) < pos(Preference::Czech), "Bosanski sorts under B"); + assert!(pos(Preference::Swedish) < pos(Preference::Vietnamese), "Tiếng Việt sorts under T"); + assert!(pos(Preference::Vietnamese) < pos(Preference::Turkish), "Tiếng comes before Türkçe"); assert_eq!(name_sort_key("Türkçe"), "turkce"); } } diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 6bf85f2c3..dc4e5322b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -187,6 +187,7 @@ fn assert_additional_locale_aliases() { ("hu", &["hu", "hu-HU", "hu_HU.UTF-8", "HU-hu", " hu-HU "]), ("tr", &["tr", "tr-TR", "tr_TR.UTF-8", "TR-tr", " tr-TR ", "tr-CY"]), ("bs", &["bs", "bs-BA", "bs_BA.UTF-8", "BS-ba", " bs-BA ", "bs-Latn-BA"]), + ("vi", &["vi", "vi-VN", "vi_VN.UTF-8", "VI-vn", " vi-VN "]), ("el", &["el", "el-GR", "el_GR.UTF-8", "EL-cy"]), ("zh", &["zh", "zh-CN"]), ] { @@ -432,12 +433,13 @@ fn dialogs_render_in_every_language_and_keep_their_source_ids() { } /// The letters of every catalog have glyphs in both UI families. Latin, Cyrillic and Greek come -/// from egui's bundled fonts alone, as in the web build; the scripts they lack need a font that -/// `install_fonts` finds, and are checked only where one is there. +/// from egui's bundled fonts alone, as in the web build; the scripts they lack (and Vietnamese's +/// tone-marked letters) need a font that `install_fonts` finds, and are checked only where one is +/// there. #[test] fn interface_fonts_cover_every_letter_in_each_catalog() { for language in translated() { - let extra_font = ["ko", "zh", "ar"].contains(&language.code); + let extra_font = ["ko", "zh", "ar", "vi"].contains(&language.code); if extra_font && !crate::theme::can_show(language.code) { continue; } @@ -566,3 +568,22 @@ fn bosnian_counts_take_one_few_other() { assert_eq!(Preference::parse("bs"), Some(Preference::Bosnian)); assert_eq!(Preference::Bosnian.native_name(), "Bosanski"); } + +/// Vietnamese has one form for every count, and shows only with an interface font that has its +/// tone-marked letters; without one it stays English and says why. +#[test] +fn vietnamese_takes_one_form_and_needs_a_font_with_its_letters() { + assert_eq!(Preference::parse("vi"), Some(Preference::Vietnamese)); + assert_eq!(Preference::Vietnamese.native_name(), "Tiếng Việt"); + let vi = LANGUAGES.iter().find(|l| l.code == "vi").unwrap(); + assert_eq!(vi.plural_forms, 1); + assert!([0, 1, 2, 5, 21, 111].into_iter().all(|n| (vi.plural)(n) == 0)); + let mut app = CadApp::new(Session::new(), Services::default()); + let r = app.run("ui.language", json!({"lang": "vi"})).unwrap(); + let shown = crate::theme::can_show("vi"); + assert_eq!(r["shown"], if shown { "vi" } else { "en" }); + if !shown { + assert!(app.status.as_ref().is_some_and(|(s, _)| s.contains("Vietnamese letters"))); + assert_eq!(Preference::Vietnamese.name(), "Vietnamese"); + } +} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv new file mode 100644 index 000000000..9b1493031 --- /dev/null +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -0,0 +1,1453 @@ +# CADCraft Vietnamese interface catalog — original translations by @2ez4gcx with Claude Code (AI-assisted). +# SPDX-License-Identifier: MIT OR Apache-2.0 +# Written from the meaning of CADCraft English strings; no proprietary translations copied. +# AutoCAD command names, command-line keywords and system variables stay in English. +# UTF-8: contextEnglish sourceVietnamese translation. +# @plural = one form for every integer count (Vietnamese doesn't inflect a noun for number). + Apply Áp dụng + Attach DWG... Đính kèm DWG... + Bind Gắn kết + Detach Tách + Loaded Đã nạp + Make it a block of this drawing, keeping its layer names Biến thành block của bản vẽ này, giữ nguyên tên layer + Make it a block of this drawing; its layers become NAME$0$LAYER Biến thành block của bản vẽ này; các layer của nó trở thành NAME$0$LAYER + No external references are attached. Không có tham chiếu ngoài nào được đính kèm. + Not Found Không tìm thấy + Not loaded Chưa nạp + Open Mở + Overlay Chồng lên + Reference Manager Trình quản lý tham chiếu + Reference Name Tên tham chiếu + References: {n} Tham chiếu: {n} + Reload Tải lại + Reload All Tải lại tất cả + Saved Path Đường dẫn đã lưu + Unload Bỏ nạp + Unloaded Đã bỏ nạp + Unreferenced Không được tham chiếu + Unresolved Chưa phân giải + Cancel Hủy + OK OK + or [ hoặc [ + % of all commits % của tất cả commit + * Wildcard Match * Khớp ký tự đại diện + *VARIES* *KHÁC NHAU* + + | Top | 2D Wireframe + | Trên | Khung dây 2D + +Bin +Bin + +LOC +LOC + 1 Viewport 1 khung nhìn + 2 Points 2 điểm + 2 Viewports 2 khung nhìn + 2D Solid Solid 2D + 3 Points 3 điểm + 3 Viewports 3 khung nhìn + 3D Face Mặt 3D + 3D Operations Thao tác 3D + 3D Polyline Polyline 3D + 4 Viewports 4 khung nhìn + < Less than < Nhỏ hơn + <> Not Equal <> Không bằng + = Equals = Bằng + > Greater than > Lớn hơn + A variable name starts with a letter and has only letters, digits and _ Tên biến bắt đầu bằng một chữ cái và chỉ gồm chữ cái, chữ số và _ + About Giới thiệu + About CADCraft Giới thiệu CADCraft + Absolute Tuyệt đối + Add Leader Thêm đường dẫn ghi chú + Additional angles Các góc bổ sung + Align Căn chỉnh + Align Text Căn chỉnh chữ + Aligned Thẳng hàng + All Tất cả + All Annotation Objects Tất cả đối tượng chú thích + All Used Layers Tất cả layer đã dùng + All files Tất cả tệp + Angle Góc + Angular Góc + Annotation Visibility Hiển thị chú thích + Annotation scale Tỉ lệ chú thích + Apparent Intersection Giao biểu kiến + Append to current selection set Thêm vào tập chọn hiện hành + Apply to: Áp dụng cho: + Apply true color Áp dụng màu thực + Arc Cung tròn + Arc Length Chiều dài cung + Area Diện tích + Arrange Panel Sắp xếp bảng + Array Sao chép theo dãy + Attach Đính kèm + Attribute Attribute + Attribute Definition Định nghĩa attribute + Attribute Display Hiển thị attribute + Audit Kiểm tra lỗi + Auto (system language) Tự động (ngôn ngữ hệ thống) + Auto Constrain Ràng buộc tự động + AutoConstrain AutoConstrain + Axis, End Trục, Điểm cuối + Base Gốc + Baseline Đường cơ sở + Batch Publish Xuất bản hàng loạt + Binary assets added Đã thêm tài nguyên nhị phân + Binary assets removed Đã xóa tài nguyên nhị phân + Bind... Gắn kết... + Blend Pha trộn + Block Block + Block Attribute Manager... Trình quản lý attribute của block... + Block Description... Mô tả block... + Block Editor Trình sửa block + Block Reference Tham chiếu block + Block... Block... + Blocks Block + Blue Xanh dương + Bold Đậm + Boolean Boolean + Boundary Biên + Boundary... Biên... + Box Hộp + Break Ngắt + Break At Point Ngắt tại điểm + Bring Above Objects Đưa lên trên các đối tượng + Bring Annotations to Front Đưa chú thích lên trước + Bring to Front Đưa lên trước + Bulleted list Danh sách có dấu đầu dòng + ByBlock ByBlock + ByColor ByColor + ByLayer ByLayer + CADCraft Help Trợ giúp CADCraft + Cancel Hủy + Cartesian (x, y) Đề-các (x, y) + Center Tâm + Center Line Đường tâm + Center Mark Dấu tâm + Center X Tâm X + Center Y Tâm Y + Center Z Tâm Z + Center, Diameter Tâm, Đường kính + Center, Radius Tâm, Bán kính + Center, Start, Angle Tâm, Điểm đầu, Góc + Center, Start, End Tâm, Điểm đầu, Điểm cuối + Center, Start, Length Tâm, Điểm đầu, Chiều dài + Chamfer Vát góc + Change Space Đổi không gian + Change to Current Layer Đổi sang layer hiện hành + Changed: {n} Đã thay đổi: {n} + Circle Đường tròn + Circumference Chu vi + Clear History Xóa lịch sử + Clear Xóa + Clip Xén + Clip Viewport Xén khung nhìn + Clipboard Bảng tạm + Close Đóng + Close All Đóng tất cả + Close All Other Drawings Đóng tất cả bản vẽ khác + Closed Khép kín + Close Comparison Đóng so sánh + Export Comparison Xuất so sánh + Coincident Trùng khớp + Collapse Tool Sets Thu gọn bộ công cụ + Collinear Cùng đường thẳng + Color Màu + Color 8 Màu 8 + Color 9 Màu 9 + Color Index Chỉ số màu + Color... Màu... + Command Aliases Bí danh lệnh + Command History Lịch sử lệnh + Clear Command History Xóa lịch sử lệnh + Command Line Dòng lệnh + Command Line History Lines Số dòng lịch sử dòng lệnh + Command Reference Tham chiếu lệnh + Commits Commit + Company Công ty + Compare Drawings... So sánh bản vẽ... + Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust. Thiết kế và vẽ có sự hỗ trợ của máy tính: ứng dụng CAD mã nguồn mở, được viết hoàn toàn bằng Rust theo kiểu clean-room. + Concentric Đồng tâm + Cone Hình nón + Constraint Bars Thanh ràng buộc + Constraint Settings Cài đặt ràng buộc + Construction Line Đường dựng + Contents Nội dung + Continue Tiếp tục + Contributors Người đóng góp + Control Vertices Đỉnh điều khiển + Convert Chuyển đổi + Copy Sao chép + Copy Full File Path Sao chép đường dẫn đầy đủ của tệp + Copy History Sao chép lịch sử + Copy Layout Sao chép layout + Copy Nested Objects Sao chép đối tượng lồng nhau + Copy Selection Sao chép vùng chọn + Copy with Base Point Sao chép với điểm gốc + Count Đếm + Count List Danh sách đếm + Count Table Bảng đếm + Create Block Tạo block + Creates a user parameter Tạo một tham số người dùng + Ctrl+Enter to finish Ctrl+Enter để kết thúc + Current layer Layer hiện hành + Current selection Tập chọn hiện hành + Current: {color} Hiện tại: {color} + Cut Cắt + Cut with Base Point Cắt với điểm gốc + Cyan Lục lam + Cylinder Hình trụ + DWG DWG + DWG Reference... Tham chiếu DWG... + DXF DXF + Dark Tối + Data Extraction... Trích xuất dữ liệu... + Default Mặc định + Data Link... Liên kết dữ liệu... + Default Save Format Định dạng lưu mặc định + Default Save Version Phiên bản lưu mặc định + Define Attributes Định nghĩa attribute + Define Attributes... Định nghĩa attribute... + Defined width Bề rộng đã định nghĩa + Degree Độ + Degrees of Freedom Bậc tự do + Degrees of freedom: {n} Bậc tự do: {n} + Delete Xóa + Delete Column Xóa cột + Delete Constraints Xóa ràng buộc + Delete Dimension Style Xóa kiểu kích thước + Delete Duplicate Objects Xóa đối tượng trùng lặp + Delete Layer Xóa layer + Delete Layer State Xóa trạng thái layer + Delete Layout Xóa layout + Delete Row Xóa hàng + Delete Text Style Xóa kiểu chữ + Delta X Chênh lệch X + Delta Y Chênh lệch Y + Description Mô tả + Deselect All Bỏ chọn tất cả + Diameter Đường kính + Dim style Kiểu kích thước + Dimension Break Ngắt kích thước + Dimension Edit Sửa kích thước + Dimension Kích thước + Dimension Objects Only Chỉ đối tượng kích thước + Dimension Space Khoảng cách kích thước + Dimension Style Override Ghi đè kiểu kích thước + Dimension Style... Kiểu kích thước... + Dimension Text Edit Sửa chữ kích thước + Dimension style Kiểu kích thước + Dimensional Constraint Ràng buộc kích thước + Dimensional Constraint Parameters Tham số ràng buộc kích thước + Dimensional Constraints Ràng buộc kích thước + Disassociate Dimensions Tách liên kết kích thước + Display name Tên hiển thị + Distance Khoảng cách + Divide Chia + Do not plot (click: plot) Không in (nhấp để in) + Donut Vành tròn + Double-click to edit the description Nhấp đúp để sửa mô tả + Down Xuống + Drafting Vẽ kỹ thuật + Drafting Settings Cài đặt hỗ trợ vẽ + Drafting Settings... Cài đặt hỗ trợ vẽ... + Draw Vẽ + Draw Order Thứ tự vẽ + Drawing (DWG) Bản vẽ (DWG) + Drawing (DXF) Bản vẽ (DXF) + Drawing Limits Giới hạn bản vẽ + Drawing Template (DWT) Mẫu bản vẽ (DWT) + Drawing Utilities Tiện ích bản vẽ + Drawings (DWG, DXF) Bản vẽ (DWG, DXF) + Dynamic Động + Dynamic Dimensions Kích thước động + Dynamic Input Dynamic input + Dynamic Input (F12) Dynamic input (F12) + E E + Edit Sửa + Edit Attributes... Sửa attribute... + Edit Text... Sửa chữ... + Edit Table Cell Sửa ô bảng + Elevation Cao độ + Ellipse Elip + Elliptical Arc Cung elip + Enable Dynamic Input (F12) Bật dynamic input (F12) + End Object Isolation Kết thúc cô lập đối tượng + End Width Bề rộng cuối + End X Điểm cuối X + End Y Điểm cuối Y + End angle Góc cuối + Endpoint Đầu mút + Enter Enter + Enter Top, Zero or Bottom. Nhập Top, Zero hoặc Bottom. + Enter a fit data option Nhập tùy chọn dữ liệu khớp + Enter a pattern name Nhập tên mẫu + Enter a vertex editing option Nhập tùy chọn sửa đỉnh + Enter an option Nhập một tùy chọn + Enter angle of xline Nhập góc của đường dựng + Enter angle of xline (0) or Nhập góc của đường dựng (0) hoặc + Enter area of rectangle in current units Nhập diện tích hình chữ nhật theo đơn vị hiện hành + Enter attribute prompt Nhập lời nhắc attribute + Enter attribute tag name Nhập tên thẻ attribute + Enter attribute value Nhập giá trị attribute + Enter block name Nhập tên block + Enter constraint type Nhập loại ràng buộc + Enter continuity Nhập tính liên tục + Enter default attribute value Nhập giá trị attribute mặc định + Enter degree of spline Nhập bậc của spline + Enter delta angle Nhập góc chênh lệch + Enter delta length or Nhập chiều dài chênh lệch hoặc + Enter dimension text Nhập chữ kích thước + Enter dimension text (<> = measurement) Nhập chữ kích thước (<> = số đo) + Enter dimension value or [name=expression] Nhập giá trị kích thước hoặc [name=expression] + Enter dimension variable name to override Nhập tên biến kích thước để ghi đè + Enter justification type Nhập kiểu căn lề + Enter leader text Nhập chữ đường dẫn ghi chú + Enter mline scale Nhập tỉ lệ mline + Enter mode Nhập chế độ + Enter name of block to insert Nhập tên block cần chèn + Enter new text Nhập chữ mới + Enter next point Nhập điểm tiếp theo + Enter number of columns Nhập số cột + Enter number of data rows Nhập số hàng dữ liệu + Enter number of items Nhập số mục + Enter number of items along path Nhập số mục dọc theo đường dẫn + Enter number of sides Nhập số cạnh + Enter number of turns Nhập số vòng + Enter percentage length Nhập chiều dài theo phần trăm + Enter rectangle length Nhập chiều dài hình chữ nhật + Enter rectangle width Nhập chiều rộng hình chữ nhật + Enter scale factor Nhập hệ số tỉ lệ + Enter text Nhập chữ + Enter text (use \P for new paragraphs) Nhập chữ (dùng \P để xuống đoạn mới) + Enter the number of segments Nhập số đoạn + Enter twist direction of helix Nhập chiều xoắn của đường xoắn ốc + Entire drawing Toàn bộ bản vẽ + Equal Bằng nhau + Erase Xóa + Evaluate Tính giá trị + Exclude from new selection set Loại khỏi tập chọn mới + Explode Phân rã + Export Xuất + Export Table Xuất bảng + Export to PDF... Xuất ra PDF... + Expression Biểu thức + Extend Kéo dài + Extension Phần kéo dài + Extents Phạm vi + External Reference Tham chiếu ngoài + External References Tham chiếu ngoài + Extrude Đùn + File Tệp + File Tab Thẻ tệp + Fillet Bo góc + Filter Bộ lọc + Filters Bộ lọc + Find and Replace Tìm và thay thế + Find... Tìm... + First Đầu tiên + First commit Commit đầu tiên + Fit Points Điểm khớp + Fix Cố định + Flatten Objects Làm phẳng đối tượng + Format Định dạng + Freehand Tự do + Freeze Đóng băng + Freeze Layer Đóng băng layer + Freeze in new viewports Đóng băng trong khung nhìn mới + Freeze/Thaw Đóng băng/Tan băng + Freeze/Thaw in all viewports Đóng băng/Tan băng trong tất cả khung nhìn + Freeze/Thaw in the current viewport Đóng băng/Tan băng trong khung nhìn hiện hành + From Từ + From Template... Từ mẫu... + General Chung + Geometric Center Tâm hình học + Geometric Constraint Ràng buộc hình học + Geometric Constraints Ràng buộc hình học + Geometry Hình học + Get from the Drawing Lấy từ bản vẽ + Get Variable Lấy biến + Get View Lấy góc nhìn + Global Toàn cục + Global width Bề rộng toàn cục + Grab bag Tổng hợp + Gradient Gradient + Gradient... Gradient... + Green Xanh lục + Grid (F7) Lưới (F7) + Grid Display Hiển thị lưới + Grid On (F7) Bật lưới (F7) + Grid snap Snap lưới + Grid spacing Khoảng cách lưới + Grip Edit Chỉnh sửa grip + Grip Mirror Grip đối xứng + Grip Option Tùy chọn grip + Grip Rotate Grip xoay + Grip Scale Grip tỉ lệ + Grip Stretch Grip kéo giãn + Group Nhóm + Group Edit Chỉnh sửa nhóm + Group Options Tùy chọn nhóm + Group Selection Chọn nhóm + Hatch Hatch + Hatch Edit Chỉnh sửa hatch + Hatch Patterns Mẫu hatch + Hatch... Hatch... + Height Chiều cao + Height: {height} Chiều cao: {height} + Helix Đường xoắn ốc + Help Trợ giúp + Hide All Ẩn tất cả + Hide All Constraint Bars Ẩn tất cả thanh ràng buộc + Hide All Dynamic Dimensions Ẩn tất cả kích thước động + Hide Layer List Ẩn danh sách layer + Hide Objects Ẩn đối tượng + Hide Palettes Ẩn các bảng + History Lịch sử + Home Trang chủ + Horizontal Ngang + HorizontalDistance Khoảng cách ngang + How to apply: Cách áp dụng: + ID Point Điểm ID + Import Nhập + In Phóng to + In-window Menu Bar Thanh menu trong cửa sổ + Include in new selection set Đưa vào tập chọn mới + Increment angle Góc tăng dần + Index Color Màu chỉ số + Index color: {index} Màu chỉ số: {index} + Infer Constraints Suy luận ràng buộc + Inquiry Truy vấn + Insert Chèn + Insert Block Chèn block + Insert Column Chèn cột + Insert Row Chèn hàng + Insert tab Thẻ chèn + Insert this block Chèn block này + Insert Table Formula Chèn công thức bảng + Insertion Điểm chèn + Insertion X Điểm chèn X + Insertion Y Điểm chèn Y + Insertion Z Điểm chèn Z + Inspect Constraints Kiểm tra ràng buộc + Inspect Drawing Kiểm tra bản vẽ + Inspection Kiểm tra + Interface Language Ngôn ngữ giao diện + Interface Theme Chủ đề giao diện + Intersect Giao + Intersection Giao điểm + Isolate Cô lập + Isolate Layer Cô lập layer + Isolate Objects Cô lập đối tượng + Isometric Drafting Vẽ đẳng trắc + Jogged Gãy khúc + Jogged Linear Gãy khúc tuyến tính + Join Nối + Join the ArtCraft Discord… Tham gia Discord ArtCraft… + Join us on Discord Tham gia cùng chúng tôi trên Discord + Isometric Plane Mặt phẳng đẳng trắc + Isometric snap Snap đẳng trắc + Language Ngôn ngữ + Last Cuối cùng + Last commit Commit gần nhất + Layer Layer + Layer Delete Xóa layer + Layer Match Khớp layer + Layer Merge Gộp layer + Layer Off Tắt layer + Layer Properties Thuộc tính layer + Layer Properties Manager Quản lý layer + Layer Properties Manager — current viewport Quản lý layer — khung nhìn hiện hành + Layer State Trạng thái layer + Layer States Manager... Trình quản lý trạng thái layer... + Layer Tools Công cụ layer + Layer contains objects (double-click to make current) Layer có chứa đối tượng (nhấp đúp để đặt làm hiện hành) + Layer is empty (double-click to make current) Layer trống (nhấp đúp để đặt làm hiện hành) + Layers Layer + Layers Palette Bảng layer + Hide Palette Ẩn bảng + Layers displayed: {shown} of {total}. Current layer: {layer} Đang hiển thị {shown} trên {total} layer. Layer hiện hành: {layer} + Layout Layout + Layout list Danh sách layout + Leader Đường dẫn ghi chú + Leaders Only Chỉ đường dẫn ghi chú + Left Trái + Length Chiều dài + Length X Chiều dài X + Length Y Chiều dài Y + Lengthen Đổi chiều dài + Light Sáng + Line Đoạn thẳng + Line delta Chênh lệch dòng + Linear Tuyến tính + Lines +/− Dòng +/− + Lines added Dòng đã thêm + Lines deleted Dòng đã xóa + Lines of Command History Số dòng lịch sử lệnh + Linetype Loại nét + Linetype Scale Tỉ lệ loại nét + Linetype scale Tỉ lệ loại nét + Ltscale Ltscale + Linetype... Loại nét... + Lineweight Bề dày nét + Lineweight... Bề dày nét... + List Liệt kê + List Blocks Liệt kê block + List Dimension Styles Liệt kê kiểu kích thước + List Groups Liệt kê nhóm + List Layer States Liệt kê trạng thái layer + List Layouts Liệt kê layout + List System Variables Liệt kê biến hệ thống + List Text Styles Liệt kê kiểu chữ + Load all Tải tất cả + Load... Tải... + Loaded linetypes Loại nét đã tải + Lock Khóa + Lock Layer Khóa layer + Lock viewport Khóa khung nhìn + Lock/Unlock Khóa/Mở khóa + Loft Loft + MIT OR Apache-2.0. Not affiliated with Autodesk, Inc. MIT OR Apache-2.0. Không liên kết với Autodesk, Inc. + MODEL MODEL + MText Chữ nhiều dòng + Magenta Magenta + Major line every Đường chính mỗi + Make Current Đặt làm hiện hành + Make Object's Layer Current Đặt layer của đối tượng làm hiện hành + Make... Tạo... + Match Layer Khớp layer + Match Properties Sao chép thuộc tính + Measure Đo + Measure Distance Đo khoảng cách + Measure Geometry Đo hình học + Merge Cells Gộp ô + Merged PRs PR đã gộp + Mid Between 2 Points Điểm giữa 2 điểm + Midpoint Điểm giữa + Mirror Lấy đối xứng + Model Model + Model Space (in viewport) Không gian mô hình (trong khung nhìn) + Modeling Mô hình hóa + Models Model + Modify Hiệu chỉnh + Move Di chuyển + Multileader Multileader + Multileader Style... Kiểu multileader... + Multileader style Kiểu multileader + Multiline Multiline + Multiline Text Chữ nhiều dòng + Multiline Text... Chữ nhiều dòng... + Multiple Nhiều + Multiple Point Nhiều điểm + My Của tôi + My properties: not available yet Thuộc tính của tôi: chưa khả dụng + N N + Name Tên + Name (A–Z) Tên (A–Z) + Named Viewports... Khung nhìn đã đặt tên... + Named Views... Góc nhìn đã đặt tên... + Nearest Điểm gần nhất + New Mới + New (metric) Mới (hệ mét) + New Drawing Bản vẽ mới + New Drawing (⌘N) Bản vẽ mới (⌘N) + New Drawing... Bản vẽ mới... + New Layer Layer mới + New Layout Layout mới + New VP Freeze Đóng băng VP mới + New Viewports... Khung nhìn mới... + New from Template... Tạo từ bản mẫu... + New layout Layout mới + New state name Tên trạng thái mới + Next Change Thay đổi tiếp theo + No Không + No blocks defined in this drawing. Chưa định nghĩa block nào trong bản vẽ này. + No contributor data was built into this copy. Bản này không chứa dữ liệu người đóng góp. + No model credits were built into this copy. Bản này không chứa thông tin ghi nhận mô hình. + No saved layer states Chưa lưu trạng thái layer nào + No selection Chưa có lựa chọn + Node Điểm nút + None Không có + Normal Bình thường + Not available Không khả dụng + Not available yet Chưa khả dụng + Numbered list Danh sách đánh số + OK OK + Object Đối tượng + Object Snap Bắt điểm + Object Snap (F3) Bắt điểm (F3) + Object Snap On (F3) Bật bắt điểm (F3) + Object Snap Tracking Dò theo điểm bắt + Object Snap Tracking (F11) Dò theo điểm bắt (F11) + Object Snap Tracking Settings Cài đặt dò theo điểm bắt + Object type: Loại đối tượng: + Oblique Nghiêng + Off Tắt + Offset Offset + On Bật + On/Off Bật/Tắt + One of the Crafting Apps by the ArtCraft team and community. Một trong các ứng dụng Crafting của nhóm và cộng đồng ArtCraft. + Only in this drawing: {n} Chỉ có trong bản vẽ này: {n} + Only in {name}: {n} Chỉ có trong {name}: {n} + Open (⌘O) Mở (⌘O) + Open Sample Drawing Mở bản vẽ mẫu + Open sample drawing Mở bản vẽ mẫu + Open Xref Mở xref + Open... Mở... + Operator: Toán tử: + Orbit Xoay quanh + Ordinate Kích thước tọa độ + Ortho (F8) Ortho (F8) + Ortho Mode Chế độ Ortho + Ortho Mode (F8) Chế độ Ortho (F8) + Osnap Settings... Cài đặt bắt điểm... + Out Thu nhỏ + Over-constrained Thừa ràng buộc + Override Ghi đè + PAPER PAPER + Percent Phần trăm + Polar (distance < angle) Cực (khoảng cách < góc) + PRs PR + Page Setup Manager Trình quản lý thiết lập trang + Page Setup Manager... Trình quản lý thiết lập trang... + Pan Pan + Pan Down Pan xuống + Pan Left Pan sang trái + Pan Right Pan sang phải + Pan Up Pan lên + Paper Space Không gian giấy + Parallel Song song + Parameters Manager Trình quản lý tham số + Parametric Tham số + Paste Dán + Paste as Block Dán thành block + Paste to Command Line Dán vào dòng lệnh + Paste to Original Coordinates Dán theo tọa độ gốc + Path Array Mảng theo đường dẫn + Pattern Mẫu + Perpendicular Vuông góc + Plot In + Plot (click: do not plot) In (nhấp để không in) + Plot Preview Xem trước bản in + Plot Window Cửa sổ in + Plot style Kiểu in + Plot style attached to Kiểu in được gắn vào + Plot style table Bảng nét in + Plot Style... Kiểu in... + Plot Style Manager Trình quản lý kiểu in + Plot Style Manager... Trình quản lý kiểu in... + Plot Styles... Kiểu in... + Plotter Manager Trình quản lý máy in + Plotter Manager... Trình quản lý máy in... + New CTB CTB mới + New STB STB mới + New style Kiểu mới + Reset Panel Layout Đặt lại bố cục bảng điều khiển + Send Hatches to Back Đưa hatch xuống dưới cùng + Send Under Objects Đưa xuống dưới đối tượng + Text Objects Only Chỉ đối tượng chữ + Use for this layout Dùng cho layout này + Display plot styles Hiển thị kiểu in + No plot style tables. Không có bảng nét in nào. + A built-in table: editing it keeps an edited copy in the drawing. Bảng dựng sẵn: khi chỉnh sửa, một bản sao đã sửa sẽ được giữ trong bản vẽ. + Keep an editable copy of this table in the drawing Giữ một bản sao có thể chỉnh sửa của bảng này trong bản vẽ + Layout {name}: {table} Layout {name}: {table} + Grayscale Thang xám + Screening Tỉ lệ phủ + Use object linetype Dùng loại nét của đối tượng + Use object lineweight Dùng bề dày nét của đối tượng + Remove Gỡ bỏ + Add Thêm + Open a drawing first. Hãy mở một bản vẽ trước. + Plot table type Loại bảng nét in + Color-dependent Phụ thuộc màu + Named Theo tên + Plus/minus Cộng/trừ + Point Điểm + Point Filters Bộ lọc điểm + Point Style... Kiểu điểm... + Polar Array Mảng tròn + Polar Tracking Dò theo góc + Polar Tracking (F10) Dò theo góc (F10) + Polar Tracking On (F10) Bật dò theo góc (F10) + Polar angle measurement Đo góc cực + Polar distance Khoảng cách cực + Polar: {distance} < {angle}° Cực: {distance} < {angle}° + PolarSnap PolarSnap + Polygon Đa giác + Polygonal Đa giác + Polygonal Viewport Khung nhìn đa giác + Polyline Polyline + Polyline Edit Chỉnh sửa polyline + Position X Vị trí X + Position Y Vị trí Y + Position Z Vị trí Z + Previous Trước + Previous Change Thay đổi trước + Previous Layer Layer trước + Primitives Khối cơ bản + Print In ra máy in + Print... In ra máy in... + Properties Thuộc tính + Properties Inspector Trình kiểm tra thuộc tính + Properties: Thuộc tính: + Proxy Proxy + Purge Dọn dẹp + Pyramid Hình chóp + Quadrant Góc phần tư + Query Entities Truy vấn đối tượng + Quick Nhanh + Quick Dimension Kích thước nhanh + Quick Properties Thuộc tính nhanh + Quick Select Chọn nhanh + Quick Select Properties Thuộc tính chọn nhanh + Quick Select... Chọn nhanh... + QuickCalc QuickCalc + QuickCalc Pick Chọn QuickCalc + Quit CADCraft Thoát CADCraft + Radius Bán kính + Raster Image Ảnh raster + Ray Tia + Read-only Chỉ đọc + Real name Tên thực + Realtime Thời gian thực + Reassociate Dimensions Liên kết lại kích thước + Recent Gần đây + Recent Commands Lệnh gần đây + Recent Input Đầu vào gần đây + Recover... Khôi phục... + Rectangle Hình chữ nhật + Recalculate Table Formulas Tính lại công thức bảng + Rectangular Hình chữ nhật + Rectangular snap Snap hình chữ nhật + Rectangular Array Mảng chữ nhật + Red Đỏ + Redo Làm lại + Redo (⇧⌘Z) Làm lại (⇧⌘Z) + Redraw Vẽ lại + Regen Tái tạo hình + Regen All Tái tạo hình toàn bộ + Region Miền + Region/Mass Properties Thuộc tính miền/khối + Reinitialize Khởi tạo lại + Relative Tương đối + Relative to last segment Tương đối với đoạn cuối + Remove Leader Xóa đường dẫn ghi chú + Remove the viewport override Xóa ghi đè khung nhìn + Rename Dimension Style Đổi tên kiểu kích thước + Rename Layer Đổi tên layer + Rename Layer State Đổi tên trạng thái layer + Rename Layout Đổi tên layout + Rename Text Style Đổi tên kiểu chữ + Rename... Đổi tên... + Repeat {command} Lặp lại {command} + Replace Block... Thay thế block... + Requires a point (x,y, @dx,dy or @d Chỉ định điểm thứ hai hoặc + Specify second source point Chỉ định điểm nguồn thứ hai + Specify side to offset Chỉ định phía offset + Specify start angle Chỉ định góc bắt đầu + Specify start point Chỉ định điểm bắt đầu + Specify start point of arc Chỉ định điểm bắt đầu của cung + Specify start point of polyline Chỉ định điểm bắt đầu của polyline + Specify start point of text Chỉ định điểm bắt đầu của chữ + Specify starting width Chỉ định bề rộng bắt đầu + Specify starting width for next segment Chỉ định bề rộng bắt đầu cho đoạn tiếp theo + Specify tangent direction for the start point of arc Chỉ định hướng tiếp tuyến tại điểm bắt đầu của cung + Specify the elevation for rectangles Chỉ định cao độ cho hình chữ nhật + Specify thickness for rectangles Chỉ định độ dày cho hình chữ nhật + Specify third point on circle Chỉ định điểm thứ ba trên đường tròn + Specify third point on circle: _tan to Chỉ định điểm thứ ba trên đường tròn: _tan to + Specify third source point or Chỉ định điểm nguồn thứ ba hoặc + Specify through point Chỉ định điểm đi qua + Specify top diameter Chỉ định đường kính trên + Specify top radius or Chỉ định bán kính trên hoặc + Specify total angle Chỉ định tổng góc + Specify total length or Chỉ định tổng chiều dài hoặc + Specify width for rectangles Chỉ định bề rộng cho hình chữ nhật + Sphere Hình cầu + Spline Spline + Spline Edit Chỉnh sửa spline + Stack (type 1/2 then select) Xếp chồng (nhập 1/2 rồi chọn) + Standard Standard + Start Bắt đầu + Start Width Bề rộng bắt đầu + Start X X bắt đầu + Start Y Y bắt đầu + Start angle Góc đầu + Start, Center, Angle Điểm đầu, tâm, góc + Start, Center, End Điểm đầu, tâm, điểm cuối + Start, Center, Length Điểm đầu, tâm, chiều dài + Start, End, Angle Điểm đầu, điểm cuối, góc + Start, End, Direction Điểm đầu, điểm cuối, hướng + Start, End, Radius Điểm đầu, điểm cuối, bán kính + Status Trạng thái + Status Bar Thanh trạng thái + Stretch Kéo giãn + Style: Standard Kiểu: Standard + Subtract Trừ + Sweep Quét + Switch Drawing Chuyển bản vẽ + Switch Layout Chuyển layout + Switch between model space in a viewport and paper space Chuyển giữa không gian mô hình trong khung nhìn và không gian giấy + Symmetric Đối xứng + Synchronize Attributes Đồng bộ attribute + To Đến + Toggle PICKADD (off: each pick replaces the selection) Bật/tắt PICKADD (tắt: mỗi lần chọn sẽ thay thế tập chọn) + Toggle PICKADD (on: picks add to the selection) Bật/tắt PICKADD (bật: mỗi lần chọn sẽ thêm vào tập chọn) + TOP TOP + Table Bảng + Table Breaks Ngắt bảng + Table Cell Style Kiểu ô bảng + Table Style... Kiểu bảng... + Table style Kiểu bảng + Table... Bảng... + Tan, Tan, Radius Tiếp tuyến, tiếp tuyến, bán kính + Tan, Tan, Tan Tiếp tuyến, tiếp tuyến, tiếp tuyến + Tangent Tiếp tuyến + Temporary track point Điểm dò tạm thời + Text Chữ + Text Editor Trình soạn thảo chữ + Text Height Chiều cao chữ + Text Style... Kiểu chữ... + Text height Chiều cao chữ + Text override Chữ đè + Text style Kiểu chữ + Thaw All Layers Tan băng tất cả layer + Thaw Layer Tan băng layer + There is nothing here yet. Chưa có gì ở đây. + Thickness Độ dày + Time Thời gian + To get started, create or open a drawing. Để bắt đầu, hãy tạo hoặc mở một bản vẽ. + Tool Bar Thanh công cụ + Tool Sets Bộ công cụ + Tools Công cụ + Torus Xuyến + Trace Nét rộng + Track orthogonally only Chỉ dò theo phương ngang và dọc + Track using all polar angle settings Dò theo mọi góc cực đã đặt + Transparency Độ trong suốt + Trim Cắt xén + True Color Màu thực + Turn All Layers On Bật tất cả layer + Turn Off Layer Tắt layer + Turn On Layer Bật layer + Turn Quick Properties off (QPMODE) Tắt thuộc tính nhanh (QPMODE) + Type Loại + Type a command Nhập lệnh + Type text; Enter starts a new paragraph Nhập chữ; Enter để bắt đầu đoạn mới + UCS Icon Biểu tượng UCS + Undo Hoàn tác + Undo (⌘Z) Hoàn tác (⌘Z) + Ungroup Hủy nhóm + Union Hợp + Unisolate Layer Hủy cô lập layer + Units Conversion Chuyển đổi đơn vị + Units... Đơn vị... + Unlock Layer Mở khóa layer + Unlock viewport Mở khóa khung nhìn + Unmerge Cells Tách ô + Unsaved Layer State Trạng thái layer chưa lưu + Up Lên + Update Data Links Cập nhật liên kết dữ liệu + Update Cập nhật + Use System Setting Dùng cài đặt hệ thống + User Người dùng + User Parameters Tham số người dùng + Username Tên người dùng + Volume Thể tích + VP Color Màu VP + VP Freeze Đóng băng VP + Value Giá trị + Value: Giá trị: + Variables Biến + Version Phiên bản + Version 2000 Phiên bản 2000 + Version 2004 Phiên bản 2004 + Version 2007 Phiên bản 2007 + Version 2010 Phiên bản 2010 + Version 2013 Phiên bản 2013 + Version 2018 Phiên bản 2018 + Version {version} Phiên bản {version} + Vertical Dọc + VerticalDistance Khoảng cách dọc + View Góc nhìn + ViewCube ViewCube + Viewport Khung nhìn + Viewport Layer Freeze Đóng băng layer khung nhìn + Viewport Properties Thuộc tính khung nhìn + Viewport is locked Khung nhìn đã bị khóa + Viewport scale Tỉ lệ khung nhìn + Viewport {id} Khung nhìn {id} + Viewports Khung nhìn + W W + WCS WCS + White Trắng + Width factor Hệ số rộng + Window Cửa sổ + Wipeout Che phủ + Workspace Switching Chuyển đổi không gian làm việc + Write Block Ghi block + Xline Đường thẳng vô hạn + Yellow Vàng + Yes Có + Zoom Thu phóng + Zoom All Thu phóng tất cả + Zoom Dynamic Thu phóng động + Zoom Extents Thu phóng toàn bộ + Zoom In Phóng to + Zoom Object Thu phóng đối tượng + Zoom Out Thu nhỏ + Zoom Previous Thu phóng trước đó + Zoom Realtime Thu phóng thời gian thực + Zoom Window Thu phóng cửa sổ + error lỗi + {contributors} · {commits} {contributors} · {commits} + {kind} (constraint {id}) {kind} (ràng buộc {id}) + {kind} constraint {name} = {expression} (double-click to edit) {kind} ràng buộc {name} = {expression} (nhấp đúp để sửa) + {name}: {distance} < {angle}° {name}: {distance} < {angle}° + ƒx New User Parameter ƒx Tham số người dùng mới + ΔLOC ΔLOC + −Bin −Bin + −LOC −LOC + ⌘↩ to finish ⌘↩ để kết thúc +@plural {n} commit {n} commit +@plural {n} contributor {n} người đóng góp + Drawing as bytes Bản vẽ dưới dạng byte + Services Dịch vụ + Hide CADCraft Ẩn CADCraft + Hide Others Ẩn các ứng dụng khác + Accessibility Trợ năng + Show System Cursor Hiển thị con trỏ hệ thống + Animation Effects Hiệu ứng hoạt hình + Animation effects Hiệu ứng hoạt hình + Import... Nhập... + Export... Xuất... + Batch Publish... Xuất bản hàng loạt... + Scale List... Danh sách tỉ lệ... + Annotative Object Scale Tỉ lệ đối tượng chú thích + Add Current Scale Thêm tỉ lệ hiện hành + Delete Current Scale Xóa tỉ lệ hiện hành + Add/Delete Scales... Thêm/Xóa tỉ lệ... + Synchronize Multiple-scale Positions Đồng bộ vị trí đa tỉ lệ + Annotative Update Cập nhật chú thích + Show Annotative Objects Hiển thị đối tượng chú thích + Current Scale Only Chỉ tỉ lệ hiện hành + All Scales Tất cả tỉ lệ + Drawing Recovery Manager... Trình quản lý khôi phục bản vẽ... + Tolerance... Dung sai... + Add Vertex Thêm đỉnh + Remove Vertex Xóa đỉnh + Convert to Arc Chuyển thành cung tròn + Convert to Line Chuyển thành đoạn thẳng + Stretch Vertex Kéo giãn đỉnh + Edit Array Sửa mảng + Close Array Editing Đóng chỉnh sửa mảng + Multiline... Multiline... + Multiline Style... Kiểu multiline... + Solid Editing Chỉnh sửa solid + X X + Y Y + B B + CADCraft CADCraft + More toolbar commands Thêm lệnh thanh công cụ +menu View Xem +menu Draw Vẽ +menu Dimension Kích thước +menu Modify Hiệu chỉnh + Hatch Pattern Mẫu hatch + Search for pattern Tìm mẫu + Not a number or distance: {text} Không phải số hoặc khoảng cách: {text} + Query Texts Truy vấn chữ + Analyze Shapes Phân tích hình dạng + Check for Updates… Kiểm tra cập nhật… + CADCraft is up to date. CADCraft đã là phiên bản mới nhất. + Could not check for updates. Không thể kiểm tra cập nhật. + 3D Mouse Chuột 3D + 3D Mouse Navigation Điều hướng chuột 3D + 3D Mouse... Chuột 3D... + 3D mouse busy, possibly 3DxWare or missing device permissions Chuột 3D đang bận, có thể do 3DxWare hoặc thiếu quyền thiết bị + 3D mouse connected Đã kết nối chuột 3D + 3D mouse disconnected Đã ngắt kết nối chuột 3D + 3D mouse input could not be started Không thể khởi động đầu vào chuột 3D + 3D mouse input is unavailable on this platform Đầu vào chuột 3D không khả dụng trên nền tảng này + Automatic save every Tự động lưu mỗi + Automatic save file location Vị trí tệp tự động lưu + Calibrate Hiệu chỉnh + Calibrate 3D Mouse Hiệu chỉnh chuột 3D + Collapse Palettes Thu gọn bảng + Default save version Phiên bản lưu mặc định + Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. Bản vẽ chưa có tệp sẽ được lưu theo phiên bản mặc định. 0 phút sẽ tắt tự động lưu. + Enable 3D mouse navigation Bật điều hướng chuột 3D + Left device button: zoom extents. Right device button: calibrate. Nút trái của thiết bị: thu phóng toàn bộ. Nút phải của thiết bị: hiệu chỉnh. + Move sideways to pan; push/pull or twist to zoom. Di chuyển ngang để pan; đẩy/kéo hoặc xoay để thu phóng. + No supported 3D mouse found Không tìm thấy chuột 3D được hỗ trợ + Pan sensitivity Độ nhạy pan + Release the 3D mouse to calibrate its resting position Thả chuột 3D để hiệu chỉnh vị trí nghỉ của nó + Reverse zoom direction Đảo chiều thu phóng + Run Script... Chạy script... + SVG drawings (SVG, SVGZ) Bản vẽ SVG (SVG, SVGZ) + Show and hide the tools of this category Hiện và ẩn các công cụ trong danh mục này + Show in Tool Sets Hiển thị trong bộ công cụ + Time-sensitive right-click: a quick click is Enter, holding opens the menu Nhấp phải theo thời gian: nhấp nhanh là Enter, giữ lâu để mở menu + Turned off, a right-click while a command runs always opens the shortcut menu. Khi tắt, nhấp phải trong lúc lệnh đang chạy luôn mở menu ngữ cảnh. + Zoom sensitivity Độ nhạy thu phóng + min phút + Align Multileaders Căn chỉnh multileader + Collect Gom + Collect Multileaders Gom multileader + Edit Multileader Sửa multileader + Italic Nghiêng + Underline Gạch dưới + Overline Gạch trên + Justify Căn lề + Text color Màu chữ + Click the ruler to add a tab stop, right-click to remove one Nhấp vào thước để thêm điểm dừng tab, nhấp phải để xóa + Add: Pick points Thêm: chọn điểm + Add: Select objects Thêm: chọn đối tượng + Associative Liên kết + Block to create or edit Block để tạo hoặc sửa + Bottom left Dưới trái + Bottom right Dưới phải + Boundaries Đường bao + Boundaries picked: {n} Đã chọn đường bao: {n} + Centered Căn giữa + Clear Recent Files Xóa tệp gần đây + Click to set new origin Nhấp để đặt gốc mới + Close Block Editor Đóng trình sửa block + Color 1 Màu 1 + Color 2 Màu 2 + contains authoring elements. Open in Block Editor? chứa các phần tử tạo lập. Mở trong trình sửa block? + Create separate hatches Tạo hatch riêng biệt + Crossing selection color: Màu vùng chọn cắt: + Curved Cong + Custom Tùy chỉnh + Default to boundary extents Mặc định theo phạm vi đường bao + Drag Dynamic Grip Kéo grip động + Dynamic Block Data Dữ liệu block động + Dynamic Block Grips Grip block động + Dynamic Block Reference Tham chiếu block động + Edit Block Definition Sửa định nghĩa block + Evaluate LISP Tính giá trị LISP + Exclude: Loại trừ: + Grips Grip + Groups Nhóm + Hatch and Gradient Hatch và gradient + Hatch origin Gốc hatch + Hatch Pick Chọn hatch + Hatches Hatch + Hemispherical Bán cầu + Ignore Bỏ qua + Indicate selection area Chỉ định vùng chọn + Inverted Đảo ngược + Island detection Phát hiện đảo + Load Application... Tải ứng dụng... + Multiline text Chữ nhiều dòng + New block Block mới + Object grouping Gom nhóm đối tượng + Object selection limit for display of grips Giới hạn chọn đối tượng để hiển thị grip + Objects on locked layers Đối tượng trên layer bị khóa + Open in Block Editor Mở trong trình sửa block + Open Recent Mở gần đây + Origin: {x}, {y} Gốc: {x}, {y} + Outer Ngoài + Preview Xem trước + Save Block Lưu block + Save Block As Lưu block thành + Selection Area Effect Hiệu ứng vùng chọn + Selection area opacity: Độ mờ vùng chọn: + Selection effect color Màu hiệu ứng chọn + Selection modes Chế độ chọn + Selection preview Xem trước vùng chọn + Selection Preview Filter Bộ lọc xem trước vùng chọn + Set Dynamic Property Đặt thuộc tính động + Shape Hình dạng + Sheet Books to PDF... Xuất sổ tờ vẽ sang PDF... + Show grips Hiển thị grip + Specified origin Gốc đã chỉ định + Spherical Hình cầu + Tables Bảng + This drawing Bản vẽ này + Top left Trên trái + Top right Trên phải + Unsaved changes Thay đổi chưa lưu + Use current origin Dùng gốc hiện hành + Visual Effect Settings Cài đặt hiệu ứng hình ảnh + Visual Effect Settings... Cài đặt hiệu ứng hình ảnh... + When a command is active Khi có lệnh đang hoạt động + When no command is active Khi không có lệnh nào đang hoạt động + Window selection color: Màu vùng chọn cửa sổ: + Xrefs Xref + Arrow size Kích thước mũi tên + Dim scale overall Tỉ lệ kích thước tổng thể + Precision Độ chính xác + Break-line Symbol Ký hiệu ngắt đường + Convert Text to Mtext Chuyển chữ một dòng thành chữ nhiều dòng + Explode Attributes to Text Phân rã attribute thành chữ + Express Tools Express Tools + Move/Copy/Rotate Di chuyển/Sao chép/Xoay + Type an alias name. Nhập tên bí danh. + Choose the command the alias starts. Chọn lệnh mà bí danh sẽ chạy. + {command} is an unknown command. {command} là lệnh không xác định. + {alias} is already defined; select it and use Edit. {alias} đã được định nghĩa; chọn nó và dùng nút Sửa. + More than {n} aliases. Hơn {n} bí danh. + Alias file: {file} Tệp bí danh: {file} + No alias file loaded. REINIT replaces these aliases with a file's. Chưa tải tệp bí danh nào. REINIT sẽ thay các bí danh này bằng bí danh trong tệp. + Alias Bí danh + Command Lệnh + overrides built-in ghi đè lệnh tích hợp + built-in tích hợp + Add… Thêm… + Edit… Sửa… + Save alias Lưu bí danh + Discard Bỏ + Customize Tùy chỉnh + Edit Command Aliases (PGP)... Sửa bí danh lệnh (PGP)... + Interface scale Tỉ lệ giao diện + Select boundaries to remove Chọn đường bao cần xóa + Island Đảo + Select using two clicks only Chỉ chọn bằng hai lần nhấp + Define each corner of the selection window with a separate click. Xác định từng góc của cửa sổ chọn bằng một lần nhấp riêng. + Apply to Layout Áp dụng cho layout + Center the plot Căn giữa bản in + Enter block names to extract Nhập tên block cần trích xuất + Enter geometric characteristic Nhập đặc tính hình học + Enter name of LISP file to load Nhập tên tệp LISP cần tải + First corner Góc thứ nhất + Fit to paper Vừa khổ giấy + Landscape Ngang + Limits Giới hạn + Opposite corner Góc đối diện + Orientation Hướng + Paper size Khổ giấy + Plot area Vùng in + Plot object lineweights In bề dày nét đối tượng + Plot offset Độ lệch khi in + Plot transparency In độ trong suốt + Portrait Dọc + Printer/plotter Máy in/máy vẽ + Window < Cửa sổ < + X offset (mm) Độ lệch X (mm) + Y offset (mm) Độ lệch Y (mm) + AutoLISP (LSP) AutoLISP (LSP) + Units of new drawings Đơn vị của bản vẽ mới + Imperial (inches) Hệ Anh (inch) + Metric (millimetres) Hệ mét (milimét) + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). Bản vẽ mới và bản vẽ đầu tiên khi khởi động dùng các đơn vị này, trừ khi đã đặt mẫu mặc định (QNEWTEMPLATE). + Analyze Usage Phân tích sử dụng + Implied Loops Vòng kín ngầm định + Angstroms Angstrom + Architectural Kiến trúc + Astronomical Units Đơn vị thiên văn + Centimeters Centimét + Decameters Decamét + Decimal Thập phân + Decimal Degrees Độ thập phân + Decimeters Decimét + Deg/Min/Sec Độ/Phút/Giây + Don't Save Không lưu + Drawing Units Đơn vị bản vẽ + Engineering Kỹ thuật + Feet Feet + Fractional Phân số + Gigameters Gigamét + Grads Grad + Hectometers Hectomét + Inches Inch + Insertion scale Tỉ lệ chèn + Kilometers Kilomét + Light Years Năm ánh sáng + Meters Mét + Microinches Microinch + Microns Micron + Miles Dặm + Millimeters Milimét + Mils Mil + Nanometers Nanomét + Parsecs Parsec + Radians Radian + Sample output Đầu ra mẫu + Save changes to {name}? Lưu thay đổi cho {name}? + Scientific Khoa học + Surveyor's Units Đơn vị trắc địa + Unitless Không đơn vị + Units to scale inserted content Đơn vị để co giãn nội dung được chèn + US Survey Feet Feet khảo sát Mỹ + US Survey Inch Inch khảo sát Mỹ + US Survey Mile Dặm khảo sát Mỹ + US Survey Yard Yard khảo sát Mỹ + Yards Yard + Your changes will be lost if you don't save them. Các thay đổi của bạn sẽ bị mất nếu bạn không lưu chúng. + Save changes to block "{name}"? Lưu thay đổi cho block "{name}"? + Layouts Layout + Associate Liên kết + Backup copy Bản sao lưu + Create backup copy with each save Tạo bản sao lưu mỗi khi lưu + Change Properties Đổi thuộc tính + Font Phông chữ + Save Layout as Template Lưu layout thành mẫu diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d7c1c9078..bf0468d08 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -265,10 +265,15 @@ fn run_language_command(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." + } + "vi" => { + "No installed interface font has the Vietnamese letters, so the interface stays in English. Install one that does (Segoe UI, Arial, DejaVu Sans or Noto Sans) to use Vietnamese." + } + "ar" => "No Arabic font is installed, so the interface stays in English. Install one (Noto Sans Arabic, for example) to use Arabic.", + _ => "No Chinese font is installed, so the interface stays in English. Install one (Noto Sans CJK, for example) to use Chinese.", }); } Some(Ok(json!({"interfaceLanguage": preference.code(), "shown": shown}))) diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index dba0814b7..27f778735 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.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"`, `"bs"` or `"el"` | +//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"hu"`, `"tr"`, `"bs"`, `"vi"` or `"el"` | //! | `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/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9aeac31a1..17409f3ed 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -326,19 +326,11 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) { let chinese = language.starts_with("zh"); #[cfg(not(target_arch = "wasm32"))] { - let candidates: &[&str] = if cfg!(target_os = "macos") { - &["/System/Library/Fonts/SFNS.ttf", "/System/Library/Fonts/Helvetica.ttc", "/Library/Fonts/Arial.ttf"] - } else if cfg!(windows) { - &["C:\\Windows\\Fonts\\segoeui.ttf", "C:\\Windows\\Fonts\\arial.ttf"] - } else { - &[ - "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", - "/usr/share/fonts/TTF/DejaVuSans.ttf", - "/usr/share/fonts/noto/NotoSans-Regular.ttf", - "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", - ] - }; - for path in candidates { + for path in system_ui_candidates() { + // A Vietnamese interface takes the first one with its letters. + if language == "vi" && vietnamese_font() != Some(std::path::Path::new(path)) { + continue; + } if let Ok(bytes) = std::fs::read(path) { fonts.font_data.insert("system-ui".into(), std::sync::Arc::new(egui::FontData::from_owned(bytes))); if let Some(f) = fonts.families.get_mut(&FontFamily::Proportional) { @@ -409,6 +401,82 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) { ctx.set_fonts(fonts); } +/// The system interface fonts [`install_fonts`] looks for, in order; it loads the first installed +/// one ahead of egui's bundled faces. +#[cfg(not(target_arch = "wasm32"))] +fn system_ui_candidates() -> &'static [&'static str] { + if cfg!(target_os = "macos") { + &["/System/Library/Fonts/SFNS.ttf", "/System/Library/Fonts/Helvetica.ttc", "/Library/Fonts/Arial.ttf"] + } else if cfg!(windows) { + &["C:\\Windows\\Fonts\\segoeui.ttf", "C:\\Windows\\Fonts\\arial.ttf"] + } else { + &[ + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/TTF/DejaVuSans.ttf", + "/usr/share/fonts/noto/NotoSans-Regular.ttf", + "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", + ] + } +} + +/// The first of `candidates` that is `installed` and, for the Vietnamese interface, has the +/// Vietnamese letters: the system interface font [`install_fonts`] loads ahead of egui's faces. +#[cfg(not(target_arch = "wasm32"))] +fn ui_font_choice<'a>( + candidates: &[&'a str], + vietnamese: bool, + installed: impl Fn(&str) -> bool, + has_vietnamese: impl Fn(&str) -> bool, +) -> Option<&'a str> { + candidates.iter().copied().find(|p| installed(p) && (!vietnamese || has_vietnamese(p))) +} + +/// Whether `face` has every letter Vietnamese adds to Latin: the tone-marked vowels of Latin +/// Extended Additional (U+1EA0–U+1EF9), and ơ, ư, đ. +#[cfg(not(target_arch = "wasm32"))] +fn covers_vietnamese(face: &cadcraft_fonts::ttf::Face) -> bool { + ('\u{1ea0}'..='\u{1ef9}').chain(['ơ', 'Ơ', 'ư', 'Ư', 'đ', 'Đ']).all(|c| face.has_glyph(c)) +} + +/// The system interface font the Vietnamese interface takes: the first of +/// [`system_ui_candidates`] whose first face (the one egui uses) has every Vietnamese letter. +/// Segoe UI, Arial, SF, DejaVu Sans and Noto Sans do; egui's bundled faces stop at Latin +/// Extended-A, so without one the interface stays English (as the web build does). Checked once. +pub fn vietnamese_font() -> Option<&'static std::path::Path> { + #[cfg(not(target_arch = "wasm32"))] + { + static FOUND: std::sync::OnceLock> = std::sync::OnceLock::new(); + FOUND + .get_or_init(|| { + let has_vietnamese = |p: &str| { + read_capped(std::path::Path::new(p), MAX_UI_FONT_BYTES) + .and_then(|bytes| cadcraft_fonts::ttf::faces(&std::sync::Arc::new(bytes)).into_iter().next()) + .is_some_and(|face| covers_vietnamese(&face)) + }; + ui_font_choice(system_ui_candidates(), true, |p| std::path::Path::new(p).is_file(), has_vietnamese).map(std::path::PathBuf::from) + }) + .as_deref() + } + #[cfg(target_arch = "wasm32")] + None +} + +/// Whether the interface in `language` shows the Vietnamese letters (Tiếng Việt in the language +/// picker): the Vietnamese interface with [`vietnamese_font`], any other when the system interface +/// font it loads is that one. +pub fn shows_vietnamese(language: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + let loaded = || ui_font_choice(system_ui_candidates(), false, |p| std::path::Path::new(p).is_file(), |_| true); + vietnamese_font().is_some_and(|v| language == "vi" || loaded().is_some_and(|p| std::path::Path::new(p) == v)) + } + #[cfg(target_arch = "wasm32")] + { + let _ = language; + false + } +} + /// The faces `build.rs` embedded from craft-fonts that the interface loads, in order: every CJK /// face, because file, layout and layer names can be Japanese or Chinese whatever the interface /// shows (#513), with the interface's own face leading. A sans-serif face reads best, and a @@ -659,10 +727,12 @@ 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, Tiếng Việt a +/// system interface font with its tone-marked letters ([`vietnamese_font`]). pub fn can_show(language: &str) -> bool { match language { "ko" => shows_hangul("ko"), + "vi" => vietnamese_font().is_some(), "ar" => arabic_font().is_some() || embedded_script("Arab"), l if l.starts_with("zh") => cjk_font().is_some() || embedded_script("Hans") || embedded_script("Hant"), _ => true, @@ -737,6 +807,18 @@ pub fn apply(ctx: &egui::Context, theme: Theme, follow_system: bool) { #[cfg(test)] mod tests { + /// The system interface font loaded: the first installed one, and for Vietnamese the first + /// installed one with its letters (a later one when the first lacks them). + #[test] + fn the_vietnamese_interface_takes_the_first_installed_font_with_its_letters() { + let candidates = ["a.ttf", "b.ttf", "c.ttf", "d.ttf"]; + let installed = |p: &str| p != "a.ttf"; + let has_vietnamese = |p: &str| p == "c.ttf" || p == "d.ttf"; + assert_eq!(super::ui_font_choice(&candidates, false, installed, has_vietnamese), Some("b.ttf")); + assert_eq!(super::ui_font_choice(&candidates, true, installed, has_vietnamese), Some("c.ttf")); + assert_eq!(super::ui_font_choice(&candidates, true, installed, |_| false), None); + } + use cadcraft_fonts::CraftFont; /// A face shaped like `build.rs` writes them, with no font file (as in `cadcraft-fonts`). From 931c0c711aecf8aa1766c3157f0c87f5bd52b090 Mon Sep 17 00:00:00 2001 From: Tolga Date: Sat, 31 Oct 2026 17:33:07 +0300 Subject: [PATCH 295/900] Turkish catalog: fix wrong registers and resolve term collisions (#2536) * Turkish catalog: fix wrong registers and resolve term collisions Proofreading by a native speaker. 32 rows, wording only: - From/To were e-mail words (Kimden/Kime) -> Kaynak/Hedef - ViewCube Home was Giris (login) -> Baslangic - untranslated "or" in the zoom scale prompt -> veya - BREAK vs Cut both "Kes" -> BREAK family uses "Kir" - TRIM vs CLIP both "Kirp" -> TRIM uses "Buda" - spline vs curve both "egri" -> spline stays "spline" - plot style/preview/window said "Cizim X" (= drawing) -> "Cizdirme X" - Elevation vs Height both "Yukseklik" -> Elevation is "Kot" Co-Authored-By: Claude Fable 5 * Add GULERTOLGA to contributors Co-Authored-By: Claude Fable 5 --------- Co-authored-by: Claude Fable 5 --- contributors/people.toml | 3 ++ crates/ui-egui/src/i18n/tr.tsv | 64 +++++++++++++++++----------------- 2 files changed, 35 insertions(+), 32 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index cd1925e36..fc3f7a2a1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -96,3 +96,6 @@ sync_github_name = false [people.dylanmtaylor] sync_github_name = true + +[people.GULERTOLGA] +sync_github_name = true diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 11369e751..2bf979f85 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -130,8 +130,8 @@ Boundary Sınır Boundary... Sınır... Box Kutu - Break Kes - Break At Point Noktadan Kes + Break Kır + Break At Point Noktadan Kır Bring Above Objects Nesnelerin Üstüne Getir Bring Annotations to Front Açıklamaları Öne Getir Bring to Front En Öne Getir @@ -281,7 +281,7 @@ Diameter Çap Dim style Ölçü stili Dimension Ölçü - Dimension Break Ölçü Kesme + Dimension Break Ölçü Kırma Dimension Edit Ölçü Düzenleme Dimension Objects Only Yalnızca Ölçülendirme Nesneleri Dimension Space Ölçü Aralığı @@ -295,7 +295,7 @@ Disassociate Dimensions Ölçülerin İlişkisini Kaldır Display Görüntü Display name Görünen ad - Display plot styles Çizim stillerini göster + Display plot styles Çizdirme stillerini göster Distance Uzaklık Divide Böl Do not plot (click: plot) Çizdirme (tıklayın: çizdir) @@ -333,7 +333,7 @@ Edit Reference In-Place Referansı Yerinde Düzenle Edit Table Cell Tablo Hücresini Düzenle Edit Text... Metni Düzenle... - Elevation Yükseklik + Elevation Kot Ellipse Elips Elliptical Arc Eliptik Yay Enable 3D mouse navigation 3B fare ile gezinmeyi etkinleştir @@ -360,7 +360,7 @@ Enter constraint type Kısıtlama türünü girin Enter continuity Süreklilik girin Enter default attribute value Varsayılan öznitelik değerini girin - Enter degree of spline Eğrinin derecesini girin + Enter degree of spline Spline derecesini girin Enter delta angle Açı farkını girin Enter delta length or Uzunluk farkını girin veya Enter dimension text Ölçü metnini girin @@ -427,7 +427,7 @@ Freeze/Thaw Dondur/Çöz Freeze/Thaw in all viewports Tüm görünüm pencerelerinde dondur/çöz Freeze/Thaw in the current viewport Geçerli görünüm penceresinde dondur/çöz - From Kimden + From Kaynak From Template... Şablondan... General Genel Geometric Center Geometrik Merkez @@ -487,7 +487,7 @@ Hide Palettes Paletleri Gizle History Geçmiş Hold Shift to add to the selection Seçime eklemek için Shift'i basılı tutun - Home Giriş + Home Başlangıç Horizontal Yatay HorizontalDistance Yatay Uzaklık How to apply: Uygulama biçimi: @@ -677,7 +677,7 @@ No contributor data was built into this copy. Bu kopyaya katkıda bulunan verisi eklenmemiş. No external references are attached. İliştirilmiş dış referans yok. No model credits were built into this copy. Bu kopyaya model emeği bilgisi eklenmemiş. - No plot style tables. Çizim stili tablosu yok. + No plot style tables. Çizdirme stili tablosu yok. No saved layer states Kayıtlı katman durumu yok No selection Seçim yok No supported 3D mouse found Desteklenen 3B fare bulunamadı @@ -763,16 +763,16 @@ Pickbox size Seçim kutusu boyutu Plot Çizdir Plot (click: do not plot) Çizdir (tıklayın: çizdirme) - Plot Preview Çizim Önizlemesi - Plot Style Manager Çizim Stili Yöneticisi - Plot Style Manager... Çizim Stili Yöneticisi... - Plot Style... Çizim Stili... - Plot Styles... Çizim Stilleri... - Plot Window Çizim Penceresi - Plot style Çizim stili - Plot style attached to Çizim stilinin bağlı olduğu yer - Plot style table Çizim stili tablosu - Plot table type Çizim tablosu türü + Plot Preview Çizdirme Önizlemesi + Plot Style Manager Çizdirme Stili Yöneticisi + Plot Style Manager... Çizdirme Stili Yöneticisi... + Plot Style... Çizdirme Stili... + Plot Styles... Çizdirme Stilleri... + Plot Window Çizdirme Penceresi + Plot style Çizdirme stili + Plot style attached to Çizdirme stilinin bağlı olduğu yer + Plot style table Çizdirme stili tablosu + Plot table type Çizdirme tablosu türü Plotter Manager Çizici Yöneticisi Plotter Manager... Çizici Yöneticisi... Plus/minus Artı/eksi @@ -913,7 +913,7 @@ Select a block reference. Bir blok referansı seçin. Select a circle or arc. Bir daire veya yay seçin. Select a closed polyline Kapalı bir çoklu çizgi seçin - Select a closed polyline, circle, ellipse or closed spline. Kapalı bir çoklu çizgi, daire, elips veya kapalı eğri seçin. + Select a closed polyline, circle, ellipse or closed spline. Kapalı bir çoklu çizgi, daire, elips veya kapalı spline seçin. Select a closed polyline. Kapalı bir çoklu çizgi seçin. Select a curve as the path. Yol olarak bir eğri seçin. Select a dimension constraint type Bir ölçü kısıtlaması türü seçin @@ -922,7 +922,7 @@ Select a line or an arc. Bir çizgi veya yay seçin. Select a line or polyline segment Bir çizgi veya çoklu çizgi parçası seçin Select a line, arc or open polyline. Bir çizgi, yay veya açık çoklu çizgi seçin. - Select a line, arc, circle, polyline, ellipse or spline as the path. Yol olarak bir çizgi, yay, daire, çoklu çizgi, elips veya eğri seçin. + Select a line, arc, circle, polyline, ellipse or spline as the path. Yol olarak bir çizgi, yay, daire, çoklu çizgi, elips veya spline seçin. Select a line, circle, arc or polyline segment. Bir çizgi, daire, yay veya çoklu çizgi parçası seçin. Select a line. Bir çizgi seçin. Select a polyline. Bir çoklu çizgi seçin. @@ -935,7 +935,7 @@ Select an object to measure or Ölçülecek nesneyi seçin veya Select an object. Bir nesne seçin. Select an open curve. Açık bir eğri seçin. - Select an open line, arc, polyline, ellipse arc or spline. Açık bir çizgi, yay, çoklu çizgi, elips yayı veya eğri seçin. + Select an open line, arc, polyline, ellipse arc or spline. Açık bir çizgi, yay, çoklu çizgi, elips yayı veya spline seçin. Select arc or circle Yay veya daire seçin Select arc or polyline arc segment Yay veya çoklu çizgi yay parçası seçin Select arc style Yay stilini seçin @@ -952,10 +952,10 @@ Select object Nesne seçin Select object to dimension Ölçülendirilecek nesneyi seçin Select object to divide Bölünecek nesneyi seçin - Select object to extend or shift-select to trim Uzatılacak nesneyi seçin ya da kırpmak için Shift ile seçin + Select object to extend or shift-select to trim Uzatılacak nesneyi seçin ya da budamak için Shift ile seçin Select object to measure Ölçülecek nesneyi seçin Select object to offset Ötelenecek nesneyi seçin - Select object to trim or shift-select to extend Kırpılacak nesneyi seçin ya da uzatmak için Shift ile seçin + Select object to trim or shift-select to extend Budanacak nesneyi seçin ya da uzatmak için Shift ile seçin Select objects Nesneleri seçin Select objects (crossing window first corner) Nesneleri seçin (kesişen pencerenin ilk köşesi) Select objects first, then choose a command Önce nesneleri seçin, sonra bir komut belirleyin @@ -971,7 +971,7 @@ Select second object İkinci nesneyi seçin Select second object or shift-select to apply corner İkinci nesneyi seçin ya da köşe uygulamak için Shift ile seçin Select second point İkinci noktayı seçin - Select spline Eğri seçin + Select spline Spline seçin Select symmetry line Simetri çizgisini seçin Select two points İki nokta seçin Selection Seçim @@ -1057,7 +1057,7 @@ Specify center point of array Dizinin merkez noktasını belirtin Specify center point of base Tabanın merkez noktasını belirtin Specify corner of viewport Görünüm penceresinin köşesini belirtin - Specify corner of window, enter a scale factor (nX or nXP) Pencerenin köşesini belirtin, bir ölçek faktörü girin (nX or nXP) + Specify corner of window, enter a scale factor (nX or nXP) Pencerenin köşesini belirtin, bir ölçek faktörü girin (nX veya nXP) Specify diameter of circle Dairenin çapını belirtin Specify dimension arc line location Ölçü yayı çizgisinin konumunu belirtin Specify dimension line location Ölçü çizgisinin konumunu belirtin @@ -1125,7 +1125,7 @@ Specify rotation angle or Döndürme açısını belirtin veya Specify scale factor Ölçek faktörünü belirtin Specify second angle endpoint Açının ikinci uç noktasını belirtin - Specify second break point İkinci kesme noktasını belirtin + Specify second break point İkinci kırma noktasını belirtin Specify second chamfer distance for rectangles Dikdörtgenler için ikinci pah uzaklığını belirtin Specify second constraint point İkinci kısıtlama noktasını belirtin Specify second destination point İkinci hedef noktayı belirtin @@ -1148,7 +1148,7 @@ Specify starting width Başlangıç genişliğini belirtin Specify starting width for next segment Sonraki parçanın başlangıç genişliğini belirtin Specify tangent direction for the start point of arc Yayın başlangıç noktası için teğet yönünü belirtin - Specify the elevation for rectangles Dikdörtgenler için yüksekliği belirtin + Specify the elevation for rectangles Dikdörtgenler için kotu belirtin Specify thickness for rectangles Dikdörtgenler için kalınlığı belirtin Specify third point on circle Daire üzerindeki üçüncü noktayı belirtin Specify third point on circle: _tan to Daire üzerindeki üçüncü noktayı belirtin: _tan to @@ -1161,8 +1161,8 @@ Specify width for rectangles Dikdörtgenler için genişliği belirtin Sphere Küre Spherical Küresel - Spline Eğri - Spline Edit Eğri Düzenle + Spline Spline + Spline Edit Spline Düzenle Stack (type 1/2 then select) Yığ (1/2 yazıp seçin) Standard Standart Start Başlangıç @@ -1218,7 +1218,7 @@ This drawing Bu çizim Time Zaman Time-sensitive right-click: a quick click is Enter, holding opens the menu Süreye bağlı sağ tıklama: kısa tıklama Enter'dır, basılı tutmak menüyü açar - To Kime + To Hedef To get started, create or open a drawing. Başlamak için bir çizim oluşturun veya açın. Toggle PICKADD (off: each pick replaces the selection) PICKADD'i değiştir (kapalı: her seçim öncekinin yerini alır) Toggle PICKADD (on: picks add to the selection) PICKADD'i değiştir (açık: seçimler mevcut seçime eklenir) @@ -1233,7 +1233,7 @@ Track orthogonally only Yalnızca dik açılarla izle Track using all polar angle settings Tüm kutupsal açı ayarlarını kullanarak izle Transparency Saydamlık - Trim Kırp + Trim Buda True Color Gerçek Renk Turn All Layers On Tüm Katmanları Aç Turn Off Layer Katmanı Kapat From b6331c8603f9cc51b8044237f4517f79da1932b6 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:34:44 +0700 Subject: [PATCH 296/900] -ARRAY: the classic command-line array, as AutoCAD lays it out (#2538) * Add -ARRAY, the classic command-line array, as AutoCAD lays it out Rectangular arrays move the copy in row r and column c by (c * column distance, r * row distance), asking for a distance only when there is more than one row or column; polar arrays space n items 360/n apart around a full circle and fill/(n - 1) otherwise, turning the copies or moving them with the group 10 point of the object selected last. The copies are separate objects; the type asked defaults to the one used last. Co-Authored-By: Claude Opus 5.5 * -ARRAY: refuse an unknown type and oversized arrays before making transforms The JSON form errors on a type other than rectangular or polar, and checks MAXARRAY before the copies' transforms are made; the command line bounds the columns by the rows (CodeRabbit). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/cmd/array.rs | 7 +- crates/engine/src/cmd/array/classic.rs | 255 ++++++++++++++++++++++++ crates/engine/src/last_used.rs | 3 + crates/engine/src/session.rs | 2 + crates/engine/src/session/picking.rs | 2 +- crates/engine/tests/it/classic_array.rs | 194 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 7 files changed, 462 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/array/classic.rs create mode 100644 crates/engine/tests/it/classic_array.rs diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 9d4a2fd9c..255555a28 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -1,4 +1,5 @@ -//! Array commands: ARRAY, ARRAYRECT and ARRAYPOLAR (ARRAYPATH lives in `modify2`). +//! Array commands: ARRAY, ARRAYRECT, ARRAYPOLAR and the classic -ARRAY (ARRAYPATH lives in +//! `modify2`). //! //! Arrays are associative by default (ARRAYASSOCIATIVITY): the source objects move into an //! anonymous source block and the array becomes one block reference to an anonymous array block @@ -21,6 +22,7 @@ use super::{CommandSpec, bad, bool_or, f64_or, find_command, point_param, point_ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; +mod classic; mod edit; /// Most preview entities drawn while the array is edited. @@ -48,6 +50,9 @@ pub fn specs() -> Vec { "{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)}", ) .interactive(|_| Ok(Box::new(PolarM::default()))), + CommandSpec::new("-array", "Array", classic::run_classic) + .params("{handles?, type?: \"rectangular\" (default) | \"polar\", rows? (1), cols? (1), rowSpacing?, colSpacing?, center, count, angle? (degrees, default 360), rotate?: bool (default true), base? ([x, y], default the DXF group 10 point of the last object)} → {created}: separate copies, as the classic -ARRAY makes them") + .interactive(|_| Ok(Box::new(classic::ClassicM::default()))), ] .into_iter() .chain(edit::specs()) diff --git a/crates/engine/src/cmd/array/classic.rs b/crates/engine/src/cmd/array/classic.rs new file mode 100644 index 000000000..5fecefa2a --- /dev/null +++ b/crates/engine/src/cmd/array/classic.rs @@ -0,0 +1,255 @@ +//! -ARRAY: the classic command-line array, as AutoCAD 2024 runs it from AutoLISP's `command` +//! (accoreconsole, every copy read back with `entget`). It makes separate copies, never an +//! associative array: +//! - "Enter the type of array [Rectangular/Polar] ": the default is the type used last; +//! - Rectangular asks "Enter the number of rows (---) <1>" and "Enter the number of columns (|||) +//! <1>", then "Enter the distance between rows or specify unit cell (---)" only for more than one +//! row (two corners give both distances) and "Specify the distance between columns (|||)" only for +//! more than one column. The copy in row r and column c moves by (c·columns, r·rows): 2 rows and +//! 2 columns at −12.57 and −18.01 put the copies below and to the left; +//! - Polar asks "Specify center point of array or [Base]", "Enter the number of items in the +//! array", "Specify the angle to fill (+=ccw, -=cw) <360>" and "Rotate arrayed objects? +//! [Yes/No] ". Items are 360/n apart around a full circle, else fill/(n − 1) apart (6 items in +//! 270°: 54°; −90° turns clockwise). Not rotated, each copy moves as the DXF group 10 point of the +//! object selected last turns about the centre (a polyline's first vertex, an arc's centre), or +//! as the Base point does. + +use cadcraft_doc::Handle; +use cadcraft_geom::{Mat3, Vec2}; +use serde_json::{Value, json}; + +use super::super::machines::{SelOutcome, SelectPhase, number}; +use super::super::{bad, bool_or, f64_or, point_param, point_req, str_param, targets}; +use super::{KEYWORDS, angle, check_size, copy_all, count, count_or, max_count, other, yes_no}; +use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Stage { + #[default] + Select, + Kind, + Rows, + Columns, + RowDistance, + /// The unit cell's other corner, after the first one. + Corner(Vec2), + ColumnDistance, + Center, + Base, + Items, + Fill, + Rotate, +} + +#[derive(Default)] +pub(super) struct ClassicM { + sel: SelectPhase, + objs: Vec, + stage: Stage, + rows: u64, + columns: u64, + row_distance: f64, + center: Vec2, + base: Option, + items: u64, + fill: f64, +} + +/// The moves of a rectangular array's copies (the objects themselves stay in row 0, column 0). +fn rect_mats(rows: u64, columns: u64, row_distance: f64, column_distance: f64) -> Vec { + (0..rows) + .flat_map(|r| (0..columns).map(move |c| (r, c))) + .filter(|rc| *rc != (0, 0)) + .map(|(r, c)| Mat3::translate(Vec2::new(c as f64 * column_distance, r as f64 * row_distance))) + .collect() +} + +/// The transforms of a polar array's copies: `items` around `center` filling `fill` degrees, +/// turned with it or moved as `base` turns. +fn polar_mats(center: Vec2, items: u64, fill: f64, rotate: bool, base: Vec2) -> Vec { + let full = (fill.abs() - 360.0).abs() < 1e-9; + let gaps = if full { items } else { items.saturating_sub(1) }.max(1); + let step = fill.to_radians() / gaps as f64; + (1..items) + .map(|k| { + let a = step * k as f64; + if rotate { Mat3::rotate_about(center, a) } else { Mat3::translate(base.rotate_about(center, a) - base) } + }) + .collect() +} + +/// The DXF group 10 point of the last of `hs`, which a polar array that doesn't rotate its copies +/// moves around the centre. +fn last_point(s: &Session, hs: &[Handle]) -> Option { + let d = s.doc().ok()?; + hs.last().and_then(|h| d.entity(*h)).and_then(|e| crate::session::group_10(d, e)) +} + +/// -ARRAY's JSON form. +pub(super) fn run_classic(s: &mut Session, p: &Value) -> Result { + let hs = targets(s, p)?; + let polar = match str_param(p, "type").map(str::to_ascii_lowercase).as_deref() { + None | Some("rectangular") => false, + Some("polar") => true, + Some(_) => return Err(bad("-array", "type must be \"rectangular\" or \"polar\"")), + }; + // The size is checked before the copies' transforms are made. + let mats = if polar { + let center = point_req("-array", p, "center")?; + let items = count_or("-array", p, "count", 1)?; + check_size(s, items, hs.len())?; + let base = point_param(p, "base").or_else(|| last_point(s, &hs)).unwrap_or(center); + polar_mats(center, items, f64_or(p, "angle", 360.0), bool_or(p, "rotate", true), base) + } else { + let rows = count_or("-array", p, "rows", 1)?; + let columns = count_or("-array", p, "cols", 1)?; + check_size(s, rows.saturating_mul(columns), hs.len())?; + rect_mats(rows, columns, f64_or(p, "rowSpacing", 0.0), f64_or(p, "colSpacing", 0.0)) + }; + let created = copy_all(s, &hs, mats.into_iter())?; + Ok(json!({ "created": created })) +} + +impl ClassicM { + /// Make the copies. + fn finish(&mut self, s: &mut Session, mats: Vec) -> Result { + check_size(s, mats.len() as u64 + 1, self.objs.len())?; + copy_all(s, &self.objs, mats.into_iter())?; + s.set_selection(Vec::new()); + Ok(Step::Done) + } + + /// After the rows and columns: the distances still needed, or the copies. + fn after_counts(&mut self, s: &mut Session) -> Result { + if self.rows > 1 { + self.stage = Stage::RowDistance; + } else if self.columns > 1 { + self.stage = Stage::ColumnDistance; + } else { + return self.finish(s, Vec::new()); + } + Ok(Step::Continue) + } + + fn rect(&mut self, s: &mut Session, column_distance: f64) -> Result { + let mats = rect_mats(self.rows, self.columns, self.row_distance, column_distance); + self.finish(s, mats) + } +} + +impl Interactive for ClassicM { + fn name(&self) -> &'static str { + "-ARRAY" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + if self.sel.done { + self.objs = self.sel.picked.clone(); + self.stage = Stage::Kind; + } + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + match self.stage { + Stage::Select => self.sel.prompt(), + Stage::Kind => Prompt::new("Enter the type of array", KEYWORDS) + .kw(&["Rectangular", "Polar"]) + .default(if s.last_used.classic_array_polar { "P" } else { "R" }), + Stage::Rows => Prompt::new("Enter the number of rows (---)", Accept::NUMBER).default("1"), + Stage::Columns => Prompt::new("Enter the number of columns (|||)", Accept::NUMBER).default("1"), + Stage::RowDistance => Prompt::new("Enter the distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER), + Stage::Corner(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a), + Stage::ColumnDistance => Prompt::new("Specify the distance between columns (|||)", Accept::NUMBER), + Stage::Center => Prompt::new("Specify center point of array", Accept::POINT).kw(&["Base"]), + Stage::Base => Prompt::new("Specify base point of objects", Accept::POINT), + Stage::Items => Prompt::new("Enter the number of items in the array", Accept::NUMBER), + Stage::Fill => Prompt::new("Specify the angle to fill (+=ccw, -=cw)", Accept::NUMBER).default("360"), + Stage::Rotate => Prompt::new("Rotate arrayed objects?", KEYWORDS).kw(&["Yes", "No"]).default("Y"), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let max = max_count(s, 1, self.objs.len()); + match (self.stage, i) { + (Stage::Select, i) => match self.sel.feed(s, &i)? { + SelOutcome::More => {} + SelOutcome::Done(hs) => { + self.objs = hs; + self.stage = Stage::Kind; + } + SelOutcome::Empty => return Ok(Step::Done), + }, + (Stage::Kind, i) => { + let polar = match &i { + Input::Enter => s.last_used.classic_array_polar, + Input::Keyword(k) | Input::Text(k) => match k.trim().trim_start_matches('_').to_ascii_lowercase().chars().next() { + Some('p') => true, + Some('r') => false, + _ => return Err(other("Invalid option keyword.")), + }, + _ => return Ok(Step::Continue), + }; + s.last_used.classic_array_polar = polar; + self.stage = if polar { Stage::Center } else { Stage::Rows }; + } + (Stage::Rows, i) => { + if let Some(n) = count(&i, 1, max)? { + self.rows = n; + self.stage = Stage::Columns; + } + } + // No more columns than MAXARRAY allows with the rows. + (Stage::Columns, i) => { + if let Some(n) = count(&i, 1, max_count(s, self.rows, self.objs.len()))? { + self.columns = n; + return self.after_counts(s); + } + } + (Stage::RowDistance, Input::Point(a)) => self.stage = Stage::Corner(a), + (Stage::RowDistance, Input::Text(t)) => { + self.row_distance = number(&t).filter(|v| v.is_finite()).ok_or_else(|| other("Requires a distance."))?; + if self.columns <= 1 { + return self.rect(s, 0.0); + } + self.stage = Stage::ColumnDistance; + } + // A unit cell gives both distances. + (Stage::Corner(a), Input::Point(b)) => { + self.row_distance = b.y - a.y; + return self.rect(s, b.x - a.x); + } + (Stage::ColumnDistance, Input::Text(t)) => { + let d = number(&t).filter(|v| v.is_finite()).ok_or_else(|| other("Requires a distance."))?; + return self.rect(s, d); + } + (Stage::Center, Input::Point(c)) => { + self.center = c; + self.stage = Stage::Items; + } + (Stage::Center, Input::Keyword(k)) if k == "Base" => self.stage = Stage::Base, + (Stage::Base, Input::Point(b)) => { + self.base = Some(b); + self.stage = Stage::Center; + } + (Stage::Items, i @ Input::Text(_)) => { + if let Some(n) = count(&i, 1, max)? { + self.items = n; + self.stage = Stage::Fill; + } + } + (Stage::Fill, i) => { + if let Some(a) = angle(&i, 360.0, &s.angle_settings())? { + self.fill = a; + self.stage = Stage::Rotate; + } + } + (Stage::Rotate, i) => { + let Some(rotate) = yes_no(&i, true) else { return Err(other("Invalid option keyword.")) }; + let base = self.base.or_else(|| last_point(s, &self.objs)).unwrap_or(self.center); + let mats = polar_mats(self.center, self.items, self.fill, rotate, base); + return self.finish(s, mats); + } + _ => {} + } + Ok(Step::Continue) + } +} diff --git a/crates/engine/src/last_used.rs b/crates/engine/src/last_used.rs index 88a1d4f59..e884caf1b 100644 --- a/crates/engine/src/last_used.rs +++ b/crates/engine/src/last_used.rs @@ -25,6 +25,8 @@ pub struct LastUsed { pub mleader_block: String, /// BREAKLINE's Block, Size and Extension. pub breakline: cmd::BreaklineOptions, + /// -ARRAY's type: Polar instead of Rectangular. + pub classic_array_polar: bool, /// RECTANG's chamfer, fillet, width, elevation, thickness and rotation. pub rectang: RectangModes, } @@ -41,6 +43,7 @@ impl Default for LastUsed { mleader: MLeaderOptions::default(), mleader_block: String::new(), breakline: cmd::BreaklineOptions::default(), + classic_array_polar: false, rectang: RectangModes::default(), } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index d1ae67ee1..f465b7a55 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -13,3 +13,5 @@ mod files; mod interactive; mod picking; mod zoom; + +pub(crate) use picking::group_10; diff --git a/crates/engine/src/session/picking.rs b/crates/engine/src/session/picking.rs index a9d146571..1ab773a00 100644 --- a/crates/engine/src/session/picking.rs +++ b/crates/engine/src/session/picking.rs @@ -162,7 +162,7 @@ impl Session { /// An object's DXF group 10 point: the first point of its entity list, or its first grip where /// entity lists are not built in. -fn group_10(d: &Drawing, e: &Entity) -> Option { +pub(crate) fn group_10(d: &Drawing, e: &Entity) -> Option { let Some(codec) = cmd::file::entity_codec() else { return e.kind.grips().first().copied() }; let (_, tags) = (codec.groups)(d, e); let i = tags.iter().position(|t| t.code == 10)?; diff --git a/crates/engine/tests/it/classic_array.rs b/crates/engine/tests/it/classic_array.rs new file mode 100644 index 000000000..8f74f8f48 --- /dev/null +++ b/crates/engine/tests/it/classic_array.rs @@ -0,0 +1,194 @@ +//! -ARRAY, the classic command-line array, as AutoCAD 2024 runs it from AutoLISP's `command` +//! (accoreconsole, every copy read back with `entget`). + +use std::f64::consts::TAU; + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec}; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +/// A session with the object `made` (an entity list) as `a` in LISP, after `code`. +fn run(made: &str, code: &str) -> Session { + // `entmake` goes through the DXF codec, as in the app. + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + let mut s = Session::new(); + s.cmdline(&format!("(progn (setq a (progn (entmake '({made})) (entlast))) {code})")).unwrap(); + s +} + +/// Where each object is: a line's start, a circle's or arc's centre, a polyline's first vertex, a +/// text's insertion point. +fn points(s: &Session) -> Vec<[f64; 2]> { + s.doc() + .unwrap() + .model + .iter() + .map(|e| match &e.kind { + EntityKind::Line(l) => [l.a.x, l.a.y], + EntityKind::Circle(c) => [c.center.x, c.center.y], + EntityKind::Arc(a) => [a.center.x, a.center.y], + EntityKind::LwPolyline(p) => [p.vertices[0].p.x, p.vertices[0].p.y], + EntityKind::Text(t) => [t.insert.x, t.insert.y], + k => panic!("unexpected {k:?}"), + }) + .collect() +} + +/// `got` holds each of `want` to `tol`, and nothing else. +fn same(got: &[[f64; 2]], want: &[[f64; 2]], tol: f64) -> bool { + got.len() == want.len() && want.iter().all(|w| got.iter().any(|g| (g[0] - w[0]).abs() <= tol && (g[1] - w[1]).abs() <= tol)) +} + +fn line(a: [f64; 2], b: [f64; 2]) -> String { + format!("(0 . \"LINE\") (10 {} {} 0.0) (11 {} {} 0.0)", a[0], a[1], b[0], b[1]) +} + +fn circle(c: [f64; 2], r: f64) -> String { + format!("(0 . \"CIRCLE\") (10 {} {} 0.0) (40 . {r})", c[0], c[1]) +} + +fn arc(c: [f64; 2], r: f64, a1: f64, a2: f64) -> String { + format!("(0 . \"ARC\") (10 {} {} 0.0) (40 . {r}) (50 . {}) (51 . {})", c[0], c[1], a1.to_radians(), a2.to_radians()) +} + +/// The measured polyline: four vertices with bulges 0.3, 0, −0.7, 0, from `at`, `scale` × the +/// drawn size, `width` wide. +fn polyline(at: [f64; 2], scale: f64, width: f64) -> String { + let v = [(0.0, 0.0, 0.3), (20.0, 5.0, 0.0), (35.0, -10.0, -0.7), (50.0, 0.0, 0.0)]; + let vs: String = v.iter().map(|(x, y, b)| format!(" (10 {} {}) (42 . {b})", at[0] + x * scale, at[1] + y * scale)).collect(); + format!("(0 . \"LWPOLYLINE\") (90 . 4) (70 . 0) (43 . {width}){vs}") +} + +#[test] +fn rectangular_copies_move_by_rows_and_columns() { + let s = run( + &line([-1.1929712440222175, 9.67888030686079], [44.51297824124873, 11.673136668914886]), + "(command \"_.-ARRAY\" a \"\" \"_R\" 2 2 -12.570757111654931 -18.0084920904546)", + ); + let want = [ + [-19.20146333447681, -2.891876804794138], + [-19.20146333447681, 9.67888030686079], + [-1.192971244022217, -2.891876804794138], + [-1.192971244022217, 9.67888030686079], + ]; + assert!(same(&points(&s), &want, 1e-9), "{:?}", points(&s)); + // One row or one column: that distance isn't asked for. + let s = run(&circle([5.801226536663419, -5.877116775641122], 23.343762414841144), "(command \"_.-ARRAY\" a \"\" \"_R\" 1 3 -26.90504352387681)"); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let want = [[-48.0088605110902, -5.877116775641122], [-21.10381698721339, -5.877116775641122], [5.801226536663419, -5.877116775641122]]; + assert!(same(&points(&s), &want, 1e-9), "{:?}", points(&s)); + let s = run(&polyline([0.5, 0.25], 0.001, 0.0005), "(command \"_.-ARRAY\" a \"\" \"_R\" 3 1 -0.010095474538067209)"); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert!(same(&points(&s), &[[0.5, 0.2298090509238659], [0.5, 0.239904525461933], [0.5, 0.25]], 1e-12), "{:?}", points(&s)); + let s = run( + "(0 . \"TEXT\") (10 5.4185272544331635 4.443702697220587 0.0) (40 . 2.5) (1 . \"AB12\") (50 . 0.20972899)", + "(command \"_.-ARRAY\" a \"\" \"_R\" 1 4 26.03962020976745)", + ); + let want = [ + [83.53738788373552, 4.443702697220587], + [57.49776767396807, 4.443702697220587], + [31.45814746420061, 4.443702697220587], + [5.418527254433163, 4.443702697220587], + ]; + assert!(same(&points(&s), &want, 1e-9), "{:?}", points(&s)); +} + +#[test] +fn polar_copies_turn_about_the_centre() { + // Five items around a full circle: 72° apart. + let s = run( + &arc([8.737608057965836, 8.018370437941456], 25.76749991913238, 246.54512163341687, 4.3030133419271355), + "(command \"_.-ARRAY\" a \"\" \"_P\" '(10.631794214160564 -5.07952370466397) 5 360 \"_Y\")", + ); + let want = [ + [22.50329607545565, 0.769426262850251], + [19.86297201814329, -14.56256796884801], + [4.465473991920418, -16.78931734426366], + [-2.410379072682379, -2.833529910999876], + [8.737608057965836, 8.018370437941456], + ]; + assert!(same(&points(&s), &want, 1e-9), "{:?}", points(&s)); + let starts: Vec = + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Arc(a) = &e.kind { Some(a.start) } else { None }).collect(); + for want in [3.046387065797107, 1.789750004361188, 0.5331129429252733, 5.559661188668941, 4.303024127233024] { + assert!(starts.iter().any(|a| ((a - want).rem_euclid(TAU) + 1e-9).rem_euclid(TAU) < 2e-9), "{want}: {starts:?}"); + } + // Six items in 270°: 54° apart. + let s = run( + &line([14.349623930607876, -18.237839127538827], [57.5895083326729, 8.515990272720988]), + "(command \"_.-ARRAY\" a \"\" \"_P\" '(9.968618268950948 -10.513614962917108) 6 270 \"_Y\")", + ); + let want = [ + [2.244394104329227, -14.89462062457403], + [1.884125186851836, -6.839676863508278], + [8.18895082173591, -1.813636035924282], + [15.96098679213407, -3.960114445242588], + [18.79273740462331, -11.50949197954958], + [14.34962393060787, -18.23783912753882], + ]; + assert!(same(&points(&s), &want, 1e-9), "{:?}", points(&s)); +} + +#[test] +fn polar_copies_not_rotated_move_with_the_group_10_point() { + // A polyline moves with its first vertex: three items in 270°. + let s = run( + &polyline([612345.678, 2398765.432], 1.0, 0.5), + "(command \"_.-ARRAY\" a \"\" \"_P\" '(612362.9804954464 2398768.822523769) 3 270 \"_N\")", + ); + let want = [[612359.5899716774, 2398786.125019215], [612377.612669657, 2398758.985274256], [612345.678, 2398765.432]]; + assert!(same(&points(&s), &want, 1e-6), "{:?}", points(&s)); + // A circle with its centre, five items in −90° (clockwise). + let s = run( + &circle([612340.715727557, 2398755.830080357], 26.60109393014347), + "(command \"_.-ARRAY\" a \"\" \"_P\" '(612346.260090821 2398771.804712544) 5 -90 \"_N\")", + ); + let want = [ + [612330.2854586337, 2398777.349075808], + [612329.3797191395, 2398770.813809208], + [612331.0438632132, 2398764.429398659], + [612335.0245400043, 2398759.16781279], + [612340.715727557, 2398755.830080357], + ]; + assert!(same(&points(&s), &want, 1e-6), "{:?}", points(&s)); + // An arc with its centre, its angles unchanged. + let s = run( + &arc([612339.185864084, 2398766.23253733], 13.970352776505141, 238.67958380809327, 80.40871664680844), + "(command \"_.-ARRAY\" a \"\" \"_P\" '(612358.7800675274 2398749.633182222) 7 360 \"_N\")", + ); + let want = [ + [612359.541179917, 2398775.302075975], + [612379.3233625971, 2398765.042414074], + [612383.6360250826, 2398743.179286296], + [612369.2316445602, 2398726.176073787], + [612346.957013359, 2398726.836542366], + [612333.585383093, 2398744.663345723], + [612339.185864084, 2398766.23253733], + ]; + assert!(same(&points(&s), &want, 1e-6), "{:?}", points(&s)); + assert!(s.doc().unwrap().model.iter().all(|e| matches!(&e.kind, EntityKind::Arc(a) if (a.start - 4.165744594740973).abs() < 1e-9))); +} + +#[test] +fn the_type_asked_defaults_to_the_one_used_last() { + let mut s = run(&circle([0.0, 0.0], 1.0), "(command \"_.-ARRAY\" a \"\" \"_P\" '(10.0 0.0) 3 360 \"_Y\")"); + s.cmdline("(command \"_.-ARRAY\" a \"\")").unwrap(); + assert!(s.prompt_text().contains("[Rectangular/Polar]

"), "{}", s.prompt_text()); +} + +#[test] +fn classic_array_by_json() { + let mut s = run(&circle([0.0, 0.0], 1.0), ""); + let first = s.doc().unwrap().model.iter().next().unwrap().handle.hex(); + let r = s.execute("-array", &json!({ "handles": [first], "type": "polar", "center": [10, 0], "count": 4, "rotate": false })).unwrap(); + assert_eq!(r["created"].as_u64(), Some(3), "{r}"); + assert!(same(&points(&s), &[[0.0, 0.0], [10.0, -10.0], [20.0, 0.0], [10.0, 10.0]], 1e-9), "{:?}", points(&s)); + let r = s.execute("-array", &json!({ "handles": [first], "rows": 2, "cols": 3, "rowSpacing": 5, "colSpacing": 7 })).unwrap(); + assert_eq!(r["created"].as_u64(), Some(5), "{r}"); + // An unknown type, or an array past MAXARRAY, is refused before anything is made. + assert!(s.execute("-array", &json!({ "handles": [first], "type": "path" })).is_err()); + assert!(s.execute("-array", &json!({ "handles": [first], "rows": 4294967296u64, "cols": 4294967296u64 })).is_err()); + assert!(s.execute("-array", &json!({ "handles": [first], "type": "polar", "center": [0, 0], "count": u64::MAX })).is_err()); + assert_eq!(s.doc().unwrap().model.iter().count(), 4 + 5); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 9b0907e24..0763ee6eb 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -21,6 +21,7 @@ mod break_keeps_z; mod burst; mod change_command; mod chprop_command; +mod classic_array; mod compare_export; mod constraint_geometry; mod constraint_infer; 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 297/900] 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 5caaf73e3b065856f38e9cb58571e68edfbd2a59 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 31 Oct 2026 18:52:40 -0400 Subject: [PATCH 298/900] packaging(flatpak): add OCI image build and GHCR publishing helper (#2577) --- packaging/linux/flatpak-bundle.sh | 8 ++++ packaging/linux/flatpak-oci.sh | 64 +++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100755 packaging/linux/flatpak-oci.sh diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 5154fe076..5c84b8470 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -20,10 +20,12 @@ APP_ID=ai.storyteller.cadcraft FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 +OCI=0 TARBALL="" while [[ $# -gt 0 ]]; do case "$1" in --no-test) TEST=0; shift ;; + --oci) OCI=1; shift ;; -h | --help) sed -n '2,14p' "$0"; exit 0 ;; -*) echo "unknown argument: $1" >&2; exit 2 ;; *) TARBALL="$1"; shift ;; @@ -61,6 +63,12 @@ OUT="$DIST/$BASENAME.flatpak" # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" +if [[ "$OCI" = 1 ]]; then + OUT_OCI="$DIST/$BASENAME-oci" + rm -rf "$OUT_OCI" + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + echo "wrote OCI layout to $OUT_OCI" +fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" diff --git a/packaging/linux/flatpak-oci.sh b/packaging/linux/flatpak-oci.sh new file mode 100755 index 000000000..d2d2e0f25 --- /dev/null +++ b/packaging/linux/flatpak-oci.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Build cadcraft as an OCI container layout and push it to GitHub Container Registry (GHCR) +# for consumption by Flatpak OCI clients (flatpak-oci-specs). +# +# Usage: +# packaging/linux/flatpak-oci.sh [--push] [TARBALL] +# +# Environment variables: +# REGISTRY Target registry image (default: ghcr.io/storytold/cadcraft) +# TAG Target image tag (default: $VERSION-$ARCH, also tags stable-$ARCH) +# GITHUB_TOKEN Token for GHCR authentication when --push is used +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" + +PUSH=0 +TARBALL="" +while [[ $# -gt 0 ]]; do + case "$1" in + --push) PUSH=1; shift ;; + -h | --help) sed -n '2,12p' "$0"; exit 0 ;; + -*) echo "unknown argument: $1" >&2; exit 2 ;; + *) TARBALL="$1"; shift ;; + esac +done + +ARCH="$(uname -m)" +case "$ARCH" in + x86_64) ;; + aarch64 | arm64) ARCH=aarch64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac + +BASENAME="cadcraft-$VERSION-linux-$ARCH" +OUT_OCI="$DIST/$BASENAME-oci" + +echo "==> Building Flatpak OCI layout for $BASENAME" +"$HERE/flatpak-bundle.sh" --oci --no-test "${TARBALL:-}" + +[[ -d "$OUT_OCI" ]] || { echo "error: $OUT_OCI layout not generated" >&2; exit 1; } + +REGISTRY="${REGISTRY:-ghcr.io/storytold/cadcraft}" +TAG="${TAG:-$VERSION-$ARCH}" + +echo "==> OCI layout ready at $OUT_OCI (Target: $REGISTRY:$TAG)" + +if [[ "$PUSH" = 1 ]]; then + command -v skopeo >/dev/null || { echo "error: skopeo is required to push OCI images (apt install skopeo)" >&2; exit 1; } + + AUTH_ARGS=() + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + AUTH_ARGS=(--dest-creds "${GITHUB_ACTOR:-storytold}:$GITHUB_TOKEN") + fi + + echo "==> Pushing to $REGISTRY:$TAG" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:$TAG" + + # Also update architecture-specific stable tag + echo "==> Pushing to $REGISTRY:stable-$ARCH" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:stable-$ARCH" + + echo "==> Push complete" +fi From 62e70432e7f5f46a6d7f88373d70877c0426c487 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 11:05:33 +1100 Subject: [PATCH 299/900] 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 300/900] 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 301/900] 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 9c84141e3899bd17a5747e578b11bcbf91ad28e1 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Sun, 1 Nov 2026 04:56:59 +0300 Subject: [PATCH 302/900] style: rustfmt the write_atomic map_err in render --- crates/mcp/src/backend.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index d27012418..4ed805979 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -395,8 +395,7 @@ impl Backend for Headless { let png = cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()).ok_or("render failed")?; if let Some(path) = str_p("path") { - cadcraft_engine::atomic_write::write_atomic(std::path::Path::new(&path), &png) - .map_err(|e| format!("{path}: {e}"))?; + cadcraft_engine::atomic_write::write_atomic(std::path::Path::new(&path), &png).map_err(|e| format!("{path}: {e}"))?; } Ok(json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h})) } From d03af7d7a603ba207882501dba7b974dd74699c8 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:08:24 +0300 Subject: [PATCH 303/900] fonts: a substitute's text scales by the cap height the installation pins for it, not the substitute's own --- crates/fonts/src/ttf.rs | 58 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 9c1888aa8..1fcb9f967 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -719,9 +719,36 @@ pub fn descent_ratio(face: &Face) -> Option { (r.is_finite() && r > 0.0 && r < 2.0).then_some(r) } -/// Cap height of a font in font units at 1000 units per em: the OS/2 value, else the height -/// of its "H", else an estimate from the ascent. +/// Cap heights the installation pins for metric-compatible substitutes, from `CADCRAFT_CAP_HEIGHT` +/// (`LiberationSans=715.8;LiberationSans-Bold=715.8`): a substitute keeps the advance widths of +/// the font it stands in for but not its cap height, so scaling by the substitute's own OS/2 +/// value draws text the size of the substitute, not of the requested font. Each entry names a +/// PostScript name and its cap height in font units at 1000 per em. +fn cap_height_overrides() -> &'static HashMap { + static OVERRIDES: OnceLock> = OnceLock::new(); + OVERRIDES.get_or_init(|| parse_cap_height_overrides(&std::env::var("CADCRAFT_CAP_HEIGHT").unwrap_or_default())) +} + +/// Parse a `Name=height;…` list; entries without a name or with a non-positive or non-finite +/// height are dropped. Names are matched normalised, like family names. +fn parse_cap_height_overrides(spec: &str) -> HashMap { + spec.split(';') + .filter_map(|entry| { + let (name, height) = entry.split_once('=')?; + let height: f64 = height.trim().parse().ok()?; + (height.is_finite() && height > 0.0 && !name.trim().is_empty()).then(|| (norm(name.trim()), height)) + }) + .collect() +} + +/// Cap height of a font in font units at 1000 units per em: the value `CADCRAFT_CAP_HEIGHT` +/// pins for this font's PostScript name, else the OS/2 value, else the height of its "H", +/// else an estimate from the ascent. fn cap_height(f: &FontRef) -> f64 { + let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string())); + if let Some(height) = named.as_deref().and_then(|n| cap_height_overrides().get(n)) { + return *height; + } let metrics = f.metrics(Size::new(UPEM), LocationRef::default()); let measured = || { let gid = f.charmap().map('H')?; @@ -935,6 +962,33 @@ mod family_tests { } } +#[cfg(test)] +mod cap_height_override_tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn cap_height_env_parses_name_height_entries() { + let m = parse_cap_height_overrides("LiberationSans=715.8;LiberationSans-Bold=715.8"); + let mut want = HashMap::new(); + want.insert("liberationsans".to_string(), 715.8); + want.insert("liberationsansbold".to_string(), 715.8); + assert_eq!(m, want); + assert_eq!(parse_cap_height_overrides("LiberationSans = 715.8 ; NotoSansCJK=1466"), parse_cap_height_overrides("LiberationSans=715.8;NotoSansCJK=1466").into_iter().collect::>(), "spaces around names and heights are tolerated"); + assert!(parse_cap_height_overrides("noheight;=5;Arial=0;Arial=-1;Arial=abc").is_empty(), "entries without a name or a positive finite height are dropped"); + assert!(parse_cap_height_overrides("").is_empty()); + } + + #[test] + fn cap_height_override_applies_only_to_the_named_font() { + let m = parse_cap_height_overrides("LiberationSans=715.8"); + assert_eq!(m.get(&norm("LiberationSans")), Some(&715.8)); + assert_eq!(m.get(&norm("Liberation Sans")), Some(&715.8), "names match normalised"); + assert_eq!(m.get(&norm("DejaVuSans")), None); + assert_eq!(m.get(&norm("LiberationSans-Bold")), None); + } +} + #[cfg(test)] mod geometry_budget_tests { use super::*; From 44f026833cd7d435fd79ecd50a3e379d94430a34 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Sun, 1 Nov 2026 05:19:01 +0300 Subject: [PATCH 304/900] io: a handle repeated across ENTITIES sections keeps both entities --- crates/io/src/dxf_read.rs | 29 +++++++- crates/io/src/dxf_read/document.rs | 64 +++++++++++++---- crates/io/tests/it/exhausted_handseed.rs | 57 +++++++++++++++ crates/io/tests/it/main.rs | 1 + crates/io/tests/it/split_entities_section.rs | 76 +++++++++++++++++++- 5 files changed, 210 insertions(+), 17 deletions(-) create mode 100644 crates/io/tests/it/exhausted_handseed.rs diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 1489f4def..ffdc19795 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -1,6 +1,6 @@ //! DXF → Drawing. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use cadcraft_color::{Color, Rgb}; use cadcraft_doc::{ @@ -90,6 +90,18 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { let mut blocks: Vec = Vec::new(); let mut layout_objs: Vec = Vec::new(); let mut entities = Vec::new(); + // One set for every list: a generated handle must be unique across blocks and ENTITIES + // (a *MODEL_SPACE block and an ENTITIES record both land in the model space). + let mut seen_handles = HashSet::new(); + // Model/paper-space handles retain priority if an in-memory drawing or damaged DXF also + // assigns one to a block entity. This preserves top-level references while letting block + // handles be repaired before their deferred fixups are recorded. + let reserved_entity_handles: HashSet = secs + .iter() + .filter(|s| s.name == "ENTITIES") + .flat_map(|s| records(&s.tags)) + .filter_map(|(_, tags)| common::T(&tags).s(5).and_then(|h| Handle::parse_hex(&h))) + .collect(); let mut objs = Objects::default(); // Every handle another program's file already uses is taken before anything gets a new one: // its $HANDSEED can be lower than its handles, and entities made while reading (the faces of @@ -108,11 +120,22 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { match s.name.as_str() { "HEADER" => header(&s.tags, &mut d), "TABLES" => tables(&s.tags, &mut d, &mut rx), - "BLOCKS" => blocks.extend(read_blocks(&s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped)), + "BLOCKS" => { + blocks.extend(read_blocks(&s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles)) + } // A damaged file may split its entities over several ENTITIES sections (#865). "ENTITIES" => { let mut n = 0; - entities.extend(parse_entities(&records(&s.tags), &mut d, &mut rx, &mut n, &mut table_cells_left)); + entities.extend(parse_entities( + &records(&s.tags), + &mut d, + &mut rx, + &mut n, + &mut table_cells_left, + &mut seen_handles, + &reserved_entity_handles, + true, + )); count_skipped(&mut skipped, "ENTITIES", n); } "OBJECTS" => read_objects(&s.tags, &mut objs, &mut layout_objs), diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index d732f4450..096148515 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -1,14 +1,51 @@ +use std::collections::HashSet; + use super::common::T; use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity}; use super::objects::{MAX_OBJECTS, Objects, page_setup}; use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, records}; +/// Allocate an entity handle that is unique within the DXF, including against handles assigned +/// to earlier malformed or generated entities. +fn fresh_entity_handle(d: &mut Drawing, seen: &mut HashSet, reserved: &HashSet) -> Handle { + // The seed saturates at `u64::MAX`: once a file uses that handle, `new_handle` keeps + // returning it and a plain retry loop would never terminate. Stop as soon as it stops + // advancing. + let mut previous = None; + loop { + let h = d.new_handle(); + if !reserved.contains(&h) && seen.insert(h) { + return h; + } + if previous == Some(h) { + break; + } + previous = Some(h); + } + // Every value the seed can still reach is taken, so scan from the bottom: the occupied set + // is finite, which guarantees a free handle within its size plus one candidates. + let limit = seen.len().saturating_add(reserved.len()).saturating_add(1); + let mut candidate = 1u64; + for _ in 0..limit { + let h = Handle(candidate); + if !reserved.contains(&h) && seen.insert(h) { + return h; + } + candidate = candidate.saturating_add(1); + } + // Unreachable in practice (pigeonhole over the finite occupied set); never lose the entity. + d.new_handle() +} + pub(super) fn parse_entities( recs: &[(String, Vec)], d: &mut Drawing, rx: &mut Rx, skipped: &mut usize, table_cells_left: &mut usize, + seen_handles: &mut HashSet, + reserved_handles: &HashSet, + source_handles_win: bool, ) -> Vec<(Option, bool, Entity)> { let mut out = Vec::new(); let mut i = 0; @@ -54,13 +91,20 @@ pub(super) fn parse_entities( let h = match handle { Some(h) => { d.bump_handseed(h); - h + // A file's own handle wins when it is the first copy on a source list that + // keeps them (ENTITIES); block copies yield to the reserved top-level ones. + let kept = if source_handles_win { seen_handles.insert(h) } else { !reserved_handles.contains(&h) && seen_handles.insert(h) }; + if kept { h } else { fresh_entity_handle(d, seen_handles, reserved_handles) } } - None => d.new_handle(), + None => fresh_entity_handle(d, seen_handles, reserved_handles), }; entity_extras(kind, tags, h, &mut k, rx); - let more: Vec<_> = - extra.into_iter().map(|f| (owner.clone(), paper, Entity { handle: d.new_handle(), common: c.clone(), kind: f })).collect(); + let more: Vec<_> = extra + .into_iter() + .map(|f| { + (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, seen_handles, reserved_handles), common: c.clone(), kind: f }) + }) + .collect(); out.push((owner, paper, Entity { handle: h, common: c, kind: k })); out.extend(more); } else if kind == "HATCH" { @@ -69,14 +113,6 @@ pub(super) fn parse_entities( *skipped = skipped.saturating_add(1); } } - // Assign fresh handles to duplicates (hostile files). - let mut seen = std::collections::HashSet::new(); - for (_, _, e) in &mut out { - if !seen.insert(e.handle) { - e.handle = d.new_handle(); - seen.insert(e.handle); - } - } out } @@ -87,6 +123,8 @@ pub(super) fn read_blocks( rx: &mut Rx, table_cells_left: &mut usize, skipped: &mut std::collections::BTreeMap, + seen_handles: &mut HashSet, + reserved_handles: &HashSet, ) -> Vec { let recs = records(tags); for (k, tg) in &recs { @@ -111,7 +149,7 @@ pub(super) fn read_blocks( j += 1; } let body = recs.get(i + 1..j).unwrap_or(&[]); - let ents = parse_entities(body, d, rx, &mut n, table_cells_left); + let ents = parse_entities(body, d, rx, &mut n, table_cells_left, seen_handles, reserved_handles, false); blocks.push((name, base, description, ents, xref)); i = j + 1; } else { diff --git a/crates/io/tests/it/exhausted_handseed.rs b/crates/io/tests/it/exhausted_handseed.rs new file mode 100644 index 000000000..448eed024 --- /dev/null +++ b/crates/io/tests/it/exhausted_handseed.rs @@ -0,0 +1,57 @@ +//! A file whose `$HANDSEED` is the top of the handle range must not hang the importer: the seed +//! saturates at `u64::MAX`, so allocating past a taken handle has to stop and fall back to a free +//! one instead of retrying the same handle forever. + +use std::collections::HashSet; + +use cadcraft_doc::Handle; + +/// One line holding the top handle, and one line with no handle at all, so the importer has to +/// allocate one after the seed is exhausted. +fn dxf() -> String { + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\nFFFFFFFFFFFFFFFF\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n1.0\n31\n0.0\n\ + 0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n2.0\n21\n2.0\n31\n0.0\n\ + 0\nENDSEC\n0\nEOF\n" + .to_string() +} + +#[test] +fn an_exhausted_handle_seed_still_finds_a_free_handle() { + let d = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap(); + assert_eq!(d.model.iter().count(), 2); + let handles: Vec = d.model.iter().map(|e| e.handle).collect(); + let unique: HashSet = handles.iter().copied().collect(); + assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}"); + // The file's own top handle stays with its entity. + assert!(handles.contains(&Handle(u64::MAX))); +} + +/// A `*MODEL_SPACE` block entity with no handle, a handleless `ENTITIES` record, and a later +/// `ENTITIES` record declaring handle 1: the two generated handles must differ (both lists land +/// in the model space) and must not take the handle the later record declares. +fn dxf_with_model_space_block() -> String { + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\nFFFFFFFFFFFFFFFF\n0\nENDSEC\n\ + 0\nSECTION\n2\nBLOCKS\n\ + 0\nBLOCK\n5\n20\n8\n0\n2\n*MODEL_SPACE\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n\ + 0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n1.0\n31\n0.0\n\ + 0\nENDBLK\n5\n21\n8\n0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n2.0\n21\n2.0\n31\n0.0\n\ + 0\nLINE\n5\n1\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n3.0\n21\n3.0\n31\n0.0\n\ + 0\nENDSEC\n0\nEOF\n" + .to_string() +} + +#[test] +fn generated_handles_are_unique_across_lists_and_avoid_later_source_handles() { + let d = cadcraft_io::read_dxf(dxf_with_model_space_block().as_bytes()).unwrap(); + let handles: Vec = d.model.iter().map(|e| e.handle).collect(); + assert_eq!(handles.len(), 3, "{handles:?}"); + let unique: HashSet = handles.iter().copied().collect(); + assert_eq!(unique.len(), handles.len(), "duplicate handles: {handles:?}"); + // The record that declares handle 1 keeps it; the generated ones went elsewhere. + assert!(handles.contains(&Handle(1)), "{handles:?}"); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 52f37068a..5755ea9b0 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -26,6 +26,7 @@ mod dwt_template; mod dxf_versions; mod dynblock_read; mod entity_props_roundtrip; +mod exhausted_handseed; mod followups_626; mod groups_roundtrip; mod hatch_assoc_roundtrip; diff --git a/crates/io/tests/it/split_entities_section.rs b/crates/io/tests/it/split_entities_section.rs index 6d89725a3..0ab6f63e9 100644 --- a/crates/io/tests/it/split_entities_section.rs +++ b/crates/io/tests/it/split_entities_section.rs @@ -2,7 +2,7 @@ //! variables and ENDSECs between them, and no EOF). Every section is read, not just the last //! one (#865). -use cadcraft_doc::EntityKind; +use cadcraft_doc::{EntityKind, Handle}; #[test] fn entities_of_every_entities_section_are_read() { @@ -17,3 +17,77 @@ fn entities_of_every_entities_section_are_read() { let texts = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Text(_))).count(); assert_eq!((lines, texts, d.model.len()), (2, 1, 3)); } + +#[test] +fn repeated_handles_across_entities_sections_keep_both_entities() { + // A damaged file can repeat a handle across its sections (within one section duplicates are + // already renumbered). The store replaces an entity with the same handle, so the earlier + // section's line was silently lost — and a save kept only the later one (#939). + let text = "0\nSECTION\n2\nENTITIES\n\ + 0\nLINE\n5\n300\n8\n0\n10\n0\n20\n0\n11\n1\n21\n0\n\ + 0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n300\n8\n0\n10\n0\n20\n1\n11\n1\n21\n1\n0\nENDSEC\n\ + 0\nEOF\n"; + let d = cadcraft_io::read(text.as_bytes(), "t.dxf").unwrap(); + let lines = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(); + assert_eq!(lines, 2, "the second section's line replaced the first"); + 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.entity(Handle::parse_hex("300").unwrap()).is_some(), "the file's own handle stays with one of them"); +} + +#[test] +fn duplicate_mleader_handles_keep_each_deferred_style_fixup() { + let mleader = |style: &str| format!("0\nMULTILEADER\n5\n300\n100\nAcDbEntity\n8\n0\n100\nAcDbMLeader\n340\n{style}\n"); + let text = format!( + "0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nD\n3\nACAD_MLEADERSTYLE\n350\nE\n\ + 0\nDICTIONARY\n5\nE\n3\nFirst\n350\nA\n3\nSecond\n350\nB\n3\nThird\n350\nC\n\ + 0\nMLEADERSTYLE\n5\nA\n0\nMLEADERSTYLE\n5\nB\n0\nMLEADERSTYLE\n5\nC\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n{}0\nENDSEC\n0\nEOF\n", + mleader("A"), + mleader("B"), + mleader("C"), + ); + let d = cadcraft_io::read(text.as_bytes(), "t.dxf").unwrap(); + let mut handles_by_style = std::collections::HashMap::new(); + for e in d.model.iter() { + if let EntityKind::MLeader(m) = &e.kind { + assert!(handles_by_style.insert(m.style.as_str(), e.handle).is_none(), "duplicate style {}", m.style); + } + } + assert_eq!(handles_by_style.len(), 3, "styles were assigned to the wrong records: {handles_by_style:?}"); + assert_eq!(handles_by_style.get("First"), Some(&Handle::parse_hex("300").unwrap())); + assert_ne!(handles_by_style.get("First"), handles_by_style.get("Second")); + assert_ne!(handles_by_style.get("Second"), handles_by_style.get("Third")); +} + +#[test] +fn duplicate_table_handles_keep_each_deferred_style_fixup() { + let table = |style: &str| format!("0\nACAD_TABLE\n5\n400\n100\nAcDbEntity\n8\n0\n100\nAcDbTable\n91\n1\n92\n1\n141\n1\n142\n1\n342\n{style}\n"); + let text = format!( + "0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nD\n3\nACAD_TABLESTYLE\n350\nE\n\ + 0\nDICTIONARY\n5\nE\n3\nFirst\n350\nA\n3\nSecond\n350\nB\n\ + 0\nTABLESTYLE\n5\nA\n100\nAcDbTableStyle\n70\n0\n280\n0\n281\n0\n7\nStandard\n140\n0.45\n\ + 0\nTABLESTYLE\n5\nB\n100\nAcDbTableStyle\n70\n0\n280\n0\n281\n0\n7\nStandard\n140\n0.85\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", + table("A"), + table("B"), + ); + let d = cadcraft_io::read(text.as_bytes(), "t.dxf").unwrap(); + let tables: Vec<_> = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Table(t) => Some((e.handle, t)), + _ => None, + }) + .collect(); + assert_eq!(tables.len(), 2); + assert_eq!((tables[0].1.style.as_str(), tables[0].1.text_height), ("First", 0.45)); + assert_eq!((tables[1].1.style.as_str(), tables[1].1.text_height), ("Second", 0.85)); + assert_ne!(tables[0].0, tables[1].0); +} 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 305/900] 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 d7ef7da872fbd4158a5b2fc493f2da191f461d03 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 31 Oct 2026 23:43:11 -0400 Subject: [PATCH 306/900] ci: grant packages write permission to release workflow --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 368d4f322..dc9c462db 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -62,6 +62,7 @@ jobs: permissions: # The reusable release workflow tags and uploads the draft release. contents: write + packages: write # 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/release.yml@main with: From c22700d3aff6c3f8939e337404abc7ef2f6e5e60 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 15:27:09 +1100 Subject: [PATCH 307/900] 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 308/900] 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 309/900] 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 310/900] 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 311/900] 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 722aeb1080e9ab5e1d57d5b68961003fa78d6011 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:29:13 +0300 Subject: [PATCH 312/900] fonts: cover the cap-height fallback chain and document CADCRAFT_CAP_HEIGHT --- crates/fonts/src/ttf.rs | 41 +++++++++++++++++++++++++++++++++++++++-- docs/cli.md | 7 +++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 1fcb9f967..d0867cf6d 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -974,8 +974,15 @@ mod cap_height_override_tests { want.insert("liberationsans".to_string(), 715.8); want.insert("liberationsansbold".to_string(), 715.8); assert_eq!(m, want); - assert_eq!(parse_cap_height_overrides("LiberationSans = 715.8 ; NotoSansCJK=1466"), parse_cap_height_overrides("LiberationSans=715.8;NotoSansCJK=1466").into_iter().collect::>(), "spaces around names and heights are tolerated"); - assert!(parse_cap_height_overrides("noheight;=5;Arial=0;Arial=-1;Arial=abc").is_empty(), "entries without a name or a positive finite height are dropped"); + assert_eq!( + parse_cap_height_overrides("LiberationSans = 715.8 ; NotoSansCJK=1466"), + parse_cap_height_overrides("LiberationSans=715.8;NotoSansCJK=1466").into_iter().collect::>(), + "spaces around names and heights are tolerated" + ); + assert!( + parse_cap_height_overrides("noheight;=5;Arial=0;Arial=-1;Arial=abc").is_empty(), + "entries without a name or a positive finite height are dropped" + ); assert!(parse_cap_height_overrides("").is_empty()); } @@ -987,6 +994,36 @@ mod cap_height_override_tests { assert_eq!(m.get(&norm("DejaVuSans")), None); assert_eq!(m.get(&norm("LiberationSans-Bold")), None); } + + /// With no override for the face, `cap_height` walks its chain: the OS/2 value when the face + /// has one, else the height of its "H", else an estimate from the ascent. Uses the first of + /// these common fonts that is installed (Windows, macOS and Linux each have one); skips + /// without any. No override is in play: `CADCRAFT_CAP_HEIGHT` names other faces, and the + /// test binary's env is read once — a face this test does not name stays unoverridden. + #[test] + fn cap_height_without_an_override_follows_the_fallback_chain() { + let found = ["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find_map(find); + let Some(face) = found else { return }; + let f = face.font().expect("the face parses"); + let named = f.localized_strings(skrifa::string::StringId::POSTSCRIPT_NAME).next().map(|s| norm(&s.to_string())).unwrap_or_default(); + let m = f.metrics(Size::new(UPEM), LocationRef::default()); + let h_height = || { + let gid = f.charmap().map('H')?; + let b = f.glyph_metrics(Size::new(UPEM), LocationRef::default()).bounds(gid)?; + Some(b.y_max).filter(|y| y.is_finite() && *y > 0.0) + }; + let got = cap_height(&f); + let want = if cap_height_overrides().contains_key(&named) { + return; // this installation pins the face: the override leg is covered by the parser tests + } else if let Some(cap) = m.cap_height.filter(|c| c.is_finite() && *c > 0.0) { + f64::from(cap) + } else if let Some(h) = h_height() { + f64::from(h) + } else { + f64::from(m.ascent) * 0.72 + }; + assert!((got - want.max(1.0)).abs() < 1.0, "cap height {got} tracks the chain's value {want}"); + } } #[cfg(test)] diff --git a/docs/cli.md b/docs/cli.md index ba68a1d09..2199a307b 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -36,6 +36,13 @@ The desktop app's are listed by `cadcraft --help`; its one flag fallback is `CADCRAFT_CONTROL_PORT` for `--control`, where a bad value is a usage error that names the variable. +One variable is not a flag fallback: **`CADCRAFT_CAP_HEIGHT`** pins cap heights for +metric-compatible substitute fonts, so text scaled by a substitute keeps the requested font's +size (`LiberationSans=715.8;LiberationSans-Bold=715.8`; each entry names a font's PostScript +name and its cap height in font units at 1000 units per em; entries without a name or with a +non-positive or non-finite height are dropped). It is a packaging hook for installations whose +substitutes lack the original's OS/2 cap height, and applies to every subcommand. + ## Not followed yet - **`CADCRAFT_CONFIG_DIR` is the one flag fallback where an empty variable doesn't count as From 8dc927e01c8b8c860b09c1fd6d7d82f2b2daf4cc Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 16:57:17 +1100 Subject: [PATCH 313/900] 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 314/900] 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 315/900] 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 cc74fe32edbade833da52b4f8b2221a51b8688de Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:44:41 -0600 Subject: [PATCH 316/900] DWG: the scale action byte doc names acadrust 0.6.6, the version in use Co-Authored-By: Claude Sonnet 5.5 --- crates/dwg/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 65df1833a..a5c46b7df 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -293,7 +293,7 @@ mod native { /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as /// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, - /// acadrust 0.6.5 reads and writes itself. + /// acadrust 0.6.6 reads and writes itself. fn dimension_flags(doc: &mut acadrust::CadDocument) { for e in doc.entities_mut() { let acadrust::entities::EntityType::Dimension(d) = e else { continue }; @@ -915,7 +915,8 @@ mod tests { /// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three /// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD /// read past the object and refused every DWG CADCraft wrote with a dynamic block that scales - /// ("Error Decrypting Data"); 0.6.5 keeps it. The byte reaches the DWG, and a scale action + /// ("Error Decrypting Data"); 0.6.5 added it and 0.6.6, which this uses, still keeps it (0.6.6 also + /// fixes multi-layout DWGs, #1463). The byte reaches the DWG, and a scale action /// from DXF is written whole, with the byte AutoCAD writes (0). #[cfg(not(target_arch = "wasm32"))] #[test] From 09b5fb9328fbf706aa58aec54ba0277facf4aad2 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 18:40:45 +1100 Subject: [PATCH 317/900] 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 318/900] 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 319/900] 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 320/900] 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 321/900] 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 322/900] 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 323/900] 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 324/900] 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 325/900] 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 258c89fbb021fd22cf25ef519e5caf018b692093 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Sun, 1 Nov 2026 18:11:08 +0600 Subject: [PATCH 326/900] Window opens centred; the Chinese menus have no English entries left (#1129) (#2510) * Window opens centred; the Chinese menus have no English entries left (#1129) The main window opened where the system cascades new windows, off to the top-left on wide screens; it now opens centred. 26 menu and command labels the Simplified Chinese update missed (Multileader > Collect, Block Editor, dynamic blocks, Express Tools, Customize, ...) are translated, and a test keeps every menu, command, tool and snap label translated in Chinese. The start page question in the issue is left to the owner. Co-Authored-By: Claude Opus 5.5 * File > Open Recent's Clear Recent Files is translated in Chinese (#1129) The Open Recent submenu is built at run time, so the Chinese completeness test never saw its labels, and Clear Recent Files showed in English. The label is now menus::CLEAR_RECENT, the test collects it with OPEN_RECENT, and zh.tsv translates it. The other runtime-built menu labels (context and tab menus) are all in zh.tsv already. Co-Authored-By: Claude Opus 5.5 * i18n(zh): translate Change and Units, which landed after this branch (#1129) --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- apps/cadcraft/src/main.rs | 52 +++++++++++++++++++++----------- crates/ui-egui/src/i18n/tests.rs | 9 ++++++ crates/ui-egui/src/i18n/zh.tsv | 31 +++++++++++++++++++ crates/ui-egui/src/menus.rs | 4 ++- 4 files changed, 78 insertions(+), 18 deletions(-) diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 4d7bdc39b..c591c10b3 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -194,6 +194,31 @@ fn filters_for_save(name: &str) -> [(&'static str, &'static str); 6] { filters } +/// The main window: its size, title bar, placement and rendering needs. +fn window_options() -> eframe::NativeOptions { + eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("CADCraft") + .with_inner_size([1600.0, 1000.0]) + .with_min_inner_size([900.0, 560.0]) + .with_drag_and_drop(true) + .with_fullsize_content_view(true) + .with_titlebar_shown(false) + .with_title_shown(false) + .with_app_id(APP_ID), + persist_window: false, + // The window opens centred on its screen, not cascaded from the top-left corner (#1129). + // Wayland compositors place windows themselves. + centered: true, + // CADCraft installs its own capped font chain (`theme::install_fonts`); never run + // system-font discovery as a hidden fallback. + system_font_fallback: false, + // A stencil buffer clips the contents of clipped layout viewports on the GPU. + stencil_buffer: STENCIL_BITS, + ..Default::default() + } +} + const APP_ID: &str = "ai.storyteller.cadcraft"; /// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`). @@ -256,22 +281,7 @@ fn main() -> eframe::Result { // The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11 // swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync). wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface), - viewport: egui::ViewportBuilder::default() - .with_title("CADCraft") - .with_inner_size([1600.0, 1000.0]) - .with_min_inner_size([900.0, 560.0]) - .with_drag_and_drop(true) - .with_fullsize_content_view(true) - .with_titlebar_shown(false) - .with_title_shown(false) - .with_app_id(APP_ID), - persist_window: false, - // CADCraft installs its own capped font chain (`theme::install_fonts`); never run - // system-font discovery as a hidden fallback. - system_font_fallback: false, - // A stencil buffer clips the contents of clipped layout viewports on the GPU. - stencil_buffer: STENCIL_BITS, - ..Default::default() + ..window_options() }; if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); @@ -383,7 +393,7 @@ fn main() -> eframe::Result { #[cfg(test)] mod tests { - use super::{filters_for_save, follow_desktop}; + use super::{filters_for_save, follow_desktop, window_options}; #[test] fn save_dialog_offers_dwg_with_the_drawing_format_first() { @@ -401,6 +411,14 @@ mod tests { } } + /// #1129: the window opens centred, not cascaded from the top-left corner. + #[test] + fn the_window_opens_centred() { + let o = window_options(); + assert!(o.centered, "centred on launch"); + assert!(!o.persist_window, "no saved position to restore instead"); + } + /// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in; /// without one (or where winit answers and the desktop doesn't) the input is left alone. #[test] diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index dc4e5322b..034f261e1 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -63,6 +63,8 @@ fn missing_commands_menus_tools_and_snap_labels(language: &str) -> Vec { let catalog = catalog(language).unwrap(); let mut sources = BTreeSet::new(); sources.extend(crate::menus::MENUS.iter().copied()); + // File ▸ Open Recent is built at run time, not from a command's menu path. + sources.extend([crate::menus::OPEN_RECENT, crate::menus::CLEAR_RECENT]); for c in cadcraft_engine::command_specs() { sources.insert(c.label); sources.extend(c.menu.iter().copied()); @@ -560,6 +562,13 @@ fn production_font_chain_covers_latin_and_shortcut_symbols() { }); } +/// #1129: in Chinese every menu, submenu, command, tool palette and object-snap label is +/// translated, so no menu shows English entries. +#[test] +fn chinese_menus_and_commands_are_fully_translated() { + assert_eq!(missing_commands_menus_tools_and_snap_labels("zh"), Vec::::new()); +} + /// Bosnian counts: 1, 21 `one`; 2–4, 22–24 (not 12–14) `few`; everything else `other`. #[test] fn bosnian_counts_take_one_few_other() { diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 4d8da1698..2663105a2 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1349,3 +1349,34 @@ Check for Updates… 检查更新… CADCraft is up to date. CADCraft 已是最新版本。 Could not check for updates. 无法检查更新。 +# Menu and command labels the October 2026 update missed (#1129). + Align Multileaders 对齐多重引线 + Analyze Usage 分析使用情况 + Break-line Symbol 折断线符号 + Change 更改 + Change Properties 修改特性 + Clear Recent Files 清除最近的文件 + Close Block Editor 关闭块编辑器 + Collect 合并 + Collect Multileaders 合并多重引线 + Convert Text to Mtext 将文字转换为多行文字 + Customize 自定义 + Drag Dynamic Grip 拖动动态夹点 + Dynamic Block Data 动态块数据 + Dynamic Block Grips 动态块夹点 + Dynamic Block Reference 动态块参照 + Edit Command Aliases (PGP)... 编辑命令别名 (PGP)... + Edit Multileader 编辑多重引线 + Evaluate LISP 求值 LISP + Explode Attributes to Text 将属性分解为文字 + Express Tools 扩展工具 + Groups 编组 + Hatch Pick 拾取图案填充 + Implied Loops 隐含环 + Justify 对正 + Move/Copy/Rotate 移动/复制/旋转 + Save Block 保存块 + Save Block As 块另存为 + Save Layout as Template 将布局另存为样板 + Set Dynamic Property 设置动态特性 + Units 单位 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index bf0468d08..55d058811 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -10,6 +10,8 @@ pub const MENUS: &[&str] = &["File", "Edit", "View", "Insert", "Format", "Tools" /// File ▸ Open Recent: one `ui.recent.` item per recent file, then Clear Recent Files. pub const OPEN_RECENT: &str = "Open Recent"; +/// The last item of File ▸ Open Recent. +pub const CLEAR_RECENT: &str = "Clear Recent Files"; const RECENT_ITEM: &str = "ui.recent."; const RECENT_CLEAR: &str = "ui.recent.clear"; @@ -634,7 +636,7 @@ pub fn recent_entries(app: &CadApp) -> Vec { .map(|(i, path)| Entry::Item { label: file_name(path), id: format!("{RECENT_ITEM}{i}"), shortcut: None, enabled: true }) .collect(); let enabled = !app.ui.recent_files.is_empty(); - entries.push(Entry::Item { label: "Clear Recent Files".into(), id: RECENT_CLEAR.into(), shortcut: None, enabled }); + entries.push(Entry::Item { label: CLEAR_RECENT.into(), id: RECENT_CLEAR.into(), shortcut: None, enabled }); entries } From 1dcb30426c4d1bf822506e83e3f30017053e46c0 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:18:55 +0300 Subject: [PATCH 327/900] io: group the ENTITIES handle rules into one HandlePolicy parameter clippy -D warnings refused parse_entities' eight parameters; the seen / reserved / source-wins trio travels together anyway. --- crates/io/src/dxf_read.rs | 7 +++---- crates/io/src/dxf_read/document.rs | 31 ++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index ffdc19795..0c3e0d020 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -24,7 +24,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, + HandlePolicy, apply_sortents, count_skipped, outside_sections, parse_entities, place_blocks, place_entities, read_blocks, read_objects, + setup_layouts, }; #[cfg(test)] use entities::acad_table; @@ -132,9 +133,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { &mut rx, &mut n, &mut table_cells_left, - &mut seen_handles, - &reserved_entity_handles, - true, + &mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true }, )); count_skipped(&mut skipped, "ENTITIES", n); } diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 096148515..b02d611f0 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -37,15 +37,21 @@ fn fresh_entity_handle(d: &mut Drawing, seen: &mut HashSet, reserved: &H d.new_handle() } +/// How an ENTITIES list assigns handles: the handles already seen anywhere in the file, the +/// ones the block records reserved, and whether a record's own handle beats the reservation. +pub(super) struct HandlePolicy<'a> { + pub seen: &'a mut HashSet, + pub reserved: &'a HashSet, + pub source_wins: bool, +} + pub(super) fn parse_entities( recs: &[(String, Vec)], d: &mut Drawing, rx: &mut Rx, skipped: &mut usize, table_cells_left: &mut usize, - seen_handles: &mut HashSet, - reserved_handles: &HashSet, - source_handles_win: bool, + hp: &mut HandlePolicy<'_>, ) -> Vec<(Option, bool, Entity)> { let mut out = Vec::new(); let mut i = 0; @@ -93,17 +99,15 @@ pub(super) fn parse_entities( d.bump_handseed(h); // A file's own handle wins when it is the first copy on a source list that // keeps them (ENTITIES); block copies yield to the reserved top-level ones. - let kept = if source_handles_win { seen_handles.insert(h) } else { !reserved_handles.contains(&h) && seen_handles.insert(h) }; - if kept { h } else { fresh_entity_handle(d, seen_handles, reserved_handles) } + let kept = if hp.source_wins { hp.seen.insert(h) } else { !hp.reserved.contains(&h) && hp.seen.insert(h) }; + if kept { h } else { fresh_entity_handle(d, hp.seen, hp.reserved) } } - None => fresh_entity_handle(d, seen_handles, reserved_handles), + None => fresh_entity_handle(d, hp.seen, hp.reserved), }; entity_extras(kind, tags, h, &mut k, rx); let more: Vec<_> = extra .into_iter() - .map(|f| { - (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, seen_handles, reserved_handles), common: c.clone(), kind: f }) - }) + .map(|f| (owner.clone(), paper, Entity { handle: fresh_entity_handle(d, hp.seen, hp.reserved), common: c.clone(), kind: f })) .collect(); out.push((owner, paper, Entity { handle: h, common: c, kind: k })); out.extend(more); @@ -149,7 +153,14 @@ pub(super) fn read_blocks( j += 1; } let body = recs.get(i + 1..j).unwrap_or(&[]); - let ents = parse_entities(body, d, rx, &mut n, table_cells_left, seen_handles, reserved_handles, false); + let ents = parse_entities( + body, + d, + rx, + &mut n, + table_cells_left, + &mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false }, + ); blocks.push((name, base, description, ents, xref)); i = j + 1; } else { From 90806a74769ba0b3002bf69ea9407810afbecf5a Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sun, 1 Nov 2026 06:25:21 -0600 Subject: [PATCH 328/900] 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 329/900] 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 330/900] 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 331/900] 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 332/900] 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 333/900] 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 334/900] 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 335/900] 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 336/900] 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 7400119120a667d662a3f475372403f97d67b75d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 1 Nov 2026 12:30:06 -0500 Subject: [PATCH 337/900] docs: sync Craft App Suite list with ArtCraft Launcher --- README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c45b619dc..a24b33980 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,15 @@ stand on its own. | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | -| | **CADCraft** | **Computer-aided design and drafting · you are here** | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. From 5787b3634f7d663330af1855fc6a806c77de43f9 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 13:06:16 -0500 Subject: [PATCH 338/900] 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 339/900] 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 340/900] 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 4b4ec8043ec6e378e1cbe238a56b7bab793ae5d0 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 1 Nov 2026 13:59:24 -0500 Subject: [PATCH 341/900] Release 0.16.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 32 ++++++++++++++++---------------- Cargo.toml | 2 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c45ba071c..aa4e1961c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -643,7 +643,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -659,14 +659,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.15.1" +version = "0.16.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -676,7 +676,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -687,14 +687,14 @@ dependencies = [ [[package]] name = "cadcraft-dwg" -version = "0.15.1" +version = "0.16.0" dependencies = [ "acadrust", ] [[package]] name = "cadcraft-dxf" -version = "0.15.1" +version = "0.16.0" dependencies = [ "encoding_rs", "log", @@ -703,7 +703,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -724,7 +724,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-geom", "harfrust 0.14.0", @@ -734,14 +734,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.15.1" +version = "0.16.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.15.1" +version = "0.16.0" dependencies = [ "acadrust", "cadcraft-color", @@ -762,7 +762,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -775,7 +775,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -789,7 +789,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -815,7 +815,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.15.1" +version = "0.16.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -5894,7 +5894,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.15.1" +version = "0.16.0" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 8e16721a3..c6b9590fa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.15.1" +version = "0.16.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 8b91646795aa3a3e135cf79c076eefa7b85fbb74 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 14:10:07 -0500 Subject: [PATCH 342/900] 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 520394858c679b992038b83087e61316f4eb0a12 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:37:49 +0700 Subject: [PATCH 343/900] -ATTDEF at the command line: attribute modes, AFLAGS, and the text's prompts (#2597) * -ATTDEF at the command line: attribute modes, AFLAGS, and the text's prompts -ATTDEF asked for the tag first. A script's mode answer ("_V", "_C", "_P") became the tag; the attribute kept no mode; AFLAGS never changed. The definition was made at the start point, so the height and rotation a script gives next ran as commands. It now asks as AutoCAD 2024 does: - "Current attribute modes:" from AFLAGS, then "Enter an option to change [Invisible/Constant/Verify/Preset/Lock position/Annotative/ Multiple lines] ", each answer toggling a mode, kept in AFLAGS. - The tag (spaces taken, upper-cased; an empty one gets "Tag cannot be null"), the prompt and default value, or a constant attribute's value. - "Current text style: ...", the point with Justify and Style, the height and the rotation. The definition takes Invisible, Constant, Verify, Preset and Lock position from the modes; a constant attribute stays in its block. Co-Authored-By: Claude Opus 5.5 * -ATTDEF: a typed height is a distance, as TEXT takes it The height was read with str::parse, so 1'6" (or any distance TEXT takes) was refused as "Requires a positive height." It now goes through the shared distance parser, `number`. Co-Authored-By: Claude Opus 5.5 * -ATTDEF: a wrong answer at Justify is asked again A wrong answer at "Enter an option [Left/Center/...]", or Align or Fit (not available here), went on to the point prompt with the justification unchanged, so a script's next answers landed one prompt off. Only a justification goes on to its point now; anything else is asked again. Co-Authored-By: Claude Opus 5.5 * -ATTDEF test: the modes start from AFLAGS, not from the default The other cases start from AFLAGS 16, which is also the default, so reading the modes from the drawing went untested. This starts from 0. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks.rs | 49 +--- crates/engine/src/cmd/blocks/attdef.rs | 293 +++++++++++++++++++++++ crates/engine/src/cmd/draw.rs | 1 + crates/engine/tests/it/attdef_command.rs | 186 ++++++++++++++ crates/engine/tests/it/main.rs | 1 + 5 files changed, 483 insertions(+), 47 deletions(-) create mode 100644 crates/engine/src/cmd/blocks/attdef.rs create mode 100644 crates/engine/tests/it/attdef_command.rs diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 19543141e..c25b7c913 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -17,6 +17,7 @@ use super::{CommandSpec, bad, bool_or, f64_or, find_command, ok, point_param, po use super::has_doc; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; +mod attdef; mod attedit; mod burst; mod description; @@ -45,7 +46,7 @@ pub fn specs() -> Vec { .menu(&["Draw", "Block", "Define Attributes..."]) .alias(&["att", "-attdef"]) .params("{tag, prompt?, default?, at, height?, invisible?}") - .interactive(|_| Ok(Box::new(AttdefM::default()))), + .interactive(|_| Ok(Box::new(attdef::AttdefM::default()))), attedit::attedit_spec(), attedit::dash_attedit_spec(), CommandSpec::new("wblock", "Write Block", run_wblock).alias(&["w"]).params("{path, name? | handles?, base?}"), @@ -983,52 +984,6 @@ impl Interactive for InsertM { } } -#[derive(Default)] -struct AttdefM { - tag: Option, - prompt: Option, - default: Option, -} - -impl Interactive for AttdefM { - fn name(&self) -> &'static str { - "ATTDEF" - } - fn prompt(&self, _s: &Session) -> Prompt { - 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), - } - } - fn input(&mut self, s: &mut Session, i: Input) -> Result { - let text = match &i { - Input::Text(t) => Some(t.clone()), - Input::Enter => Some(String::new()), - _ => None, - }; - match (&self.tag, &self.prompt, &self.default) { - (None, ..) => { - if let Some(t) = text.filter(|t| !t.trim().is_empty() && !t.contains(' ')) { - self.tag = Some(t.to_ascii_uppercase()); - } - } - (Some(_), None, _) => self.prompt = text, - (Some(_), Some(_), None) => self.default = text, - (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); - s.add_entity(k)?; - return Ok(Step::Done); - } - } - } - Ok(Step::Continue) - } -} - mod attribs; mod battman; mod blockreplace; diff --git a/crates/engine/src/cmd/blocks/attdef.rs b/crates/engine/src/cmd/blocks/attdef.rs new file mode 100644 index 000000000..0803cfe95 --- /dev/null +++ b/crates/engine/src/cmd/blocks/attdef.rs @@ -0,0 +1,293 @@ +//! -ATTDEF at the command line, as AutoCAD 2024 runs it (accoreconsole): the attribute modes +//! (kept in AFLAGS), the tag, prompt and default value (a constant attribute's value instead), +//! then the text's point, justification, style, height and rotation. + +use cadcraft_doc::{AttribModes, HAlign, VAlign}; + +use super::{Accept, Attrib, EntityKind, Input, Interactive, Prompt, Result, Session, Step, Text, Vec2, number, v3}; +use crate::cmd::curves::KW; +use crate::cmd::draw::justify; + +/// AFLAGS bits, as AutoCAD numbers the modes. +const INVISIBLE: i64 = 1; +const CONSTANT: i64 = 2; +const VERIFY: i64 = 4; +const PRESET: i64 = 8; +const LOCK: i64 = 16; +const MULTILINE: i64 = 32; + +const MODES: [&str; 7] = ["Invisible", "Constant", "Verify", "Preset", "Lock position", "Annotative", "Multiple lines"]; +const JUSTIFY: [&str; 15] = ["Left", "Center", "Right", "Align", "Middle", "Fit", "TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"]; + +/// Where -ATTDEF is in its prompts. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Ask { + #[default] + Modes, + Tag, + Prompt, + Value, + Point, + Justify, + Style, + Height, + Rotation, +} + +pub(super) struct AttdefM { + ask: Ask, + flags: i64, + tag: String, + prompt: String, + value: String, + justify: (HAlign, VAlign), + style: String, + at: Vec2, + height: f64, +} + +impl Default for AttdefM { + fn default() -> Self { + AttdefM { + ask: Ask::Modes, + flags: LOCK, + tag: String::new(), + prompt: String::new(), + value: String::new(), + justify: (HAlign::Left, VAlign::Baseline), + style: "Standard".into(), + at: Vec2::ZERO, + height: 0.0, + } + } +} + +impl AttdefM { + fn echo_modes(&self, s: &mut Session) { + let yn = |bit: i64| if self.flags & bit != 0 { "Y" } else { "N" }; + s.echo("Current attribute modes:"); + s.echo(format!( + "Invisible={} Constant={} Verify={} Preset={} Lock position={} Annotative=N Multiple line={}", + yn(INVISIBLE), + yn(CONSTANT), + yn(VERIFY), + yn(PRESET), + yn(LOCK), + yn(MULTILINE) + )); + } + + fn echo_style(&self, s: &mut Session) -> Result<()> { + let th = s.doc()?.header.f64("TEXTSIZE", 0.2); + s.echo(format!("Current text style: \"{}\" Text height: {th:.4} Justify: {}", self.style, justify_name(self.justify))); + Ok(()) + } + + fn point_prompt(&self) -> &'static str { + match self.justify { + (HAlign::Center, VAlign::Baseline) => "Specify center point of text", + (HAlign::Right, VAlign::Baseline) => "Specify right endpoint of text baseline", + (HAlign::Middle, _) | (HAlign::Center, VAlign::Middle) => "Specify middle point of text", + (HAlign::Left, VAlign::Top) => "Specify top-left point of text", + (HAlign::Center, VAlign::Top) => "Specify top-center point of text", + (HAlign::Right, VAlign::Top) => "Specify top-right point of text", + (HAlign::Left, VAlign::Middle) => "Specify middle-left point of text", + (HAlign::Right, VAlign::Middle) => "Specify middle-right point of text", + (HAlign::Left, VAlign::Bottom) => "Specify bottom-left point of text", + (HAlign::Center, VAlign::Bottom) => "Specify bottom-center point of text", + (HAlign::Right, VAlign::Bottom) => "Specify bottom-right point of text", + _ => "Specify start point of text", + } + } + + fn finish(&mut self, s: &mut Session, rotation: f64) -> Result { + let (h, v) = self.justify; + let left = h == HAlign::Left && v == VAlign::Baseline; + s.add_entity(EntityKind::AttDef(Attrib { + tag: self.tag.to_uppercase(), + text: Text { + insert: v3(self.at), + align_pt: if left { None } else { Some(v3(self.at)) }, + height: self.height, + value: std::mem::take(&mut self.value), + rotation, + width_factor: 1.0, + oblique: 0.0, + style: self.style.clone(), + halign: h, + valign: v, + }, + invisible: self.flags & INVISIBLE != 0, + constant: self.flags & CONSTANT != 0, + prompt: std::mem::take(&mut self.prompt), + props: Default::default(), + multiline: None, + modes: AttribModes { verify: self.flags & VERIFY != 0, preset: self.flags & PRESET != 0, lock_position: self.flags & LOCK != 0 }, + }))?; + Ok(Step::Done) + } +} + +/// The justification's name in "Current text style: … Justify: …". +fn justify_name(j: (HAlign, VAlign)) -> &'static str { + JUSTIFY.into_iter().find(|k| justify(k) == Some(j)).unwrap_or("Left") +} + +impl Interactive for AttdefM { + fn name(&self) -> &'static str { + "ATTDEF" + } + fn begin(&mut self, s: &mut Session) -> Result { + let d = s.doc()?; + self.flags = d.header.i64("AFLAGS", LOCK); + self.style = d.header.str("TEXTSTYLE", "Standard"); + self.echo_modes(s); + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + match self.ask { + Ask::Modes => Prompt::new("Enter an option to change", KW).kw(&MODES).default("done"), + Ask::Tag => Prompt::new("Enter attribute tag name", Accept::TEXT), + Ask::Prompt => Prompt::new("Enter attribute prompt", Accept::TEXT), + Ask::Value if self.flags & CONSTANT != 0 => Prompt::new("Enter attribute value", Accept::TEXT), + Ask::Value => Prompt::new("Enter default attribute value", Accept::TEXT), + // Once a justification is chosen AutoCAD asks for its point alone. + Ask::Point if self.justify == (HAlign::Left, VAlign::Baseline) => { + Prompt::new(self.point_prompt(), Accept::POINT).kw(&["Justify", "Style"]) + } + Ask::Point => Prompt::new(self.point_prompt(), Accept::POINT), + Ask::Justify => Prompt::new("Enter an option", Accept::TEXT).kw(&JUSTIFY), + Ask::Style => Prompt::new("Enter style name", Accept::TEXT).kw(&["?"]).default(self.style.clone()), + Ask::Height => { + let th = s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2); + Prompt::new("Specify height", Accept::POINT_OR_NUMBER).default(format!("{th:.4}")).base(self.at) + } + Ask::Rotation => Prompt::new("Specify rotation angle of text", Accept::POINT_OR_NUMBER).default("0").base(self.at), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match self.ask { + Ask::Modes => match &i { + Input::Keyword(k) => { + let bit = match k.as_str() { + "Invisible" => INVISIBLE, + "Constant" => CONSTANT, + "Verify" => VERIFY, + "Preset" => PRESET, + "Lock position" => LOCK, + _ => { + s.echo(format!("{k} attributes are not available yet.")); + return Ok(Step::Continue); + } + }; + self.flags ^= bit; + s.doc_mut()?.header.set_i64("AFLAGS", self.flags); + self.echo_modes(s); + } + Input::Enter => self.ask = Ask::Tag, + Input::Text(_) => s.echo("Invalid option keyword."), + _ => {} + }, + Ask::Tag => match &i { + // AutoCAD takes spaces in a tag here, and upper-cases it. + Input::Text(t) if !t.trim().is_empty() => { + self.tag = t.trim().to_string(); + self.ask = if self.flags & CONSTANT != 0 { Ask::Value } else { Ask::Prompt }; + } + Input::Text(_) | Input::Enter => s.echo("Tag cannot be null"), + _ => {} + }, + Ask::Prompt | Ask::Value => { + let t = match i { + Input::Text(t) => t, + Input::Enter => String::new(), + _ => return Ok(Step::Continue), + }; + if self.ask == Ask::Prompt { + self.prompt = t; + self.ask = Ask::Value; + } else { + self.value = t; + self.echo_style(s)?; + self.ask = Ask::Point; + } + } + Ask::Point => match i { + Input::Point(p) => { + self.at = p; + self.ask = Ask::Height; + } + Input::Keyword(k) if k == "Justify" => self.ask = Ask::Justify, + Input::Keyword(_) => self.ask = Ask::Style, + _ => {} + }, + Ask::Justify => { + // A justification goes on to its point; anything else is asked again. + if let Input::Keyword(k) | Input::Text(k) = &i { + match justify(k) { + // Aligned and fitted text take two points: not here yet. + Some((HAlign::Aligned | HAlign::Fit, _)) => s.echo("Align and Fit are not available here yet."), + Some(j) => { + self.justify = j; + self.ask = Ask::Point; + } + None => s.echo("Invalid option keyword."), + } + } + } + Ask::Style => { + let name = match i { + Input::Enter => self.style.clone(), + Input::Text(t) | Input::Keyword(t) => t.trim().to_string(), + _ => return Ok(Step::Continue), + }; + if name == "?" { + let names: Vec = s.doc()?.text_styles.iter().map(|st| st.name.clone()).collect(); + s.echo(format!("Text styles: {}", names.join(", "))); + return Ok(Step::Continue); + } + match s.doc()?.text_style(&name).map(|st| st.name.clone()) { + Some(n) => { + self.style = n; + self.echo_style(s)?; + self.ask = Ask::Point; + } + None => s.echo(format!("Cannot find text style \"{name}\".")), + } + } + Ask::Height => { + let th = s.doc()?.header.f64("TEXTSIZE", 0.2); + let h = match &i { + Input::Enter => th, + Input::Point(p) => self.at.dist(*p), + // A distance, as TEXT takes its height (1'6" in feet and inches, too). + Input::Text(t) => number(t).unwrap_or(0.0), + _ => return Ok(Step::Continue), + }; + if !(h.is_finite() && h > 0.0) { + s.echo("Requires a positive height."); + return Ok(Step::Continue); + } + self.height = h; + s.doc_mut()?.header.set_f64("TEXTSIZE", h); + self.ask = Ask::Rotation; + } + Ask::Rotation => { + let r = match &i { + Input::Enter => 0.0, + Input::Point(p) => self.at.angle_to(*p), + Input::Text(t) => match s.angle_settings().direction(t) { + Some(a) => a, + None => { + s.echo("Requires an angle."); + return Ok(Step::Continue); + } + }, + _ => return Ok(Step::Continue), + }; + return self.finish(s, r); + } + } + Ok(Step::Continue) + } +} diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index 1b0e0c1cf..cebc44e6f 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -33,6 +33,7 @@ use point::{DonutM, PointM, RayM, run_donut, run_point, run_ray}; use polygon::{PolygonM, run_polygon}; use solid::{SolidM, run_solid}; 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 diff --git a/crates/engine/tests/it/attdef_command.rs b/crates/engine/tests/it/attdef_command.rs new file mode 100644 index 000000000..7bbec7c37 --- /dev/null +++ b/crates/engine/tests/it/attdef_command.rs @@ -0,0 +1,186 @@ +//! -ATTDEF at the command line, as AutoCAD 2024 runs it (accoreconsole: these scripts with +//! TEXTSIZE 2.5 and AFLAGS 16, the drawing and AFLAGS read back afterwards). + +use cadcraft_engine::doc::{Attrib, EntityKind, HAlign, VAlign}; +use cadcraft_engine::{Session, sysvars}; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "TEXTSIZE", "value": 2.5 })).unwrap(); + s.execute("setvar", &json!({ "name": "AFLAGS", "value": 16 })).unwrap(); + s +} + +fn attdefs(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).collect() +} + +fn aflags(s: &Session) -> i64 { + sysvars::get(s, "AFLAGS").and_then(|v| v.as_f64()).unwrap() as i64 +} + +fn run(script: &str) -> Session { + let mut s = session(); + s.cmdline(script).unwrap(); + assert!(s.running.is_none(), "{script}: {}", s.prompt_text()); + s +} + +#[test] +fn modes_are_toggled_kept_in_aflags_and_stored_on_the_definition() { + // (script, AFLAGS after, invisible, constant, verify, preset, lock position, tag, prompt, value) + type Case = (&'static str, i64, [bool; 5], &'static str, &'static str, &'static str); + let cases: [Case; 5] = [ + // ATTDEF-000: the modes as they are. + ( + "(command \"_.-ATTDEF\" \"\" \"T1\" \"Nhap ten\" \"MAC\" '(5.0 10.0) 2.5 0)", + 16, + [false, false, false, false, true], + "T1", + "Nhap ten", + "MAC", + ), + // ATTDEF-001: Invisible and Verify. + ( + "(command \"_.-ATTDEF\" \"_I\" \"_V\" \"\" \"T2\" \"Hoi hai\" \"D2\" '(5.0 10.0) 3.0 30)", + 21, + [true, false, true, false, true], + "T2", + "Hoi hai", + "D2", + ), + // ATTDEF-002: Constant asks for the value, not a prompt and a default. + ("(command \"_.-ATTDEF\" \"_C\" \"\" \"T3\" \"GIATRI\" '(5.0 10.0) 2.5 0)", 18, [false, true, false, false, true], "T3", "", "GIATRI"), + // ATTDEF-003: Preset. + ( + "(command \"_.-ATTDEF\" \"_P\" \"\" \"T4\" \"Hoi bon\" \"D4\" '(612350.678 2398775.432) 2.5 0)", + 24, + [false, false, false, true, true], + "T4", + "Hoi bon", + "D4", + ), + // ATTDEF-004: Lock position off. + ( + "(command \"_.-ATTDEF\" \"_L\" \"\" \"T5\" \"Hoi nam\" \"D5\" '(5.0 10.0) 2.5 0)", + 0, + [false, false, false, false, false], + "T5", + "Hoi nam", + "D5", + ), + ]; + for (script, flags, [inv, con, ver, pre, lock], tag, prompt, value) in cases { + let s = run(script); + assert_eq!(aflags(&s), flags, "{script}"); + let a = attdefs(&s).remove(0); + assert_eq!((a.invisible, a.constant, a.modes.verify, a.modes.preset, a.modes.lock_position), (inv, con, ver, pre, lock), "{script}"); + assert_eq!((a.tag.as_str(), a.prompt.as_str(), a.text.value.as_str()), (tag, prompt, value), "{script}"); + } + // ATTDEF-001's height 3 and 30 degrees. + let a = attdefs(&run(cases[1].0)).remove(0); + assert!((a.text.height - 3.0).abs() < 1e-12 && (a.text.rotation - 30f64.to_radians()).abs() < 1e-12, "{a:?}"); +} + +#[test] +fn tags_justification_and_style_as_autocad_takes_them() { + // ATTDEF-021, ATTDEF-022: a tag is upper-cased, spaces and all. + for (typed, tag) in [("maso", "MASO"), ("ten ban ve", "TEN BAN VE")] { + let s = run(&format!("(command \"_.-ATTDEF\" \"\" \"{typed}\" \"Hoi\" \"D\" '(5.0 10.0) 2.5 0)")); + assert_eq!(attdefs(&s)[0].tag, tag); + } + // ATTDEF-023: an empty prompt stays empty. + let s = run("(command \"_.-ATTDEF\" \"\" \"T10\" \"\" \"D10\" '(612350.678 2398775.432) 2.5 0)"); + assert_eq!(attdefs(&s)[0].prompt, ""); + // ATTDEF-025: an empty tag is refused and asked again. + let s = run("(command \"_.-ATTDEF\" \"\" \"\" \"T11\" \"Hoi muoi mot\" \"D11\" '(5.0 10.0) 2.5 0)"); + assert!(s.log.iter().any(|l| l == "Tag cannot be null"), "{:?}", s.log); + assert_eq!(attdefs(&s)[0].tag, "T11"); + // ATTDEF-005: Justify MC at the middle point. + let s = run("(command \"_.-ATTDEF\" \"\" \"T6\" \"Hoi sau\" \"D6\" \"_J\" \"_MC\" '(5.0 10.0) 2.5 0)"); + let a = attdefs(&s).remove(0); + assert_eq!((a.text.halign, a.text.valign), (HAlign::Center, VAlign::Middle)); + assert!(a.text.align_pt.is_some_and(|p| p.x == 5.0 && p.y == 10.0), "{a:?}"); + // ATTDEF-006: Style, then the point. + let s = run("(command \"_.-ATTDEF\" \"\" \"T7\" \"Hoi bay\" \"D7\" \"_S\" \"Standard\" '(0.505 0.26) 2.5 0)"); + let a = attdefs(&s).remove(0); + assert!(a.text.style == "Standard" && a.text.insert.x == 0.505 && a.text.insert.y == 0.26, "{a:?}"); +} + +#[test] +fn the_prompts_are_autocads() { + let mut s = session(); + s.cmdline("-attdef").unwrap(); + assert!(s.log.iter().any(|l| l == "Current attribute modes:"), "{:?}", s.log); + assert_eq!(s.log.last().map(String::as_str), Some("Invisible=N Constant=N Verify=N Preset=N Lock position=Y Annotative=N Multiple line=N")); + assert!(s.prompt_text().contains("[Invisible/Constant/Verify/Preset/Lock position/Annotative/Multiple lines] :"), "{}", s.prompt_text()); + s.cmdline("X").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Invalid option keyword.")); + s.cmdline("_C").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Invisible=N Constant=Y Verify=N Preset=N Lock position=Y Annotative=N Multiple line=N")); + s.cmdline("").unwrap(); + assert!(s.prompt_text().ends_with("Enter attribute tag name:"), "{}", s.prompt_text()); + s.cmdline("T3").unwrap(); + assert!(s.prompt_text().ends_with("Enter attribute value:"), "{}", s.prompt_text()); + s.cmdline("GIATRI").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Current text style: \"Standard\" Text height: 2.5000 Justify: Left")); + assert!(s.prompt_text().ends_with("Specify start point of text or [Justify/Style]:"), "{}", s.prompt_text()); + s.cmdline("_J").unwrap(); + // A wrong answer, or a justification not available here, is asked again. + for typed in ["X", "_A"] { + s.cmdline(typed).unwrap(); + assert!(s.prompt_text().contains("[Left/Center/Right/Align/Middle/Fit/TL/"), "{typed}: {}", s.prompt_text()); + } + s.cmdline("_MC").unwrap(); + assert!(s.prompt_text().ends_with("Specify middle point of text:"), "{}", s.prompt_text()); + s.cmdline("0,0").unwrap(); + assert!(s.prompt_text().ends_with("Specify height <2.5000>:"), "{}", s.prompt_text()); + s.cmdline("").unwrap(); + assert!(s.prompt_text().ends_with("Specify rotation angle of text <0>:"), "{}", s.prompt_text()); + s.cancel(); +} + +#[test] +fn a_constant_attribute_stays_in_the_block() { + // INSERTATT-011: the constant TC is no attribute of the reference; the other one, TN, is. + let mut s = session(); + s.execute("line", &json!({ "points": [[612345.678, 2398765.432], [612355.678, 2398765.432]] })).unwrap(); + s.cmdline("(setq hl_A (entlast))").unwrap(); + s.cmdline("(progn (command \"_.-ATTDEF\" \"_C\" \"\" \"TC\" \"HANG\" '(612350.678 2398775.432) 2.5 0) (setq hl_a1 (entlast)))").unwrap(); + s.cmdline("(setvar \"AFLAGS\" 16)").unwrap(); + s.cmdline("(progn (command \"_.-ATTDEF\" \"\" \"TN\" \"Hoi N\" \"MN\" '(612350.678 2398785.432) 2.5 0) (setq hl_a2 (entlast)))").unwrap(); + s.cmdline("(command \"_.-BLOCK\" \"B11\" '(612345.678 2398765.432) hl_a1 hl_a2 hl_A \"\")").unwrap(); + s.cmdline("(command \"_.-INSERT\" \"B11\" '(612445.678 2398815.432) 1 1 0 \"XN\")").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + let ins = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.clone()) } else { None }).unwrap(); + let tags: Vec<(String, String)> = ins.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect(); + assert_eq!(tags, [("TN".to_string(), "XN".to_string())]); +} + +#[test] +fn a_typed_height_is_a_distance() { + let mut s = session(); + for typed in ["-attdef", "", "T1", "P", "V", "5,10", "x"] { + s.cmdline(typed).unwrap(); + } + assert_eq!(s.log.last().map(String::as_str), Some("Requires a positive height.")); + // Feet and inches, as TEXT takes them. + for typed in ["1'6\"", "0"] { + s.cmdline(typed).unwrap(); + } + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(attdefs(&s)[0].text.height, 18.0); +} + +#[test] +fn the_modes_start_from_aflags() { + // AFLAGS 0, not the default 16: Invisible toggled on gives 1, and nothing else. + let mut s = session(); + s.execute("setvar", &json!({ "name": "AFLAGS", "value": 0 })).unwrap(); + s.cmdline("(command \"_.-ATTDEF\" \"_I\" \"\" \"T1\" \"Hoi\" \"D\" '(5.0 10.0) 2.5 0)").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(aflags(&s), 1); + let a = attdefs(&s).remove(0); + assert_eq!((a.invisible, a.modes.lock_position), (true, false)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 0763ee6eb..88cbefe31 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -5,6 +5,7 @@ mod annotative; mod arc_ctrl_direction; mod array_commands; mod assoc_array; +mod attdef_command; mod attdisp_attsync; mod attedit_prompts; mod attrib_modes; From 210cfc2a1d20317c6f35c587d93afd0fbe68f9aa Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:37:52 +0700 Subject: [PATCH 344/900] -WBLOCK at the command line, as AutoCAD runs it (#2594) * -WBLOCK at the command line, as AutoCAD runs it WBLOCK had only its JSON form, so a script's -WBLOCK did nothing: the objects it should write and erase stayed in the drawing. This adds the command-line command, with AutoCAD 2024's prompts: - "Current settings: Object conversion=Delete", then the output file. A name without .dwg or .dxf gets .dwg. A DXF file asks for its decimal places first. A file that exists asks "... already exists, do you want to replace it? [Yes/No] "; No ends the command. - An existing block by name, "=" (the block named as the file), "*" (the whole drawing), or Enter for objects. A name that isn't a block is answered Block "NAME" not found. and asked again. - For objects: the base point (with mOde), then the objects, which are written and erased. AutoCAD erases them whatever mOde says, and keeps Delete as the setting. Nothing selected writes nothing. Its JSON form, -wblock, erases what it writes. WBLOCK's JSON form moves into the new module unchanged, sharing the writer. The web build refuses -WBLOCK rather than erase objects it can't save. Co-Authored-By: Claude Opus 5.5 * -WBLOCK's JSON form: nothing to write writes no file With no handles, an empty selection or only handles of objects that aren't there, the JSON form wrote an empty drawing. It now refuses with "no objects selected" before writing or erasing anything, as the command line writes nothing when nothing is selected. Co-Authored-By: Claude Opus 5.5 * -WBLOCK: only Yes replaces an existing file At "... already exists, do you want to replace it? [Yes/No] ", any text starting with "y" counted as Yes, so "yodel" replaced the file, and any other text ended the command. Now only the Yes keyword replaces it, No and Enter end the command, and anything else gets "Invalid option keyword." and the prompt again. Co-Authored-By: Claude Opus 5.5 * WBLOCK and -WBLOCK write their file through a temporary file Replacing an existing file truncated it first, so a write that failed part way lost it. The file now goes through atomic_write::write_atomic, as SAVE, EXPORT and autosave write theirs. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks.rs | 61 +--- crates/engine/src/cmd/blocks/insert_file.rs | 2 +- crates/engine/src/cmd/blocks/wblock.rs | 323 ++++++++++++++++++++ crates/engine/tests/dash_wblock.rs | 244 +++++++++++++++ 4 files changed, 572 insertions(+), 58 deletions(-) create mode 100644 crates/engine/src/cmd/blocks/wblock.rs create mode 100644 crates/engine/tests/dash_wblock.rs diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index c25b7c913..81732a3f8 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -7,7 +7,7 @@ pub(in crate::cmd) mod purge; use std::sync::Arc; use cadcraft_doc::{Attrib, Block, Entity, EntityKind, HAlign, Handle, Insert, Text, VAlign}; -use cadcraft_geom::{Mat3, Vec2, Vec3}; +use cadcraft_geom::{Vec2, Vec3}; use serde_json::{Value, json}; use super::helpers::v3; @@ -24,6 +24,7 @@ mod description; mod dyngrip; mod extract; pub(crate) mod refedit; +mod wblock; pub fn specs() -> Vec { vec![ @@ -49,7 +50,8 @@ pub fn specs() -> Vec { .interactive(|_| Ok(Box::new(attdef::AttdefM::default()))), attedit::attedit_spec(), attedit::dash_attedit_spec(), - CommandSpec::new("wblock", "Write Block", run_wblock).alias(&["w"]).params("{path, name? | handles?, base?}"), + wblock::wblock_spec(), + wblock::dash_wblock_spec(), CommandSpec::new("base", "Base", run_base).menu(&["Draw", "Block", "Base"]).params("{at: [x,y]}"), CommandSpec::new("blocks.dynamic", "Dynamic Block Data", run_dynamic) .params("{name (a block, or \"*Model_Space\" for a drawing that is a dynamic block's own)} → {parameters, actions, other} | null (not a dynamic block)") @@ -362,61 +364,6 @@ fn run_attdef(s: &mut Session, p: &Value) -> Result { Ok(json!({ "handle": s.add_entity(k)?.hex() })) } -fn run_wblock(s: &mut Session, p: &Value) -> Result { - let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string(); - let src = s.doc()?; - let mut d = cadcraft_doc::Drawing::new_imperial(); - // The written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its - // units ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches - // and scaled on insert, and its defaults (text size, current styles, annotation scales). - d.header = src.header.clone(); - d.layers = src.layers.clone(); - d.linetypes = src.linetypes.clone(); - d.text_styles = src.text_styles.clone(); - d.dim_styles = src.dim_styles.clone(); - d.mleader_styles = src.mleader_styles.clone(); - d.table_styles = src.table_styles.clone(); - d.mline_styles = src.mline_styles.clone(); - d.scales = src.scales.clone(); - d.blocks = src.blocks.clone(); - // The base point becomes the written drawing's origin, its insertion base: by default 0,0 for - // objects and the block's base point for a block (`base` is then in block coordinates). - let base = point_param(p, "base"); - d.header.set("INSBASE", cadcraft_doc::HVal::Point(Vec3::ZERO)); - let m = Mat3::translate(-base.unwrap_or(Vec2::ZERO)); - let ents: Vec = if let Some(name) = str_param(p, "name") { - let b = src.block(name).ok_or_else(|| bad("wblock", format!("no block `{name}`")))?; - let m = Mat3::translate(-base.unwrap_or(b.base.xy())); - b.entities - .iter() - .map(|e| { - let mut e = (**e).clone(); - e.kind.transform(&m); - e - }) - .collect() - } else { - targets(s, p)? - .iter() - .filter_map(|h| src.entity(*h)) - .map(|e| { - let mut e = (**e).clone(); - e.kind.transform(&m); - e - }) - .collect() - }; - for mut e in ents { - e.handle = d.new_handle(); - d.model.push(e); - } - let hooks = super::file::io().ok_or_else(|| bad("wblock", "file formats are not available in this build"))?; - let bytes = (hooks.write)(&d, &path).map_err(|e| bad("wblock", e))?; - #[cfg(not(target_arch = "wasm32"))] - std::fs::write(&path, &bytes).map_err(|e| bad("wblock", format!("{path}: {e}")))?; - Ok(json!({ "path": path, "entities": d.model.len(), "bytes": bytes.len() })) -} - fn run_base(s: &mut Session, p: &Value) -> Result { let at = point_req("base", p, "at")?; s.doc_mut()?.header.set("INSBASE", cadcraft_doc::HVal::Point(v3(at))); diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 4d0af93b3..1a90502b5 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -59,7 +59,7 @@ pub(super) fn file_ref(s: &Session, t: &str) -> Option { } /// The file name without folders and extension (either separator, so Windows paths work anywhere). -fn stem(path: &str) -> String { +pub(super) fn stem(path: &str) -> String { let file = path.rsplit(['/', '\\']).next().unwrap_or(path); match file.rsplit_once('.') { Some((stem, _)) if !stem.is_empty() => stem.to_string(), diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs new file mode 100644 index 000000000..03356269e --- /dev/null +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -0,0 +1,323 @@ +//! WBLOCK (its JSON form) and -WBLOCK at the command line: objects, a block or the whole drawing +//! written to a drawing file. + +use cadcraft_doc::{Drawing, Entity, Handle}; +use cadcraft_geom::{Mat3, Vec2, Vec3}; +use serde_json::{Value, json}; + +use super::super::curves::KW; +use super::super::machines::{SelOutcome, SelectPhase}; +use super::super::{CommandSpec, bad, point_param, str_param, targets}; +use super::insert_file::stem; +use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn wblock_spec() -> CommandSpec { + CommandSpec::new("wblock", "Write Block", run_wblock).alias(&["w"]).params("{path, name? | handles?, base?}") +} + +/// -WBLOCK erases the objects it writes, whatever its mOde option says: AutoCAD 2024 does, and +/// keeps "Object conversion=Delete" as the setting. +pub(super) fn dash_wblock_spec() -> CommandSpec { + CommandSpec::new("-wblock", "Write Block", run_dash_wblock) + .params("{path, name? | handles?, base?} (the objects written are erased)") + .interactive(|_| Ok(Box::new(DashWblockM::default()))) +} + +/// The web build has no file system: -WBLOCK would erase objects it can't save. +const NO_FILES: &str = "files can't be written in the web build"; + +/// What WBLOCK writes. +enum Source<'a> { + /// These objects, `base` becoming the written drawing's origin. + Objects(&'a [Handle], Vec2), + /// A block's objects, from its base point or `base` (in block coordinates). + Block(&'a str, Option), + /// The whole drawing. + Whole, +} + +fn run_wblock(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string(); + let base = point_param(p, "base"); + let (entities, bytes) = match str_param(p, "name") { + Some(name) => write(s, "wblock", &path, Source::Block(name, base))?, + None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?, + }; + Ok(json!({ "path": path, "entities": entities, "bytes": bytes })) +} + +fn run_dash_wblock(s: &mut Session, p: &Value) -> Result { + if cfg!(target_arch = "wasm32") { + return Err(bad("-wblock", NO_FILES)); + } + let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string(); + let base = point_param(p, "base"); + let (entities, bytes) = match str_param(p, "name") { + Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?, + None => { + let hs = targets(s, p)?; + // As at the command line, nothing selected writes no file. + if !hs.iter().any(|h| s.doc().is_ok_and(|d| d.entity(*h).is_some())) { + return Err(bad("-wblock", "no objects selected")); + } + let written = write(s, "-wblock", &path, Source::Objects(&hs, base.unwrap_or(Vec2::ZERO)))?; + erase(s, &hs)?; + written + } + }; + Ok(json!({ "path": path, "entities": entities, "bytes": bytes })) +} + +/// Write `what` to `path` through the io hooks; the objects written and the file's size. The +/// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units +/// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and +/// scaled on insert, and its defaults (text size, current styles, annotation scales). +fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize)> { + let src = s.doc()?; + // The base point becomes the written drawing's origin: by default 0,0 for objects and the + // block's base point for a block. + let d = match what { + Source::Whole => src.clone(), + Source::Block(name, base) => { + let b = src.block(name).ok_or_else(|| bad(cmd, format!("no block `{name}`")))?; + let m = Mat3::translate(-base.unwrap_or(b.base.xy())); + with_objects(src, b.entities.iter().map(|e| moved(e, &m))) + } + Source::Objects(hs, base) => { + let m = Mat3::translate(-base); + with_objects(src, hs.iter().filter_map(|h| src.entity(*h)).map(|e| moved(e, &m))) + } + }; + let hooks = super::super::file::io().ok_or_else(|| bad(cmd, "file formats are not available in this build"))?; + 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::atomic_write::write_atomic(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + Ok((d.model.len(), bytes.len())) +} + +/// A new drawing of `ents`, with `src`'s settings, styles and blocks; its insertion base 0,0. +fn with_objects(src: &Drawing, ents: impl Iterator) -> Drawing { + let mut d = Drawing::new_imperial(); + d.header = src.header.clone(); + d.layers = src.layers.clone(); + d.linetypes = src.linetypes.clone(); + d.text_styles = src.text_styles.clone(); + d.dim_styles = src.dim_styles.clone(); + d.mleader_styles = src.mleader_styles.clone(); + d.table_styles = src.table_styles.clone(); + d.mline_styles = src.mline_styles.clone(); + d.scales = src.scales.clone(); + d.blocks = src.blocks.clone(); + d.header.set("INSBASE", cadcraft_doc::HVal::Point(Vec3::ZERO)); + for mut e in ents { + e.handle = d.new_handle(); + d.model.push(e); + } + d +} + +fn moved(e: &Entity, m: &Mat3) -> Entity { + let mut e = e.clone(); + e.kind.transform(m); + e +} + +fn erase(s: &mut Session, hs: &[Handle]) -> Result<()> { + let doc = s.doc_mut()?; + for h in hs { + doc.remove_entity(*h); + } + s.set_selection(Vec::new()); + Ok(()) +} + +/// The file -WBLOCK writes for a typed name: as named when it ends in .dwg or .dxf, else with +/// .dwg added, as AutoCAD names a drawing. +fn output_path(typed: &str) -> String { + let t = typed.trim().trim_matches('"'); + let lower = t.to_ascii_lowercase(); + if lower.ends_with(".dwg") || lower.ends_with(".dxf") { t.to_string() } else { format!("{t}.dwg") } +} + +/// Whether a file is there to replace; the web has no file system. +fn exists(path: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + std::path::Path::new(path).exists() + } + #[cfg(target_arch = "wasm32")] + { + let _ = path; + false + } +} + +/// Where -WBLOCK is in its prompts, as AutoCAD 2024 asks them. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Ask { + #[default] + File, + /// The file exists: "… already exists, do you want to replace it? [Yes/No] ". + Replace, + /// A DXF file's decimal places of accuracy. + Precision, + /// An existing block, `=` (the block named as the file), `*` (the whole drawing), or Enter + /// for objects. + Block, + Base, + /// mOde at the base point prompt: asked, but the objects are erased whatever it says. + Mode, + Objects, +} + +const SAME_NAME: &str = "= (block=output file)"; +const WHOLE: &str = "* (whole drawing)"; + +#[derive(Default)] +struct DashWblockM { + ask: Ask, + path: String, + base: Vec2, + sel: SelectPhase, +} + +impl Interactive for DashWblockM { + fn name(&self) -> &'static str { + "WBLOCK" + } + fn begin(&mut self, s: &mut Session) -> Result { + if cfg!(target_arch = "wasm32") { + s.echo(format!("-WBLOCK: {NO_FILES}.")); + return Ok(Step::Cancel); + } + s.echo("Current settings: Object conversion=Delete"); + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.ask { + Ask::File => Prompt::new("Enter name of output file", Accept::TEXT), + Ask::Replace => Prompt::new(format!("{} already exists, do you want to replace it?", self.path), KW).kw(&["Yes", "No"]).default("N"), + Ask::Precision => Prompt::new("Enter decimal places of accuracy (0 to 16)", Accept::NUMBER).kw(&["Binary", "Preview"]).default("16"), + Ask::Block => Prompt::new("Enter name of existing block", Accept::TEXT).kw(&[SAME_NAME, WHOLE]).default("define new drawing"), + Ask::Base => Prompt::new("Specify insertion base point", Accept::POINT).kw(&["mOde"]), + Ask::Mode => { + Prompt::new("Choose mode for selected object conversion", KW).kw(&["Convert to block", "Retain", "Delete"]).default("Delete") + } + Ask::Objects => self.sel.prompt(), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match self.ask { + Ask::File => { + if let Input::Text(t) = &i + && !t.trim().trim_matches('"').is_empty() + { + self.path = output_path(t); + self.ask = if exists(&self.path) { Ask::Replace } else { self.after_file(s) }; + } + Ok(Step::Continue) + } + Ask::Replace => match &i { + // Yes goes on; No, the default, ends the command; anything else is asked again. + Input::Keyword(k) if k == "Yes" => { + self.ask = self.after_file(s); + Ok(Step::Continue) + } + Input::Keyword(_) | Input::Enter => Ok(Step::Done), + _ => { + s.echo("Invalid option keyword."); + Ok(Step::Continue) + } + }, + Ask::Precision => { + match &i { + Input::Enter => self.ask = Ask::Block, + // The file is written at full precision whatever is asked. + Input::Text(t) if t.trim().parse::().is_ok_and(|n| n <= 16) => self.ask = Ask::Block, + Input::Keyword(k) if k == "Binary" => s.echo("Binary DXF output is not available."), + Input::Keyword(_) => {} + _ => s.echo("Requires an integer between 0 and 16."), + } + Ok(Step::Continue) + } + Ask::Block => { + let name = match &i { + Input::Enter => { + self.ask = Ask::Base; + return Ok(Step::Continue); + } + Input::Keyword(k) if k == WHOLE => return self.write(s, Source::Whole), + Input::Keyword(k) if k == SAME_NAME => stem(&self.path), + Input::Text(t) => t.trim().to_string(), + // A point (from a LISP list) is a name too: AutoCAD answers Block "0,0" not found. + Input::Point(p) => format!("{},{}", p.x, p.y), + _ => return Ok(Step::Continue), + }; + if s.doc()?.block(&name).is_none() { + s.echo(format!("Block \"{name}\" not found.")); + return Ok(Step::Continue); + } + self.write(s, Source::Block(&name, None)) + } + Ask::Base => { + match i { + Input::Keyword(_) => self.ask = Ask::Mode, + Input::Enter | Input::Text(_) => s.echo("Point or option keyword required."), + Input::Point(p) => { + self.base = p; + self.sel = SelectPhase::begin(s); + if self.sel.done { + let picked = self.sel.picked.clone(); + return self.write_objects(s, &picked); + } + self.ask = Ask::Objects; + } + _ => {} + } + Ok(Step::Continue) + } + Ask::Mode => { + // Any answer, Enter included, goes back to the base point. + self.ask = Ask::Base; + Ok(Step::Continue) + } + Ask::Objects => match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + // Nothing selected: nothing is written. + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.write_objects(s, &hs), + }, + } + } +} + +impl DashWblockM { + /// The prompt after the file name: a DXF file's precision, else the block. + fn after_file(&self, s: &mut Session) -> Ask { + if self.path.to_ascii_lowercase().ends_with(".dxf") { + s.echo("Current DXF settings: Precision= 16 Format= ASCII Preview= No"); + Ask::Precision + } else { + Ask::Block + } + } + + fn write(&self, s: &mut Session, what: Source) -> Result { + if let Err(e) = write(s, "-wblock", &self.path, what) { + s.echo(e.to_string()); + } + Ok(Step::Done) + } + + fn write_objects(&self, s: &mut Session, hs: &[Handle]) -> Result { + if hs.is_empty() { + return Ok(Step::Done); + } + match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) { + Ok(_) => erase(s, hs)?, + Err(e) => s.echo(e.to_string()), + } + Ok(Step::Done) + } +} diff --git a/crates/engine/tests/dash_wblock.rs b/crates/engine/tests/dash_wblock.rs new file mode 100644 index 000000000..348cde45a --- /dev/null +++ b/crates/engine/tests/dash_wblock.rs @@ -0,0 +1,244 @@ +//! -WBLOCK at the command line, as AutoCAD 2024 runs it (accoreconsole: these scripts, the +//! drawing read back afterwards). It writes objects from a base point and erases them, whatever +//! its mOde option says; a block by name, `=` (the block named as the file) or `*` (the whole +//! drawing); asks before replacing a file; and writes nothing when nothing is selected. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::{Drawing, EntityKind, Handle}; +use serde_json::json; + +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +/// One line per object written: a line's start (where the base point puts it), else its type. +fn write(d: &Drawing, _path: &str) -> Result, String> { + let mut out = String::new(); + for e in d.model.iter() { + match &e.kind { + EntityKind::Line(l) => out.push_str(&format!("LINE {},{}\n", l.a.x, l.a.y)), + k => out.push_str(&format!("{}\n", k.dxf_name())), + } + } + Ok(out.into_bytes()) +} + +/// A session writing through [`write`], with the drawing the measured scripts start from: line A +/// (0,0)-(10,0), circle B at (5,5) radius 3, line C (0,20)-(10,20). +fn drawing() -> (Session, Handle, Handle, Handle) { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write, plot: None }); + let mut s = Session::new(); + let handle = |v: serde_json::Value| Handle::parse_hex(v["handles"][0].as_str().or(v["handle"].as_str()).unwrap()).unwrap(); + let a = handle(s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap()); + let b = handle(s.execute("circle", &json!({ "center": [5, 5], "radius": 3 })).unwrap()); + let c = handle(s.execute("line", &json!({ "points": [[0, 20], [10, 20]] })).unwrap()); + (s, a, b, c) +} + +/// A file in a test's own folder, with forward slashes for a LISP string. +fn file(dir: &TempDir, name: &str) -> String { + dir.path_str(name).replace('\\', "/") +} + +fn lisp(s: &mut Session, expr: &str) { + s.cmdline(expr).unwrap(); +} + +fn ent(h: Handle) -> String { + format!("(handent \"{}\")", h.hex()) +} + +fn alive(s: &Session, h: Handle) -> bool { + s.doc().unwrap().entity(h).is_some() +} + +fn read(path: &str) -> Vec { + std::fs::read_to_string(path).unwrap().lines().map(str::to_string).collect() +} + +#[test] +fn objects_are_written_from_the_base_point_and_erased() { + // WBLOCK-000: A and B from (5,5); AutoCAD erases both and keeps C. + let (mut s, a, b, c) = drawing(); + let dir = TempDir::new("dash-wblock"); + let path = file(&dir, "WB00.dwg"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{path}\" \"\" '(5.0 5.0) {} {} \"\")", ent(a), ent(b))); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(read(&path), ["LINE -5,-5", "CIRCLE"]); + assert!(!alive(&s, a) && !alive(&s, b) && alive(&s, c)); + assert!(s.log.iter().any(|l| l == "Current settings: Object conversion=Delete"), "{:?}", s.log); +} + +#[test] +fn the_prompts_are_autocads() { + let (mut s, a, _, _) = drawing(); + let dir = TempDir::new("dash-wblock"); + s.cmdline("-wblock").unwrap(); + assert!(s.prompt_text().ends_with("Enter name of output file:"), "{}", s.prompt_text()); + s.cmdline(&file(&dir, "P.dwg")).unwrap(); + assert!( + s.prompt_text().ends_with("Enter name of existing block or [= (block=output file)/* (whole drawing)] :"), + "{}", + s.prompt_text() + ); + s.cmdline("").unwrap(); + assert!(s.prompt_text().ends_with("Specify insertion base point or [mOde]:"), "{}", s.prompt_text()); + // WBLOCK-008: anything but a point or mOde there. + s.cmdline("").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Point or option keyword required.")); + s.cmdline("_O").unwrap(); + assert!(s.prompt_text().ends_with("[Convert to block/Retain/Delete] :"), "{}", s.prompt_text()); + s.cmdline("_R").unwrap(); + assert!(s.prompt_text().ends_with("Specify insertion base point or [mOde]:"), "{}", s.prompt_text()); + s.cmdline("0,0").unwrap(); + assert!(s.prompt_text().ends_with("Select objects:"), "{}", s.prompt_text()); + lisp(&mut s, &ent(a)); + s.cmdline("").unwrap(); + assert!(s.running.is_none()); +} + +#[test] +fn mode_is_asked_but_the_objects_are_erased_whatever_it_says() { + // WBM-01, WBM-02: Retain and Convert to block are taken, yet A is erased (no block reference + // takes its place), and the next -WBLOCK still says "Object conversion=Delete". + for mode in ["_R", "_C"] { + let (mut s, a, b, c) = drawing(); + let dir = TempDir::new("dash-wblock"); + let first = file(&dir, "M01a.dwg"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{first}\" \"\" \"_O\" \"{mode}\" '(0.0 0.0) {} \"\")", ent(a))); + assert!(s.running.is_none(), "{mode}: {}", s.prompt_text()); + assert_eq!(read(&first), ["LINE 0,0"]); + assert!(!alive(&s, a) && alive(&s, b) && alive(&s, c), "{mode}"); + assert_eq!(s.doc().unwrap().model.len(), 2, "{mode}: nothing takes A's place"); + let before = s.log.len(); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{}\" \"\" '(0.0 0.0) {} \"\")", file(&dir, "M01b.dwg"), ent(b))); + assert!(s.log[before..].iter().any(|l| l == "Current settings: Object conversion=Delete"), "{mode}: {:?}", s.log); + assert!(!alive(&s, b) && alive(&s, c), "{mode}"); + } +} + +#[test] +fn nothing_selected_writes_nothing() { + // WBM-05: the command ends; no file, nothing erased. + let (mut s, a, b, c) = drawing(); + let dir = TempDir::new("dash-wblock"); + let path = file(&dir, "M05.dwg"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{path}\" \"\" '(0.0 0.0) \"\")")); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert!(!std::path::Path::new(&path).exists()); + assert!(alive(&s, a) && alive(&s, b) && alive(&s, c)); +} + +#[test] +fn an_existing_file_is_replaced_only_on_yes() { + // WBM-06: No (the default) ends the command; WBM-07: Yes goes on to the block prompt. + let (mut s, a, b, _) = drawing(); + let dir = TempDir::new("dash-wblock"); + let path = file(&dir, "M06.dwg"); + std::fs::write(&path, "old").unwrap(); + s.cmdline("-wblock").unwrap(); + s.cmdline(&path).unwrap(); + assert!(s.prompt_text().ends_with(&format!("{path} already exists, do you want to replace it? [Yes/No] :")), "{}", s.prompt_text()); + // Only Yes replaces it: other text is asked again. + s.cmdline("yodel").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Invalid option keyword.")); + assert!(s.prompt_text().ends_with("[Yes/No] :"), "{}", s.prompt_text()); + s.cmdline("_N").unwrap(); + assert!(s.running.is_none()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "old"); + // Enter is No too. + s.cmdline("-wblock").unwrap(); + s.cmdline(&path).unwrap(); + s.cmdline("").unwrap(); + assert!(s.running.is_none()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "old"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{path}\" \"_Y\" \"\" '(0.0 0.0) {} \"\")", ent(b))); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(read(&path), ["CIRCLE"]); + assert!(alive(&s, a) && !alive(&s, b)); +} + +#[test] +fn a_block_is_written_by_name_by_equals_or_the_whole_drawing_by_star() { + let (mut s, a, b, c) = drawing(); + let dir = TempDir::new("dash-wblock"); + s.execute("block", &json!({ "name": "WB01K", "base": [5, 5], "handles": [a.hex(), b.hex()], "keep": "delete" })).unwrap(); + // WBLOCK-001: a block by name, from its base point; nothing is erased. + let path = file(&dir, "WB01.dwg"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{path}\" \"WB01K\")")); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(read(&path), ["LINE -5,-5", "CIRCLE"]); + assert!(alive(&s, c)); + // WBLOCK-002: "=" is the block named as the file. + let path = file(&dir, "WB01K.dwg"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{path}\" \"=\")")); + assert_eq!(read(&path), ["LINE -5,-5", "CIRCLE"]); + // WBLOCK-003: "*" is the whole drawing. + let path = file(&dir, "WB03.dwg"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{path}\" \"*\")")); + assert_eq!(read(&path), ["LINE 0,20"]); + assert!(alive(&s, c)); + // WBLOCK-005: a point given there is a name too. + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{}\" '(0.0 0.0))", file(&dir, "WB05.dwg"))); + assert!(s.log.iter().any(|l| l == "Block \"0,0\" not found."), "{:?}", s.log); + s.cancel(); + // WBLOCK-008, WBLOCK-015: a name that isn't a block, typed or by "=", is refused and asked again. + for (answer, name) in [("WB08ZZ", "WB08ZZ"), ("=", "WB15")] { + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{}\" \"{answer}\")", file(&dir, "WB15.dwg"))); + assert!(s.log.iter().any(|l| *l == format!("Block \"{name}\" not found.")), "{answer}: {:?}", s.log); + assert!(s.prompt_text().contains("Enter name of existing block"), "{}", s.prompt_text()); + s.cancel(); + } + assert!(!std::path::Path::new(&file(&dir, "WB15.dwg")).exists()); +} + +#[test] +fn a_name_without_extension_is_a_dwg_and_a_dxf_asks_for_its_precision() { + // WBLOCK-004: no extension. + let (mut s, a, b, _) = drawing(); + let dir = TempDir::new("dash-wblock"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{}\" \"\" '(0.0 0.0) {} \"\")", file(&dir, "WB04"), ent(a))); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(read(&file(&dir, "WB04.dwg")), ["LINE 0,0"]); + // WBLOCK-010: a DXF file asks for its decimal places first; Enter takes 16. + let path = file(&dir, "WB10.dxf"); + s.cmdline("-wblock").unwrap(); + s.cmdline(&path).unwrap(); + assert!(s.log.iter().any(|l| l.starts_with("Current DXF settings: Precision= 16 Format= ASCII")), "{:?}", s.log); + assert!(s.prompt_text().ends_with("Enter decimal places of accuracy (0 to 16) or [Binary/Preview] <16>:"), "{}", s.prompt_text()); + s.cancel(); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{path}\" \"\" \"\" '(0.0 0.0) {} \"\")", ent(b))); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(read(&path), ["CIRCLE"]); + assert!(!alive(&s, b)); +} + +#[test] +fn undo_brings_the_written_objects_back() { + // WBM-09: U after -WBLOCK. + let (mut s, a, b, c) = drawing(); + let dir = TempDir::new("dash-wblock"); + lisp(&mut s, &format!("(command \"_.-WBLOCK\" \"{}\" \"\" '(5.0 5.0) {} {} \"\")", file(&dir, "M09.dwg"), ent(a), ent(b))); + assert!(!alive(&s, a) && !alive(&s, b)); + s.cmdline("u").unwrap(); + assert!(alive(&s, a) && alive(&s, b) && alive(&s, c)); +} + +#[test] +fn the_json_form_of_dash_wblock_erases_what_it_writes() { + let (mut s, a, b, _) = drawing(); + let dir = TempDir::new("dash-wblock"); + s.execute("wblock", &json!({ "path": file(&dir, "keep.dwg"), "handles": [a.hex()] })).unwrap(); + assert!(alive(&s, a), "WBLOCK's JSON form keeps them"); + s.execute("-wblock", &json!({ "path": file(&dir, "erase.dwg"), "handles": [b.hex()], "base": [5, 5] })).unwrap(); + assert_eq!(read(&file(&dir, "erase.dwg")), ["CIRCLE"]); + assert!(!alive(&s, b)); + // Nothing selected writes no file, as at the command line. + let none = file(&dir, "none.dwg"); + assert!(s.execute("-wblock", &json!({ "path": none, "handles": [] })).is_err()); + assert!(s.execute("-wblock", &json!({ "path": none, "handles": [b.hex()] })).is_err(), "erased already"); + assert!(s.execute("-wblock", &json!({ "path": none })).is_err()); + assert!(!std::path::Path::new(&none).exists()); +} From 0e2bff3b2b22c922b03ffa811cd3fc18f1d92d17 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:37:56 +0700 Subject: [PATCH 345/900] LEADER at the command line, as AutoCAD runs it (#2596) LEADER had only its JSON form, so a script's LEADER drew nothing. This adds the command-line command with AutoCAD 2024's prompts: the points, Format (Spline/STraight/Arrow/None) and Undo, then annotation lines, or the options None, Block, Copy, and Mtext and Tolerance (which come back to the first line at the command line, as in accoreconsole). Measured, and followed: - A hook line, a horizontal last segment DIMASZ long, is added when the last segment is straight and more than 15 degrees off horizontal and text follows: 14.9 and 15 degrees keep the end, 15.1 hooks. A spline, no annotation and a block take none. - The text sits DIMGAP past the end on the side the leader runs to: above it, bottom-attached, with DIMTAD on; centred on it with DIMTAD 0. Sizes are DIMSCALE times the style's, with SETVAR overrides. - A copied text keeps its contents, height and width, is centred on its line, and with DIMTAD on the leader ends half the text height lower. The JSON form now draws through the same code. The drawing model has no link from a leader to its annotation, so the two are separate objects. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/annotate.rs | 6 +- crates/engine/src/cmd/annotate/leader.rs | 330 +++++++++++++++++++++ crates/engine/src/cmd/annotate/mleader.rs | 30 +- crates/engine/tests/it/leader_command.rs | 340 ++++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 5 files changed, 678 insertions(+), 29 deletions(-) create mode 100644 crates/engine/src/cmd/annotate/leader.rs create mode 100644 crates/engine/tests/it/leader_command.rs diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index 08f87fc4b..d983ce25d 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -16,6 +16,7 @@ use crate::{Accept, EngineError, Input, Interactive, LeaderOrder, MLeaderOptions mod angular; mod common; mod edit; +mod leader; mod linear; mod mleader; mod radial; @@ -88,7 +89,10 @@ pub fn specs() -> Vec { .alias(&["mld"]) .params("{points: [[arrow], ..., [landing]] ([location] with leaderType none), text?, leaderType?: straight|spline|none, block?: name, blockAttach?: center|insertion}") .interactive(|s| Ok(Box::new(MLeaderM::new(s)))), - CommandSpec::new("leader", "Leader", run_leader).alias(&["lead"]).params("{points: [[x,y]...], text?}"), + CommandSpec::new("leader", "Leader", run_leader) + .alias(&["lead"]) + .params("{points: [[x,y]...], text?}") + .interactive(|_| Ok(Box::new(leader::LeaderM::default()))), CommandSpec::new("dimstyle.update", "Update", run_update) .menu(&["Dimension", "Update"]) .params("{handles?}") diff --git a/crates/engine/src/cmd/annotate/leader.rs b/crates/engine/src/cmd/annotate/leader.rs new file mode 100644 index 000000000..1c5ce7276 --- /dev/null +++ b/crates/engine/src/cmd/annotate/leader.rs @@ -0,0 +1,330 @@ +//! LEADER at the command line, as AutoCAD 2024 runs it (accoreconsole, synthetic drawings): the +//! points, Format and Undo, then annotation text, no annotation, or a block. +//! +//! The leader takes a hook line, a horizontal last segment DIMASZ long, when its last segment is +//! straight and more than 15° off horizontal and text follows it; the text sits DIMGAP past the +//! leader's end, above it (DIMTAD on) or centred on it (DIMTAD 0), on the side the leader runs to. +//! All sizes are scaled by DIMSCALE. The text and the leader are separate objects here: the +//! drawing model has no link from a leader to its annotation. + +use super::common::style; +use super::{Accept, EntityKind, Handle, Input, Interactive, MText, Prompt, Result, Session, Step, Vec2, v3}; +use crate::cmd::curves::KW; + +/// Where LEADER is in its prompts. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Ask { + #[default] + Points, + Format, + FirstLine, + NextLine, + Option, + /// Copy: the text or multiline text to copy. + Copy, + BlockName, + BlockPoint, + BlockX, + BlockY, + BlockRotation, +} + +#[derive(Default)] +pub(super) struct LeaderM { + ask: Ask, + pts: Vec, + spline: bool, + no_arrow: bool, + lines: Vec, + block: String, + block_at: Vec2, + block_scale: Vec2, +} + +/// What follows the leader. +enum Annotation { + Text(Vec), + /// A copy of a text or multiline text: its contents, height, width and style. + Copy(MText), + None, + Block { + name: String, + at: Vec2, + scale: Vec2, + rotation: f64, + }, +} + +impl Interactive for LeaderM { + fn name(&self) -> &'static str { + "LEADER" + } + fn prompt(&self, _s: &Session) -> Prompt { + let last = self.pts.last().copied(); + match self.ask { + Ask::Points => match self.pts.len() { + 0 => Prompt::new("Specify leader start point", Accept::POINT), + 1 => Prompt::new("Specify next point", Accept::POINT).base_opt(last), + _ => Prompt::new("Specify next point", Accept::POINT).kw(&["Annotation", "Format", "Undo"]).default("Annotation").base_opt(last), + }, + Ask::Format => Prompt::new("Enter leader format option", KW).kw(&["Spline", "STraight", "Arrow", "None"]).default("Exit"), + // "or ": the default is the options, not a keyword list. + Ask::FirstLine => Prompt::new("Enter first line of annotation text or", Accept::TEXT).default("options"), + Ask::NextLine => Prompt::new("Enter next line of annotation text", Accept::TEXT), + Ask::Copy => Prompt::new("Select an object to copy", Accept::SELECT), + Ask::Option => Prompt::new("Enter an annotation option", KW).kw(&["Tolerance", "Copy", "Block", "None", "Mtext"]).default("Mtext"), + Ask::BlockName => Prompt::new("Enter block name", Accept::TEXT).kw(&["?"]), + Ask::BlockPoint => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]), + Ask::BlockX => Prompt::new("Enter X scale factor, specify opposite corner", Accept::NUMBER).kw(&["Corner", "XYZ"]).default("1"), + Ask::BlockY => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"), + Ask::BlockRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + match self.ask { + Ask::Points => match i { + Input::Point(p) => self.pts.push(p), + // Enter after one point: no leader. + Input::Enter if self.pts.len() < 2 => return Ok(Step::Done), + Input::Enter => self.ask = Ask::FirstLine, + Input::Keyword(k) => match k.as_str() { + "Annotation" => self.ask = Ask::FirstLine, + "Format" => self.ask = Ask::Format, + _ => { + self.pts.pop(); + } + }, + _ => {} + }, + Ask::Format => { + // Enter, or Exit typed, changes nothing; either way back to the points. + if let Input::Keyword(k) = &i { + match k.as_str() { + "Spline" => self.spline = true, + "STraight" => self.spline = false, + "Arrow" => self.no_arrow = false, + _ => self.no_arrow = true, + } + } + self.ask = Ask::Points; + } + Ask::FirstLine | Ask::NextLine => match i { + Input::Text(t) if !t.is_empty() => { + self.lines.push(t); + self.ask = Ask::NextLine; + } + _ if self.ask == Ask::NextLine => { + let lines = std::mem::take(&mut self.lines); + return self.finish(s, Annotation::Text(lines)); + } + _ => self.ask = Ask::Option, + }, + Ask::Option => match &i { + Input::Keyword(k) if k == "None" => return self.finish(s, Annotation::None), + Input::Keyword(k) if k == "Block" => self.ask = Ask::BlockName, + Input::Keyword(k) if k == "Copy" => self.ask = Ask::Copy, + Input::Text(_) => s.echo("Invalid option keyword."), + // Mtext (the default) and Tolerance open an editor or a dialog in AutoCAD; at the + // command line, as in accoreconsole, they come back to the first line. + _ => self.ask = Ask::FirstLine, + }, + Ask::Copy => { + let picked = match &i { + Input::Pick(hs) => hs.first().copied(), + Input::Point(p) => crate::select::pick(s.doc()?, &s.state()?.edit_space(), *p, s.settings.pickbox.max(1.0) * s.pixel_size()), + _ => None, + }; + let text = picked.and_then(|h| s.doc().ok()?.entity(h).cloned()).and_then(|e| match &e.kind { + EntityKind::Text(t) => Some(MText { + insert: t.insert, + height: t.height, + width: 0.0, + attach: 4, + rotation: 0.0, + style: t.style.clone(), + contents: t.value.clone(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }), + EntityKind::MText(m) => Some(m.clone()), + _ => None, + }); + match text { + Some(m) => return self.finish(s, Annotation::Copy(m)), + None if picked.is_some() => s.echo("The object is not text."), + None => {} + } + } + Ask::BlockName => { + let name = match i { + Input::Text(t) => t.trim().to_string(), + Input::Keyword(k) => k, + _ => return Ok(Step::Continue), + }; + if name == "?" { + let names: Vec = s.doc()?.blocks.values().filter(|b| !b.anonymous).map(|b| b.name.clone()).collect(); + s.echo(format!("Defined blocks: {}", if names.is_empty() { "(none)".into() } else { names.join(", ") })); + } else if s.doc()?.block(&name).is_none() { + s.echo(format!("Block \"{name}\" not found.")); + } else { + self.block = name; + self.ask = Ask::BlockPoint; + } + } + Ask::BlockPoint => match i { + Input::Point(p) => { + self.block_at = p; + self.ask = Ask::BlockX; + } + Input::Keyword(_) => s.echo("This option is not available here yet."), + _ => {} + }, + Ask::BlockX => match scale(&i) { + Some(x) => { + self.block_scale = Vec2::new(x, x); + self.ask = Ask::BlockY; + } + None => s.echo("Requires a nonzero number."), + }, + Ask::BlockY => { + match scale(&i) { + Some(y) if !matches!(i, Input::Enter) => self.block_scale.y = y, + Some(_) => {} + None => { + s.echo("Requires a nonzero number."); + return Ok(Step::Continue); + } + } + self.ask = Ask::BlockRotation; + } + Ask::BlockRotation => { + let rotation = match &i { + Input::Enter => 0.0, + Input::Text(t) => match s.angle_settings().direction(t) { + Some(a) => a, + None => { + s.echo("Requires a valid angle."); + return Ok(Step::Continue); + } + }, + _ => return Ok(Step::Continue), + }; + let a = Annotation::Block { name: self.block.clone(), at: self.block_at, scale: self.block_scale, rotation }; + return self.finish(s, a); + } + } + Ok(Step::Continue) + } +} + +/// A scale factor typed, or 1 for Enter; `None` for zero or anything that isn't a number. +fn scale(i: &Input) -> Option { + match i { + Input::Enter => Some(1.0), + Input::Text(t) => t.trim().parse::().ok().filter(|v| v.is_finite() && *v != 0.0), + _ => None, + } +} + +impl LeaderM { + fn finish(&mut self, s: &mut Session, ann: Annotation) -> Result { + let pts = std::mem::take(&mut self.pts); + add_leader(s, &pts, self.spline, !self.no_arrow, ann)?; + Ok(Step::Done) + } +} + +/// The dimension settings LEADER draws with, from the current dimension style and DIMSCALE. +struct Sizes { + arrow: f64, + gap: f64, + text: f64, + above: bool, + text_style: String, +} + +fn sizes(s: &Session) -> Sizes { + // The current style with the drawing's DIM* overrides (what SETVAR DIMTXT… sets). + let st = s.doc().ok().and_then(|d| d.dim_style(&style(s)).map(|st| st.with_overrides(&d.dim_overrides()))).unwrap_or_default(); + let k = if st.scale > 0.0 { st.scale } else { 1.0 }; + let text_style = if st.text_style.is_empty() { "Standard".to_string() } else { st.text_style.clone() }; + Sizes { arrow: st.arrow_size * k, gap: st.text_gap.abs() * k, text: st.text_height * k, above: st.text_above != 0, text_style } +} + +/// LEADER's JSON form: a straight leader with an arrow through `pts`, and `text` (lines split at +/// `\n`) placed as the command line places it. The handles of the leader and its text. +pub(super) fn json_leader(s: &mut Session, pts: &[Vec2], text: Option<&str>) -> Result> { + let ann = match text { + Some(t) if !t.is_empty() => Annotation::Text(t.split('\n').map(str::to_string).collect()), + _ => Annotation::None, + }; + add_leader(s, pts, false, true, ann) +} + +/// Draw the leader through `pts` and its annotation, as AutoCAD 2024 places them; their handles. +fn add_leader(s: &mut Session, pts: &[Vec2], spline: bool, arrow: bool, ann: Annotation) -> Result> { + let (Some(&end), Some(&before)) = (pts.last(), pts.len().checked_sub(2).and_then(|i| pts.get(i))) else { return Ok(Vec::new()) }; + let z = sizes(s); + // The side the leader runs to: right unless its last segment runs left. + let dir = if end.x < before.x { -1.0 } else { 1.0 }; + let mut vertices = pts.to_vec(); + if let Annotation::Text(_) | Annotation::Copy(_) = ann { + let d = end - before; + // A copied text is centred on its line, and with DIMTAD on that line is above the leader: + // the leader ends half the text height lower. + if let (Annotation::Copy(_), true, Some(last)) = (&ann, z.above, vertices.last_mut()) { + last.y -= z.text / 2.0; + } + let end = vertices.last().copied().unwrap_or(end); + // More than 15° off horizontal: a hook line DIMASZ long into the end. + if !spline && d.y.abs() > d.x.abs() * 15f64.to_radians().tan() { + let at = vertices.len() - 1; + vertices.insert(at, Vec2::new(end.x - dir * z.arrow, end.y)); + } + } + let leader = s.add_entity(EntityKind::Leader(cadcraft_doc::Leader { + vertices: vertices.iter().map(|p| v3(*p)).collect(), + arrow, + spline, + style: style(s), + }))?; + let annotation = match ann { + Annotation::Text(lines) => { + let (attach, lift) = match (z.above, dir > 0.0) { + (true, true) => (7, z.gap), + (true, false) => (9, z.gap), + (false, true) => (4, 0.0), + (false, false) => (6, 0.0), + }; + Some(s.add_entity(EntityKind::MText(MText { + insert: v3(end + Vec2::new(dir * z.gap, lift)), + height: z.text, + width: 0.0, + attach, + rotation: 0.0, + style: z.text_style, + contents: lines.join("\\P"), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }))?) + } + Annotation::Copy(m) => { + let lift = if z.above { z.gap } else { 0.0 }; + let attach = if dir > 0.0 { 4 } else { 6 }; + Some(s.add_entity(EntityKind::MText(MText { insert: v3(end + Vec2::new(dir * z.gap, lift)), attach, rotation: 0.0, ..m }))?) + } + Annotation::Block { name, at, scale, rotation } => { + match crate::cmd::blocks::insert_with(s, &name, at, scale, rotation, None, &serde_json::Map::new()) { + Ok(h) => Some(h), + Err(e) => { + s.doc_mut()?.remove_entity(leader); + return Err(e); + } + } + } + Annotation::None => None, + }; + Ok(std::iter::once(leader).chain(annotation).collect()) +} diff --git a/crates/engine/src/cmd/annotate/mleader.rs b/crates/engine/src/cmd/annotate/mleader.rs index 536e83b8c..9b4e74128 100644 --- a/crates/engine/src/cmd/annotate/mleader.rs +++ b/crates/engine/src/cmd/annotate/mleader.rs @@ -1,4 +1,3 @@ -use super::common::style; use super::{ Accept, EngineError, EntityKind, Input, Interactive, LeaderOrder, MLeader, MLeaderOptions, MText, Prompt, Result, Session, Step, Value, Vec2, bad, json, points_param, str_param, v3, @@ -57,33 +56,8 @@ pub(super) fn run_leader(s: &mut Session, p: &Value) -> Result { if pts.len() < 2 { return Err(bad("leader", "need 2+ points")); } - let st = style(s); - let h = s.add_entity(EntityKind::Leader(cadcraft_doc::Leader { - vertices: pts.iter().map(|q| v3(*q)).collect(), - arrow: true, - spline: false, - style: st, - }))?; - let mut out = vec![h.hex()]; - if let (Some(t), Some(last)) = (str_param(p, "text"), pts.last()) { - let th = s.doc()?.dim_style(&style(s)).map(|d| d.text_height).unwrap_or(0.18); - out.push( - s.add_entity(EntityKind::MText(MText { - insert: v3(*last + Vec2::new(th * 0.5, th * 0.5)), - height: th, - width: 0.0, - attach: 4, - rotation: 0.0, - style: "Standard".into(), - contents: t.into(), - line_spacing: 1.0, - line_spacing_exact: false, - columns: None, - }))? - .hex(), - ); - } - Ok(json!({ "handles": out })) + let hs = super::leader::json_leader(s, &pts, str_param(p, "text"))?; + Ok(json!({ "handles": hs.iter().map(|h| h.hex()).collect::>() })) } /// The MLEADER Options prompt being answered. diff --git a/crates/engine/tests/it/leader_command.rs b/crates/engine/tests/it/leader_command.rs new file mode 100644 index 000000000..f71c99462 --- /dev/null +++ b/crates/engine/tests/it/leader_command.rs @@ -0,0 +1,340 @@ +//! LEADER at the command line, as AutoCAD 2024 runs it (accoreconsole: these scripts, with +//! DIMTAD 1, DIMGAP 0.625, DIMASZ 2.5, DIMSCALE 1 and DIMTXT 2.5 unless a case sets another, and +//! the drawing read back afterwards). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Insert, Leader, MText}; +use serde_json::json; + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1.0) +} + +/// A drawing as the measured scripts start from: the dimension settings, and a text "XYZ" 2.5 +/// high at (100,40) that the Copy cases copy (`(entlast)` after it). +fn session(setup: &str) -> Session { + let mut s = Session::new(); + for (name, v) in [("DIMTAD", 1.0), ("DIMGAP", 0.625), ("DIMASZ", 2.5), ("DIMSCALE", 1.0), ("DIMTXT", 2.5)] { + s.execute("setvar", &json!({ "name": name, "value": v })).unwrap(); + } + s.execute("text", &json!({ "at": [100, 40], "text": "XYZ", "height": 2.5 })).unwrap(); + s.cmdline("(setq hl_T (entlast))").unwrap(); + if !setup.is_empty() { + s.cmdline(setup).unwrap(); + } + s +} + +fn run(setup: &str, script: &str) -> Session { + let mut s = session(setup); + s.cmdline(script).unwrap(); + assert!(s.running.is_none(), "{script}: {}", s.prompt_text()); + s +} + +fn leaders(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Leader(l) = &e.kind { Some(l.clone()) } else { None }).collect() +} + +fn mtexts(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::MText(m) = &e.kind { Some(m.clone()) } else { None }).collect() +} + +fn inserts(s: &Session) -> Vec { + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.clone()) } else { None }).collect() +} + +fn vertices(l: &Leader) -> Vec<[f64; 2]> { + l.vertices.iter().map(|v| [v.x, v.y]).collect() +} + +fn same_points(got: &[[f64; 2]], want: &[[f64; 2]]) -> bool { + got.len() == want.len() && got.iter().zip(want).all(|(g, w)| near(g[0], w[0]) && near(g[1], w[1])) +} + +/// (case, setup, script, leader vertices, text insertion point, attachment, height, contents) +type Case = (&'static str, &'static str, &'static str, &'static [[f64; 2]], [f64; 2], u8, f64, &'static str); + +#[test] +fn leaders_and_their_text_are_where_autocad_puts_them() { + let cases: [Case; 17] = [ + // A horizontal last segment: no hook line; the text DIMGAP right of and above the end. + ( + "000", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(40.0 15.0) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [40.0, 15.0]], + [40.625, 15.625], + 7, + 2.5, + "ABC", + ), + // More than 15° off horizontal: a hook line DIMASZ long into the end. + ( + "001", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(35.0 30.0) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [32.5, 30.0], [35.0, 30.0]], + [35.625, 30.625], + 7, + 2.5, + "ABC", + ), + ( + "002", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"\" \"AB\" \"CD\" \"\")", + &[[0.0, 0.0], [17.5, 15.0], [20.0, 15.0]], + [20.625, 15.625], + 7, + 2.5, + "AB\\PCD", + ), + // To the left: the text right-attached, DIMGAP left of the end. + ( + "004", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(-20.0 15.0) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [-17.5, 15.0], [-20.0, 15.0]], + [-20.625, 15.625], + 9, + 2.5, + "ABC", + ), + // A vertical last segment hooks to the right. + ( + "007-VN", + "", + "(command \"_.LEADER\" '(612345.678 2398765.432) '(612345.678 2398795.432) \"\" \"ABC\" \"\")", + &[[612345.678, 2398765.432], [612343.178, 2398795.432], [612345.678, 2398795.432]], + [612346.303, 2398796.057], + 7, + 2.5, + "ABC", + ), + // 14.9° and 15° keep the end; 15.1° hooks. + ( + "100", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(40.0 20.32158853384029) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [40.0, 20.32158853384029]], + [40.625, 20.94658853384029], + 7, + 2.5, + "ABC", + ), + ( + "101", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(40.0 20.358983848622454) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [40.0, 20.358983848622454]], + [40.625, 20.983983848622454], + 7, + 2.5, + "ABC", + ), + ( + "102", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(40.0 20.39641415635812) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [37.5, 20.39641415635812], [40.0, 20.39641415635812]], + [40.625, 21.02141415635812], + 7, + 2.5, + "ABC", + ), + // DIMTAD 0: centred on the end, left- or right-attached. + ( + "020", + "(setvar \"DIMTAD\" 0)", + "(command \"_.LEADER\" '(0.5 0.25) '(0.52 0.265) '(0.54 0.265) \"\" \"ABC\" \"\")", + &[[0.5, 0.25], [0.52, 0.265], [0.54, 0.265]], + [1.165, 0.265], + 4, + 2.5, + "ABC", + ), + ( + "103-VN", + "(setvar \"DIMTAD\" 0)", + "(command \"_.LEADER\" '(612345.678 2398765.432) '(612325.678 2398780.432) '(612305.678 2398780.432) \"\" \"ABC\" \"\")", + &[[612345.678, 2398765.432], [612325.678, 2398780.432], [612305.678, 2398780.432]], + [612305.053, 2398780.432], + 6, + 2.5, + "ABC", + ), + // DIMGAP, DIMSCALE (hook, gap and height) and DIMTXT. + ( + "021", + "(setvar \"DIMGAP\" 2.0)", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(40.0 15.0) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [40.0, 15.0]], + [42.0, 17.0], + 7, + 2.5, + "ABC", + ), + ( + "022", + "(setvar \"DIMSCALE\" 2.0)", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(35.0 30.0) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [30.0, 30.0], [35.0, 30.0]], + [36.25, 31.25], + 7, + 5.0, + "ABC", + ), + ( + "024", + "(setvar \"DIMTXT\" 5.0)", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(40.0 15.0) \"\" \"AB\" \"CD\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [40.0, 15.0]], + [40.625, 15.625], + 7, + 5.0, + "AB\\PCD", + ), + // A spline takes no hook line. + ( + "026", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"_F\" \"_S\" '(35.0 30.0) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [35.0, 30.0]], + [35.625, 30.625], + 7, + 2.5, + "ABC", + ), + // Undo takes the last point back. + ( + "014", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) '(35.0 30.0) \"_U\" '(40.0 15.0) \"\" \"ABC\" \"\")", + &[[0.0, 0.0], [20.0, 15.0], [40.0, 15.0]], + [40.625, 15.625], + 7, + 2.5, + "ABC", + ), + // Annotation options: Mtext, at the command line, comes back to the first line. + ( + "106", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"\" \"\" \"_M\" \"ABC\" \"\")", + &[[0.0, 0.0], [17.5, 15.0], [20.0, 15.0]], + [20.625, 15.625], + 7, + 2.5, + "ABC", + ), + // Copy: centred on its line; with DIMTAD on the leader ends half the text height lower. + ( + "016", + "", + "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"\" \"\" \"_C\" hl_T)", + &[[0.0, 0.0], [17.5, 13.75], [20.0, 13.75]], + [20.625, 15.625], + 4, + 2.5, + "XYZ", + ), + ]; + for (case, setup, script, want_vertices, at, attach, height, contents) in cases { + let s = run(setup, script); + let ls = leaders(&s); + assert_eq!(ls.len(), 1, "{case}"); + assert!(same_points(&vertices(&ls[0]), want_vertices), "{case}: {:?}", vertices(&ls[0])); + let ms = mtexts(&s); + assert_eq!(ms.len(), 1, "{case}"); + let m = &ms[0]; + assert!(near(m.insert.x, at[0]) && near(m.insert.y, at[1]), "{case}: {:?}", m.insert); + assert_eq!((m.attach, m.contents.as_str()), (attach, contents), "{case}"); + assert!(near(m.height, height) && m.width == 0.0, "{case}: {} {}", m.height, m.width); + } +} + +#[test] +fn format_sets_the_path_and_the_arrow() { + // LEADER-011 Format None; LEADER-012 None then Arrow; LEADER-013 Spline then STraight. + for (script, spline, arrow) in [ + ("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"_F\" \"_N\" '(40.0 15.0) \"\" \"ABC\" \"\")", false, false), + ("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"_F\" \"_N\" \"_F\" \"_A\" '(40.0 15.0) \"\" \"ABC\" \"\")", false, true), + ("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"_F\" \"_S\" \"_F\" \"_ST\" '(40.0 15.0) \"\" \"ABC\" \"\")", false, true), + ("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"_F\" \"\" '(40.0 15.0) \"\" \"ABC\" \"\")", false, true), + ] { + let l = leaders(&run("", script)).remove(0); + assert_eq!((l.spline, l.arrow), (spline, arrow), "{script}"); + } +} + +#[test] +fn no_annotation_a_block_or_a_copied_multiline_text() { + // LEADER-015: None leaves the leader alone, without a hook line. + let s = run("", "(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"\" \"\" \"_N\")"); + assert!(same_points(&vertices(&leaders(&s)[0]), &[[0.0, 0.0], [20.0, 15.0]])); + assert!(mtexts(&s).is_empty()); + // LEADER-107: a block, scale 2 (Y as X), 30°, where it is placed; no hook line. + let mut s = session(""); + s.execute("line", &json!({ "points": [[100, 0], [110, 0]] })).unwrap(); + s.cmdline("(command \"_.-BLOCK\" \"LB107\" '(100.0 0.0) (entlast) \"\")").unwrap(); + s.cmdline("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"\" \"\" \"_B\" \"LB107\" '(50.0 20.0) 2 \"\" 30)").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert!(same_points(&vertices(&leaders(&s)[0]), &[[0.0, 0.0], [20.0, 15.0]])); + let i = inserts(&s).remove(0); + assert!(i.block == "LB107" && near(i.insert.x, 50.0) && near(i.insert.y, 20.0), "{i:?}"); + assert!(near(i.scale.x, 2.0) && near(i.scale.y, 2.0) && near(i.rotation, 30f64.to_radians()), "{i:?}"); + // LEADER-105: a copied multiline text keeps its width; LEADER-137 to the left. + let mut s = session(""); + s.cmdline("(command \"_.MTEXT\" '(60.0 40.0) '(90.0 30.0) \"MT\" \"\")").unwrap(); + s.cmdline("(command \"_.LEADER\" '(0.0 0.0) '(20.0 15.0) \"\" \"\" \"_C\" (entlast))").unwrap(); + let copy = mtexts(&s).into_iter().find(|m| near(m.insert.x, 20.625)).unwrap(); + assert!(near(copy.width, 30.0) && copy.attach == 4 && copy.contents == "MT", "{copy:?}"); + let s = run("", "(command \"_.LEADER\" '(0.0 0.0) '(-20.0 15.0) \"\" \"\" \"_C\" hl_T)"); + assert!(same_points(&vertices(&leaders(&s)[0]), &[[0.0, 0.0], [-17.5, 13.75], [-20.0, 13.75]])); + let m = mtexts(&s).into_iter().next().unwrap(); + assert!(near(m.insert.x, -20.625) && near(m.insert.y, 15.625) && m.attach == 6, "{m:?}"); +} + +#[test] +fn the_json_form_places_its_text_as_the_command_line_does() { + let mut s = session(""); + let v = s.execute("leader", &json!({ "points": [[0, 0], [20, 15], [35, 30]], "text": "ABC" })).unwrap(); + assert_eq!(v["handles"].as_array().map(Vec::len), Some(2)); + assert!(same_points(&vertices(&leaders(&s)[0]), &[[0.0, 0.0], [20.0, 15.0], [32.5, 30.0], [35.0, 30.0]])); + let m = mtexts(&s).remove(0); + assert!(near(m.insert.x, 35.625) && near(m.insert.y, 30.625) && m.attach == 7 && near(m.height, 2.5), "{m:?}"); +} + +#[test] +fn the_prompts_are_autocads_and_one_point_draws_nothing() { + let mut s = session(""); + s.cmdline("leader").unwrap(); + assert!(s.prompt_text().ends_with("Specify leader start point:"), "{}", s.prompt_text()); + s.cmdline("0,0").unwrap(); + assert!(s.prompt_text().ends_with("Specify next point:"), "{}", s.prompt_text()); + s.cmdline("20,15").unwrap(); + assert!(s.prompt_text().ends_with("Specify next point or [Annotation/Format/Undo] :"), "{}", s.prompt_text()); + s.cmdline("_F").unwrap(); + assert!(s.prompt_text().ends_with("[Spline/STraight/Arrow/None] :"), "{}", s.prompt_text()); + s.cmdline("").unwrap(); + s.cmdline("").unwrap(); + assert!(s.prompt_text().ends_with("Enter first line of annotation text or :"), "{}", s.prompt_text()); + s.cmdline("").unwrap(); + assert!(s.prompt_text().ends_with("[Tolerance/Copy/Block/None/Mtext] :"), "{}", s.prompt_text()); + // LEADER-019: Tolerance, at the command line, comes back to the first line. + s.cmdline("_T").unwrap(); + assert!(s.prompt_text().ends_with("Enter first line of annotation text or :"), "{}", s.prompt_text()); + // An answer that isn't an option is refused; `?` at the block name lists the blocks. + s.cmdline("").unwrap(); + s.cmdline("X").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Invalid option keyword.")); + s.cmdline("_B").unwrap(); + assert!(s.prompt_text().ends_with("Enter block name or [?]:"), "{}", s.prompt_text()); + s.cmdline("?").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Defined blocks: (none)")); + s.cancel(); + // LEADER-139: one point and Enter. + let s = run("", "(command \"_.LEADER\" '(0.0 0.0) \"\")"); + assert!(leaders(&s).is_empty() && mtexts(&s).is_empty()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 88cbefe31..2aae7c117 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -70,6 +70,7 @@ mod layer_cmdline; mod layer_merge_delete; mod layoff_repeat; mod layout_prompts; +mod leader_command; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod lisp_corpus; mod malformed_handles; From 4a9371ad2cacd067837d30ff03ec592820fcad91 Mon Sep 17 00:00:00 2001 From: NateMarida Date: Mon, 2 Nov 2026 02:38:00 +0700 Subject: [PATCH 346/900] Thai text: stacked marks, Thai fonts first, MTEXT word wrap (#2591) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Thai text: stacked marks, Thai fonts first, MTEXT word wrap, Windows fonts under WSL Thai text in DWG/DXF files decoded correctly but laid out badly. Vowels and tone marks stacked on one consonant collided (ดิ์), because only right-to-left text went through the shaper. - Thai lines go through the harfrust shaper (complex::needed). Shaped left-to-right glyphs keep their characters (TextGlyph) for PDF text. - Thai fallback fonts: Cordia, Angsana and Browallia first (Thai drawings are laid out with their widths), then IBM Plex Sans Thai, Noto Sans/Serif Thai and the fonts each OS ships. - The web build embeds the craft-fonts Thai regular faces. - MTEXT wraps a run of Thai between words when the run is too wide for the column by itself. Text that fits at its spaces keeps those line breaks, so existing drawings lay out as before. Word breaks come from icu_segmenter's LSTM model (about 410 KB). ICU's dictionary segmenter was not used: after loanwords it breaks inside words, even between a consonant and its tone mark. Breaks inside a character cluster are dropped, and results are cached. - Under WSL the font scan also reads /mnt/c/Windows/Fonts, at the lowest priority, so drawings find the Windows fonts they name (Cordia New). The scan reads entry types from the directory listing instead of a stat per file. * Thai fallback: match older Angsana and Browallia file names; document touched functions Today's Windows ships Angsana New and Browallia New as angsana.ttc and browalia.ttc. Older Windows used single faces (angsa.ttf, angsab.ttf, browa.ttf, ...), which still turn up when fonts are copied to Linux machines. The Thai fallback list now matches the shorter stems `angsa` and `browa`, which cover both. Review feedback on #2591. Doc comments for scan, plain_lines and the paragraph layout's word_width and place. * MTEXT: wrap a Thai run after a first-line indent or a tab A Thai run that fit a line at the left indent, but not the room left after a first-line indent or a tab stop, wasn't split between its words: the first line of a paragraph can't wrap, so it ran out of the column. An empty line now measures the run from where it starts. Review feedback on #2591. Also restores the space in `image = {` in Cargo.toml. * Font scan: take the WSL font folder out of this change Thai text doesn't depend on it: with no Windows or system fonts, the craft-fonts Thai faces (Noto Sans Thai, IBM Plex Sans Thai) stack marks and wrap MTEXT the same way. Reading the Windows host's /mnt/c/Windows/Fonts under WSL is a separate decision, so the scan is back to main's: Linux system and user font folders only. --- Cargo.lock | 33 +++++ Cargo.toml | 3 + crates/fonts/Cargo.toml | 1 + crates/fonts/build.rs | 11 +- crates/fonts/src/complex.rs | 173 +++++++++++++++++++++++++- crates/fonts/src/craft_fonts.rs | 5 +- crates/fonts/src/lib.rs | 8 +- crates/fonts/src/linebreak.rs | 205 +++++++++++++++++++++++++++++++ crates/fonts/src/mtext.rs | 209 ++++++++++++++++++++++++++++---- crates/fonts/src/mtext/para.rs | 30 ++++- crates/fonts/src/ttf.rs | 102 +++++++++++++--- 11 files changed, 726 insertions(+), 54 deletions(-) create mode 100644 crates/fonts/src/linebreak.rs diff --git a/Cargo.lock b/Cargo.lock index aa4e1961c..81a772f6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -728,6 +728,7 @@ version = "0.16.0" dependencies = [ "cadcraft-geom", "harfrust 0.14.0", + "icu_segmenter", "skrifa 0.48.0", "unicode-bidi", ] @@ -1115,6 +1116,15 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -2435,6 +2445,29 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_segmenter" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db" +dependencies = [ + "core_maths", + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" + [[package]] name = "idna" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index c6b9590fa..b84651eee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,9 @@ skrifa = "0.48" # so the graph has both) and the Unicode Bidirectional Algorithm for right-to-left drawing text. harfrust = "0.14" unicode-bidi = "0.3.18" +# Line-break opportunities between Thai words for MTEXT word wrap (Thai writes no spaces between +# words): UAX #14 with ICU4X's compiled-in LSTM word model (not its dictionaries). +icu_segmenter = { version = "~2.3", default-features = false, features = ["compiled_data", "lstm"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } encoding_rs = "0.8.35" # XML for the SVG reader (streaming parser, no entity expansion beyond the five predefined ones) diff --git a/crates/fonts/Cargo.toml b/crates/fonts/Cargo.toml index d2bdddf88..0fc676c7b 100644 --- a/crates/fonts/Cargo.toml +++ b/crates/fonts/Cargo.toml @@ -13,3 +13,4 @@ cadcraft-geom = { workspace = true } skrifa = { workspace = true } harfrust = { workspace = true } unicode-bidi = { workspace = true } +icu_segmenter = { workspace = true } diff --git a/crates/fonts/build.rs b/crates/fonts/build.rs index 6df86f7eb..8f46dcc44 100644 --- a/crates/fonts/build.rs +++ b/crates/fonts/build.rs @@ -3,9 +3,10 @@ //! 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, the `Arab` faces and the `Thai` Regular faces +//! (about 5.9 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 Thai text. use std::fmt::Write as _; use std::path::PathBuf; @@ -54,8 +55,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 has = |script: &str| scripts.split(',').any(|s| s.trim() == script); + let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || has("Arab") || (has("Thai") && *style == "Regular"); if wasm && !web_face { continue; } diff --git a/crates/fonts/src/complex.rs b/crates/fonts/src/complex.rs index a8dd367c3..4a4ac461f 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -1,10 +1,15 @@ -//! Lines with right-to-left text: the line is split into bidi runs in display order +//! Lines with right-to-left text or Thai: the line is split into bidi runs in display order //! ([`crate::bidi::visual_runs`]), each run into pieces by the font that draws them (the text's //! font, a fallback font for characters it lacks, or the stroke font), and each font piece is //! shaped with `harfrust` (OpenType GSUB/GPOS: Arabic contextual forms, lam-alef and other //! ligatures, mark positioning, mirroring) before its glyphs are placed. Shaping happens per //! piece in the font that draws it, so Arabic in a stroke-font style is joined by the fallback //! font. Fonts without OpenType Arabic features get Unicode presentation forms instead. +//! +//! Thai is left to right but needs the shaper too: a consonant carries up to two stacked marks +//! above (a vowel, then a tone mark) and one below, placed by the font's `mark`/`mkmk` +//! positioning; letters with a descender (ฐ, ญ) lose it under a below vowel (`ccmp`); and sara +//! am (ำ) splits into nikhahit and sara aa with the nikhahit moved before any tone mark. use std::ops::Range; use std::panic::{AssertUnwindSafe, catch_unwind}; @@ -17,6 +22,17 @@ use crate::{Shaped, bidi, stroke}; /// Longest line (characters) laid out this way; longer lines keep one glyph per character. const MAX_CHARS: usize = 10_000; +/// Whether a line is laid out here rather than one glyph per character: it has right-to-left +/// text, or Thai (see the module notes). +pub(crate) fn needed(s: &str) -> bool { + s.chars().any(|c| bidi::is_rtl(c) || is_thai(c)) +} + +/// Whether `c` is in the Thai block. +pub(crate) fn is_thai(c: char) -> bool { + matches!(c, '\u{0E00}'..='\u{0E7F}') +} + /// What draws a piece of a run. #[derive(Clone)] enum Src { @@ -100,7 +116,11 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 } } Src::Face(face) => { - for g in shape_run(face, &cs, r, rtl) { + let glyphs = shape_run(face, &cs, r.clone(), rtl); + // Right-to-left runs stay outlines only: their glyphs come in display order + // and include ligatures (lam-alef) that stand for several characters. + let shows = if rtl { Vec::new() } else { glyph_chars(face, &cs, &glyphs, r.end) }; + for (n, g) in glyphs.iter().enumerate() { let outline = ttf::glyph_by_id(face, g.gid); let k = h / outline.cap * wf; let dy = g.dy * h / outline.cap; @@ -108,7 +128,14 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 for p in contours.iter_mut().flatten() { *p += Vec2::new(dy * shear, dy); } - out.push_glyph(contours, None); + let origin = Vec2::new(x + g.dx * k + dy * shear, dy); + let text = shows + .get(n) + .copied() + .flatten() + .filter(|c| !c.is_whitespace()) + .and_then(|c| ttf::text_glyph_at(&outline, c, origin, h / outline.cap, wf, shear)); + out.push_glyph(contours, text); } let adv = g.advance * k; let (u, o) = flags(g.cluster); @@ -216,6 +243,44 @@ fn shape_run(face: &Face, cs: &[char], r: Range, rtl: bool) -> Vec .collect() } +/// Longest cluster whose glyphs are matched to its characters by glyph id; the glyphs of a +/// longer one (a hostile run of thousands of stacked marks) take its characters in order. +const MAX_MATCHED_CLUSTER: usize = 32; + +/// The character each glyph of a left-to-right run shows, for output that keeps text as text +/// ([`crate::TextGlyph`]). The shaper reorders, splits and substitutes glyphs inside a cluster +/// (a letter with its marks), so within each cluster a glyph that is a character's own glyph +/// takes that character first, then the other glyphs take the cluster's remaining characters in +/// order. Each character is shown once: a glyph left over (the second half of a split Thai sara +/// am) shows none and is drawn as an outline only. +fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec> { + let mut out: Vec> = vec![None; glyphs.len()]; + let mut i = 0; + while let Some(cluster) = glyphs.get(i).map(|g| g.cluster) { + let j = glyphs.iter().skip(i).position(|g| g.cluster != cluster).map_or(glyphs.len(), |n| i + n); + // Clusters ascend in a left-to-right run: this one's characters end where the next starts. + let to = glyphs.get(j).map_or(end, |g| g.cluster).clamp(cluster, end.max(cluster)); + let chars = cs.get(cluster..to).unwrap_or_default(); + let mut free: Vec> = chars.iter().copied().map(Some).collect(); + if chars.len() <= MAX_MATCHED_CLUSTER { + let ids = face.glyph_ids(chars); + for n in i..j { + let gid = glyphs.get(n).map(|g| g.gid); + let own = ids.iter().zip(&free).position(|(id, f)| f.is_some() && *id == gid); + if let (Some(p), Some(o)) = (own, out.get_mut(n)) { + *o = free.get_mut(p).and_then(Option::take); + } + } + } + let mut rest = free.into_iter().flatten(); + for o in out.iter_mut().take(j).skip(i).filter(|o| o.is_none()) { + *o = rest.next(); + } + i = j; + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -372,6 +437,108 @@ mod tests { assert!(matches!((adv, hmtx), (Some(a), Some(h)) if (a - f64::from(h)).abs() < 1e-3), "{adv:?} vs {hmtx:?}"); } + #[test] + fn thai_lines_are_shaped_and_latin_lines_are_not() { + assert!(needed("ระดับดินเดิม") && needed("ขนาด 50x50 mm.") && needed("\u{0E4C}")); + assert!(needed("abc سلام")); + assert!(!needed("50x50 mm.") && !needed("Ünïcödé %%c25") && !needed("")); + } + + fn glyph(cluster: usize) -> Glyph { + Glyph { gid: 0, cluster, advance: 500.0, dx: 0.0, dy: 0.0 } + } + + /// Without installed fonts: a face that maps no character, so glyphs take their cluster's + /// characters in order. + #[test] + fn glyphs_show_their_cluster_characters_once() { + let face = empty_glyph_face(); + let cs: Vec = "xabcd".chars().collect(); + // A run from index 1: cluster 1 has "ab" (two glyphs), cluster 3 has "cd" and a split + // character's extra glyph, which shows nothing. + let gs = Vec::from([1, 1, 3, 3, 3].map(glyph)); + assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![Some('a'), Some('b'), Some('c'), Some('d'), None]); + // Clusters out of order, past the run or past the line show nothing and don't panic. + let gs = Vec::from([3, 1, usize::MAX, 9].map(glyph)); + assert_eq!(glyph_chars(&face, &cs, &gs, 5), vec![None, Some('a'), None, None]); + assert!(glyph_chars(&face, &cs, &[], 5).is_empty()); + // A cluster longer than the matching limit still shows each character once, in order. + let long: Vec = std::iter::once('ก').chain(std::iter::repeat_n('\u{0E48}', MAX_CHARS)).collect(); + let gs: Vec = (0..long.len()).map(|_| glyph(0)).collect(); + let shows = glyph_chars(&face, &long, &gs, long.len()); + assert_eq!(shows.first(), Some(&Some('ก'))); + assert!(shows.iter().all(Option::is_some)); + } + + /// An installed font with Thai, or `None` (the tests then skip). + fn thai_face() -> Option { + ttf::fallback_for('\u{0E01}').filter(|f| ['\u{0E14}', '\u{0E34}', '\u{0E4C}', '\u{0E33}', '\u{0E10}'].iter().all(|c| f.has_glyph(*c))) + } + + /// Lowest point of the glyph that shows `c`. + fn bottom_of(sh: &Shaped, c: char) -> Option { + let t = sh.text.iter().find(|t| t.ch == c)?; + sh.glyphs.get(t.outline)?.iter().flatten().map(|p| p.y).reduce(f64::min) + } + + #[test] + fn thai_marks_stack_in_an_installed_font() { + let Some(face) = thai_face() else { return }; + let shape = |s: &str| ttf::shape(&face, s, 1.0, 1.0, 0.0).expect("the face parses"); + // Thanthakhat over sara i (ดิ์) sits above the vowel, higher than over the bare consonant + // (ด์): the font's mark-to-mark positioning. One glyph per character drew both marks at + // the same height, on top of each other. + let stacked = shape("ดิ์"); + let alone = shape("ด์"); + let (Some(over_vowel), Some(over_letter)) = (bottom_of(&stacked, '\u{0E4C}'), bottom_of(&alone, '\u{0E4C}')) else { + panic!("thanthakhat drawn as text: {:?}", stacked.text.iter().map(|t| t.ch).collect::()) + }; + assert!(over_vowel > over_letter + 0.05, "stacked {over_vowel} vs alone {over_letter}"); + // Every character is written as text exactly once, however the shaper reorders, splits + // (sara am) or substitutes (ฐ without its tail under sara u) the glyphs. + for s in ["ดิ์", "น้ำ", "ฐุ", "ปั้น", "จีรศักดิ์"] { + let mut shown: Vec = shape(s).text.iter().map(|t| t.ch).collect(); + let mut typed: Vec = s.chars().collect(); + shown.sort_unstable(); + typed.sort_unstable(); + assert_eq!(shown, typed, "{s}"); + } + // Measured and laid-out widths agree, in the face and in a stroke-font style. + let s = "ทาสีขาว 50x50 mm."; + assert!((ttf::width(&face, s, 1.0, 1.0).unwrap_or_default() - shape(s).width).abs() < 1e-9); + assert!((crate::line_width(s, 1.0, 1.0) - crate::shape_stroke(s, 1.0, 1.0, 0.0).width).abs() < 1e-9); + // In a stroke-font style Thai comes from the fallback font as text, without + // missing-glyph boxes, and the Latin stays in the stroke font. + let sh = crate::shape_stroke("ระดับดินเดิม +0.00", 1.0, 1.0, 0.0); + assert!(!sh.strokes.iter().any(|s| s.len() == 5 && s.first() == s.last()), "no missing-glyph boxes"); + assert_eq!(sh.text.len(), "ระดับดินเดิม".chars().count()); + assert!(!sh.strokes.is_empty(), "\"+0.00\" in the stroke font"); + } + + #[test] + fn hostile_thai_lines_never_panic() { + for s in [ + "\u{0E33}\u{0E33}\u{0E33}", + "\u{0E4C}\u{0E49}\u{0E34}", + "ก\u{0E49}\u{0E49}\u{0E49}\u{0E33}\u{0E33}", + "%%u\u{0E34}%%o", + "\u{0E01}\u{200D}\u{0E33}\u{10FFFF}", + ] { + let _ = crate::shape_stroke(s, f64::NAN, -1.0, f64::INFINITY); + let _ = crate::line_width(s, 0.0, 0.0); + if let Some(face) = thai_face() { + let _ = ttf::shape(&face, s, f64::NAN, 0.0, f64::NAN); + let _ = ttf::width(&face, s, -1.0, f64::INFINITY); + } + } + // One consonant under thousands of tone marks: a single huge cluster. + let marks = format!("ก{}", "\u{0E48}".repeat(MAX_CHARS - 1)); + assert!(crate::shape_stroke(&marks, 1.0, 1.0, 0.0).width > 0.0); + let long = "ก".repeat(MAX_CHARS + 1); + assert!(shape(None, &long, 1.0, 1.0, 0.0).is_none()); + assert!(crate::shape_stroke(&long, 1.0, 1.0, 0.0).width > 0.0); + } + #[test] fn hostile_rtl_lines_never_panic() { for s in ["\u{202E}%%u\u{05D0}%%", "\u{2067}\u{0644}\u{0627}\u{2069}%%o", "\u{064E}\u{064E}\u{05D0}", "\u{05D0}\u{E000}\u{10FFFF}"] { diff --git a/crates/fonts/src/craft_fonts.rs b/crates/fonts/src/craft_fonts.rs index fb290775f..801b84027 100644 --- a/crates/fonts/src/craft_fonts.rs +++ b/crates/fonts/src/craft_fonts.rs @@ -1,8 +1,8 @@ //! 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). -//! Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`]) +//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular, the Arabic faces and the Thai +//! Regular 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. //! They are copied out of the binary only when first used. @@ -83,6 +83,7 @@ mod tests { let sample = match f.scripts.first().copied() { Some("Jpan") => '\u{3042}', Some("Arab") => '\u{0628}', + Some("Thai") => '\u{0E01}', Some("Hang" | "Kore") => '가', _ => 'A', }; diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 5bbae6883..dd5c37597 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -9,12 +9,14 @@ //! Right-to-left lines (Persian, Arabic, Urdu, Hebrew) go through [`bidi`] (the Unicode //! Bidirectional Algorithm, Arabic joining) and `complex` (OpenType shaping with `harfrust`): //! each run is shaped in the font that draws it before glyphs are placed, so the fallback font -//! drawing Arabic in a stroke-font style joins its letters too. +//! drawing Arabic in a stroke-font style joins its letters too. Thai lines are shaped the same +//! way, which stacks their vowels and tone marks above and below each consonant. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] pub mod bidi; mod complex; +mod linebreak; mod mtext; mod stroke; pub mod subset; @@ -153,7 +155,7 @@ pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Sh let mut under_start: Option = None; let mut over_start: Option = None; let mut gap = stroke::GAP * sc * wf; - if bidi::has_rtl(s) + if complex::needed(s) && let Some(sh) = complex::shape(None, s, h, wf, oblique) { return sh; @@ -244,7 +246,7 @@ pub fn layout_line(s: &str, height: f64, width_factor: f64, oblique: f64) -> Run /// Width of a line without building strokes. pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { - if bidi::has_rtl(s) { + if complex::needed(s) { 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 }; if let Some(sh) = complex::shape(None, s, h, wf, 0.0) { diff --git a/crates/fonts/src/linebreak.rs b/crates/fonts/src/linebreak.rs new file mode 100644 index 000000000..5669db121 --- /dev/null +++ b/crates/fonts/src/linebreak.rs @@ -0,0 +1,205 @@ +//! Line-break opportunities inside Thai text, for MTEXT word wrap. +//! +//! Thai is written without spaces between words (a space ends a phrase or sentence), so a run of +//! Thai can only wrap where one word ends and the next begins. Those places come from the Unicode +//! line breaking algorithm (UAX #14), which leaves Thai to a word segmenter: `icu_segmenter`'s +//! compiled-in LSTM model for Southeast Asian scripts. Only breaks between two Thai characters +//! are used, so text in other scripts wraps at spaces exactly as before. +//! +//! The model rather than ICU's Thai dictionary: after a word the dictionary lacks (names, +//! loanwords such as เมทัลชีท) the dictionary segmenter loses its place and breaks inside the +//! words that follow, even between a consonant and its tone mark (ทแผ|่|นเร|ียบ), where the model +//! breaks at word boundaries and, when unsure, leaves words together (a line then wraps a little +//! early, never mid-word). The model is also a sixth of the dictionary's size. Any break inside +//! a character cluster is still dropped ([`cluster_boundary`]), so a line never starts with a +//! mark or a following vowel and never ends with a leading vowel. +//! +//! The model takes a few microseconds a character and text is laid out again on every display +//! rebuild, so results are kept in a small cache. + +use std::collections::HashMap; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, OnceLock, PoisonError, RwLock}; + +use icu_segmenter::LineSegmenter; +use icu_segmenter::options::LineBreakOptions; + +use crate::complex::is_thai; + +/// Longest text (characters) looked up; longer text (hostile contents) gets no Thai breaks and +/// wraps at spaces only. +const MAX_CHARS: usize = 4_000; + +/// Most texts and bytes of text kept in the cache; it is emptied when either would be passed. +const MAX_CACHED: usize = 8_192; +const MAX_CACHED_BYTES: usize = 4 << 20; + +/// Whether a line may break between Thai characters `prev` and `next` without splitting a +/// character cluster: `next` is no combining mark (vowels above and below, tone marks) and no +/// following vowel or sign (ะ า ำ ๅ, ๆ, ฯ), and `prev` is no leading vowel (เ แ โ ใ ไ), which is +/// written before the consonant it belongs to. +fn cluster_boundary(prev: char, next: char) -> bool { + !crate::bidi::is_mark(next) && !matches!(next, 'ะ' | 'า' | 'ำ' | 'ๅ' | 'ๆ' | 'ฯ') && !matches!(prev, 'เ' | 'แ' | 'โ' | 'ใ' | 'ไ') +} + +/// The line segmenter with the Southeast Asian LSTM models, built once. +fn segmenter() -> &'static icu_segmenter::LineSegmenterBorrowed<'static> { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| LineSegmenter::new_lstm(LineBreakOptions::default())) +} + +#[derive(Default)] +struct Cache { + entries: HashMap>, + bytes: usize, +} + +/// A read-write lock: text is laid out on all cores and nearly every lookup is a hit. +fn cache() -> &'static RwLock { + static CACHE: OnceLock> = OnceLock::new(); + CACHE.get_or_init(|| RwLock::new(Cache::default())) +} + +/// Character offsets in `text`, ascending, where a line may break between two Thai characters +/// (between two Thai words, at a cluster boundary). Empty when `text` has no Thai, is longer than +/// [`MAX_CHARS`], or the segmenter fails. +pub(crate) fn thai_breaks(text: &str) -> Arc<[usize]> { + if !text.chars().any(is_thai) || text.chars().nth(MAX_CHARS).is_some() { + return Arc::default(); + } + if let Some(found) = cache().read().unwrap_or_else(PoisonError::into_inner).entries.get(text) { + return found.clone(); + } + let breaks: Arc<[usize]> = segment(text).into(); + let mut c = cache().write().unwrap_or_else(PoisonError::into_inner); + let bytes = text.len().saturating_add(breaks.len().saturating_mul(std::mem::size_of::())); + if c.entries.len() >= MAX_CACHED || c.bytes.saturating_add(bytes) > MAX_CACHED_BYTES { + c.entries.clear(); + c.bytes = 0; + } + if c.entries.insert(text.to_string(), breaks.clone()).is_none() { + c.bytes = c.bytes.saturating_add(bytes); + } + breaks +} + +/// [`thai_breaks`] without the cache. +fn segment(text: &str) -> Vec { + let chars: Vec<(usize, char)> = text.char_indices().collect(); + // A last-resort guard around the segmenter: a panic in it must not take the drawing down + // (the text then wraps at spaces only). + let bytes: Vec = catch_unwind(AssertUnwindSafe(|| segmenter().segment_str(text).collect())).unwrap_or_default(); + bytes + .into_iter() + .filter_map(|b| chars.binary_search_by_key(&b, |(at, _)| *at).ok()) + .filter(|&i| { + let prev = i.checked_sub(1).and_then(|p| chars.get(p)).map(|(_, c)| *c); + let next = chars.get(i).map(|(_, c)| *c); + matches!((prev, next), (Some(p), Some(n)) if is_thai(p) && is_thai(n) && cluster_boundary(p, n)) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The pieces of `text` between its Thai breaks. + fn words(text: &str) -> Vec { + let chars: Vec = text.chars().collect(); + let mut out = Vec::new(); + let mut from = 0; + for at in thai_breaks(text).iter().copied().chain(std::iter::once(chars.len())) { + out.push(chars.get(from..at).unwrap_or_default().iter().collect()); + from = at; + } + out + } + + #[test] + fn thai_breaks_between_words() { + assert_eq!(words("ภาษาไทย"), ["ภาษา", "ไทย"]); + assert_eq!(words("เหล็กกล่อง"), ["เหล็ก", "กล่อง"]); + assert_eq!(words("น้ำทำให้ไม่ใช่"), ["น้ำ", "ทำ", "ให้", "ไม่", "ใช่"]); + // The sample drawing's specification text, with a loanword (metal sheet) inside: the + // words after it are still whole. + let spec = words("เหล็กกล่องขนาดมาตรฐานสำหรับโครงหลังคาเมทัลชีทแผ่นเรียบสีขาว"); + for w in ["เหล็ก", "กล่อง", "ขนาด", "มาตรฐาน", "สำหรับ", "เมทัล", "ชีท", "สี", "ขาว"] + { + assert!(spec.iter().any(|p| p == w), "{w}: {spec:?}"); + } + let wrong = ["ทแผ", "นเร", "ยบ"]; + assert!(spec.iter().all(|p| !wrong.iter().any(|w| p.starts_with(w))), "{spec:?}"); + } + + /// Words no dictionary has (names, loanwords from the sample drawing): no break splits a + /// character cluster there. + #[test] + fn breaks_never_split_a_character_cluster() { + for text in ["จีรศักดิ์สุพรมวัน", "เมทัลชีทแผ่นเรียบสีขาว", "ศุภประดิษฐ์มาสงค์", "น้ำทำให้ไม่ใช่ๆฯ"] + { + let pieces = words(text); + assert_eq!(pieces.concat(), text); + for w in &pieces { + let first = w.chars().next().unwrap_or(' '); + assert!(!crate::bidi::is_mark(first) && !matches!(first, 'ะ' | 'า' | 'ำ' | 'ๅ' | 'ๆ' | 'ฯ'), "{text}: {pieces:?}"); + assert!(!w.ends_with(['เ', 'แ', 'โ', 'ใ', 'ไ']), "{text}: {pieces:?}"); + } + } + } + + #[test] + fn breaks_inside_a_cluster_are_dropped() { + assert!(cluster_boundary('ก', 'ข') && cluster_boundary('า', 'เ') && cluster_boundary('\u{0E48}', 'น')); + for (prev, next) in [ + ('ก', '\u{0E48}'), + ('ด', '\u{0E34}'), + ('\u{0E34}', '\u{0E4C}'), + ('ช', '\u{0E35}'), + ('ก', 'า'), + ('น', 'ำ'), + ('ก', 'ๆ'), + ('เ', 'ม'), + ('ไ', 'ท'), + ] { + assert!(!cluster_boundary(prev, next), "{prev}|{next}"); + } + } + + #[test] + fn other_scripts_and_mixed_text_keep_their_breaks() { + assert!(thai_breaks("hello world").is_empty()); + assert!(thai_breaks("").is_empty()); + // Between Thai and Latin or digits there is no break added (spaces still break). + let text = "ขนาด50x50mm"; + assert!(thai_breaks(text).is_empty(), "{:?}", thai_breaks(text)); + } + + #[test] + fn hostile_text_never_panics_and_stays_bounded() { + for s in ["\u{0E33}\u{0E33}\u{0E33}", "\u{0E4C}\u{0E49}\u{0E34}", "ก\u{0E49}\u{0E49}\u{0E49}", "ก\u{200B}ข\u{FFFF}\u{10FFFF}ค"] { + let n = s.chars().count(); + assert!(thai_breaks(s).iter().all(|&i| i > 0 && i < n)); + } + assert!(thai_breaks(&"ภาษาไทย".repeat(MAX_CHARS)).is_empty(), "too long: no lookup"); + // The limit is on characters, not bytes (a Thai character is three bytes). + assert!(!thai_breaks(&"ภาษาไทย".repeat(MAX_CHARS / 7)).is_empty()); + let long = "ภาษาไทย".repeat(MAX_CHARS / 8); + let n = long.chars().count(); + let b = thai_breaks(&long); + assert!(!b.is_empty() && b.windows(2).all(|w| w[0] < w[1]) && b.iter().all(|&i| i < n)); + } + + #[test] + fn cached_breaks_match_and_the_cache_stays_bounded() { + let text = "เหล็กกล่องขนาดมาตรฐาน"; + assert_eq!(thai_breaks(text), segment(text).into()); + assert_eq!(thai_breaks(text), thai_breaks(text)); + // Many different texts: the cache empties itself rather than growing. + for i in 0..MAX_CACHED + 10 { + let _ = thai_breaks(&format!("ภาษา{i}ไทย")); + } + let c = cache().read().unwrap_or_else(PoisonError::into_inner); + assert!(c.entries.len() <= MAX_CACHED && c.bytes <= MAX_CACHED_BYTES); + } +} diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index 23736d017..a8d49fcbd 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -407,6 +407,67 @@ fn parse(contents: &str, base: Fmt) -> (Vec, Vec) { (atoms, fmts) } +/// `word` split where a line may wrap inside it: between two Thai words, as Thai writes no +/// spaces between words ([`crate::linebreak::thai_breaks`]). The pieces keep the word's segments +/// and formats in order and are laid out side by side, so the text looks the same and only gains +/// places to wrap. A word without Thai comes back whole. +/// +/// Lines still wrap at spaces first, as before: only a word too wide for a line of its own (which +/// would run out of the column) is split, so text that fits keeps its line breaks, as its author +/// saw them. +fn split_thai(word: Vec<(Seg, usize)>) -> Vec> { + if !word.iter().any(|(seg, _)| matches!(seg, Seg::Text(t) if t.chars().any(crate::complex::is_thai))) { + return vec![word]; + } + // The word's characters, a stacked fraction standing as one object replacement character + // (never next to a Thai break). + let text: String = word + .iter() + .map(|(seg, _)| match seg { + Seg::Text(t) => t.as_str(), + Seg::Stack(..) => "\u{FFFC}", + }) + .collect(); + let breaks = crate::linebreak::thai_breaks(&text); + if breaks.is_empty() { + return vec![word]; + } + let mut pieces = Vec::with_capacity(breaks.len().saturating_add(1)); + let mut breaks = breaks.iter().copied().peekable(); + let mut piece: Vec<(Seg, usize)> = Vec::new(); + // Character offset of the segment being split. + let mut at = 0usize; + for (seg, format) in word { + let Seg::Text(t) = seg else { + piece.push((seg, format)); + at += 1; + continue; + }; + let n = t.chars().count(); + let (mut rest, mut rest_at) = (t.as_str(), at); + while let Some(b) = breaks.next_if(|&b| b < at + n) { + let k = b.saturating_sub(rest_at); + let byte = rest.char_indices().nth(k).map_or(rest.len(), |(i, _)| i); + let (head, tail) = rest.split_at_checked(byte).unwrap_or((rest, "")); + if !head.is_empty() { + piece.push((Seg::Text(head.to_string()), format)); + } + if !piece.is_empty() { + pieces.push(std::mem::take(&mut piece)); + } + (rest, rest_at) = (tail, b.max(rest_at)); + } + if !rest.is_empty() { + piece.push((Seg::Text(rest.to_string()), format)); + } + at += n; + } + if !piece.is_empty() { + pieces.push(piece); + } + pieces +} + fn seg_width(seg: &Seg, f: &Fmt) -> f64 { match seg { Seg::Text(t) => text_width(&f.font, t, f.height, f.wf), @@ -537,6 +598,8 @@ pub fn layout_mtext(contents: &str, insert: Vec2, height: f64, width: f64, attac layout_mtext_with(contents, &MTextParams { insert, height, width, attach, rotation, line_spacing, ..MTextParams::new(insert, height) }) } +/// The lines of MTEXT without paragraph codes: words wrap at spaces to `width` (0: no wrapping), +/// and a word too wide for a line of its own wraps between its Thai words. fn plain_lines(atoms: &[Atom], fmts: &[Fmt], base: &Fmt, width: f64) -> Vec { let fmt = |index: usize| fmts.get(index).unwrap_or(base); let mut lines = Vec::new(); @@ -566,32 +629,44 @@ fn plain_lines(atoms: &[Atom], fmts: &[Fmt], base: &Fmt, width: f64) -> Vec { - let word_width: f64 = segments.iter().map(|(segment, format)| seg_width(segment, fmt(*format))).sum(); - let space_width = - pending_space.map(|format| crate::space_width(&fmt(format).font, fmt(format).height, fmt(format).wf)).unwrap_or(0.0); - if width > 0.0 && !line.items.is_empty() && line.width + space_width + word_width > width + 1e-9 { - finish(&mut lines, &mut line, fmt(last_fmt), paragraph); - } else if !line.items.is_empty() || pending_space.is_some() { - if let Some(format) = pending_space { + Atom::Word(word) => { + let word_width = + |segments: &[(Seg, usize)]| -> f64 { segments.iter().map(|(segment, format)| seg_width(segment, fmt(*format))).sum() }; + // Wider than the column: Thai breaks between its words (see `split_thai`). + let split; + let pieces = if width > 0.0 && word_width(word) > width + 1e-9 { + split = split_thai(word.clone()); + split.as_slice() + } else { + std::slice::from_ref(word) + }; + for segments in pieces { + let word_width = word_width(segments); + let space_width = + pending_space.map(|format| crate::space_width(&fmt(format).font, fmt(format).height, fmt(format).wf)).unwrap_or(0.0); + if width > 0.0 && !line.items.is_empty() && line.width + space_width + word_width > width + 1e-9 { + finish(&mut lines, &mut line, fmt(last_fmt), paragraph); + } else if !line.items.is_empty() || pending_space.is_some() { + if let Some(format) = pending_space { + let at = line.chars; + line.items.push(Item { seg: None, fmt: format, x: line.width, w: space_width, at }); + line.text.push(' '); + line.chars += 1; + } + line.width += space_width; + } + pending_space = None; + for (segment, format) in segments { + let segment_width = seg_width(segment, fmt(*format)); + line.max_h = line.max_h.max(fmt(*format).height); let at = line.chars; - line.items.push(Item { seg: None, fmt: format, x: line.width, w: space_width, at }); - line.text.push(' '); - line.chars += 1; + let plain = seg_plain(segment); + line.chars += plain.chars().count(); + line.text.push_str(&plain); + line.items.push(Item { seg: Some(segment.clone()), fmt: *format, x: line.width, w: segment_width, at }); + line.width += segment_width; + last_fmt = *format; } - line.width += space_width; - } - pending_space = None; - for (segment, format) in segments { - let segment_width = seg_width(segment, fmt(*format)); - line.max_h = line.max_h.max(fmt(*format).height); - let at = line.chars; - let plain = seg_plain(segment); - line.chars += plain.chars().count(); - line.text.push_str(&plain); - line.items.push(Item { seg: Some(segment.clone()), fmt: *format, x: line.width, w: segment_width, at }); - line.width += segment_width; - last_fmt = *format; } } } @@ -608,10 +683,10 @@ pub fn layout_mtext_with(contents: &str, p: &MTextParams) -> MTextLayout { 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 (atoms, fmts) = parse(contents, base.clone()); if para::needed(contents, p) { return para::layout(contents, p, &base); } + let (atoms, fmts) = parse(contents, base.clone()); let fmt = |i: usize| fmts.get(i).unwrap_or(&base); let mut lines = plain_lines(&atoms, &fmts, &base, width); // Right-to-left text: each line in display order, its paragraph's direction from the @@ -875,5 +950,89 @@ mod tests { } let long = "word ".repeat(5000); assert!(lay(&long, 10.0).lines.len() > 100); + // Thai with stacks, format runs, stray marks and unpaired braces in one word. + for s in ["ก\\S1/2;ข{\\C1;ภาษา}ไทย\u{0E4C}\u{0E4C}", "{\\H2x;ภาษา}{\\H3x;ไทย}", "\u{0E33}\u{0E49}\\S/;ไทย}}", "ภาษาไทย\tภาษาไทย"] + { + let _ = lay(s, 0.5); + let _ = lay(&format!("\\pi1,l2,t3;{s}"), 0.5); + } + // Too long to look up: one unbreakable word, like a long Latin word. + assert_eq!(lay(&"ภาษาไทย".repeat(20_000), 3.0).lines.len(), 1); + } + + /// Thai writes no spaces between words: a long line wraps between words, in the plain and the + /// paragraph layout, without fonts installed (the line breaks don't depend on glyph widths). + #[test] + fn thai_wraps_between_words() { + let text = "เหล็กกล่องขนาดมาตรฐานสำหรับโครงหลังคาเมทัลชีทแผ่นเรียบสีขาว"; + let one = lay(text, 0.0); + assert_eq!(one.lines, vec![text]); + let wide = one.bounds.width(); + for contents in [text.to_string(), format!("\\pi0,l0;{text}"), format!("{{\\C1;เหล็กกล่อง}}{}", text.trim_start_matches("เหล็กกล่อง"))] + { + let l = lay(&contents, wide / 3.0); + assert!(l.lines.len() >= 3, "{contents}: {:?}", l.lines); + assert_eq!(l.lines.concat(), text, "nothing lost or added: {:?}", l.lines); + for line in &l.lines { + let first = line.chars().next().unwrap_or(' '); + assert!(!crate::bidi::is_mark(first) && !matches!(first, 'ะ' | 'า' | 'ำ'), "{line}"); + assert!(!line.ends_with(['เ', 'แ', 'โ', 'ใ', 'ไ']), "{line}"); + } + } + // The pieces sit side by side with nothing between them: drawn with a Thai font they are + // as wide as the word laid out in one piece (up to kerning). + let pieces = split_thai(vec![(Seg::Text(text.to_string()), 0)]); + if one.pieces.iter().any(|p| !p.shaped.glyphs.is_empty()) { + let base = Fmt { font: TextFont::Stroke, height: 1.0, color: None, under: false, over: false, wf: 1.0, oblique: 0.0, valign: 1 }; + let sum: f64 = pieces.iter().flatten().map(|(seg, _)| seg_width(seg, &base)).sum(); + assert!((sum - wide).abs() < 0.01 * wide, "{sum} {wide}"); + } + assert!(pieces.len() > 3); + // Latin and other words stay whole; stacks keep their place. + assert_eq!(split_thai(vec![(Seg::Text("hello".into()), 0)]).len(), 1); + let mixed = split_thai(vec![(Seg::Text("ภาษา".into()), 0), (Seg::Stack("1".into(), "2".into(), '/'), 0), (Seg::Text("ภาษาไทย".into()), 1)]); + let flat: Vec = mixed.iter().map(|p| p.iter().map(|(s, _)| seg_plain(s)).collect()).collect(); + assert_eq!(flat, ["ภาษา1/2ภาษา", "ไทย"]); + } + + /// A Thai run that would fit a line at the left indent but not after a first-line indent or a + /// leading tab still breaks between its words instead of running out of the column. The indent + /// is well over the slack: with no Thai font the stroke font's pieces are narrower than the run + /// (each loses its trailing letter gap). + #[test] + fn thai_wraps_after_first_line_indent_and_tab() { + let text = "เหล็กกล่องขนาดมาตรฐานสำหรับโครงหลังคา"; + let wide = lay(text, 0.0).bounds.width(); + for contents in [format!("\\pi4,l0;{text}"), format!("\\pxt4;\t{text}")] { + let l = lay(&contents, wide + 1.0); + assert!(l.lines.len() >= 2, "{contents}: {:?}", l.lines); + assert_eq!(l.lines.concat().trim_start(), text, "{contents}: {:?}", l.lines); + } + } + + /// Text that fits at its spaces keeps those line breaks: a note from the sample drawing + /// (frame, box section 50x50 mm, painted white) at every column width from one word up never + /// breaks inside ทาสีขาว or any other spaced word, in the plain and the paragraph layout. + #[test] + fn spaced_thai_keeps_its_space_breaks() { + let text = "โครงแนวนอน เหล็กกล่อง ขนาด 50x50 mm. ทาสีขาว"; + let words: Vec<&str> = text.split(' ').collect(); + let widest = words.iter().map(|w| lay(w, 0.0).bounds.width()).fold(0.0, f64::max); + let full = lay(text, 0.0).bounds.width(); + let mut width = widest * 1.001; + while width < full * 1.05 { + for contents in [text.to_string(), format!("\\pxql;\\A1;{text}")] { + let l = lay(&contents, width); + assert_eq!(l.lines.join(" "), text, "{width}: {:?}", l.lines); + assert!(l.lines.iter().flat_map(|line| line.split(' ')).all(|w| words.contains(&w)), "{width}: {:?}", l.lines); + } + width *= 1.05; + } + // After a Latin word, a Thai run too long for any line breaks between its words, filling + // the line it starts on. + let long = "เหล็กกล่องขนาดมาตรฐานสำหรับโครงหลังคา"; + let l = lay(&format!("abc {long}"), lay(long, 0.0).bounds.width() / 2.0); + assert!(l.lines.len() >= 3 && l.lines.first().is_some_and(|f| f.starts_with("abc ") && f.len() > 4), "{:?}", l.lines); + assert_eq!(l.lines.concat(), format!("abc {long}")); } } diff --git a/crates/fonts/src/mtext/para.rs b/crates/fonts/src/mtext/para.rs index 064e62d02..c3b6da3e6 100644 --- a/crates/fonts/src/mtext/para.rs +++ b/crates/fonts/src/mtext/para.rs @@ -7,7 +7,7 @@ use cadcraft_geom::{Bounds2, Vec2}; -use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, arg, num, parse, seg_plain, seg_shape, seg_width}; +use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, arg, num, parse, seg_plain, seg_shape, seg_width, split_thai}; /// Columns an MTEXT's text flows through, each as wide as the MTEXT's width. #[derive(Clone, Debug, Default, PartialEq)] @@ -512,8 +512,34 @@ impl<'a> LineBuilder<'a> { } } + /// Place a word (`index` > 0: the part of a word after a tab, with no space before it). A + /// word too wide for a line of its own breaks between its Thai words (see `split_thai`). fn push_text(&mut self, index: usize, segments: &[(Seg, usize)]) { - let word_width: f64 = segments.iter().map(|(segment, format)| seg_width(segment, self.format(*format))).sum(); + // An empty line can't wrap, so the word gets the room from where the line starts (a + // first-line indent or a tab stop); otherwise it can wrap to a line at the left indent. + let room = { + let props = self.paragraphs.props(self.paragraph); + let start = if self.line.items.is_empty() { self.line.width } else { props.left.max(0.0) }; + self.available_width(props) - start + }; + if self.width > 0.0 && self.word_width(segments) > room + 1e-9 { + for (k, piece) in split_thai(segments.to_vec()).iter().enumerate() { + self.place(if k == 0 { index } else { index.max(1) }, piece); + } + } else { + self.place(index, segments); + } + } + + /// Width of a word's segments, each in its format. + fn word_width(&self, segments: &[(Seg, usize)]) -> f64 { + segments.iter().map(|(segment, format)| seg_width(segment, self.format(*format))).sum() + } + + /// Put a word, or a piece of one, on the current line after any pending space, or start a + /// new line when it doesn't fit (`index` as in [`Self::push_text`]). + fn place(&mut self, index: usize, segments: &[(Seg, usize)]) { + let word_width = self.word_width(segments); let space_width = if index == 0 { self.pending_space .map(|format| crate::space_width(&self.format(format).font, self.format(format).height, self.format(format).wf)) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 9c1888aa8..c426db243 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -74,6 +74,12 @@ impl Face { pub fn has_glyph(&self, c: char) -> bool { self.font().is_some_and(|f| f.charmap().map(c).is_some()) } + /// 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()] }; + let map = f.charmap(); + chars.iter().map(|c| map.map(*c).map(|g| g.to_u32())).collect() + } fn names(&self) -> Vec { let Some(f) = self.font() else { return Vec::new() }; [skrifa::string::StringId::FAMILY_NAME, skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FULL_NAME] @@ -155,14 +161,58 @@ const ARABIC_FALLBACK: &[&str] = &[ "dejavusans", ]; const HEBREW_FALLBACK: &[&str] = &["notosanshebrew", "notoserifhebrew", "arial", "tahoma", "segoeui", "dejavusans"]; +/// Fonts known to cover Thai, with the OpenType mark positioning its stacked vowels and tone +/// marks need. First the Windows faces Thai drawings are laid out with (Cordia New, Angsana New, +/// Browallia New: Thai SHX fonts such as `cordia2.shx` copy their design and widths, so text +/// keeps its fit in title blocks and tables), then IBM Plex Sans Thai (installed, or embedded +/// from craft-fonts, which makes it the web build's Thai font), then Noto and the fonts each OS +/// ships (macOS Thonburi and Sukhumvit, Windows Leelawadee and Tahoma, the Linux TLWG fonts). +/// Matched as parts of file names: `angsa` and `browa` find both today's Windows collections +/// (`angsana.ttc`, `browalia.ttc`) and the older single faces (`angsa.ttf`, `browab.ttf`). +const THAI_FALLBACK: &[&str] = &[ + "cordia", + "angsa", + "browa", + "ibmplexsansthai", + "notosansthai", + "notoserifthai", + "thonburi", + "sukhumvit", + "leelawui", + "leelawadeeui", + "leelawad", + "tahoma", + "kinnari", + "norasi", + "garuda", + "loma", + "waree", + "sarabun", +]; /// Script-specific fallback files loaded per character, at most. const MAX_SCRIPT_FILES: usize = 4; +/// The font file stems matching a script's fallback `names`, best first: regular weights before +/// bold, light and the like, then in the order of `names`, then by name. +fn script_candidates(stems: &[String], names: &[&str]) -> Vec { + let mut v: Vec<(usize, usize, String)> = stems + .iter() + .filter_map(|s| { + let n = norm(s); + names.iter().position(|p| n.contains(p)).map(|pref| (weight_penalty(s, ""), pref, s.clone())) + }) + .collect(); + v.sort(); + v.dedup_by(|a, b| a.2 == b.2); + v.into_iter().map(|(_, _, s)| s).collect() +} + /// Script-specific fallback font names for `c`, if any. fn script_fallback(c: char) -> &'static [&'static str] { match c { '\u{0600}'..='\u{08FF}' | '\u{FB50}'..='\u{FDFF}' | '\u{FE70}'..='\u{FEFF}' => ARABIC_FALLBACK, '\u{0590}'..='\u{05FF}' | '\u{FB1D}'..='\u{FB4F}' => HEBREW_FALLBACK, + '\u{0E00}'..='\u{0E7F}' => THAI_FALLBACK, _ => &[], } } @@ -362,18 +412,8 @@ impl Db { if names.is_empty() { return None; } - let mut stems: Vec<(usize, usize, String)> = self - .paths - .keys() - .chain(self.files.keys()) - .filter_map(|s| { - let n = norm(s); - names.iter().position(|p| n.contains(p)).map(|pref| (weight_penalty(s, ""), pref, s.clone())) - }) - .collect(); - stems.sort(); - stems.dedup_by(|a, b| a.2 == b.2); - for (_, _, stem) in stems.into_iter().take(MAX_SCRIPT_FILES) { + let stems: Vec = self.paths.keys().chain(self.files.keys()).cloned().collect(); + for stem in script_candidates(&stems, names).into_iter().take(MAX_SCRIPT_FILES) { let Some(bytes) = self.file(&stem) else { continue }; let Some(face) = faces(&bytes).into_iter().find(|f| f.has_glyph(c)) else { continue }; if let Some(i) = self.fallback.faces.iter().position(|f| f.same(&face)) { @@ -855,7 +895,7 @@ pub(crate) fn place_glyph_at(g: &GlyphOutline, origin: Vec2, scale: f64, wf: f64 /// Characters the face lacks come from a fallback font, scaled to its own cap height. pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) -> Option { face.font()?; - if crate::bidi::has_rtl(s) + if crate::complex::needed(s) && let Some(sh) = crate::complex::shape(Some(face), s, height, width_factor, oblique) { return Some(sh); @@ -893,7 +933,7 @@ pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) /// Width of one line set in a TrueType face. pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option { face.font()?; - if crate::bidi::has_rtl(s) + if crate::complex::needed(s) && let Some(sh) = crate::complex::shape(Some(face), s, height, width_factor, 0.0) { return Some(sh.width); @@ -923,6 +963,40 @@ pub fn layout_line(face: &Face, s: &str, height: f64, width_factor: f64, oblique mod family_tests { use super::*; + #[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 + // files with the CJK fonts first, none of which has Thai. + for c in ['\u{0E01}', '\u{0E33}', '\u{0E34}', '\u{0E4C}', '\u{0E50}'] { + assert!(script_fallback(c).contains(&"notosansthai"), "{c}"); + } + assert!(script_fallback('a').is_empty() && script_fallback('\u{0E80}').is_empty()); + // Windows, macOS and Linux each ship one of them under these file names. + let stems: Vec = ["LeelawUI", "Thonburi", "Loma", "msyh"].map(norm).to_vec(); + assert!(stems.iter().filter(|s| THAI_FALLBACK.iter().any(|p| s.contains(p))).count() == 3); + // The faces Thai drawings are laid out with come first, then IBM Plex Sans Thai (an + // installed file or the craft-fonts face, both under this stem), then the others; regular + // weights before bold. + let stems: Vec = + ["notosansthai-regular", "ibmplexsansthai-bold", "ibmplexsansthai-regular", "msyh", "cordiab", "cordia", "ibmplexsansthailooped-regular"] + .map(String::from) + .to_vec(); + assert_eq!( + script_candidates(&stems, THAI_FALLBACK), + ["cordia", "cordiab", "ibmplexsansthai-regular", "ibmplexsansthailooped-regular", "notosansthai-regular", "ibmplexsansthai-bold"] + ); + // A text style naming the family looks in its regular file first, not the Latin Plex + // Sans or the looped or bold variants. + let stems: Vec = ["ibmplexsans-regular", "ibmplexsansthai-bold", "ibmplexsansthailooped-regular", "ibmplexsansthai-regular", "arial"] + .map(String::from) + .to_vec(); + let found = family_candidates(&stems, &norm("IBM Plex Sans Thai"), "ibm"); + assert_eq!(found.first().map(String::as_str), Some("ibmplexsansthai-regular"), "{found:?}"); + // Angsana New and Browallia New under today's Windows file names and the older ones. + let stems: Vec = ["browa", "notosansthai-regular", "angsana", "browalia", "angsa", "arial"].map(String::from).to_vec(); + assert_eq!(script_candidates(&stems, THAI_FALLBACK), ["angsa", "angsana", "browa", "browalia", "notosansthai-regular"]); + } + #[test] fn a_family_is_looked_for_in_files_starting_with_its_first_word() { let stems: Vec = ["gost", "gost2304a", "gost common", "arial", "isocpeur"].map(String::from).to_vec(); From c72c0eebfb445abddc35e159efbbd153d851c608 Mon Sep 17 00:00:00 2001 From: Andrea Ficarra Date: Sun, 1 Nov 2026 20:38:04 +0100 Subject: [PATCH 347/900] SAVEAS portableFonts: Windows fonts for Linux text style fonts (#2576) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * SAVEAS portableFonts: Windows fonts for Linux text style fonts A text style using a Linux TrueType font (Liberation, DejaVu, Open Sans) shows in AutoCAD on Windows with a substitute it picks. A save now names those styles on the command line (and as `nonPortableFonts` in the result), and SAVEAS {"portableFonts": true} writes the Windows equivalent in the file (Liberation -> Arial, Times New Roman, Courier New; DejaVu Sans -> Verdana; Open Sans -> Arial) while the drawing keeps its own fonts. Narrow and condensed families have no Windows stand-in (Arial Narrow comes with Office) and are kept and named. QSAVE takes no SAVEAS options. Tests: stand_in_tests in cmd/file.rs, tests/save_portable_fonts.rs. Co-Authored-By: Claude Opus 5.5 * Portable fonts kept in the file, applied by the writer Reworked after review. SAVEAS `portableFonts` writes a copy of the drawing with `Drawing::portable_fonts` set, and the DXF/DWG writer turns each style's Linux font into its Windows font, keeping the style's own font in the CADCraft FONT xdata already used for the built-in font. Reading the file gives the Linux fonts back (unless the font was changed since, in AutoCAD); the drawing itself is never changed. It applies to that save: a later QSAVE writes the drawing's fonts and says so, naming the styles and SAVEAS portableFonts. The family table moves to `cadcraft_fonts::windows`, used by the writer and the note. Styles from an xref aren't saved and aren't named. The parity docs are left to the maintainers (CLAUDE.md). Tests: crates/io/tests/it/portable_fonts.rs (DXF, DWG, a font changed in AutoCAD), crates/engine/tests/save_portable_fonts.rs, windows.rs tests. Co-Authored-By: Claude Opus 5.5 * Portable fonts: match the Windows font by file name A STYLE whose Windows font carries a path (C:\Windows\Fonts\…) still gets its own font back. Co-Authored-By: Claude Opus 5.5 * Portable fonts: say the font list again only when it changes A save still returns nonPortableFonts, but the command line note isn't repeated on every QSAVE of the same drawing. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/lib.rs | 5 ++ crates/engine/src/cmd/file.rs | 59 ++++++++++++++-- crates/engine/src/doc_state.rs | 4 ++ crates/engine/tests/save_portable_fonts.rs | 54 ++++++++++++++ crates/fonts/src/lib.rs | 1 + crates/fonts/src/windows.rs | 82 ++++++++++++++++++++++ crates/io/src/dxf_read/tables.rs | 10 +-- crates/io/src/dxf_write/sections.rs | 7 +- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/portable_fonts.rs | 59 ++++++++++++++++ 10 files changed, 268 insertions(+), 14 deletions(-) create mode 100644 crates/engine/tests/save_portable_fonts.rs create mode 100644 crates/fonts/src/windows.rs create mode 100644 crates/io/tests/it/portable_fonts.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index e07a08609..8f2a1e2e4 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -132,6 +132,10 @@ pub struct Drawing { /// Records of the file this drawing was read from that the reader could not place (a damaged /// file), counted by the section they came from. Never written to a file. pub skipped_records: BTreeMap, + /// A save option, set on the copy SAVEAS `portableFonts` writes: the file gets Windows fonts + /// for the Linux fonts of text styles, and each style keeps its own in CADCraft xdata, so the + /// drawing reopens with it. Never set on an open drawing. + pub portable_fonts: bool, } impl Default for Drawing { @@ -191,6 +195,7 @@ impl Drawing { read_notes: Vec::new(), refedit: None, skipped_records: BTreeMap::new(), + portable_fonts: false, } } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 1c3fbd5c8..234769ad4 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -85,12 +85,13 @@ pub fn deliver() -> Option { DELIVER.get().copied() } -/// How a drawing file is written: its version (`None`: the drawing's own, `$ACADVER`) and -/// binary instead of ASCII DXF. +/// How a drawing file is written: its version (`None`: the drawing's own, `$ACADVER`), binary +/// instead of ASCII DXF, and Windows fonts for Linux ones ([`cadcraft_doc::Drawing::portable_fonts`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct SaveAs { pub version: Option, pub binary: bool, + pub portable_fonts: bool, } /// Write a drawing with [`SaveAs`] options (installed by hosts whose writer supports them). @@ -131,7 +132,12 @@ fn save_options(cmd: &str, p: &Value) -> Result { Some(Value::Bool(b)) => *b, Some(_) => return Err(bad(cmd, "`binary` must be true or false")), }; - Ok(SaveAs { version, binary }) + let portable_fonts = match p.get("portableFonts") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`portableFonts` must be true or false")), + }; + Ok(SaveAs { version, binary, portable_fonts }) } /// Whether `path` names a DXF file (or has no extension, which saves as DXF). @@ -148,7 +154,9 @@ fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result Vec { CommandSpec::new("saveas", "Save As...", run_saveas_reporting) .menu(&["File", "Save As..."]) .key("Cmd+Shift+S") - .params("{path, version?: 2000|2004|2007|2010|2013|2018, binary?: bool}") + .params( + "{path, version?: 2000|2004|2007|2010|2013|2018, binary?: bool, portableFonts?: bool (Windows fonts for Linux ones, in this file)}", + ) .noundo(), CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(), CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes) - .params("{format?: dxf, version?: 2000…2018, binary?: bool} → {data: base64}") + .params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64}") .noundo(), CommandSpec::new("script", "Run Script...", run_script) .menu(&["Tools", "Run Script..."]) @@ -395,7 +405,7 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result { } pub(crate) fn save_to(s: &mut Session, path: &str) -> Result { - let opts = SaveAs { version: None, binary: s.state()?.binary_dxf && is_dxf(path) }; + let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() }; save_as(s, "save", path, &opts) } @@ -677,6 +687,7 @@ fn run_saveas(s: &mut Session, p: &Value) -> Result { if is_drawing_file(&path) { r["version"] = json!(opts.version.unwrap_or_else(|| drawing_version(s, &path)).year()); r["binary"] = json!(opts.binary); + r["portableFonts"] = json!(opts.portable_fonts); } Ok(r) } @@ -799,9 +810,43 @@ fn save_reporting(s: &mut Session, p: &Value, run: fn(&mut Session, &Value) -> R if r.get("path").and_then(Value::as_str).is_some_and(drops_unknown) { report_not_saved(s, &mut r, &lost); } + if r.get("path").and_then(Value::as_str).is_some_and(is_drawing_file) { + report_fonts(s, &mut r); + } Ok(r) } +/// Name the text styles whose font in the saved file AutoCAD on Windows doesn't have: in the +/// result, and at the command line when the list changed since the last save. Styles from an xref +/// (`XREF|name`) aren't saved: AutoCAD takes them from the xref. +fn report_fonts(s: &mut Session, r: &mut Value) { + use cadcraft_fonts::windows::{missing_on_windows, windows_font, written_font}; + let portable = r.get("portableFonts").and_then(Value::as_bool).unwrap_or(false); + let Ok(d) = s.state().map(|st| st.drawing()) else { return }; + let fonts: Vec<(String, String)> = d + .text_styles + .iter() + .filter(|t| !t.name.contains('|') && missing_on_windows(written_font(&t.font, portable))) + .map(|t| (t.name.clone(), t.font.clone())) + .collect(); + let list = fonts.iter().map(|(style, font)| format!("{style} ({font})")).collect::>().join(", "); + let changed = s.state_mut().map(|st| std::mem::replace(&mut st.fonts_noted, list.clone()) != list).unwrap_or(true); + if fonts.is_empty() { + return; + } + if changed { + let hint = if fonts.iter().any(|(_, font)| windows_font(font).is_some()) { + " SAVEAS with portableFonts writes Windows fonts for those that have one." + } else { + "" + }; + s.echo(format!("Fonts AutoCAD on Windows doesn't have: {list}.{hint}")); + } + if let Some(o) = r.as_object_mut() { + o.insert("nonPortableFonts".into(), json!(fonts.iter().map(|(style, font)| json!({ "style": style, "font": font })).collect::>())); + } +} + fn run_qsave_reporting(s: &mut Session, p: &Value) -> Result { save_reporting(s, p, run_save) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index c70989a58..d11c6f0eb 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -35,6 +35,9 @@ 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, + /// The fonts missing on Windows that a save last named: the next save names them again only + /// when they change. + pub(crate) fonts_noted: String, } static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -61,6 +64,7 @@ impl DocState { uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), binary_dxf: false, block_edit: None, + fonts_noted: String::new(), } } /// The drawing has changes not saved to its file, or the Block Editor has changes not yet diff --git a/crates/engine/tests/save_portable_fonts.rs b/crates/engine/tests/save_portable_fonts.rs new file mode 100644 index 000000000..a63016d60 --- /dev/null +++ b/crates/engine/tests/save_portable_fonts.rs @@ -0,0 +1,54 @@ +//! Text styles with Linux fonts AutoCAD on Windows doesn't have: a save names them, and SAVEAS +//! with portableFonts writes Windows fonts in that file while the drawing keeps its own. + +use cadcraft_doc::{Drawing, TextStyle}; +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use serde_json::json; + +fn dxf(d: &Drawing, _: &str) -> Result, String> { + Ok(cadcraft_io::write_dxf(d).into_bytes()) +} + +fn session() -> Session { + set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: dxf, plot: None }); + let mut d = Drawing::new_metric(); + for (name, font) in [("Notes", "DejaVuSans.ttf"), ("Plain", "arial.ttf"), ("Tight", "Liberation Sans Narrow")] { + d.text_styles.push(TextStyle { name: name.into(), font: font.into(), ..TextStyle::default() }); + } + let mut s = Session::empty(); + s.open_drawing(d, "fonts.dxf", None); + s +} + +#[test] +fn portable_fonts_writes_windows_fonts_in_that_file() { + let mut s = session(); + let dir = std::env::temp_dir().join(format!("cadcraft-portable-fonts-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = |name: &str| dir.join(name).to_string_lossy().to_string(); + let file = |name: &str| std::fs::read_to_string(dir.join(name)).unwrap(); + let both = json!([{ "style": "Notes", "font": "DejaVuSans.ttf" }, { "style": "Tight", "font": "Liberation Sans Narrow" }]); + + // portableFonts writes Verdana for DejaVu Sans; the narrow style has no Windows font. + let r = s.execute("saveas", &json!({ "path": path("portable.dxf"), "portableFonts": true })).unwrap(); + assert_eq!(r["nonPortableFonts"], json!([{ "style": "Tight", "font": "Liberation Sans Narrow" }])); + assert_eq!(s.log.last().map(String::as_str), Some("Fonts AutoCAD on Windows doesn't have: Tight (Liberation Sans Narrow).")); + assert!(file("portable.dxf").contains("verdana.ttf")); + assert!(s.state().unwrap().drawing().text_styles.iter().any(|t| t.font == "DejaVuSans.ttf"), "the drawing keeps its fonts"); + + // A later save without it writes the drawing's fonts again, and says so. + let r = s.execute("qsave", &json!({})).unwrap(); + assert_eq!(r["nonPortableFonts"], both); + assert!(s.log.last().is_some_and(|l| l.ends_with("SAVEAS with portableFonts writes Windows fonts for those that have one.")), "{:?}", s.log); + assert!(!file("portable.dxf").contains("verdana.ttf")); + + // The same list isn't said again on every save. + let lines = s.log.len(); + let r = s.execute("qsave", &json!({})).unwrap(); + assert_eq!(r["nonPortableFonts"], both); + assert!(s.log.iter().skip(lines).all(|l| !l.starts_with("Fonts AutoCAD")), "{:?}", s.log); + + assert!(s.execute("saveas", &json!({ "path": path("bad.dxf"), "portableFonts": "yes" })).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index dd5c37597..beb8996ff 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -21,6 +21,7 @@ mod mtext; mod stroke; pub mod subset; pub mod ttf; +pub mod windows; use cadcraft_geom::{Bounds2, Vec2}; diff --git a/crates/fonts/src/windows.rs b/crates/fonts/src/windows.rs new file mode 100644 index 000000000..729a2eea0 --- /dev/null +++ b/crates/fonts/src/windows.rs @@ -0,0 +1,82 @@ +//! Linux font families that AutoCAD on Windows doesn't have, and the Windows fonts a drawing +//! saved with portable fonts gets instead. + +/// Family key (lower case, without spaces, hyphens or underscores; a longer key before a shorter +/// one it starts with) and the Windows fonts for its regular, bold, italic and bold italic styles. +const FAMILIES: [(&str, [&str; 4]); 7] = [ + ("liberationsans", ["arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf"]), + ("liberationserif", ["times.ttf", "timesbd.ttf", "timesi.ttf", "timesbi.ttf"]), + ("liberationmono", ["cour.ttf", "courbd.ttf", "couri.ttf", "courbi.ttf"]), + ("opensans", ["arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf"]), + ("dejavusansmono", ["cour.ttf", "courbd.ttf", "couri.ttf", "courbi.ttf"]), + ("dejavusans", ["verdana.ttf", "verdanab.ttf", "verdanai.ttf", "verdanaz.ttf"]), + ("dejavuserif", ["times.ttf", "timesbd.ttf", "timesi.ttf", "timesbi.ttf"]), +]; + +/// The family of a TrueType `font` (file or family name) from [`FAMILIES`], with the rest of its +/// key (the style: `bold`, `italic`, …). +fn family(font: &str) -> Option<(&'static [&'static str; 4], String)> { + let name = font.trim().rsplit(['/', '\\']).next().unwrap_or_default().to_lowercase(); + let stem = name.strip_suffix(".ttf").or_else(|| name.strip_suffix(".otf")).unwrap_or(&name); + if stem.contains('.') { + return None; // another kind of file, such as an SHX font + } + let key: String = stem.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).collect(); + let (family, fonts) = FAMILIES.iter().find(|(f, _)| key.starts_with(f))?; + Some((fonts, key.get(family.len()..).unwrap_or_default().to_string())) +} + +/// Whether `font` is a Linux font AutoCAD on Windows doesn't have. +pub fn missing_on_windows(font: &str) -> bool { + family(font).is_some() +} + +/// The Windows font for a Linux `font`. Narrow and condensed styles have none (Arial Narrow comes +/// with Office, not with Windows). +pub fn windows_font(font: &str) -> Option<&'static str> { + let (fonts, style) = family(font)?; + if style.contains("narrow") || style.contains("condensed") { + return None; + } + let bold = style.contains("bold"); + let italic = style.contains("italic") || style.contains("oblique"); + fonts.get(usize::from(bold) + 2 * usize::from(italic)).copied() +} + +/// The font a drawing file gets for a text style's `font`: with `portable`, the Windows font for +/// a Linux one. +pub fn written_font(font: &str, portable: bool) -> &str { + if portable { windows_font(font).unwrap_or(font) } else { font } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_fonts_by_file_or_family_name() { + assert_eq!(windows_font("DejaVuSans.ttf"), Some("verdana.ttf")); + assert_eq!(windows_font("/usr/share/fonts/truetype/LiberationSerif-Bold.ttf"), Some("timesbd.ttf")); + assert_eq!(windows_font("Liberation Mono"), Some("cour.ttf")); + assert_eq!(windows_font("LiberationMono-BoldItalic.ttf"), Some("courbi.ttf")); + assert_eq!(windows_font("OpenSans-SemiBold.ttf"), Some("arialbd.ttf")); + assert_eq!(windows_font("Open Sans"), Some("arial.ttf")); + assert_eq!(windows_font("DejaVuSansMono-BoldOblique.ttf"), Some("courbi.ttf")); + assert_eq!(windows_font("DejaVuSerif-Italic.ttf"), Some("timesi.ttf")); + // Narrow and condensed styles are Linux fonts with no Windows one. + for font in ["Liberation Sans Narrow", "LiberationSansNarrow-Bold.ttf", "OpenSans-CondensedBold.ttf", "DejaVuSansCondensed.ttf"] { + assert!(missing_on_windows(font) && windows_font(font).is_none(), "{font}"); + } + // Fonts AutoCAD has, other kinds of file, or names that aren't fonts. + for font in ["arial.ttf", "txt", "dejavusans.shx", "", "/", "Liberation"] { + assert!(!missing_on_windows(font) && windows_font(font).is_none(), "{font}"); + } + } + + #[test] + fn written_font_only_changes_with_portable_fonts() { + assert_eq!(written_font("DejaVuSans.ttf", true), "verdana.ttf"); + assert_eq!(written_font("DejaVuSans.ttf", false), "DejaVuSans.ttf"); + assert_eq!(written_font("Liberation Sans Narrow", true), "Liberation Sans Narrow"); + } +} diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 8a57f7f9e..ee42b8a58 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -4,6 +4,7 @@ use super::{ Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3, VportConfig, VportTile, records, }; +use cadcraft_fonts::windows::windows_font; pub(super) fn header(tags: &[Tag], d: &mut Drawing) { let mut i = 0; @@ -66,9 +67,9 @@ fn annotative(tags: &[Tag]) -> bool { } /// A text style's font: CADCraft's own font name from `CADCRAFT` xdata (`1000 FONT`, name) -/// while the font file is still the `txt` written for other readers; the TrueType family of the -/// style's `ACAD` xdata (`1000` typeface) when it has no font file (how AutoCAD stores TrueType -/// styles); otherwise the file. +/// while the font file is still the `txt` or Windows font written for other readers; the TrueType +/// family of the style's `ACAD` xdata (`1000` typeface) when it has no font file (how AutoCAD +/// stores TrueType styles); otherwise the file. fn style_font(tags: &[Tag], file: String) -> String { if file.trim().is_empty() && let Some(face) = @@ -82,8 +83,9 @@ fn style_font(tags: &[Tag], file: String) -> String { _ => None, }); let stem = file.trim().to_ascii_lowercase(); + let base = stem.rsplit(['/', '\\']).next().unwrap_or_default(); match own { - Some(name) if !name.trim().is_empty() && (stem == "txt" || stem == "txt.shx") => name, + Some(name) if !name.trim().is_empty() && (stem == "txt" || stem == "txt.shx" || windows_font(&name) == Some(base)) => name, _ => file, } } diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 9a21ef7a9..2d45a532f 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -90,9 +90,10 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap w.f(50, s.oblique.to_degrees()); w.i(71, if s.backwards { 2 } else { 0 } | if s.upside_down { 4 } else { 0 }); w.f(42, 0.2); - // The built-in font goes out as `txt`, which every reader has; CADCraft's own name - // travels in `CADCRAFT` xdata (`1000 FONT`, name) so the style reopens with it. - let file = if s.font == cadcraft_fonts_name() { "txt" } else { s.font.as_str() }; + // The built-in font goes out as `txt`, which every reader has, and a Linux font as its + // Windows one with portable fonts; CADCraft's own name travels in `CADCRAFT` xdata + // (`1000 FONT`, name) so the style reopens with it. + let file = if s.font == cadcraft_fonts_name() { "txt" } else { cadcraft_fonts::windows::written_font(&s.font, d.portable_fonts) }; w.s(3, file); w.s(4, &s.big_font); if s.annotative { diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 52f37068a..e0ff04f97 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -54,6 +54,7 @@ mod pdf_read; mod plot_layout_scale; mod plot_model_png_scale; mod plot_styles; +mod portable_fonts; mod region_roundtrip; mod roundtrip; mod roundtrip_audit; diff --git a/crates/io/tests/it/portable_fonts.rs b/crates/io/tests/it/portable_fonts.rs new file mode 100644 index 000000000..070c376e8 --- /dev/null +++ b/crates/io/tests/it/portable_fonts.rs @@ -0,0 +1,59 @@ +//! Portable fonts: a drawing saved with them gets the Windows font for each Linux font in its +//! STYLE table, keeps its own in CADCraft xdata, and reopens with it, from DXF and DWG. + +use cadcraft_doc::{Drawing, TextStyle}; +use cadcraft_io::{read, read_dxf, write, write_dxf}; + +fn drawing(portable_fonts: bool) -> Drawing { + let mut d = Drawing { portable_fonts, ..Drawing::new_metric() }; + // A Linux font, and one with no Windows font. + for (name, font) in [("Notes", "DejaVuSans-Bold.ttf"), ("Tight", "Liberation Sans Narrow")] { + d.text_styles.push(TextStyle { name: name.into(), font: font.into(), ..TextStyle::default() }); + } + d +} + +/// (style, font) of the drawing's text styles. +fn fonts(d: &Drawing) -> Vec<(String, String)> { + d.text_styles.iter().map(|t| (t.name.clone(), t.font.clone())).collect() +} + +/// (style, font file) of the STYLE records of DXF text. +fn style_files(dxf: &str) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = Vec::new(); + let mut style = false; + for t in cadcraft_dxf::parse(dxf.as_bytes()).unwrap() { + match t.code { + 0 => style = t.str() == "STYLE", + 2 if style => out.push((t.str(), String::new())), + 3 if style => out.last_mut().unwrap().1 = t.str(), + _ => {} + } + } + out +} + +#[test] +fn styles_get_windows_fonts_and_reopen_with_their_own() { + let d = drawing(true); + let dxf = write_dxf(&d); + let files = style_files(&dxf); + for (style, file) in [("Notes", "verdanab.ttf"), ("Tight", "Liberation Sans Narrow")] { + assert!(files.contains(&(style.into(), file.into())), "{style}: {files:?}"); + } + for back in [read_dxf(dxf.as_bytes()).unwrap(), read(&write(&d, "t.dwg").unwrap(), "t.dwg").unwrap()] { + assert_eq!(fonts(&back), fonts(&drawing(false))); + } + // The Windows font with a path is still the one written for the style's own. + let path = read_dxf(dxf.replace("verdanab.ttf", "C:\\Windows\\Fonts\\verdanab.ttf").as_bytes()).unwrap(); + assert_eq!(fonts(&path), fonts(&drawing(false))); + // A font changed in AutoCAD since (the xdata left as it was) is the font read. + let edited = read_dxf(dxf.replace("verdanab.ttf", "times.ttf").as_bytes()).unwrap(); + assert!(fonts(&edited).contains(&("Notes".into(), "times.ttf".into()))); +} + +#[test] +fn without_portable_fonts_the_file_has_the_drawings_fonts() { + let files = style_files(&write_dxf(&drawing(false))); + assert!(files.contains(&("Notes".into(), "DejaVuSans-Bold.ttf".into())), "{files:?}"); +} From e187c5fecb26937bd2781c7f11f4b8cdd7491058 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sun, 1 Nov 2026 22:38:07 +0300 Subject: [PATCH 348/900] i18n(ar): translate 129 new strings, use the catalog's terms in 3 (#2564) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Arabic catalog showed 129 interface strings in English: the Block Editor and REFEDIT, dynamic blocks, multileader editing, hatch islands, origin and boundaries, selection and grip settings, visual effects, command aliases, backup and units options, and the MTEXT ruler. `cargo xtask i18n` now reports `ar: nothing missing`. Hatch, Leader and Multileader now use the terms the rest of the catalog uses (تهشير, خط الإشارة) instead of تظليل and قائد. --- crates/ui-egui/src/i18n/ar.tsv | 135 ++++++++++++++++++++++++++++++++- 1 file changed, 132 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 40e14cdb5..026190729 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -412,7 +412,7 @@ Group Edit تحرير المجموعة Group Options خيارات المجموعة Group Selection تحديد المجموعة - Hatch تظليل + Hatch تهشير Hatch Edit تحرير التهشير Hatch Pattern نمط التهشير Hatch Patterns أنماط التهشير @@ -504,7 +504,7 @@ Layout list قائمة التخطيطات Layout paper ورقة التخطيط Layout {name}: {table} التخطيط {name}: {table} - Leader قائد + Leader خط الإشارة Leaders Only خطوط الإشارة فقط Left يسار Left device button: zoom extents. Right device button: calibrate. زر الجهاز الأيسر: تكبير الحدود. زر الجهاز الأيمن: معايرة. @@ -573,7 +573,7 @@ More toolbar commands المزيد من أوامر شريط الأدوات Move نقل Move sideways to pan; push/pull or twist to zoom. حرّك جانبياً للإزاحة؛ ادفع أو اسحب أو لُف للتكبير. - Multileader قائد متعدد + Multileader خط الإشارة المتعدد Multileader Style... نمط خط الإشارة المتعدد... Multileader style نمط خط الإشارة المتعدد Multiline متعدد الأسطر @@ -1242,3 +1242,132 @@ menu View عرض Check for Updates… التحقق من وجود تحديثات… CADCraft is up to date. CADCraft محدّث. Could not check for updates. تعذّر التحقق من وجود تحديثات. + Add to Working Set إضافة إلى مجموعة العمل + Add: Pick points إضافة: انتقاء نقاط + Add: Select objects إضافة: تحديد كائنات + Add… إضافة… + Alias اختصار + Alias file: {file} ملف الاختصارات: {file} + Align Multileaders محاذاة خطوط الإشارة المتعددة + Analyze Shapes تحليل الأشكال + Analyze Usage تحليل الاستخدام + Animation Effects تأثيرات الحركة + Animation effects تأثيرات الحركة + Associative ترابطي + Backup copy نسخة احتياطية + Block to create or edit الكتلة المراد إنشاؤها أو تحريرها + Bottom left أسفل اليسار + Bottom right أسفل اليمين + Boundaries الحدود + Boundaries picked: {n} الحدود المنتقاة: {n} + Break-line Symbol رمز خط الكسر + Centered متمركز + Change Properties تغيير الخصائص + Choose the command the alias starts. اختر الأمر الذي يشغّله الاختصار. + Click the ruler to add a tab stop, right-click to remove one انقر على المسطرة لإضافة علامة جدولة، وانقر بالزر الأيمن لإزالتها + Click to set new origin انقر لتعيين نقطة أصل جديدة + Close Block Editor إغلاق محرر الكتل + Collect جمع + Collect Multileaders جمع خطوط الإشارة المتعددة + Color 1 اللون 1 + Color 2 اللون 2 + Command الأمر + Convert Text to Mtext تحويل النص إلى نص متعدد الأسطر + Create backup copy with each save إنشاء نسخة احتياطية عند كل حفظ + Create separate hatches إنشاء تهشيرات منفصلة + Crossing selection color: لون تحديد التقاطع: + Curved منحنٍ + Customize تخصيص + Default to boundary extents الافتراضي: امتدادات الحدود + Define each corner of the selection window with a separate click. حدد كل زاوية من نافذة التحديد بنقرة منفصلة. + Discard تجاهل + Drag Dynamic Grip سحب المقبض الديناميكي + Dynamic Block Data بيانات الكتلة الديناميكية + Dynamic Block Grips مقابض الكتلة الديناميكية + Dynamic Block Reference مرجع كتلة ديناميكية + Edit Block Definition تحرير تعريف الكتلة + Edit Command Aliases (PGP)... تحرير اختصارات الأوامر (PGP)... + Edit Multileader تحرير خط الإشارة المتعدد + Edit Reference In-Place تحرير المرجع في مكانه + Edit… تحرير… + Evaluate LISP تقييم LISP + Exclude: استثناء: + Explode Attributes to Text تفجير السمات إلى نص + Express Tools أدوات Express + Font الخط + Grips المقابض + Groups المجموعات + Hatch Pick انتقاء التهشير + Hatch and Gradient التهشير والتدرج اللوني + Hatch origin نقطة أصل التهشير + Hatches تهشيرات + Hemispherical نصف كروي + Ignore تجاهل + Imperial (inches) إنجليزي (بوصة) + Implied Loops حلقات ضمنية + Indicate selection area إظهار منطقة التحديد + Interface scale مقياس الواجهة + Inverted معكوس + Island جزيرة + Island detection اكتشاف الجزر + Italic مائل + Justify ضبط المحاذاة + Load Application... تحميل تطبيق... + Metric (millimetres) متري (مليمتر) + More than {n} aliases. أكثر من {n} اختصار. + Move/Copy/Rotate نقل/نسخ/تدوير + Multiline text نص متعدد الأسطر + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). تستخدم الرسومات الجديدة وأول رسم عند بدء التشغيل هذه الوحدات ما لم يُعيَّن قالب افتراضي (QNEWTEMPLATE). + New block كتلة جديدة + No alias file loaded. REINIT replaces these aliases with a file's. لم يُحمَّل ملف اختصارات. يستبدل REINIT هذه الاختصارات باختصارات ملف. + Not a number or distance: {text} ليس رقماً أو مسافة: {text} + Object grouping تجميع الكائنات + Object selection limit for display of grips حد تحديد الكائنات لعرض المقابض + Objects on locked layers الكائنات على الطبقات المقفلة + Open in Block Editor فتح في محرر الكتل + Origin: {x}, {y} نقطة الأصل: {x}, {y} + Outer خارجي + Overline خط علوي + Preview معاينة + Query Texts الاستعلام عن النصوص + Save Block حفظ الكتلة + Save Block As حفظ الكتلة باسم + Save Layout as Template حفظ التخطيط كقالب + Save Reference Edits حفظ تعديلات المرجع + Save alias حفظ الاختصار + Save changes to block "{name}"? حفظ التغييرات على الكتلة "{name}"؟ + Select boundaries to remove حدد الحدود المراد إزالتها + Select using two clicks only التحديد بنقرتين فقط + Selection Area Effect تأثير منطقة التحديد + Selection Preview Filter مرشح معاينة التحديد + Selection area opacity: عتامة منطقة التحديد: + Selection effect color لون تأثير التحديد + Selection modes أوضاع التحديد + Selection preview معاينة التحديد + Set Dynamic Property تعيين خاصية ديناميكية + Shape الشكل + Sheet Books to PDF... دفاتر اللوحات إلى PDF... + Show grips إظهار المقابض + Specified origin نقطة أصل محددة + Spherical كروي + Tables الجداول + Text color لون النص + Top left أعلى اليسار + Top right أعلى اليمين + Type an alias name. اكتب اسم الاختصار. + Underline تسطير + Units of new drawings وحدات الرسومات الجديدة + Unsaved changes تغييرات غير محفوظة + Use current origin استخدام نقطة الأصل الحالية + Visual Effect Settings إعدادات التأثيرات المرئية + Visual Effect Settings... إعدادات التأثيرات المرئية... + When a command is active عندما يكون أمر ما نشطاً + When no command is active عندما لا يكون أي أمر نشطاً + Window selection color: لون تحديد النافذة: + Working Set مجموعة العمل + Xref and Block In-place Editing تحرير المراجع الخارجية والكتل في مكانها + Xrefs المراجع الخارجية + built-in مدمج + overrides built-in يتجاوز المدمج + {alias} is already defined; select it and use Edit. {alias} معرَّف مسبقاً؛ حدده واستخدم «تحرير». + {command} is an unknown command. {command} أمر غير معروف. From 5e9c478bfbd2d9520bd3535f0d9a41674f948b4c Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:38:10 +0700 Subject: [PATCH 349/900] U inside a LISP routine takes back the routine's last command (#2610) Inside a routine, commands recorded no undo step (the routine becomes one when it ends), so U inside a routine took back the step from before the routine: after drawing a line D, ERASE B then U in one routine brought B back and removed D. As AutoCAD 2024 does (accoreconsole, the drawing read back after one routine), U inside a routine now takes back the routine's last command, with what the routine did after it (entdel, entmake); U again, UNDO n and REDO go on through its commands. With none left, U takes back the drawing's step before the routine, as before, and the routine's step then starts from there. Once the routine ends it is still one undo step. The routine's steps live in the session's LISP state (RoutineSteps), not in the drawing's undo stack, so a long routine doesn't push the drawing's earlier steps out. A command inside the routine ends what REDO could bring back; UNDO Control One and None apply. DocState::swap_in is the one restore step undo, redo and the routine share. Co-authored-by: Claude Opus 5.5 --- crates/engine/src/doc_state.rs | 8 + crates/engine/src/lisp.rs | 85 +++++++++- crates/engine/src/session/execute.rs | 43 +++-- crates/engine/src/session/interactive.rs | 6 +- .../engine/tests/it/lisp_undo_in_routine.rs | 154 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 6 files changed, 278 insertions(+), 19 deletions(-) create mode 100644 crates/engine/tests/it/lisp_undo_in_routine.rs diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index d11c6f0eb..97a1ede49 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -72,6 +72,14 @@ impl DocState { pub fn is_dirty(&self) -> bool { !Arc::ptr_eq(self.drawing(), &self.saved) || self.block_unsaved() } + /// Show the drawing an undo or redo step holds, with nothing selected; returns the drawing as + /// it was, as the step back. + pub(crate) fn swap_in(&mut self, snap: Snapshot) -> Snapshot { + let cur = Snapshot { label: snap.label, doc: std::mem::replace(&mut self.doc, snap.doc), selection: std::mem::take(&mut self.selection) }; + self.follow_layout(&cur.doc); + self.revision += 1; + cur + } /// After undo/redo replaced the drawing (`before` is the one shown until then): if the current /// layout no longer exists, follow it to its other name when it was renamed (same tab order, /// a name `before` did not have), else go to the Model tab. diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index b3175c512..977d4f551 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use cadcraft_doc::{Drawing, Handle}; -use crate::{Input, Prompt, Session}; +use crate::{Input, Prompt, Session, undoctl}; use eval::{Ctx, Machine, Need, Outcome}; use value::{Sym, Value}; @@ -111,6 +111,8 @@ pub struct LispState { run: Option>, /// A routine runs, from its start to its end (also while its machine is out of `run`). active: bool, + /// The running routine's own undo steps (also while its machine is out of `run`). + steps: RoutineSteps, /// Files loaded by APPLOAD, by name, for `(load name)` where there is no file system. files: HashMap, /// Where startup files are read from (see `startup.rs`). @@ -123,6 +125,19 @@ pub struct LispState { pub(crate) limits: Limits, } +/// What U and REDO inside the running routine take back: the commands it ran, each as the drawing +/// was before it, last last. The routine is still one undo step once it ends. +#[derive(Default)] +struct RoutineSteps { + /// The drawing the routine runs in. + uid: u64, + undo: std::collections::VecDeque, + redo: std::collections::VecDeque, + /// Where the routine's undo step starts, when U or REDO inside it went on to the drawing's + /// own steps; else where the routine started. + base: Option<(Arc, Vec)>, +} + /// What a run may use (see [`value`]'s memory notes). #[derive(Clone, Copy, Debug)] pub(crate) struct Limits { @@ -247,6 +262,7 @@ impl Session { let st = self.state()?; let before = Some((st.doc.clone(), st.selection.clone())); let uid = st.uid; + self.lisp.steps = RoutineSteps { uid, ..RoutineSteps::default() }; self.lisp.run = Some(Box::new(Run { machine, uid, @@ -324,7 +340,7 @@ impl Session { Ok(o) => o, Err(p) => { // A panic inside a built-in: put the drawing back as the routine found it. - if let Some((doc, sel)) = &run.before + if let Some((doc, sel)) = self.lisp.steps.base.as_ref().or(run.before.as_ref()) && let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid) { st.doc = doc.clone(); @@ -422,6 +438,7 @@ impl Session { fn lisp_end(&mut self, result: std::result::Result) { let Some(run) = self.lisp.run.take() else { return }; self.lisp.active = false; + let steps = std::mem::take(&mut self.lisp.steps); let mut env = self.lisp.envs.remove(&run.uid).unwrap_or_default(); self.lisp_flush(&mut env, true); self.lisp.envs.insert(run.uid, env); @@ -431,7 +448,7 @@ impl Session { self.echo(text); } } - if let Some((doc, sel)) = run.before + if let Some((doc, sel)) = steps.base.or(run.before) && let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid) && !Arc::ptr_eq(&doc, &st.doc) { @@ -489,6 +506,7 @@ impl Session { self.lisp_error(LispError::quit(msg)); } else if self.lisp.active { self.lisp.active = false; + self.lisp.steps = RoutineSteps::default(); self.echo(format!("; error: {msg}")); self.lisp_last = Some(Err(msg)); } else { @@ -577,6 +595,67 @@ impl Session { self.lisp.active } + /// A command the running routine ran changed the drawing (`snap` holds it as it was): U inside + /// the routine takes it back, as AutoCAD's does, while the routine stays one undo step. UNDO + /// Control One keeps only the last, None none. + pub(crate) fn lisp_record_step(&mut self, snap: crate::Snapshot) { + let Some(uid) = self.routine_steps() else { return }; + let mut control = undoctl::Control::All; + // A command ends what REDO could bring back, the drawing's own steps too. + if let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) { + st.redo.clear(); + control = st.undo_ctl.control; + } + let steps = &mut self.lisp.steps; + steps.redo.clear(); + match control { + undoctl::Control::None => steps.undo.clear(), + undoctl::Control::One => { + steps.undo.clear(); + steps.undo.push_back(snap); + } + // As many as the drawing keeps. + undoctl::Control::All => { + steps.undo.push_back(snap); + if steps.undo.len() > undoctl::MAX_UNDO { + steps.undo.pop_front(); + } + } + } + } + + /// U (or with `redo`, REDO) inside the running routine: take its last command back (or bring + /// back what U took). None when it has none left, and the drawing's own steps go on from there. + pub(crate) fn lisp_take_back(&mut self, redo: bool) -> Option { + let uid = self.routine_steps()?; + let st = self.docs.iter_mut().find(|d| d.uid == uid)?; + let steps = &mut self.lisp.steps; + let (from, to) = if redo { (&mut steps.redo, &mut steps.undo) } else { (&mut steps.undo, &mut steps.redo) }; + let cur = st.swap_in(from.pop_back()?); + let label = cur.label.clone(); + to.push_back(cur); + Some(label) + } + + /// U or REDO inside the running routine went on to the drawing's steps before it: the + /// routine's own undo step starts from the drawing as that left it, and REDO brings back that + /// step before what U took back of the routine's. + pub(crate) fn lisp_rebase(&mut self) { + if self.routine_steps().is_none() { + return; + } + if let Ok(st) = self.state() { + self.lisp.steps.base = Some((st.doc.clone(), st.selection.clone())); + self.lisp.steps.redo.clear(); + } + } + + /// The active drawing's uid when a routine runs in it. + fn routine_steps(&self) -> Option { + let uid = self.state().ok()?.uid; + (self.lisp.active && self.lisp.steps.uid == uid).then_some(uid) + } + /// The commands the active drawing's LISP defines (`c:` functions), uppercase and sorted. pub fn lisp_commands(&self) -> Vec { let Ok(uid) = self.state().map(|s| s.uid) else { return Vec::new() }; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index a4c57eec5..230422e09 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -66,17 +66,25 @@ impl Session { (r, _) => r, }; let grouped = self.lisp_groups_undo(); + let mut in_routine = None; if spec.undoable && let Some((doc, sel, uid)) = before && let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) && !Arc::ptr_eq(&doc, &st.doc) { - // Inside a LISP routine the routine's single undo step records it. - if !grouped { - st.push_undo(Snapshot { label: spec.label.to_string(), doc, selection: sel }); + let snap = Snapshot { label: spec.label.to_string(), doc, selection: sel }; + // Inside a LISP routine the routine's single undo step records it, and the routine + // keeps it for U inside it. + if grouped { + in_routine = Some(snap); + } else { + st.push_undo(snap); } st.revision += 1; } + if let Some(snap) = in_routine { + self.lisp_record_step(snap); + } result } @@ -89,27 +97,32 @@ impl Session { // ---------------- undo ---------------- + /// Take the last step back. Inside a LISP routine, the routine's last command first; past + /// those, the drawing's step before the routine, which then starts from there. pub fn undo(&mut self) -> Result> { + if let Some(label) = self.lisp_take_back(false) { + return Ok(Some(label)); + } let st = self.state_mut()?; let Some(snap) = st.undo.pop() else { return Ok(None) }; - let cur = Snapshot { label: snap.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() }; - st.doc = snap.doc; - st.follow_layout(&cur.doc); - st.selection = Vec::new(); + let cur = st.swap_in(snap); + let label = cur.label.clone(); st.redo.push(cur); - st.revision += 1; - Ok(Some(snap.label)) + self.lisp_rebase(); + Ok(Some(label)) } + /// Bring back what the last undo took back; inside a LISP routine, what U inside it took first. pub fn redo(&mut self) -> Result> { + if let Some(label) = self.lisp_take_back(true) { + return Ok(Some(label)); + } let st = self.state_mut()?; let Some(snap) = st.redo.pop() else { return Ok(None) }; - let cur = Snapshot { label: snap.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() }; - st.doc = snap.doc; - st.follow_layout(&cur.doc); - st.selection = Vec::new(); + let cur = st.swap_in(snap); + let label = cur.label.clone(); st.undo.push(cur); - st.revision += 1; - Ok(Some(snap.label)) + self.lisp_rebase(); + Ok(Some(label)) } } diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index d90c91683..aa66bd4c5 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -379,12 +379,16 @@ impl Session { } self.after_command(Some(&run.before), None, true); // A transparent command's changes belong to the command it ran inside, and a command a - // LISP routine ran belongs to the routine's single undo step. + // LISP routine ran belongs to the routine's single undo step (the routine keeps it for U + // inside it). if self.suspended.is_some() || self.lisp_groups_undo() { if let Ok(st) = self.state_mut() && !Arc::ptr_eq(&run.before, &st.doc) { st.revision += 1; + if self.suspended.is_none() { + self.lisp_record_step(Snapshot { label: label.to_string(), doc: run.before, selection: run.selection_before }); + } } return; } diff --git a/crates/engine/tests/it/lisp_undo_in_routine.rs b/crates/engine/tests/it/lisp_undo_in_routine.rs new file mode 100644 index 000000000..9afa3c9f5 --- /dev/null +++ b/crates/engine/tests/it/lisp_undo_in_routine.rs @@ -0,0 +1,154 @@ +//! U, UNDO and REDO inside a LISP routine, as AutoCAD 2024 runs them (accoreconsole: a line A, a +//! line B, a circle C and a line D, then one routine, then the drawing's `entnext` order read back). + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec}; +use cadcraft_engine::doc::Handle; +use serde_json::json; + +/// A session with A, B, C and D in draw order, each its own undo step, and their handles. +fn drawing() -> (Session, Vec) { + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + s.execute("line", &json!({ "points": [[0, 10], [10, 10]] })).unwrap(); + s.execute("circle", &json!({ "center": [5, 25], "radius": 3 })).unwrap(); + s.execute("line", &json!({ "points": [[0, 40], [10, 40]] })).unwrap(); + let hs = handles(&s); + (s, hs) +} + +fn handles(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.handle).collect() +} + +/// The drawing's objects in draw order: A to D by their handles, E for any other. +fn order(s: &Session, hs: &[Handle]) -> String { + let name = |h: &Handle| hs.iter().position(|x| x == h).map_or('E', |i| (b'A' + i as u8) as char); + handles(s).iter().map(|h| name(h).to_string()).collect::>().join(" ") +} + +/// Run `parts` as ONE routine, `@A`…`@D` standing for the objects. +fn routine(s: &mut Session, hs: &[Handle], parts: &[&str]) { + let mut code = format!("(progn {})", parts.join(" ")); + for (i, h) in hs.iter().enumerate() { + code = code.replace(&format!("@{}", (b'A' + i as u8) as char), &format!("(handent \"{}\")", h.hex())); + } + s.cmdline(&code).unwrap(); + assert!(s.running.is_none(), "{code}: {}", s.prompt_text()); +} + +const EB: &str = "(command \"_.ERASE\" @B \"\")"; +const EC: &str = "(command \"_.ERASE\" @C \"\")"; +const U: &str = "(command \"_.U\")"; +const LINE: &str = "(command \"_.LINE\" '(0.0 50.0) '(10.0 50.0) \"\")"; +const MAKE: &str = "(entmake '((0 . \"LINE\") (8 . \"0\") (10 0.0 60.0 0.0) (11 10.0 60.0 0.0)))"; + +#[test] +fn u_in_a_routine_takes_back_the_routines_last_command() { + // (case, the routine, the drawing's order afterwards) + let cases: [(&str, &[&str], &str); 9] = [ + ("U-001: ERASE, U", &[EB, U], "A B C D"), + ("U-002: two erases, U", &[EB, EC, U], "A C D"), + ("U-003: two erases, U, U", &[EB, EC, U, U], "A B C D"), + ("U-005: entdel, ERASE, U", &["(entdel @B)", EC, U], "A C D"), + ("U-006: ERASE, entdel, U", &[EB, "(entdel @C)", U], "A B C D"), + ("U-007: LINE, U, REDO", &[LINE, U, "(command \"_.REDO\")"], "A B C D E"), + ("U-008: two erases, UNDO 2", &[EB, EC, "(command \"_.UNDO\" \"2\")"], "A B C D"), + ("U-012: ERASE, entmake, U", &[EB, MAKE, U], "A B C D"), + // OOPS-011 had an OOPS after the U, which brought B back: B was still erased. + ("OOPS-011: ERASE, LINE, U", &[EB, LINE, U], "A C D"), + ]; + for (case, parts, want) in cases { + let (mut s, hs) = drawing(); + routine(&mut s, &hs, parts); + assert_eq!(order(&s, &hs), want, "{case}"); + } +} + +#[test] +fn the_routine_is_still_one_undo_step_after_it() { + let (mut s, hs) = drawing(); + let depth = s.state().unwrap().undo.len(); + routine(&mut s, &hs, &[EB, EC, LINE, U, "(entdel @A)"]); + assert_eq!(order(&s, &hs), "D"); + assert_eq!(s.state().unwrap().undo.len(), depth + 1); + s.cmdline("U").unwrap(); + assert_eq!(order(&s, &hs), "A B C D"); + s.cmdline("REDO").unwrap(); + assert_eq!(order(&s, &hs), "D"); +} + +#[test] +fn u_with_nothing_of_the_routine_left_takes_back_the_step_before_it() { + let (mut s, hs) = drawing(); + let depth = s.state().unwrap().undo.len(); + routine(&mut s, &hs, &[EB, U, U]); + // The second U takes back D's line, drawn before the routine. + assert_eq!(order(&s, &hs), "A B C"); + assert_eq!(s.state().unwrap().undo.len(), depth - 1, "the routine changed nothing more of its own"); + // A command after that makes the routine's step, from where the U took the drawing. + routine(&mut s, &hs, &[EB, U, U, "(command \"_.ERASE\" @A \"\")"]); + assert_eq!(order(&s, &hs), "B"); + s.cmdline("U").unwrap(); + assert_eq!(order(&s, &hs), "A B"); +} + +#[test] +fn undo_off_still_refuses_inside_a_routine() { + let (mut s, hs) = drawing(); + routine(&mut s, &hs, &["(command \"_.UNDO\" \"_C\" \"_N\")", EB, U]); + assert_eq!(order(&s, &hs), "A C D"); +} + +#[test] +fn redo_inside_a_routine_brings_back_the_last_u_first() { + // U past the routine's own command, then REDO: the drawing's step comes back, not the erase. + let (mut s, hs) = drawing(); + let depth = s.state().unwrap().undo.len(); + routine(&mut s, &hs, &[EB, U, U, "(command \"_.REDO\")"]); + assert_eq!(order(&s, &hs), "A B C D"); + assert_eq!(s.state().unwrap().undo.len(), depth, "the routine left nothing of its own to undo"); + // A command inside the routine ends what REDO could bring back from before it. + let (mut s, hs) = drawing(); + s.cmdline("U").unwrap(); + assert_eq!(order(&s, &hs), "A B C"); + routine(&mut s, &hs, &[EB, "(command \"_.REDO\")"]); + assert_eq!(order(&s, &hs), "A C"); +} + +#[test] +fn a_command_without_prompts_is_a_step_of_the_routine_too() { + // HATCHTOBACK runs as its JSON form from a routine; U takes it back, not the hatch. + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + let rect = handles(&s)[0]; + s.execute("hatch", &json!({ "handles": [rect.hex()], "pattern": "SOLID" })).unwrap(); + let both = handles(&s); + assert_eq!(both.len(), 2); + s.cmdline("(progn (command \"_.HATCHTOBACK\") (command \"_.U\"))").unwrap(); + assert_eq!(handles(&s), both); +} + +#[test] +fn undo_control_one_keeps_only_the_routines_last_command() { + // As UNDO Control One keeps only the drawing's last step: the second U goes on to the step + // before the routine (D's line), the drawing as it was then. + let (mut s, hs) = drawing(); + routine(&mut s, &hs, &["(command \"_.UNDO\" \"_C\" \"_O\")", EB, EC, U, U]); + assert_eq!(order(&s, &hs), "A B C"); +} + +#[test] +fn a_routine_keeps_as_many_steps_as_the_drawing() { + use cadcraft_engine::undoctl::MAX_UNDO; + let (mut s, hs) = drawing(); + // Two lines more than the routine keeps steps for, then a U for each kept step and one more, + // which goes on to the drawing's step before the routine (D's line): the drawing as it was + // then, without the two lines whose steps went. + let code = + format!("(progn (repeat {} (command \"_.LINE\" '(0.0 50.0) '(10.0 50.0) \"\")) (repeat {} (command \"_.U\")))", MAX_UNDO + 2, MAX_UNDO + 1); + s.cmdline(&code).unwrap(); + assert!(s.running.is_none()); + assert_eq!(order(&s, &hs), "A B C"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 2aae7c117..65b8e244f 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -73,6 +73,7 @@ mod layout_prompts; mod leader_command; #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod lisp_corpus; +mod lisp_undo_in_routine; mod malformed_handles; mod matchprop; mod measure_distance_snapping; From fb05c7859030ca7063228bd4e184044ccc278814 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:38:14 +0700 Subject: [PATCH 350/900] Read bearings and compass points as AutoCAD does (#2590) Measured in AutoCAD 2024 (accoreconsole): - N, E, S and W are taken on their own in any angle format (LINE to @10 --- crates/engine/src/cmd/props/dash_units.rs | 13 +--- crates/engine/src/units.rs | 48 +++++++++------ crates/engine/tests/it/angle_settings.rs | 74 ++++++++++++++++++++++- crates/engine/tests/it/dash_units.rs | 65 +++----------------- 4 files changed, 112 insertions(+), 88 deletions(-) diff --git a/crates/engine/src/cmd/props/dash_units.rs b/crates/engine/src/cmd/props/dash_units.rs index a10153f56..95b6bc021 100644 --- a/crates/engine/src/cmd/props/dash_units.rs +++ b/crates/engine/src/cmd/props/dash_units.rs @@ -66,17 +66,10 @@ impl Units { } /// A typed direction of angle 0, in radians counterclockwise from +X: an amount in the angle - /// format, or with its own unit (`45d`, `0.5r`, `100g`, a bearing `N45dE`, and in surveyor's - /// units N, E, S or W), measured from +X as the drawing measures angles. + /// format, or with its own unit (`45d`, `0.5r`, `100g`, a bearing `N45dE`, `N`), measured + /// from +X as the drawing measures angles. fn direction(&self, t: &str) -> Option { - let cardinal = match t.trim().to_ascii_lowercase().as_str() { - "e" if self.aunits == 4 => Some(0.0), - "n" if self.aunits == 4 => Some(90f64.to_radians()), - "w" if self.aunits == 4 => Some(180f64.to_radians()), - "s" if self.aunits == 4 => Some(270f64.to_radians()), - _ => None, - }; - let a = cardinal.or_else(|| AngleSettings { aunits: self.aunits, ..AngleSettings::default() }.amount(t))?; + let a = AngleSettings { aunits: self.aunits, ..AngleSettings::default() }.amount(t)?; let a = if self.clockwise { -a } else { a }; a.is_finite().then(|| a.rem_euclid(TAU)) } diff --git a/crates/engine/src/units.rs b/crates/engine/src/units.rs index 560551f1c..edfa24377 100644 --- a/crates/engine/src/units.rs +++ b/crates/engine/src/units.rs @@ -277,7 +277,8 @@ impl AngleSettings { } /// A typed angle size in radians (included angles, sweeps, angles from an axis): a bare - /// number in AUNITS, or with an explicit unit: `30d`, `45d30'15"`, `0.5r`, `100g`. + /// number in AUNITS, or with an explicit unit: `30d`, `45d30'15"`, `0.5r`, `100g`; a + /// surveyor's bearing (`N45dE`, or `N`, `E`, `S`, `W`) is its angle counterclockwise from east. pub fn amount(&self, s: &str) -> Option { parse_units(s, self.aunits).map(|(a, _)| a) } @@ -288,20 +289,19 @@ impl AngleSettings { } /// A typed direction in radians counterclockwise from +X: the amount measured from ANGBASE in - /// the ANGDIR sense. Surveyor's bearings (`N45dE`) are absolute. The overrides measure from - /// +X counterclockwise whatever ANGBASE and ANGDIR say: `< Option { let t = s.trim(); if let Some(r) = t.strip_prefix("<<<") { return parse_units(r, self.aunits).map(|(a, _)| a); } if let Some(r) = t.strip_prefix("<<") { - return parse_units(r, 0).map(|(a, _)| a); - } - let (a, absolute) = parse_units(t, self.aunits)?; - if absolute { - return Some(a); + return parse_units(r, 0).filter(|(_, bearing)| !bearing).map(|(a, _)| a); } + let (a, _) = parse_units(t, self.aunits)?; let v = self.angbase + if self.clockwise { -a } else { a }; v.is_finite().then_some(v) } @@ -328,7 +328,8 @@ pub fn parse_angle(s: &str) -> Option { AngleSettings::default().direction(s) } -/// A typed angle in radians and whether it is absolute (a surveyor's bearing). +/// A typed angle in radians and whether it is a surveyor's bearing (`N45dE`, or `N`, `E`, `S`, +/// `W`), whose angle is its direction counterclockwise from east. fn parse_units(s: &str, aunits: i64) -> Option<(f64, bool)> { let t = s.trim().to_ascii_lowercase(); if t.is_empty() { @@ -339,10 +340,7 @@ fn parse_units(s: &str, aunits: i64) -> Option<(f64, bool)> { (num(r)?, false) } else if let Some(g) = t.strip_suffix('g') { ((num(g)? * 0.9).to_radians(), false) - } else if let Some(b) = bearing(&t) { - (b, true) - } else if let Some(b) = (aunits == 4).then(|| cardinal(&t)).flatten() { - // A due bearing as surveyor's units show it: one letter. + } else if let Some(b) = cardinal(&t).or_else(|| bearing(&t)) { (b, true) } else if let Some(v) = num(&t) { let a = match aunits { @@ -357,7 +355,8 @@ fn parse_units(s: &str, aunits: i64) -> Option<(f64, bool)> { v.0.is_finite().then_some(v) } -/// A due bearing (`n`, `e`, `s`, `w`, lower case) as radians counterclockwise from +X. +/// A compass point (`n`, `e`, `s`, `w`, lower case), a due bearing as surveyor's units show it, +/// as radians counterclockwise from +X. AutoCAD 2024 takes one in any angle format. fn cardinal(t: &str) -> Option { match t { "e" => Some(0.0), @@ -567,14 +566,19 @@ mod tests { #[test] fn surveyors_units_read_a_due_bearing_typed_as_one_letter() { - // What surveyor's units show for a due bearing can be typed back, e.g. `@10 assert_near(l.b.xy(), 0.0, -10.0, "ROTATE by N with ANGDIR 1"), + k => panic!("expected a line, got {k:?}"), + } + // ANGTOF reads them the same way: AutoCAD 2024 returns 0 for "N" with ANGBASE 90, ANGDIR 1 + // and AUNITS 3, and 4.18879020478639 for "S 30d W". + let mut s = Session::new(); + setvar(&mut s, "AUNITS", json!(3)); + setvar(&mut s, "ANGBASE", json!(90)); + setvar(&mut s, "ANGDIR", json!(1)); + let n = s.lisp_eval("(angtof \"N\")", false, true, Vec::new()).unwrap(); + assert!(matches!(n, Some(Ok(Value::Real(a))) if a.abs() < 1e-12), "{n:?}"); + let mut s = Session::new(); + setvar(&mut s, "AUNITS", json!(4)); + let sw = s.lisp_eval("(angtof \"S 30d W\")", false, true, Vec::new()).unwrap(); + assert!(matches!(sw, Some(Ok(Value::Real(a))) if (a - 4.18879020478639).abs() < 1e-12), "{sw:?}"); } #[test] diff --git a/crates/engine/tests/it/dash_units.rs b/crates/engine/tests/it/dash_units.rs index 5c8c3e761..f554378d8 100644 --- a/crates/engine/tests/it/dash_units.rs +++ b/crates/engine/tests/it/dash_units.rs @@ -39,7 +39,7 @@ fn run(s: &mut Session, answers: &str) { #[test] fn the_measured_scripts_set_the_units() { - let cases: [(Units, &str, Units); 21] = [ + let cases: [(Units, &str, Units); 22] = [ (DEFAULT, "4 16 1 0 0 \"_N\"", (4, 4, 0, 0, 0.0, 0)), (DEFAULT, "3 2 2 4 90 \"_Y\"", (3, 2, 1, 4, FRAC_PI_2, 1)), (DEFAULT, "2 3 3 2 100 \"_N\"", (2, 3, 2, 2, FRAC_PI_2, 0)), @@ -61,6 +61,7 @@ fn the_measured_scripts_set_the_units() { (DEFAULT, "\"\" \"\" \"\" \"\" \"\" \"Yes\"", (2, 4, 0, 0, 0.0, 1)), ((2, 4, 2, 6, 0.0, 0), "\"\" \"\" \"\" \"\" \"\" \"\"", (2, 4, 2, 6, 0.0, 0)), ((2, 4, 4, 2, 0.0, 1), "\"\" \"\" \"\" \"\" \"S45dE\" \"\"", (2, 4, 4, 2, 0.7853981633974482, 1)), + (DEFAULT, "\"\" \"\" \"\" \"\" \"N\" \"\"", (2, 4, 0, 0, FRAC_PI_2, 0)), ]; for (from, answers, to) in cases { let mut s = session(from); @@ -112,15 +113,7 @@ fn prompts_and_listings_show_the_drawings_units() { // Surveyor's units, clockwise: north is listed as S, as AutoCAD lists it. let mut s = session((2, 4, 0, 0, 0.0, 1)); - s.script( - "-units - - -5 - -", - ) - .unwrap(); + s.script("-units\n\n\n5\n\n").unwrap(); let directions = [ "Direction for angle E:", " East 3 o'clock = E", @@ -133,15 +126,7 @@ fn prompts_and_listings_show_the_drawings_units() { // The listing shows directions to the precision just given. let mut s = session(DEFAULT); - s.script( - "-units - - -2 -2 -", - ) - .unwrap(); + s.script("-units\n\n\n2\n2\n").unwrap(); let directions = [ "Direction for angle 0d0':", " East 3 o'clock = 0d0'", @@ -166,27 +151,11 @@ fn a_rejected_answer_is_asked_again() { s.cmdline("3").unwrap(); assert!(ends_with(&s, &["Invalid choice.", "Enter denominator of smallest fraction to display"]), "{:?}", s.log); assert_eq!(asks(&s), "(1, 2, 4, 8, 16, 32, 64, 128, or 256) <16>:"); - s.script( - " - -9 -", - ) - .unwrap(); + s.script("\n\n9\n").unwrap(); assert!(ends_with(&s, &["Requires an integer between 0 and 8."]), "{:?}", s.log); - s.script( - " -abc -", - ) - .unwrap(); + s.script("\nabc\n").unwrap(); assert!(ends_with(&s, &["Requires valid numeric angle or two points."]), "{:?}", s.log); - s.script( - " - -", - ) - .unwrap(); + s.script("\n\n").unwrap(); assert!(s.running.is_none()); assert!(same(units(&s), (4, 4, 0, 0, 0.0, 0)), "{:?}", units(&s)); } @@ -196,28 +165,12 @@ fn each_answer_is_kept_as_it_is_given() { // Esc after the angle format: the answers before it are kept, and the new angle format's // precision is reset to 4. let mut s = session(DEFAULT); - s.script( - "-units -4 -16 -2 -", - ) - .unwrap(); + s.script("-units\n4\n16\n2\n").unwrap(); s.cancel(); assert!(s.running.is_none()); assert!(same(units(&s), (4, 4, 1, 4, 0.0, 0)), "{:?}", units(&s)); let mut s = session(DEFAULT); - s.script( - "-units -3 -2 -3 -5 -90 -", - ) - .unwrap(); + s.script("-units\n3\n2\n3\n5\n90\n").unwrap(); s.cancel(); assert!(same(units(&s), (3, 2, 2, 5, 1.413716694115407, 0)), "{:?}", units(&s)); } From 7e386a2cc4761eeee217c8190c5d3d752765cf77 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 14:38:15 -0500 Subject: [PATCH 351/900] 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 5cc342b033728fe8261273abd0a578c421af61d5 Mon Sep 17 00:00:00 2001 From: Andrea Ficarra Date: Sun, 1 Nov 2026 20:38:17 +0100 Subject: [PATCH 352/900] DXF/DWG: viewport frozen layers as group 331 (341 in an R2000 DXF) (#2575) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * DXF/DWG: viewport frozen layers as group 331 (341 in an R2000 DXF) AutoCAD 2004 and later, and the DWG converter, read a VIEWPORT's frozen layers from group 331; CADCraft wrote only group 341 (the DXF 2000 form), so a DWG or 2004+ DXF lost the freeze outside CADCraft, and a file frozen only in group 331 (as AutoCAD 2026 and ezdxf write it) lost it on the first save. Now: group 341 in an R2000 DXF, 331 otherwise and for the DWG bridge; both are read, each layer once. CADCraft's own xdata still wins. Tests in crates/io/src/tests.rs, including a_331_only_viewport_freeze_survives_open_and_save. Co-Authored-By: Claude Opus 5.5 * Leave the parity docs to the maintainers CLAUDE.md: PRs don't edit the parity docs; the affected rows are named in the PR description instead. Co-Authored-By: Claude Opus 5.5 * Viewport frozen layers: group 331 wins over stale xdata AutoCAD now sees the freeze in group 331, edits it, and keeps CADCraft's VPFROZEN xdata as it was. Reading preferred the xdata, so a layer thawed in AutoCAD came back frozen. The handles now win; the xdata still gives names that have no LAYER record, and the whole list for records without handles (entget/entmod, older files). The handles are written before group 90, as in the DXF Reference. Test: viewport_frozen_331_wins_over_the_xdata. Co-Authored-By: Claude Opus 5.5 * Viewport frozen layers: handles for real layers, xdata only for the rest Simpler and safe against edits in AutoCAD. A layer with a LAYER record is written only as a handle (331, or 341 in an R2000 DXF); CADCraft's VPFROZEN xdata now holds only the names with no record (and the whole list for entget, which writes no handles). Reading takes the handles, then the xdata names, each layer once: no precedence, and a viewport thawed in AutoCAD (even its last frozen layer) stays thawed, since no stale list is left behind. The reader no longer builds a layer-name set per viewport. Tests: viewport_frozen_layers_read_from_331_or_341_once_each, viewport_freeze_edited_in_autocad_is_read_as_edited. Co-Authored-By: Claude Opus 5.5 * Viewport frozen layers: skip 102 application groups A group 331 inside another application's `102 {…}` group isn't a frozen layer. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/io/src/dxf_read.rs | 2 +- crates/io/src/dxf_read/entities.rs | 22 ++++--- crates/io/src/dxf_write.rs | 6 +- crates/io/src/dxf_write/ctx.rs | 3 + crates/io/src/dxf_write/entity.rs | 22 +++---- crates/io/src/dxf_write/sections.rs | 5 +- crates/io/src/tests.rs | 89 ++++++++++++++++++----------- 7 files changed, 93 insertions(+), 56 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 1489f4def..5b8865953 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -59,7 +59,7 @@ struct Rx { pstyles: HashMap, /// Upper-case block name → associative array parameters from its BLOCK_RECORD. block_arrays: HashMap, - /// LAYER record handle (upper case) → layer name (VIEWPORT group 341 frozen layers). + /// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers). layers: HashMap, } diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 12abae7da..a074a6517 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -466,14 +466,20 @@ pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityK } rx.mleader_fix.push((h, pending)); } - // CADCraft's VPFROZEN xdata wins; otherwise AutoCAD's group 341 layer handles. - ("VIEWPORT", EntityKind::Viewport(v)) if v.frozen_layers.is_empty() => { - v.frozen_layers = tags - .iter() - .take_while(|t| t.code < 1000) - .filter(|t| t.code == 341) - .filter_map(|t| rx.layers.get(&t.str().trim().to_ascii_uppercase()).cloned()) - .collect(); + // The frozen layers: the LAYER handles of group 331 (341 in DXF 2000), outside `102 {…}` + // application groups, then the names in CADCraft's VPFROZEN xdata, which holds those + // without one; each layer once. + ("VIEWPORT", EntityKind::Viewport(v)) => { + let mut app_group = false; + let handles = tags.iter().take_while(|t| t.code < 1000).filter(|t| { + if t.code == 102 { + app_group = t.str().starts_with('{'); + } + !app_group && (t.code == 331 || t.code == 341) + }); + let named = handles.filter_map(|t| rx.layers.get(&t.str().trim().to_ascii_uppercase())); + let mut seen = std::collections::HashSet::new(); + v.frozen_layers = named.chain(&v.frozen_layers).filter(|n| seen.insert(n.to_ascii_uppercase())).cloned().collect(); } _ => {} } diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 8eb3ab91f..341f70e62 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -41,7 +41,7 @@ struct W { next: u64, /// Upper-case plot style name → its `ACDBPLACEHOLDER` handle (group 390 of layers and objects). pstyles: HashMap, - /// Upper-case layer name → its LAYER table record handle (group 341 of viewports). + /// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports). layers: HashMap, /// Persistent reactors of boundary objects: each source object of an associative hatch → /// the hatches (groups `{ACAD_REACTORS 330 …}`), from [`hatch_reactors`]. @@ -112,13 +112,13 @@ pub fn write(d: &Drawing) -> String { /// The drawing's DXF tags, declaring `version` in `$ACADVER`. pub fn tags(d: &Drawing, version: Version) -> Vec { - tags_for(d, version, version) + tags_for(d, version, version, version < Version::R2004) } /// The R2000 DXF the DWG bridge converts to a `dwg` version DWG: its entity types are the DWG /// version's (MULTILEADER from 2007). pub(crate) fn dwg_bridge(d: &Drawing, dwg: Version) -> String { - let mut tags = tags_for(d, Version::R2000, dwg); + let mut tags = tags_for(d, Version::R2000, dwg, false); bridge_markers(&mut tags); cadcraft_dxf::write_ascii(&tags) } diff --git a/crates/io/src/dxf_write/ctx.rs b/crates/io/src/dxf_write/ctx.rs index 157dcd441..25194bb46 100644 --- a/crates/io/src/dxf_write/ctx.rs +++ b/crates/io/src/dxf_write/ctx.rs @@ -53,6 +53,9 @@ pub(super) struct Ctx { /// The version the file ends up in (the DWG version for a DWG save): it decides which /// entity types exist (MULTILEADER from 2007). pub(super) target: Version, + /// A VIEWPORT's frozen layers in group 341, as an R2000 DXF has them; otherwise 331 (DXF 2004 + /// and later, and the DWG bridge, which reads only 331). + pub(super) frozen_341: bool, /// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists). pub(super) legacy_columns: bool, } diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index f5771f106..a33437017 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -620,22 +620,24 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: // 340 entity, 131072 = off. let clip = v.clip.filter(|h| *h != e.handle && d.entity(*h).is_some()); let flags = 32768 | if v.locked { 16384 } else { 0 } | if clip.is_some() { 65536 } else { 0 } | if v.on { 0 } else { 131072 }; + // AutoCAD's frozen-layer list, before group 90 as in the DXF Reference: one pointer per + // layer, to its LAYER record. A name with no record goes in CADCraft's xdata below. + let mut unrecorded: Vec = Vec::new(); + for name in &v.frozen_layers { + match w.layers.get(&name.to_ascii_uppercase()).cloned() { + Some(h) => w.s(if cx.frozen_341 { 341 } else { 331 }, h), + None => unrecorded.push(name.clone()), + } + } w.i(90, flags); if let Some(h) = clip { w.s(340, h.hex()); } - // AutoCAD's frozen-layer list: one soft pointer per layer, to its LAYER record. Other - // programs read only this; CADCraft prefers its own xdata below when present. - for name in &v.frozen_layers { - if let Some(h) = w.layers.get(&name.to_ascii_uppercase()).cloned() { - w.s(341, h); - } - } // One CADCraft xdata group holds both lists: readers stop at the first group of an app. - if !v.frozen_layers.is_empty() || !v.layer_colors.is_empty() { + if !unrecorded.is_empty() || !v.layer_colors.is_empty() { w.s(1001, dxf_ext::APP); - if !v.frozen_layers.is_empty() { - w.xdata(dxf_ext::frozen_xdata(&v.frozen_layers)); + if !unrecorded.is_empty() { + w.xdata(dxf_ext::frozen_xdata(&unrecorded)); } if !v.layer_colors.is_empty() { w.xdata(dxf_ext::layer_colors_xdata(&v.layer_colors)); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 2d45a532f..e9f8a9e35 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -883,7 +883,8 @@ fn plan_dimension_associations(d: &Drawing, all_spaces: &[&EntityStore], w: &mut /// The drawing's DXF tags, declaring `version` in `$ACADVER`, with what `target` (the version the /// file ends up in: `version`, or the DWG version the bridge writes) has. -pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { +/// `frozen_341`: see [`Ctx::frozen_341`]. +pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_341: bool) -> Vec { // An in-place block edit in progress is not written: the drawing as before it. let committed = d.committed(); let d: &Drawing = &committed; @@ -916,7 +917,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec = user_blocks.into_iter().map(|(n, _, b)| (n, w.h(), b)).collect(); - let mut cx = Ctx { paper_views: paper_views(d), target, ..Ctx::default() }; + let mut cx = Ctx { paper_views: paper_views(d), target, frozen_341, ..Ctx::default() }; cx.block_records = user_blocks.iter().map(|(n, h, _)| (n.to_ascii_uppercase(), h.clone())).collect(); let all_spaces: Vec<&EntityStore> = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).collect(); let mut dim_defs = dimension_block_definitions(d, &all_spaces, &dim_plan, &mut w, &mut cx); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 977a7c184..12d9f0a12 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -604,6 +604,12 @@ fn viewport_frozen_layers_roundtrip() { assert!(frozen.contains(&(3, Vec::new())), "{frozen:?}"); } +/// `d` as an R2018 DXF (frozen viewport layers in group 331). +fn dxf_2018(d: &Drawing) -> String { + let opts = SaveOptions { version: Some(Version::R2018), binary: false }; + String::from_utf8(write_with(d, "t.dxf", &opts).unwrap()).unwrap() +} + /// 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)>) { @@ -624,10 +630,14 @@ fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { on: true, }); d.add(&paper, Common::default(), vp).unwrap(); - let text = write_dxf(&d); + let text = dxf_2018(&d); + (d, pairs(&text)) +} + +/// The (code, value) pairs of DXF text. +fn pairs(text: &str) -> Vec<(String, String)> { let lines: Vec<&str> = text.lines().collect(); - let pairs = lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).copied().unwrap_or("").to_string())).collect(); - (d, pairs) + lines.chunks(2).map(|c| (c[0].trim().to_string(), c.get(1).copied().unwrap_or("").to_string())).collect() } /// The pair range of the VIEWPORT record whose group 69 is `id`. @@ -676,47 +686,60 @@ fn join(p: &[(String, String)]) -> String { .collect() } -#[test] -fn viewport_frozen_layers_written_as_341_handles() { - let (_, p) = frozen_vp_dxf(); - let r = vp_record(&p, "2"); - let rec = &p[r]; - let h341: Vec<&str> = rec.iter().filter(|(c, _)| c == "341").map(|(_, v)| v.as_str()).collect(); - assert_eq!(h341, vec![layer_handle(&p, "Walls").as_str(), layer_handle(&p, "A B").as_str()]); - let last341 = rec.iter().rposition(|(c, _)| c == "341").unwrap(); - let x = rec.iter().position(|(c, _)| c == "1001").expect("xdata"); - assert!(last341 < x, "341 must precede the xdata"); +/// The group 331 values of viewport 2's record. +fn frozen_331(p: &[(String, String)]) -> Vec { + p[vp_record(p, "2")].iter().filter(|(c, _)| c == "331").map(|(_, v)| v.trim().to_string()).collect() } #[test] -fn viewport_frozen_layers_read_from_341_without_xdata() { +fn viewport_frozen_layers_written_as_331_handles() { + // Real layers go out as handles only, before group 90. let (_, p) = frozen_vp_dxf(); - let r = vp_record(&p, "2"); - // Strip the CADCraft xdata, and add a 341 to a handle that names no layer. - let x = p[r.clone()].iter().position(|(c, _)| c == "1001").unwrap() + r.start; - let mut q: Vec<(String, String)> = p[..r.start].to_vec(); - let mut head = p[r.start..x].to_vec(); - head.push(("341".into(), "FFFFF".into())); - q.extend(head); - q.extend(p[r.end..].iter().cloned()); - let back = read_dxf(join(&q).as_bytes()).unwrap(); - assert_eq!(viewport_frozen(&back, 2), vec!["Walls".to_string(), "A B".to_string()]); + assert_eq!(frozen_331(&p), [layer_handle(&p, "Walls"), layer_handle(&p, "A B")]); + let rec = &p[vp_record(&p, "2")]; + assert!(!rec.iter().any(|(c, v)| c == "1000" && v == "VPFROZEN"), "no xdata for layers with a handle"); + assert!(rec.iter().position(|(c, _)| c == "331") < rec.iter().position(|(c, _)| c == "90")); + // An R2000 DXF holds them in group 341, as the DXF 2000 Reference has them. + let (d, _) = frozen_vp_dxf(); + let p = pairs(&write_dxf(&d)); + let h341: Vec = p[vp_record(&p, "2")].iter().filter(|(c, _)| c == "341").map(|(_, v)| v.clone()).collect(); + assert_eq!(h341, [layer_handle(&p, "Walls"), layer_handle(&p, "A B")]); + assert!(frozen_331(&p).is_empty()); } #[test] -fn viewport_frozen_xdata_wins_over_341() { +fn viewport_frozen_layers_read_from_331_or_341_once_each() { let (_, p) = frozen_vp_dxf(); let r = vp_record(&p, "2"); - // Point every 341 at layer 0: the xdata list must still be what is read. - let zero = layer_handle(&p, "0"); + // 341 instead of 331, then Walls again in 331 and a handle that names no layer. let mut q = p.clone(); - for t in &mut q[r] { - if t.0 == "341" { - t.1 = zero.clone(); + for t in &mut q[r.clone()] { + if t.0 == "331" { + t.0 = "341".into(); } } + q.splice(r.end..r.end, [("331".into(), "FFFFF".into()), ("331".into(), layer_handle(&p, "Walls"))]); + // A 331 inside another application's `102 {…}` group isn't a frozen layer. + let app = [("102".into(), "{ACAD_OTHER".into()), ("331".into(), layer_handle(&p, "0")), ("102".into(), "}".into())]; + q.splice(r.start + 2..r.start + 2, app); let back = read_dxf(join(&q).as_bytes()).unwrap(); - assert_eq!(viewport_frozen(&back, 2), vec!["Walls".to_string(), "A B".to_string()]); + assert_eq!(viewport_frozen(&back, 2), ["Walls", "A B"]); +} + +#[test] +fn viewport_freeze_edited_in_autocad_is_read_as_edited() { + // Every layer thawed in AutoCAD (no 331 left) stays thawed; a layer it froze instead is read. + let (_, p) = frozen_vp_dxf(); + let r = vp_record(&p, "2"); + let thawed: Vec<(String, String)> = p.iter().enumerate().filter(|(i, (c, _))| !(r.contains(i) && c == "331")).map(|(_, t)| t.clone()).collect(); + assert!(viewport_frozen(&read_dxf(join(&thawed).as_bytes()).unwrap(), 2).is_empty()); + let mut zero = p.clone(); + for t in &mut zero[r] { + if t.0 == "331" { + t.1 = layer_handle(&p, "0"); + } + } + assert_eq!(viewport_frozen(&read_dxf(join(&zero).as_bytes()).unwrap(), 2), ["0"]); } #[test] @@ -725,7 +748,9 @@ fn viewport_frozen_layers_survive_dwg() { let dwg = write(&d, "t.dwg").unwrap(); let back = read(&dwg, "t.dwg").unwrap(); assert_eq!(viewport_frozen(&back, 2), vec!["Walls".to_string(), "A B".to_string()]); - // Survives via the CADCraft xdata: the DWG converter does not yet carry group 341 itself. + // The DWG holds them in group 331, what AutoCAD reads. + let p = pairs(&String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap()); + assert_eq!(frozen_331(&p), [layer_handle(&p, "Walls"), layer_handle(&p, "A B")]); } #[test] From 2d02a5faa599eab78497aad52af056765f29633a Mon Sep 17 00:00:00 2001 From: Andrea Ficarra Date: Sun, 1 Nov 2026 20:38:21 +0100 Subject: [PATCH 353/900] DXF: escape carets in TEXT, ATTDEF, ATTRIB and DIMENSION strings (#2574) * DXF: escape carets in TEXT, ATTDEF, ATTRIB and DIMENSION strings AutoCAD reads `^x` in a DXF string as a control character, so a TEXT of `10^2` opened in AutoCAD showed a control character instead of the caret. The DXF Reference writes a caret as `^` and a space: the writer now does for the text (group 1) of TEXT, ATTRIB, ATTDEF and DIMENSION and an ATTDEF's prompt (group 3), and the reader turns it back. A bare `^x` from older files stays as it is; single-line strings keep `^J` literal (they hold no line feeds). AutoLISP's entget shows the plain caret, and a DIMENSION's style name (also group 3) is left as written. Tests: crates/io/tests/it/text_carets_roundtrip.rs. Co-Authored-By: Claude Opus 5.5 * entget gives TEXT strings as the file has them, like MTEXT Decoding the carets in entity_groups broke entmod (it reads the groups as a file, so `A^ B` came back as `A^B`) and reached into an ATTDEF's embedded MTEXT. entity_groups is left as on main: it gives the file's groups, as it already does for MTEXT, and entmod reads them back unchanged (test entmod_of_entget_keeps_the_strings). Co-Authored-By: Claude Opus 5.5 * entget unescapes carets, entmake and entmod escape them e61b4dd left entget with the file's escapes, but entmake still read a plain `p^ q` as `p^q`. Now one rule, map_carets, picks the groups that hold an escaped string (the text, 1, and an ATTDEF's prompt, 3, up to an embedded MTEXT at group 101): entity_groups unescapes them and entity_from_groups escapes them before reading, so entget is plain, entmake takes plain strings and entmod of entget changes nothing. Tests: entget_shows_plain_carets_and_entmake_takes_them, entmod_leaves_the_embedded_text_alone. Co-Authored-By: Claude Opus 5.5 * Leave the parity docs to the maintainers CLAUDE.md: PRs don't edit the parity docs; the affected rows are named in the PR description instead. Co-Authored-By: Claude Opus 5.5 * Single-line strings read like MTEXT: a tab from AutoCAD survives AutoCAD writes a tab in a TEXT as `^I`. The reader left it as two characters and the writer then saved `^ I`, so the tab was lost. Single-line strings are now read with decode_contents, as MTEXT is (`^ `, `^I`, `^J`; other bare carets stay), and encode_line writes a caret as `^ ` and a tab as `^I`. unescape_carets is gone. Co-Authored-By: Claude Opus 5.5 * Rename map_carets to map_text_groups (it encodes tabs too) Co-Authored-By: Claude Opus 5.5 * Single-line strings keep a bare ^J; entity_from_groups doc A TEXT holding `A^JB` (from a file saved before this change, which wrote carets bare) was read as a line feed and saved as `A B`. Single-line strings now decode only `^ ` and `^I` (decode_line, decode_contents without line feeds), so `^J` stays two characters. entity_from_groups documents that it takes plain strings, as entity_groups gives them. The caret test also goes through a DWG. Co-Authored-By: Claude Opus 5.5 * Test a caret before a space and at the end of a TEXT Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/io/src/dxf_read.rs | 8 +- crates/io/src/dxf_read/entities.rs | 3 +- crates/io/src/dxf_read/mtext_dxf.rs | 37 +++++- crates/io/src/dxf_read/text.rs | 4 +- crates/io/src/dxf_write.rs | 5 +- crates/io/src/dxf_write/common.rs | 4 +- crates/io/src/dxf_write/entity.rs | 2 +- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/multiline_attributes.rs | 15 +++ crates/io/tests/it/text_carets_roundtrip.rs | 125 ++++++++++++++++++++ 10 files changed, 193 insertions(+), 11 deletions(-) create mode 100644 crates/io/tests/it/text_carets_roundtrip.rs diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 5b8865953..324caa361 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -143,9 +143,13 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { } /// An entity from the groups of a DXF record of type `kind` (without its `0` group), as the -/// reader makes it. AutoLISP's `entmake` and `entmod` are built on it. +/// reader makes it, with plain strings as [`crate::entity_groups`] gives them (not the file's +/// `^ ` escapes). AutoLISP's `entmake` and `entmod` are built on it. pub fn entity_from_groups(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> { - entity(&kind.to_ascii_uppercase(), tags) + // AutoLISP's strings are plain: escape them as the file has them (see `entity_groups`). + let mut tags = tags.to_vec(); + mtext_dxf::map_text_groups(kind, &mut tags, mtext_dxf::encode_line); + entity(&kind.to_ascii_uppercase(), &tags) } #[cfg(test)] diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index a074a6517..394feb785 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -1,5 +1,6 @@ use super::common::{T, common, ocs}; use super::hatch::hatch; +use super::mtext_dxf; use super::text::{attdef, attrib_modes, attrib_props, mtext_from, multiline_attrib, split_embedded, text_from}; use super::{ Arc, Attrib, Circle, Common, DimKind, Dimension, Ellipse, EntityKind, Face3d, Handle, HashMap, Helix, HelixConstrain, Insert, Leader, Line, @@ -189,7 +190,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef p14: t.p(14), p15: t.p(15), p16: t.p(16), - text: t.s(1).unwrap_or_default(), + text: mtext_dxf::decode_line(&t.s(1).unwrap_or_default()), style: t.s(3).unwrap_or_else(|| "Standard".into()), measurement: t.fd(42, 0.0), text_rotation: t.fd(53, 0.0).to_radians(), diff --git a/crates/io/src/dxf_read/mtext_dxf.rs b/crates/io/src/dxf_read/mtext_dxf.rs index 9d9213947..822384f73 100644 --- a/crates/io/src/dxf_read/mtext_dxf.rs +++ b/crates/io/src/dxf_read/mtext_dxf.rs @@ -1,7 +1,9 @@ //! MTEXT specifics of DXF (DXF Reference, MTEXT): control characters in the contents written //! as a caret and a letter (`^I` a tab, `^J` a line feed, `^ ` a caret), and the column groups //! 75 (type), 76 (count), 78 (flow reversed), 79 (auto height), 48 (width), 49 (gutter) and -//! 50 (column heights, after the column type; before it, 50 is the rotation). +//! 50 (column heights, after the column type; before it, 50 is the rotation). TEXT, ATTDEF, +//! ATTRIB and DIMENSION strings use the same encoding ([`encode_line`]): AutoCAD reads a bare +//! `^2` in `10^2` as a control character. use cadcraft_doc::{MText, MTextColumnType, MTextColumns}; use cadcraft_dxf::Tag; @@ -12,6 +14,15 @@ const MAX_COLUMNS: usize = 1_000; /// Decode the contents' `^I` (tab), `^J` (line feed) and `^ ` (caret). Other carets stay as /// they are (older files write stacked tolerances `\S+0.1^-0.1;` with a bare caret). pub(crate) fn decode_contents(s: &str) -> String { + decode(s, true) +} + +/// A single-line string as read: [`decode_contents`] without line feeds (`^J` stays as it is). +pub(crate) fn decode_line(s: &str) -> String { + decode(s, false) +} + +fn decode(s: &str, line_feeds: bool) -> String { if !s.contains('^') { return s.to_string(); } @@ -25,7 +36,7 @@ pub(crate) fn decode_contents(s: &str) -> String { match it.peek().copied() { Some(' ') => out.push('^'), Some('I') => out.push('\t'), - Some('J') => out.push('\n'), + Some('J') if line_feeds => out.push('\n'), _ => { out.push('^'); continue; @@ -36,6 +47,28 @@ pub(crate) fn decode_contents(s: &str) -> String { out } +/// A single-line string (TEXT, ATTDEF/ATTRIB, DIMENSION) for a DXF file: a caret as `^ ` and a +/// tab as `^I`, read back by [`decode_line`]. It holds no line break (the writer makes it a +/// space). +pub(crate) fn encode_line(s: &str) -> String { + s.replace('^', "^ ").replace('\t', "^I") +} + +/// Apply `f` ([`encode_line`] or [`decode_line`]) to the groups of a `kind` record that hold +/// an encoded string: the text (1), and an ATTDEF's prompt (3). An embedded MTEXT (from group 101) +/// has its own and is left alone. AutoLISP's entget and entmake/entmod use it. +pub(crate) fn map_text_groups(kind: &str, tags: &mut [Tag], f: fn(&str) -> String) { + let kind = kind.to_ascii_uppercase(); + if !matches!(kind.as_str(), "TEXT" | "ATTRIB" | "ATTDEF" | "DIMENSION") { + return; + } + for t in tags.iter_mut().take_while(|t| t.code != 101) { + if t.code == 1 || (t.code == 3 && kind == "ATTDEF") { + *t = Tag::s(t.code, f(&t.str())); + } + } +} + /// Encode the contents for a DXF string: a tab as `^I`, a line feed as `^J`, a caret as `^ `; /// other control characters (which draw nothing) are dropped. pub(crate) fn encode_contents(s: &str) -> String { diff --git a/crates/io/src/dxf_read/text.rs b/crates/io/src/dxf_read/text.rs index 492825df7..df73b878c 100644 --- a/crates/io/src/dxf_read/text.rs +++ b/crates/io/src/dxf_read/text.rs @@ -112,7 +112,7 @@ pub(super) fn text_from(t: &T) -> Text { insert: t.p(10), align_pt: if h == HAlign::Left && v == VAlign::Baseline { None } else { align }, height: t.fd(40, 0.2).max(1e-9), - value: t.s(1).unwrap_or_default(), + value: mtext_dxf::decode_line(&t.s(1).unwrap_or_default()), rotation: t.fd(50, 0.0).to_radians(), width_factor: t.fd(41, 1.0), oblique: t.fd(51, 0.0).to_radians(), @@ -172,7 +172,7 @@ pub(super) fn attdef(tags: &[Tag], c: &Common) -> Attrib { text, invisible: own.i(70).unwrap_or(0) & 1 != 0, constant: own.i(70).unwrap_or(0) & 2 != 0, - prompt: own.s(3).unwrap_or_default(), + prompt: mtext_dxf::decode_line(&own.s(3).unwrap_or_default()), props: Default::default(), multiline, modes: attrib_modes(own.0), diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 341f70e62..d6aa337aa 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -152,5 +152,8 @@ pub fn entity_groups(d: &Drawing, e: &Entity) -> (String, Vec) { entity(&mut w, d, e, "0", paper, &cx); let mut tags = w.t.into_iter(); let kind = tags.next().filter(|t| t.code == 0).map(|t| t.value.as_str()).unwrap_or_default(); - (kind, tags.take_while(|t| t.code != 0).filter(|t| t.code != 330).collect()) + let mut tags: Vec = tags.take_while(|t| t.code != 0).filter(|t| t.code != 330).collect(); + // Strings as AutoLISP sees them: `10^2`, not the file's `10^ 2`. + crate::dxf_read::mtext_dxf::map_text_groups(&kind, &mut tags, crate::dxf_read::mtext_dxf::decode_line); + (kind, tags) } diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index b09d90410..25d2bb074 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -255,7 +255,7 @@ pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attri }; w.p(10, insert); w.f(40, t.height); - w.s(1, &t.value); + w.s(1, crate::dxf_read::mtext_dxf::encode_line(&t.value)); if t.rotation != 0.0 { w.f(50, t.rotation.to_degrees()); } @@ -293,7 +293,7 @@ pub(super) fn text_tags(w: &mut W, d: &Drawing, t: &Text, attrib: Option<(&Attri w.i(280, 0); } if let Some(prompt) = attdef_prompt { - w.s(3, prompt); + w.s(3, crate::dxf_read::mtext_dxf::encode_line(prompt)); } w.s(2, &a.tag); w.i(70, attrib_flags(a)); diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index a33437017..f1e0a1d73 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -355,7 +355,7 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper // The actual measurement (read-only in DXF): AutoLISP's entget shows it. w.f(42, g.measurement); if !dm.text.is_empty() { - w.s(1, &dm.text); + w.s(1, crate::dxf_read::mtext_dxf::encode_line(&dm.text)); } w.s(3, &dm.style); if dm.text_rotation != 0.0 { diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index e0ff04f97..8442a7629 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -67,6 +67,7 @@ mod svg_arc_budget; mod svg_tiny_extents; mod table_cellstyle_roundtrip; mod tables_objects_roundtrip; +mod text_carets_roundtrip; mod text_left_justify; mod tolerance_roundtrip; mod user_lin_pat_roundtrip; diff --git a/crates/io/tests/it/multiline_attributes.rs b/crates/io/tests/it/multiline_attributes.rs index 625c38a30..428dc7db5 100644 --- a/crates/io/tests/it/multiline_attributes.rs +++ b/crates/io/tests/it/multiline_attributes.rs @@ -335,3 +335,18 @@ fn damaged_embedded_text_does_not_panic() { let _ = read_dxf(save(&d).as_bytes()).unwrap(); } } + +#[test] +fn entmod_leaves_the_embedded_text_alone() { + // entget and entmod convert the carets of the attribute's own groups, not the embedded MTEXT's, + // which has its own encoding: `^ J` there is a caret and a J, not a line feed. + let d = read_dxf(dxf(FIXTURE).replace("SITE\\PNAME", "SITE^ JNAME").as_bytes()).unwrap(); + let Some(e) = d.block("TAG").and_then(|b| b.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_)))) else { + panic!("no definition"); + }; + let (kind, groups) = cadcraft_io::entity_groups(&d, e); + let embedded: Vec = groups.iter().skip_while(|t| t.code != 101).filter(|t| t.code == 1).map(|t| t.str()).collect(); + assert_eq!(embedded, ["SITE^ JNAME"]); + let Some((_, EntityKind::AttDef(a))) = cadcraft_io::entity_from_groups(&kind, &groups) else { panic!("no ATTDEF") }; + assert_eq!(a.multiline.map(|m| m.mtext.contents), Some("SITE^JNAME".to_string())); +} diff --git a/crates/io/tests/it/text_carets_roundtrip.rs b/crates/io/tests/it/text_carets_roundtrip.rs new file mode 100644 index 000000000..1c30dd1a3 --- /dev/null +++ b/crates/io/tests/it/text_carets_roundtrip.rs @@ -0,0 +1,125 @@ +//! Carets in TEXT, ATTDEF, ATTRIB and DIMENSION strings are written as `^ ` and read back: AutoCAD +//! reads a bare `^2` in `10^2` as a control character. A tab is `^I`, as AutoCAD writes it. + +use cadcraft_doc::{Attrib, Common, DimKind, Dimension, Drawing, EntityKind, HAlign, Space, Text, VAlign}; +use cadcraft_geom::Vec3; +use cadcraft_io::{read_dxf, write_dxf}; + +fn text(value: &str) -> Text { + Text { + insert: Vec3::new(1.0, 1.0, 0.0), + align_pt: None, + height: 2.5, + value: value.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + } +} + +fn dimension(label: &str) -> Dimension { + Dimension { + kind: DimKind::Linear { rotation: 0.0 }, + defpt: Vec3::new(0.0, 5.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: label.into(), + 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(), + } +} + +fn drawing() -> Drawing { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Text(text("10^2 m, A^JB"))).unwrap(); + let attdef = Attrib { + tag: "AREA".into(), + text: text("1^3"), + invisible: false, + constant: false, + prompt: "Area in m^2".into(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }; + d.add(&Space::Model, Common::default(), EntityKind::AttDef(attdef)).unwrap(); + d.add(&Space::Model, Common::default(), EntityKind::Dimension(dimension("<> x10^3"))).unwrap(); + d +} + +fn strings(k: &EntityKind) -> Vec { + match k { + EntityKind::Text(t) => vec![t.value.clone()], + EntityKind::AttDef(a) => vec![a.text.value.clone(), a.prompt.clone()], + EntityKind::Dimension(dm) => vec![dm.text.clone()], + _ => Vec::new(), + } +} + +fn all_strings(d: &Drawing) -> Vec { + d.model.iter().flat_map(|e| strings(&e.kind)).collect() +} + +#[test] +fn carets_are_written_escaped_and_read_back() { + let dxf = write_dxf(&drawing()); + // `^J` stays two characters: a single-line string has no line feeds. + for escaped in ["10^ 2 m, A^ JB", "1^ 3", "Area in m^ 2", "<> x10^ 3"] { + assert!(dxf.contains(escaped), "{escaped}"); + } + let back = read_dxf(dxf.as_bytes()).unwrap(); + assert_eq!(all_strings(&back), ["10^2 m, A^JB", "1^3", "Area in m^2", "<> x10^3"]); + // Older files have bare carets, `^J` too: kept as they are (a single-line string has no line feed). + let old = read_dxf(dxf.replace("10^ 2 m, A^ JB", "10^2 m, A^JB").as_bytes()).unwrap(); + assert_eq!(all_strings(&old)[0], "10^2 m, A^JB"); + assert!(write_dxf(&old).contains("10^ 2 m, A^ JB")); + // AutoCAD writes a tab as `^I`: it is read as a tab and written back as `^I`. + let tab = read_dxf(dxf.replace("10^ 2 m, A^ JB", "A^IB").as_bytes()).unwrap(); + assert_eq!(all_strings(&tab)[0], "A\tB"); + assert!(write_dxf(&tab).contains("A^IB")); + // Through a DWG. + let dwg = cadcraft_io::write(&drawing(), "t.dwg").unwrap(); + assert_eq!(all_strings(&cadcraft_io::read(&dwg, "t.dwg").unwrap()), all_strings(&drawing())); +} + +#[test] +fn a_caret_before_a_space_or_at_the_end_round_trips() { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Text(text("x^ y^"))).unwrap(); + let dxf = write_dxf(&d); + assert!(dxf.contains("x^ y^ "), "{dxf}"); + assert_eq!(all_strings(&read_dxf(dxf.as_bytes()).unwrap()), ["x^ y^"]); +} + +#[test] +fn entget_shows_plain_carets_and_entmake_takes_them() { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), EntityKind::Text(text("x^ y 10^2"))).unwrap(); + let e = d.model.iter().next().unwrap(); + let (kind, groups) = cadcraft_io::entity_groups(&d, e); + assert!(groups.iter().any(|t| t.code == 1 && t.str() == "x^ y 10^2"), "{groups:?}"); + // entmod of entget changes nothing; entmake takes a plain string. + let (_, back) = cadcraft_io::entity_from_groups(&kind, &groups).unwrap(); + assert_eq!(strings(&back), ["x^ y 10^2"]); + let made = [cadcraft_dxf::Tag::s(1, "p^ q")]; + assert_eq!(strings(&cadcraft_io::entity_from_groups("TEXT", &made).unwrap().1), ["p^ q"]); + // Every kind, and a DIMENSION's style name (also group 3) as it is. + let d = drawing(); + for e in d.model.iter() { + let (kind, groups) = cadcraft_io::entity_groups(&d, e); + let (_, back) = cadcraft_io::entity_from_groups(&kind, &groups).unwrap(); + assert_eq!(strings(&back), strings(&e.kind), "{kind}"); + } +} From 06c5760ea6e477fa72857753b737d8a23123270b Mon Sep 17 00:00:00 2001 From: campbellcody <142101597+campbellcody@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:38:24 -0500 Subject: [PATCH 354/900] Persist QuickCalc history, variables and last answer (#2572) * Persist QuickCalc history, variables and last answer Store bounded calculator data in app preferences for desktop and web. Restore finite numeric and point variables, normalize names and ignore malformed entries without resuming transient drawing input. Covers gaps F22. Validation: 3079 workspace tests passed; wasm, fmt, assets, layers and i18n passed; UI screenshot inspected. Strict CI remains blocked by pre-existing nonminimal_bool lints in DXF and UI code; scoped UI Clippy passes with only that lint disabled. * quickcalc: apply the variable limit after validation Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 10 +- crates/ui-egui/src/palettes/quickcalc.rs | 166 +++++++++++++++++++++-- crates/ui-egui/tests/quickcalc_toggle.rs | 47 ++++++- 3 files changed, 212 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 97ab2faf4..142a589a3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -239,6 +239,8 @@ pub struct CadApp { pub canvas: canvas::CanvasState, /// Desktop HID status and navigation preferences; the web host supplies no HID backend. pub spacemouse: spacemouse::State, + /// Calculator data shared by its floating and docked views; durable fields live in prefs. + pub(crate) quickcalc: palettes::quickcalc::State, pub cmd: cmdline::CmdLine, pub status: Option<(String, f64)>, /// Drawings being read on worker threads ([`opening`]). @@ -327,6 +329,7 @@ impl CadApp { services, canvas: canvas::CanvasState::default(), spacemouse: spacemouse::State::default(), + quickcalc: palettes::quickcalc::State::default(), cmd: cmdline::CmdLine::default(), status: None, opening: opening::Opening::default(), @@ -465,6 +468,7 @@ impl CadApp { "interfaceLanguage": self.ui.interface_language.code(), "saveFormat": self.ui.save_format.as_str(), "saveVersion": self.ui.save_version, + "quickcalc": self.quickcalc.prefs(), }); if self.spacemouse.settings != spacemouse::Settings::default() { prefs["spacemouse"] = json!(self.spacemouse.settings); @@ -481,6 +485,9 @@ impl CadApp { /// Restore preferences saved by [`Self::prefs_json`]; unknown or malformed values are ignored. pub fn load_prefs(&mut self, json: &str) { let Ok(v) = serde_json::from_str::(json) else { return }; + if let Some(calculator) = v.get("quickcalc") { + self.quickcalc.load_prefs(calculator); + } if let Some(prefs) = v.get("spacemouse") { let _ = self.spacemouse.load_settings(prefs); } @@ -1129,7 +1136,8 @@ mod tests { frame(&mut a, &ctx, None); assert_eq!(Tokens::get(), Tokens::of(theme::SYSTEM_FALLBACK), "no OS appearance: the documented fallback"); assert_eq!(a.ui.theme, ThemePref::System); - assert_eq!(a.prefs_json(), r#"{"animations":"system","interfaceLanguage":"auto","saveFormat":"dxf","saveVersion":"2018","theme":"system"}"#); + let prefs: Value = serde_json::from_str(&a.prefs_json()).unwrap(); + assert_eq!(prefs["theme"], "system"); } #[test] diff --git a/crates/ui-egui/src/palettes/quickcalc.rs b/crates/ui-egui/src/palettes/quickcalc.rs index 5f601b2fa..d6948e363 100644 --- a/crates/ui-egui/src/palettes/quickcalc.rs +++ b/crates/ui-egui/src/palettes/quickcalc.rs @@ -14,10 +14,14 @@ const PICKED: &str = "QuickCalc: "; const MAX_HISTORY: usize = 100; /// Variables kept. const MAX_VARS: usize = 50; +/// Bound each saved expression/result and variable name, including hand-edited preferences. +// CAL accepts expressions up to 10,000 bytes, including a variable's name on its own. +const MAX_TEXT_BYTES: usize = 10_000; +const MAX_NAME_BYTES: usize = MAX_TEXT_BYTES; const KINDS: [(&str, &str); 4] = [("length", "Length"), ("area", "Area"), ("volume", "Volume"), ("angle", "Angle")]; #[derive(Clone, Default)] -struct State { +pub(crate) struct State { input: String, /// (expression, result) newest last. history: Vec<(String, String)>, @@ -39,8 +43,17 @@ struct State { pending: Option, } -fn id() -> egui::Id { - egui::Id::unique("cadcraft-quickcalc") +fn valid_name(name: &str) -> bool { + name.len() <= MAX_NAME_BYTES + && name.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && !["pi", "e", "ans"].contains(&name) +} + +/// CAL variables are finite numbers or 2D points; no nested arrays or objects. +fn valid_value(value: &Value) -> bool { + let number = |v: &Value| v.as_f64().is_some_and(f64::is_finite); + number(value) || value.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(number)) } /// A variable's value as typed into an expression: a number, or a point as `[x,y]`. @@ -57,6 +70,61 @@ fn result_value(r: &Value) -> Option { } impl State { + /// Only durable calculator data: never resume an in-flight drawing pick after a restart. + pub(crate) fn prefs(&self) -> Value { + let history: Vec<_> = self + .history + .iter() + .rev() + .take(MAX_HISTORY) + .filter(|(expr, result)| expr.len() <= MAX_TEXT_BYTES && result.len() <= MAX_TEXT_BYTES) + .collect(); + let vars: Vec<_> = self.vars.iter().filter(|(name, value)| valid_name(name) && valid_value(value)).take(MAX_VARS).collect(); + json!({"history": history.into_iter().rev().collect::>(), "vars": vars, + "ans": self.ans.as_ref().filter(|v| valid_value(v))}) + } + + /// Restore bounded, independently validated entries; older preferences have no calculator. + pub(crate) fn load_prefs(&mut self, value: &Value) { + if !value.is_object() { + return; + } + if let Some(history) = value.get("history").and_then(Value::as_array) { + self.history = history + .iter() + .rev() + .take(MAX_HISTORY) + .filter_map(|entry| { + let pair = entry.as_array().filter(|a| a.len() == 2)?; + let expr = pair.first()?.as_str().filter(|s| s.len() <= MAX_TEXT_BYTES)?; + let result = pair.get(1)?.as_str().filter(|s| s.len() <= MAX_TEXT_BYTES)?; + Some((expr.to_string(), result.to_string())) + }) + .collect(); + self.history.reverse(); + } + if let Some(vars) = value.get("vars").and_then(Value::as_array) { + self.vars.clear(); + for entry in vars { + // Only valid entries count toward the limit. + if self.vars.len() >= MAX_VARS { + break; + } + let Some(pair) = entry.as_array().filter(|a| a.len() == 2) else { continue }; + let Some(name) = pair.first().and_then(Value::as_str).filter(|s| s.len() <= MAX_NAME_BYTES) else { continue }; + let name = name.to_ascii_lowercase(); + let Some(value) = pair.get(1).filter(|v| valid_value(v)) else { continue }; + if valid_name(&name) { + self.vars.retain(|(key, _)| key != &name); + self.vars.push((name, value.clone())); + } + } + } + if let Some(ans) = value.get("ans") { + self.ans = valid_value(ans).then(|| ans.clone()); + } + } + fn vars_json(&self) -> Value { let mut m = serde_json::Map::new(); for (k, v) in &self.vars { @@ -88,9 +156,7 @@ impl State { } fn add_var(&mut self, app: &mut CadApp) { let name = self.var_name.trim().to_ascii_lowercase(); - let valid = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) - && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') - && !["pi", "e", "ans"].contains(&name.as_str()); + let valid = valid_name(&name); if !valid { self.error = Some(crate::tl!("A variable name starts with a letter and has only letters, digits and _").into()); return; @@ -219,7 +285,7 @@ fn value_row(ui: &mut egui::Ui, value: &mut String) { /// Quick Calculator dock body: expression entry with evaluation, variables and unit conversion. pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); - let mut st: State = ui.ctx().data_mut(|d| d.get_temp(id())).unwrap_or_default(); + let mut st = std::mem::take(&mut app.quickcalc); st.collect(app); egui::ScrollArea::vertical().id_salt("dock-quickcalc").auto_shrink([false, false]).show(ui, |ui| { ui.add_space(6.0); @@ -371,16 +437,98 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { }); }); }); - ui.ctx().data_mut(|d| d.insert_temp(id(), st)); + app.quickcalc = st; } #[cfg(test)] mod tests { + use cadcraft_engine::Session; use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; - use super::value_row; + use super::{MAX_HISTORY, MAX_TEXT_BYTES, MAX_VARS, State, value_row}; + use crate::{CadApp, Services}; + use serde_json::{Value, json}; + + #[test] + fn preferences_restore_numbers_points_history_and_ans_without_pending_input() { + let mut app = CadApp::new(Session::default(), Services::default()); + let mut state = State { var_name: "Width".into(), var_expr: "2+3".into(), ..State::default() }; + state.add_var(&mut app); + state.var_name = "origin".into(); + state.var_expr = "[3,4]".into(); + state.add_var(&mut app); + state.input = "origin*width".into(); + state.evaluate(&mut app); + state.pending = Some(123); + state.error = Some("transient error".into()); + app.quickcalc = state; + + let mut restarted = CadApp::new(Session::default(), Services::default()); + let drawing = restarted.session.doc().unwrap().clone(); + restarted.load_prefs(&app.prefs_json()); + let mut state = std::mem::take(&mut restarted.quickcalc); + assert_eq!(state.history, [("origin*width".into(), "15,20".into())]); + assert_eq!(state.vars, [("width".into(), json!(5.0)), ("origin".into(), json!([3.0, 4.0]))]); + assert_eq!(state.ans, Some(json!([15.0, 20.0]))); + assert!(state.pending.is_none()); + assert!(state.error.is_none()); + assert!(state.input.is_empty()); + state.input = "ans+origin".into(); + state.evaluate(&mut restarted); + assert_eq!(state.ans, Some(json!([18.0, 24.0]))); + assert_eq!(restarted.session.doc().unwrap(), &drawing); + assert!(restarted.session.running.is_none()); + } + + #[test] + fn malformed_entries_do_not_hide_valid_calculator_data_or_other_preferences() { + let mut app = CadApp::new(Session::default(), Services::default()); + app.load_prefs( + &json!({"theme": "light", "quickcalc": { + "history": [null, ["bad"], [false, 3], ["2+3", "5"]], + "vars": [["PI", 3], ["1bad", 5], ["nested", [[1,2],3]], ["bad", [1,2,3]], + ["object", {"x":1}], ["WIDTH", 4], ["width", 5], ["origin", [3,4]]], + "ans": "NaN" + }}) + .to_string(), + ); + assert_eq!(app.ui.theme.as_str(), "light"); + assert_eq!(app.quickcalc.history, [("2+3".into(), "5".into())]); + assert_eq!(app.quickcalc.vars, [("width".into(), json!(5)), ("origin".into(), json!([3, 4]))]); + assert!(app.quickcalc.ans.is_none()); + let saved = app.prefs_json(); + for malformed in ["not JSON", "{}", r#"{"quickcalc":null}"#, r#"{"quickcalc":{"vars":false,"history":0}}"#] { + app.load_prefs(malformed); + assert_eq!(app.prefs_json(), saved); + } + } + + #[test] + fn stored_calculator_data_is_bounded_and_cleared_data_stays_cleared() { + let mut state = State::default(); + let history: Vec<_> = (0..MAX_HISTORY + 10).map(|i| json!([i.to_string(), i.to_string()])).collect(); + let vars: Vec<_> = (0..MAX_VARS + 10).map(|i| json!([format!("v{i}"), i])).collect(); + state.load_prefs(&json!({"history": history, "vars": vars, "ans": 5})); + assert_eq!(state.history.len(), MAX_HISTORY); + assert_eq!(state.history.first().unwrap().0, "10"); + assert_eq!(state.history.last().unwrap().0, (MAX_HISTORY + 9).to_string()); + assert_eq!(state.vars.len(), MAX_VARS); + let oversized = "x".repeat(MAX_TEXT_BYTES + 1); + state.load_prefs(&json!({"history": [[oversized, "1"]], "vars": [[oversized, 1]]})); + assert!(state.history.is_empty()); + assert!(state.vars.is_empty()); + let mut restored = State { history: vec![("old".into(), "1".into())], vars: vec![("old".into(), json!(1))], ..State::default() }; + restored.load_prefs(&state.prefs()); + assert!(restored.history.is_empty()); + assert!(restored.vars.is_empty()); + assert_eq!(restored.ans, Some(json!(5))); + // An invalid answer is discarded rather than reused as a calculator value. + restored.load_prefs(&json!({"ans": [1, null]})); + assert_eq!(restored.ans, None); + assert_eq!(restored.prefs()["ans"], Value::Null); + } /// The conversion value field is named by its visible label under bundled fonts only, so a /// system face cannot hide a missing glyph and a bare "1" placeholder cannot pass as a name. diff --git a/crates/ui-egui/tests/quickcalc_toggle.rs b/crates/ui-egui/tests/quickcalc_toggle.rs index 9b6bec6d1..caf52f0df 100644 --- a/crates/ui-egui/tests/quickcalc_toggle.rs +++ b/crates/ui-egui/tests/quickcalc_toggle.rs @@ -9,10 +9,17 @@ use egui_kittest::kittest::{NodeT, Queryable, by}; use serde_json::{Value, json}; fn harness() -> Harness<'static, CadApp> { + harness_from_prefs("{}", false) +} + +fn harness_from_prefs(prefs: &str, render: bool) -> Harness<'static, CadApp> { let mut app = CadApp::new(Session::default(), Services::default()); + app.load_prefs(prefs); app.ui.start_tab = false; app.ui.in_window_menu = false; - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_ui_state( + let builder = Harness::builder().with_size(vec2(1280.0, 800.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state( |ui, app: &mut CadApp| { app.logic(&ui.ctx().clone()); app.ui(ui); @@ -23,6 +30,44 @@ fn harness() -> Harness<'static, CadApp> { h } +#[test] +fn restarting_restores_calculator_data_and_ui_edits_are_saved_when_hidden() { + let prefs = json!({"quickcalc": { + "history": [["2+3", "5"]], "vars": [["width", 5]], "ans": 5 + }}) + .to_string(); + let screenshot = std::env::var_os("CADCRAFT_QUICKCALC_SHOT"); + let mut h = harness_from_prefs(&prefs, screenshot.is_some()); + h.state_mut().run("ui.panel.quickcalc", Value::Null).unwrap(); + h.run_steps(5); + assert!(h.query_all(by().value("2+3")).next().is_some()); + expression(&h).click(); + h.run_steps(3); + expression(&h).type_text("ans+width"); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "=").click(); + h.run_steps(3); + let prefs: Value = serde_json::from_str(&h.state().prefs_json()).unwrap(); + assert_eq!(prefs["quickcalc"]["ans"], 10.0); + assert_eq!(prefs["quickcalc"]["history"][1], json!(["ans+width", "10"])); + if let Some(path) = screenshot { + h.render().unwrap().save(std::path::PathBuf::from(path)).unwrap(); + } + + h.get_by_role_and_label(Role::Button, "Clear History").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "×").click(); + h.run_steps(3); + h.state_mut().run("ui.toggle.quickcalc", Value::Null).unwrap(); + h.run_steps(5); + let mut restarted = CadApp::new(Session::default(), Services::default()); + restarted.load_prefs(&h.state().prefs_json()); + let prefs: Value = serde_json::from_str(&restarted.prefs_json()).unwrap(); + assert_eq!(prefs["quickcalc"]["history"], json!([])); + assert_eq!(prefs["quickcalc"]["vars"], json!([])); + assert_eq!(prefs["quickcalc"]["ans"], 10.0); +} + /// In these tests QuickCalc floats alone; scope to its body to avoid the Properties text fields. /// Its first text input is the expression, before conversion values and variable definitions. fn expression<'a>(h: &'a Harness<'_, CadApp>) -> egui_kittest::Node<'a> { From f0b46e34dc5a32153a2f062eee761f6660d69ab7 Mon Sep 17 00:00:00 2001 From: Steffen <576706+camperking@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:38:27 +0100 Subject: [PATCH 355/900] Hit tests don't lay out dashes: moving the mouse over a block stays smooth (#2603) * Hit tests don't lay out dashes: moving the mouse over a block stays smooth (#1285) Every mouse move hit-tests the block references under the cursor, and hit_polylines built them with a full-detail display list, one primitive per dash. A fine pattern on long lines in a block inserted at 0.001 made millions of dashes per move. Options::linetypes off draws every line whole and continuous, and hit_polylines uses it for blocks, dimensions and multileaders. A dashed line in a block is now hit across its gaps, as one outside a block already was. Co-Authored-By: Claude Opus 5.5 * render: with linetypes off, a lightweight polyline is one continuous stroke Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Steffen Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/select.rs | 52 ++++++++++++++++++++++++++- crates/io/src/pdf.rs | 1 + crates/render/src/draw.rs | 8 ++--- crates/render/src/mline.rs | 2 +- crates/render/src/pipeline.rs | 5 +++ crates/render/src/tests.rs | 25 +++++++++++++ crates/ui-egui/src/canvas/list.rs | 1 + crates/ui-egui/src/canvas/viewport.rs | 1 + 8 files changed, 89 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 6c70bee37..8047412fd 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -29,7 +29,7 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { let list = cadcraft_render::build_entities( d, std::iter::once(e), - &cadcraft_render::Options { tolerance: tol, text: false, ..Default::default() }, + &cadcraft_render::Options { tolerance: tol, text: false, linetypes: false, ..Default::default() }, ); v = list.prims.iter().map(|p| list.points(p).to_vec()).collect(); v.push(vec![c[0], c[1], c[2], c[3], c[0]]); @@ -502,6 +502,56 @@ mod tests { // Only one within reach: that one, whatever the order. assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line)); } + + /// 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(); + d.linetypes.extend(cadcraft_doc::library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED")); + let mut line = + Entity::new(Handle(1), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(length, length, 0.0) })); + line.common.linetype = "DASHED".into(); + let mut blk = cadcraft_doc::Block::new("B"); + blk.entities.push(line); + d.blocks.insert("B".into(), std::sync::Arc::new(blk)); + let insert = cadcraft_doc::Insert { + block: "B".into(), + insert: Vec3::new(0.0, 0.0, 0.0), + scale: Vec3::new(scale, scale, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }; + let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap(); + (d, h) + } + + /// Every mouse move over a block hit-tests what it draws. Two blocks with a fine pattern on + /// long lines (inserted at 0.001) made 5.8 million dashes, and half a second, per move (#1285). + #[test] + fn hit_testing_a_block_does_not_lay_out_its_dashes() { + let (d, h) = dashed_block(20_000.0, 0.001); + let e = d.entity(h).unwrap(); + let drawn = cadcraft_render::build_entities(&d, std::iter::once(e.as_ref()), &cadcraft_render::Options { text: false, ..Default::default() }); + assert!(drawn.prims.len() > 10_000, "the pattern draws {} dashes", drawn.prims.len()); + // The line, and the block's bounding rectangle. + assert_eq!(hit_polylines(&d, e, 0.01).len(), 2); + } + + /// A dashed line in a block is hit across its gaps, as one outside a block is. + #[test] + fn a_dashed_line_in_a_block_is_picked_in_a_gap() { + let (d, h) = dashed_block(100.0, 1.0); + let e = d.entity(h).unwrap(); + let drawn = cadcraft_render::build_entities(&d, std::iter::once(e.as_ref()), &cadcraft_render::Options { text: false, ..Default::default() }); + let (a, b) = (drawn.prims.first().unwrap(), drawn.prims.get(1).unwrap()); + let (end, start) = (*drawn.points(a).last().unwrap(), *drawn.points(b).first().unwrap()); + assert!(end.dist(start) > 0.01, "a gap between the first two dashes"); + let gap = end + (start - end) * 0.5; + assert_eq!(pick(&d, &Space::Model, gap, end.dist(start) / 8.0), Some(h)); + } } #[cfg(test)] diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 3f35233a8..b06580d53 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -520,6 +520,7 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String tolerance: 0.001, min_dash: 0.0, text: true, + linetypes: true, fill: true, lineweights, view_height: 0.0, diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 7e00b4c8c..39b0ddfcc 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -77,7 +77,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12); let lw = if b.opts.lineweights { lw } else { 0.0 }; // Stroke a polyline with the entity's linetype. - let stroke = |b: &mut Builder, pts: &[Vec2]| match < { + let stroke = |b: &mut Builder, pts: &[Vec2]| match lt.as_ref().filter(|_| b.opts.linetypes) { Some(lt) => { let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12); for dash in linetype::apply(pts, lt, ltscale, min) { @@ -140,7 +140,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { // the list serves a whole band of zooms. Plots and exports draw the band alone, and // a transparent band gets none (its alpha would add up along the centre). let hairline = !b.plotting && b.opts.min_dash > 0.0 && b.transparency == 0; - match < { + match lt.as_ref().filter(|_| b.opts.linetypes) { // Dashed: each dash a filled piece of the band; dots a line across it. Some(lt) => { let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12); @@ -173,7 +173,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { } EntityKind::LwPolyline(p) => { let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; - if p.plinegen || lt.is_none() { + if !b.opts.linetypes || p.plinegen || lt.is_none() { stroke(b, &pl.tessellate(tol)); } else { for s in pl.segments() { @@ -355,7 +355,7 @@ fn draw_dimension(b: &mut Builder, ctx: &Ctx, e: &Entity, dm: &cadcraft_doc::Dim /// Draw a polyline with a linetype (None: continuous). pub(crate) fn stroke_with(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, ltscale: f64, pts: &[Vec2]) { - match lt { + match lt.filter(|_| b.opts.linetypes) { Some(lt) => { let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12); for dash in linetype::apply(pts, lt, ltscale, min) { diff --git a/crates/render/src/mline.rs b/crates/render/src/mline.rs index bbaacb5cc..882f3a626 100644 --- a/crates/render/src/mline.rs +++ b/crates/render/src/mline.rs @@ -59,7 +59,7 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &MLine, rgb: Ink, #[allow(clippy::too_many_arguments)] fn stroke(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, scale: f64, min: f64, pts: &[Vec2]) { - match lt { + match lt.filter(|_| b.opts.linetypes) { Some(lt) => { for dash in linetype::apply(pts, lt, scale, min) { match dash.as_slice() { diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 8cbcb95b9..3fc72f518 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -15,6 +15,10 @@ pub struct Options { pub min_dash: f64, /// Draw text (off for very coarse previews). pub text: bool, + /// Draw lines with their linetypes. Off, every line is drawn whole and continuous, as picking + /// sees it: a dashed line is hit across its gaps, and a small pattern on a long line makes + /// millions of dashes. + pub linetypes: bool, /// Highlighted (selected) handles are not special here; the canvas overlays them. pub fill: bool, pub lineweights: bool, @@ -52,6 +56,7 @@ impl Default for Options { tolerance: 0.001, min_dash: 0.0, text: true, + linetypes: true, fill: true, lineweights: false, view_height: 0.0, diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ae35f27f9..fe2dc6470 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1122,3 +1122,28 @@ fn raster_hatch_pattern_matches_one_by_one() { assert!(render(&l, &view, &o).unwrap().data() == render_one_by_one(&l, &view, &o).data()); } } + +/// `Options::linetypes` off draws a dashed line, a dashed wide polyline and a linetype on a layer +/// as the same whole line a Continuous one draws: what hit tests look at. +#[test] +fn without_linetypes_every_line_is_drawn_whole() { + let drawing = |lt: &str| { + let mut d = Drawing::new_imperial(); + d.linetypes.extend(cadcraft_doc::library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED")); + d.layer_mut("0").unwrap().linetype = lt.into(); + let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(30.0, 0.0, 0.0) }); + d.add(&Space::Model, Common::default(), line).unwrap(); + let vertices = [(0.0, 5.0), (30.0, 5.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec(); + let wide = cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.2, elevation: 0.0, plinegen: false }; + d.add(&Space::Model, Common::default(), EntityKind::LwPolyline(wide)).unwrap(); + d + }; + let whole = Options { linetypes: false, ..Options::default() }; + let continuous = build(&drawing("Continuous"), &Space::Model, &Options::default()); + let dashed = build(&drawing("DASHED"), &Space::Model, &whole); + assert_eq!(dashed.prims.len(), continuous.prims.len()); + assert_eq!(dashed.verts, continuous.verts); + assert_eq!(dashed.tris, continuous.tris); + let drawn = build(&drawing("DASHED"), &Space::Model, &Options::default()); + assert!(drawn.prims.len() > 2 * continuous.prims.len(), "drawn with its linetype: {} primitives", drawn.prims.len()); +} diff --git a/crates/ui-egui/src/canvas/list.rs b/crates/ui-egui/src/canvas/list.rs index 2d548264e..f965b0ae1 100644 --- a/crates/ui-egui/src/canvas/list.rs +++ b/crates/ui-egui/src/canvas/list.rs @@ -128,6 +128,7 @@ pub(super) fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], c // level of detail must hold at the finest one. min_dash: 2f64.powi(lod_band) * 2.0, text: true, + linetypes: true, fill: true, lineweights: lwdisplay, view_height: st.paper_view().height, diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index c79354b6c..0857e23ee 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -128,6 +128,7 @@ pub(super) fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Con tolerance: 2f64.powi(band) * 0.5, min_dash: 2f64.powi(band) * 2.0, text: true, + linetypes: true, fill: true, lineweights: lwdisplay, view_height: st.paper_view().height, From ccbc4fa8541ec71655448eddb2f2e283006836fc Mon Sep 17 00:00:00 2001 From: Books Date: Mon, 2 Nov 2026 06:38:31 +1100 Subject: [PATCH 356/900] DXF: link dimension sources to their associations (fixes #2221) (#2589) * DXF: link dimension sources to their associations (#2221) Source objects lacked the persistent reactor back to their DIMASSOC. Register validated source and intersection references once through the existing reactor list, keeping a self-link from duplicating the dimension's own reactor. Synthetic regressions cover missing links, repeated references and self-links. * Parity checklist: regenerated for dimension reactor gate * Parity checklist: regenerated after merging main * DXF: a dimension source keeps its other reactors next to the DIMASSOC (review on #2589) The DIMASSOC reactor made the writer emit an ACAD_REACTORS group, so the raw passthrough skipped the source's retained foreign reactors. They are now merged, deduplicated, into that one group. Test: a line reactor-linked to a kept object keeps both links after an associative dimension is added. * DXF: an unmodelled DIMASSOC source gets the DIMASSOC reactor (review on #2589) Unknown entities are written by the raw passthrough, which never saw the planned reactors. The map is now passed to dxf_raw::finish and merged into the entity's reactor group. Test: an unknown entity with a dimension snapped to it names the DIMASSOC. * Docs: leave the file-format parity document to maintainers (review on #2589) * DXF: pass the unknown-entity reactors as one argument (review on #2589) * DXF: collapse the extension dictionary condition (review on #2589) * Test: pin the reactor merge for dimension sources (review on #2589) * DXF: a kept extension dictionary follows the reactors group (review on #2589) When a written record already had its reactors group, the kept extension dictionary was inserted right after the handle, ahead of it; the DXF reference puts the reactors first. The reactor tests now find each group by name, so either order can no longer pass. * docs: leave the generated parity checklist to maintainers Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/io/src/dxf_raw.rs | 60 +++++-- crates/io/src/dxf_write.rs | 4 +- crates/io/src/dxf_write/sections.rs | 17 +- crates/io/tests/dimassoc_angular_radial.rs | 47 ++++++ crates/io/tests/it/roundtrip_audit.rs | 179 +++++++++++++++++++++ 5 files changed, 288 insertions(+), 19 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9b755f80f..16ea48b6c 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -846,7 +846,7 @@ fn unknown_handles(d: &Drawing) -> HashSet { } /// Put the drawing's foreign data back into a written file's tags (see the module comment). -pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { +pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap>) { let f = d.foreign.as_ref(); let unknown = unknown_handles(d); let xd: XdataOf = all_entities(d).filter(|e| !e.common.xdata.is_empty()).map(|e| (e.handle, e.common.xdata.as_slice())).collect(); @@ -993,8 +993,10 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { let (Some(zero), Some(ub)) = (t.first(), t.get(1..)) else { continue }; let ur = Rec { sec: sec.clone(), kind: zero.str(), start: 0, end: 0 }; let x = head(ub).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h)); + // Reactors the writer planned for this source (a DIMASSOC, an associative hatch). + let extra = head(ub).handle.and_then(|h| handle(&h)).and_then(|h| reactors.get(&h)).map_or(&[][..], Vec::as_slice); out.push(zero.clone()); - record(&map, &ur, ub, x.as_deref(), true, false, &mut out); + record(&map, &ur, ub, x.as_deref(), Some(extra), false, &mut out); } out.extend(tags.get(r.start).cloned()); let x = extra_for(f, &xd, r, b, &block); @@ -1002,7 +1004,7 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing) { out.extend(b.iter().cloned()); continue; } - record(&map, r, b, x.as_deref(), false, Some(r.start) == root, &mut out); + record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out); } add_appids(&mut out); let top = max_handle(&out).saturating_add(1); @@ -1076,10 +1078,23 @@ fn plan_unknown(d: &Drawing, recs: &[Rec], tags: &[Tag], roles: &HashMap, unknown: Option<&[String]>) -> Vec { + let extra = unknown.unwrap_or_default(); + let mut have: HashSet = h.reactors.iter().cloned().collect(); + let kept = x.filter(|_| !(unknown.is_some() && h.has_reactors)).into_iter().flat_map(|x| x.reactors.iter()).filter_map(|r| map.get(&r.hex())); + kept.chain(extra.iter().cloned()).filter(|r| r != "0" && have.insert(norm(r))).collect() +} + /// A written record with its kept extras, remapped references (unknown entities) and kept /// dictionary entries (the named object dictionary). -fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: bool, root: bool, out: &mut Vec) { +fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Option<&[String]>, root: bool, out: &mut Vec) { let h = head(b); + let adds = reactors_to_add(map, &h, x, unknown); + let mut in_reactors = false; let entity = matches!(r.sec.as_str(), "ENTITIES" | "BLOCKS") && r.kind != "BLOCK"; let xdata_at = b.iter().position(|t| t.code == 1001).unwrap_or(b.len()); let own_apps: HashSet = b.iter().filter(|t| t.code == 1001).map(|t| up(&t.str())).collect(); @@ -1096,6 +1111,12 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: bool let rgb = b.iter().take(xdata_at).find(|t| t.code == 420).map(Tag::str); let has_book = b.iter().take(xdata_at).any(|t| t.code == 430); let handle_at = b.iter().position(|t| matches!(t.code, 5 | 105)); + // A kept extension dictionary follows the reactors group, as the DXF reference orders them. + let reactors_end = b.iter().position(|t| t.code == 102 && t.str().trim() == "{ACAD_REACTORS").and_then(|s| { + let rest = b.get(s + 1..)?; + rest.iter().position(|t| t.code == 102 && t.str().trim() == "}").map(|e| s + 1 + e) + }); + let xdict_at = if h.has_reactors { reactors_end.or(handle_at) } else { handle_at }; let mut seen_owner = false; for (i, t) in b.iter().enumerate() { if i == props_at @@ -1114,8 +1135,18 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: bool { xdata(map, x, &own_apps, out); } + if t.code == 102 { + match t.str().trim() { + "{ACAD_REACTORS" => in_reactors = true, + "}" if in_reactors => { + in_reactors = false; + out.extend(adds.iter().map(|a| Tag::s(330, a.clone()))); + } + _ => {} + } + } let mut t = t.clone(); - if unknown && i < xdata_at && is_pointer(t.code) && t.code != 102 { + if unknown.is_some() && i < xdata_at && is_pointer(t.code) && t.code != 102 { if t.code == 330 && !seen_owner { seen_owner = true; } else { @@ -1123,18 +1154,17 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: bool } } out.push(t); - if Some(i) == handle_at + if Some(i) == handle_at && !h.has_reactors && !adds.is_empty() { + out.push(Tag::s(102, "{ACAD_REACTORS")); + out.extend(adds.iter().map(|a| Tag::s(330, a.clone()))); + out.push(Tag::s(102, "}")); + } + if Some(i) == xdict_at && let Some(x) = x + && h.xdict.is_none() + && let Some(xd) = x.xdict { - if !h.has_reactors { - let rs: Vec = x.reactors.iter().map(|r| r.hex()).collect(); - map.handle_group(out, "ACAD_REACTORS", 330, &rs); - } - if h.xdict.is_none() - && let Some(xd) = x.xdict - { - map.handle_group(out, "ACAD_XDICTIONARY", 360, &[xd.hex()]); - } + map.handle_group(out, "ACAD_XDICTIONARY", 360, &[xd.hex()]); } } if let Some(x) = x { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index d6aa337aa..b93471b01 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -43,8 +43,8 @@ struct W { pstyles: HashMap, /// Upper-case layer name → its LAYER table record handle (group 331/341 of viewports). layers: HashMap, - /// Persistent reactors of boundary objects: each source object of an associative hatch → - /// the hatches (groups `{ACAD_REACTORS 330 …}`), from [`hatch_reactors`]. + /// Persistent reactors of source geometry: the associative hatches and DIMASSOC objects + /// that follow it (groups `{ACAD_REACTORS 330 …}`). reactors: HashMap>, } diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index e9f8a9e35..b2eff022d 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -874,7 +874,20 @@ fn plan_dimension_associations(d: &Drawing, all_spaces: &[&EntityStore], w: &mut if let EntityKind::Dimension(dm) = &e.kind { let (flags, refs) = std_assoc_refs(d, dm); if !refs.is_empty() { - cx.assoc.insert(e.handle, AssocObj { xdict: w.h(), handle: w.h(), flags, refs }); + let assoc = AssocObj { xdict: w.h(), handle: w.h(), flags, refs }; + // Source geometry must name the DIMASSOC as well, or other readers do not + // follow later edits. Both objects of an intersection need the reactor. + for source in assoc.refs.iter().flat_map(|r| std::iter::once(r.main).chain(r.other)) { + // common_x already gives the dimension its own DIMASSOC reactor. + if source == e.handle { + continue; + } + let reactors = w.reactors.entry(source).or_default(); + if !reactors.contains(&assoc.handle) { + reactors.push(assoc.handle.clone()); + } + } + cx.assoc.insert(e.handle, assoc); } } } @@ -1117,7 +1130,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34 if let Some(t) = w.t.get_mut(seed_pos + 1) { *t = Tag::s(5, seed); } - crate::dxf_raw::finish(&mut w.t, d); + crate::dxf_raw::finish(&mut w.t, d, &w.reactors); crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013); add_class_instance_counts(&mut w.t, target); mark_xrefs(&mut w.t, d); diff --git a/crates/io/tests/dimassoc_angular_radial.rs b/crates/io/tests/dimassoc_angular_radial.rs index ec1a11f69..f955ad7b5 100644 --- a/crates/io/tests/dimassoc_angular_radial.rs +++ b/crates/io/tests/dimassoc_angular_radial.rs @@ -288,3 +288,50 @@ fn standard_dimassoc_associates_in_dxf_and_dwg() { let back = read(&dwg, "case.dwg").unwrap(); assert_standard_assoc(&c, &back, "DWG"); } + +/// Every source object names each DIMASSOC that follows it once, before its owner group. +#[test] +fn dimension_sources_carry_their_persistent_reactors() { + let c = case(); + let text = write_dxf(&c.d); + let all = records(&text); + for dimension in [c.hd, c.hr, c.ha, c.hl] { + let assoc = dimassoc(&text, dimension).expect("DIMASSOC"); + let reactor = string(&assoc, 5).expect("DIMASSOC handle"); + for reference in point_refs(&assoc) { + // Both objects of an intersection need the link back. Repeated snaps to one + // object must not write the same DIMASSOC reactor twice. + for source in [string(&reference, 331), string(&reference, 332)].into_iter().flatten() { + let geometry = all.iter().find(|r| string(r, 5) == Some(source)).expect("referenced geometry"); + let start = geometry.iter().position(|(code, value)| *code == 102 && value == "{ACAD_REACTORS").expect("source reactor group"); + let end = + start + 1 + geometry.iter().skip(start + 1).position(|(code, value)| *code == 102 && value == "}").expect("reactor group end"); + assert_eq!(geometry[start + 1..end].iter().filter(|(code, value)| *code == 330 && value == reactor).count(), 1); + assert_eq!(start, 2, "reactors immediately follow the entity handle"); + assert_eq!(geometry.get(end + 1).map(|(code, _)| *code), Some(330), "entity owner follows reactors"); + assert_eq!(geometry.iter().filter(|(code, value)| *code == 102 && value == "{ACAD_REACTORS").count(), 1); + } + } + } +} + +/// Malformed self-links must not duplicate the reactor the dimension already carries. +#[test] +fn a_self_referential_dimension_writes_its_reactor_once() { + let mut c = case(); + assert!(c.d.model.modify(c.hl, |e| { + let EntityKind::Dimension(dm) = &mut e.kind else { panic!("dimension") }; + for reference in &mut dm.assoc { + reference.handle = c.hl; + } + })); + let text = write_dxf(&c.d); + let assoc = dimassoc(&text, c.hl).expect("DIMASSOC"); + let reactor = string(&assoc, 5).expect("DIMASSOC handle"); + let all = records(&text); + let handle = c.hl.hex(); + let dimension = all.iter().find(|r| string(r, 5) == Some(&handle)).expect("dimension record"); + let start = dimension.iter().position(|(code, value)| *code == 102 && value == "{ACAD_REACTORS").expect("reactor group"); + let end = start + 1 + dimension.iter().skip(start + 1).position(|(code, value)| *code == 102 && value == "}").expect("reactor group end"); + assert_eq!(dimension[start + 1..end].iter().filter(|(code, value)| *code == 330 && value == reactor).count(), 1); +} diff --git a/crates/io/tests/it/roundtrip_audit.rs b/crates/io/tests/it/roundtrip_audit.rs index 0b15f3181..c2a326935 100644 --- a/crates/io/tests/it/roundtrip_audit.rs +++ b/crates/io/tests/it/roundtrip_audit.rs @@ -1010,3 +1010,182 @@ fn dwg_keeps_extension_dictionaries_xrecords_and_entity_xdata() { assert_eq!(d.block("DOOR").map(|b| b.description.as_str()), Some("A door leaf")); assert!(d.ucss.iter().any(|u| u.name == "TILTED")); } + +/// A linear dimension whose two extension origins are snapped to `a` and `b`, so the saved file +/// carries a DIMASSOC naming both objects. +fn add_associated_dimension(d: &mut Drawing, a: cadcraft_doc::Handle, b: cadcraft_doc::Handle) { + use cadcraft_doc::{AssocSnap, Common, DimAssoc, DimKind, Dimension, Space}; + use cadcraft_geom::Vec3; + let at = |point: &str, handle| DimAssoc { point: point.into(), handle, snap: AssocSnap::Mid }; + let dm = Dimension { + kind: DimKind::Linear { rotation: 0.0 }, + defpt: Vec3::new(5.0, -3.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.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![at("p13", a), at("p14", b)], + marks: Default::default(), + }; + d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).expect("add dimension"); +} + +/// The handle of the one DIMASSOC object of a written file. +fn dimassoc_handle(o: &Out) -> String { + let assocs = o.of("DIMASSOC"); + assert_eq!(assocs.len(), 1, "one DIMASSOC"); + h(assocs.first().copied().unwrap_or_default()) +} + +/// A source object that already has a reactor to a kept foreign object (the fixture's line 2A +/// names ACME_OBJECT 42) keeps it when a DIMASSOC reactor is added: one group with both (review on #2589). +#[test] +fn a_dimension_source_keeps_its_foreign_reactors_next_to_the_dimassoc() { + let mut d = read_dxf(fixture().as_bytes()).expect("read fixture"); + add_associated_dimension(&mut d, cadcraft_doc::Handle(0x2A), cadcraft_doc::Handle(0x2A)); + let o = Out::new(&write_dxf(&d)); + let line = o.of("LINE").into_iter().find(|t| h(t).eq_ignore_ascii_case("2A")).expect("line 2A"); + assert_eq!(line.iter().filter(|t| t.code == 102 && t.str() == "{ACAD_REACTORS").count(), 1, "one reactor group"); + let reactors = group(line, "ACAD_REACTORS"); + assert!(reactors.contains(&dimassoc_handle(&o)), "DIMASSOC reactor: {reactors:?}"); + assert!(reactors.iter().any(|r| o.handle(r).is_some_and(|(k, _)| k == "ACME_OBJECT")), "foreign reactor kept: {reactors:?}"); + assert!(o.dangling().is_empty(), "{:?}", o.dangling()); +} +/// An unmodelled entity a DIMASSOC refers to gets the reactor too, next to what it had (review on #2589). +#[test] +fn an_unknown_dimension_source_carries_the_dimassoc_reactor() { + let mut d = read_dxf(fixture().as_bytes()).expect("read fixture"); + add_associated_dimension(&mut d, cadcraft_doc::Handle(0x30), cadcraft_doc::Handle(0x2A)); + let o = Out::new(&write_dxf(&d)); + let widget = entity_by_text(&o, "ACME_WIDGET", "widget-in-model"); + let reactors = group(widget, "ACAD_REACTORS"); + assert!(reactors.contains(&dimassoc_handle(&o)), "DIMASSOC reactor: {reactors:?}"); + assert_eq!(widget.iter().filter(|t| t.code == 102 && t.str() == "{ACAD_REACTORS").count(), 1); + assert_eq!(owner(widget), h(o.named("BLOCK_RECORD", "*Model_Space")), "owner unchanged"); + assert!(o.dangling().is_empty(), "{:?}", o.dangling()); +} + +/// The handles of the `{ACAD_REACTORS` group of the record of handle `at`, after checking the +/// written text holds exactly one such group, placed as the DXF reference orders a record: +/// handle (5), then the reactors, then the owner (330), then the first subclass marker (100) and +/// any xdata (1001). Each handle appears once and names a DIMASSOC when `assoc_only` is set. +fn one_reactor_group(o: &Out, at: &str, assoc_only: bool) -> Vec { + let (_, rec) = o.handle(at).expect("source record"); + let codes: Vec<(i32, String)> = rec.iter().map(|t| (t.code, t.str())).collect(); + let starts: Vec = (0..codes.len()).filter(|&i| codes[i].0 == 102 && codes[i].1 == "{ACAD_REACTORS").collect(); + assert_eq!(starts.len(), 1, "exactly one reactor group in {codes:?}"); + let start = starts[0]; + let end = start + codes[start..].iter().position(|c| c.0 == 102 && c.1 == "}").expect("group end"); + let handles: Vec = codes[start + 1..end].iter().map(|c| c.1.clone()).collect(); + assert!(codes[start + 1..end].iter().all(|c| c.0 == 330), "only 330 groups inside: {codes:?}"); + let unique: std::collections::HashSet = handles.iter().map(|r| r.to_ascii_uppercase()).collect(); + assert_eq!(unique.len(), handles.len(), "each reactor once: {handles:?}"); + let pos = |code: i32| codes.iter().position(|c| c.0 == code); + assert_eq!(pos(5), Some(0), "handle first"); + let owner_at = end + 1 + codes[end + 1..].iter().position(|c| c.0 == 330).expect("owner"); + assert!(owner_at > end, "owner after the reactors: {codes:?}"); + assert!(end < pos(100).expect("subclass marker"), "reactors before the first subclass marker"); + if let Some(x) = pos(1001) { + assert!(end < x, "reactors before the xdata"); + } + if assoc_only { + for r in &handles { + assert_eq!(o.handle(r).map(|(k, _)| k), Some("DIMASSOC"), "{r} resolves to a DIMASSOC"); + } + } + handles +} + +/// A record that already has a reactors group (line 2A names ACME_OBJECT 42) comes out with one +/// group holding the foreign handle and the DIMASSOC, each once, in the same order after a +/// second save and with the extension dictionary group still between it and the owner. +/// Pinning test for the merge (review on #2589). +#[test] +fn a_record_with_a_reactor_group_gets_one_group_with_every_handle_once() { + let mut d = read_dxf(fixture().as_bytes()).expect("read fixture"); + add_associated_dimension(&mut d, cadcraft_doc::Handle(0x2A), cadcraft_doc::Handle(0x2A)); + let text = write_dxf(&d); + let o = Out::new(&text); + let reactors = one_reactor_group(&o, "2A", false); + assert_eq!(reactors.len(), 2, "foreign + DIMASSOC: {reactors:?}"); + let assoc = dimassoc_handle(&o); + assert_eq!(reactors.iter().filter(|r| r.eq_ignore_ascii_case(&assoc)).count(), 1); + assert!(reactors.iter().any(|r| o.handle(r).is_some_and(|(k, _)| k == "ACME_OBJECT"))); + let (_, line) = o.handle("2A").expect("line"); + let order: Vec = line.iter().map(|t| t.code).collect(); + let start = |name: &str| line.iter().position(|t| t.code == 102 && t.str() == format!("{{{name}")); + let (rx, xd) = (start("ACAD_REACTORS"), start("ACAD_XDICTIONARY")); + assert!(rx.is_some() && xd.is_some() && rx < xd, "reactors group before the extension dictionary group: {order:?}"); + assert_eq!(group(line, "ACAD_XDICTIONARY").len(), 1); + // Our reader accepts it, the association survives, and a second save keeps the same group. + let back = read_dxf(text.as_bytes()).expect("reopen"); + let again = Out::new(&write_dxf(&back)); + assert_eq!(again.of("DIMASSOC").len(), 1); + let second = one_reactor_group(&again, "2A", false); + assert_eq!(second.len(), 2, "{second:?}"); + assert!(second.iter().any(|r| again.handle(r).is_some_and(|(k, _)| k == "DIMASSOC"))); + assert!(again.dangling().is_empty(), "{:?}", again.dangling()); +} + +/// A record with no reactors group (line 2A with its group removed, keeping the extension +/// dictionary and the xdata) gets a new one in the preamble, between the handle and the owner, +/// so before the first subclass marker and the xdata. Pinning test (review on #2589). +#[test] +fn a_record_without_a_reactor_group_gets_a_new_one_in_the_preamble() { + let bare = fixture().replacen("5\n2A\n102\n{ACAD_REACTORS\n330\n42\n102\n}\n", "5\n2A\n", 1); + assert_ne!(bare, fixture(), "the fixture line lost its reactors"); + let mut d = read_dxf(bare.as_bytes()).expect("read fixture"); + add_associated_dimension(&mut d, cadcraft_doc::Handle(0x2A), cadcraft_doc::Handle(0x2A)); + let text = write_dxf(&d); + let o = Out::new(&text); + let (_, line) = o.handle("2A").expect("line"); + assert!(line.iter().any(|t| t.code == 1001), "the record keeps its xdata"); + let xdict_at = line.iter().position(|t| t.code == 102 && t.str() == "{ACAD_XDICTIONARY").expect("xdict group"); + let reactors = one_reactor_group(&o, "2A", true); + assert_eq!(reactors, vec![dimassoc_handle(&o)]); + // The preamble is the handle, then the reactors group and the extension dictionary group in + // the DXF reference's order, then the owner: nothing else in between. + let reactors_at = line.iter().position(|t| t.code == 102 && t.str() == "{ACAD_REACTORS").expect("reactor group"); + let owner_at = line.iter().position(|t| t.code == 330 && t.str() != reactors[0]).expect("owner"); + assert!(reactors_at < xdict_at && xdict_at < owner_at, "reactors {reactors_at}, xdict {xdict_at}, owner {owner_at}"); + assert!(line.iter().take(owner_at).all(|t| matches!(t.code, 5 | 102 | 330 | 360)), "only handle and groups before the owner"); + // Reading it back keeps the association and the DIMASSOC still resolves. + let back = read_dxf(text.as_bytes()).expect("reopen"); + let again = Out::new(&write_dxf(&back)); + one_reactor_group(&again, "2A", true); + assert!(again.dangling().is_empty(), "{:?}", again.dangling()); +} + +/// A new line used by two dimensions (so by two DIMASSOC objects) lists both, once each, in one +/// group that sits between its handle and its owner. Pinning test (review on #2589). +#[test] +fn a_source_used_by_two_associations_lists_both_dimassocs_once() { + use cadcraft_doc::{Common, Line, Space}; + use cadcraft_geom::Vec3; + let mut d = Drawing::new_metric(); + let line = d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })).expect("add line"); + add_associated_dimension(&mut d, line, line); + add_associated_dimension(&mut d, line, line); + let text = write_dxf(&d); + let o = Out::new(&text); + let assocs: Vec = o.of("DIMASSOC").into_iter().map(h).collect(); + assert_eq!(assocs.len(), 2, "one DIMASSOC per dimension"); + let reactors = one_reactor_group(&o, &line.hex(), true); + let mut got: Vec = reactors.iter().map(|r| r.to_ascii_uppercase()).collect(); + let mut want: Vec = assocs.iter().map(|r| r.to_ascii_uppercase()).collect(); + got.sort(); + want.sort(); + assert_eq!(got, want, "both associations, once each"); + let back = read_dxf(text.as_bytes()).expect("reopen"); + let again = Out::new(&write_dxf(&back)); + assert_eq!(one_reactor_group(&again, &line.hex(), true).len(), 2); + assert!(again.dangling().is_empty(), "{:?}", again.dangling()); +} From 152617f4df0b81d733cb0ca8a0596079c97b63d1 Mon Sep 17 00:00:00 2001 From: Books Date: Mon, 2 Nov 2026 06:38:34 +1100 Subject: [PATCH 357/900] Plot: a layout's saved page setup is used by default (part of #2493) (#2586) * Plot: a layout's saved page setup is used by default (#2493) A layout whose page setup says plot window, scale to fit or a plot scale was plotted 1:1 from the sheet origin unless the caller passed fit. plot, exportpdf, the PNG device and preview now read the layout's saved window, scale to fit, scale and centring when the options don't say (render::paper::saved_plot); explicit options win, and fit: false without a scale is still the plain 1:1 sheet. Tests: saved_setup_tests in pdf.rs (four), and preview_uses_the_layouts_saved_page_setup_by_default. * Parity checklist: regenerated after merging main * Parity checklist: regenerated after merging main * Plot: saved page setup in preview and PNG matches the PDF (review on #2586) Preview honours the saved centre when fitting a window and an explicit scale beats a saved scale to fit (PDF too); PNG places a saved window without fit and clips to the printable area. * Preview: a saved window clips to the printable area (review on #2586) The preview drew the placed plot over the margins while the PDF and PNG blank them. The blanking helper now lives in the render crate and both the PNG plot and the preview use it. Test: preview_clips_a_saved_window_to_the_printable_area. * Preview: pin hostile saved page setups and the default setup (review on #2586) Degenerate or far-away saved windows and saved scales of 0 or not finite already fall back to the plain plot in the PDF, PNG and preview; tests now pin that, and that a layout with no saved setup plots as before. * Preview: the printable clip follows the view's fit (review on #2586) The clip assumed the sheet filled the image; when the height cap applies View::fit scales and centres it. The printable corners now go through View::to_screen. Test: preview_clip_follows_the_view_when_the_height_cap_applies. * docs: leave the generated parity checklist to maintainers Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/exchange.rs | 169 ++++++++++++++++++++++++++++-- crates/io/src/pdf.rs | 129 +++++++++++++++++++++-- crates/io/src/plotter.rs | 158 +++++++++++++++++++++++++--- crates/render/src/paper.rs | 27 +++++ crates/render/src/raster.rs | 31 ++++++ 5 files changed, 487 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index e28de89fc..f6ce1e9b6 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -330,17 +330,23 @@ fn run_preview(s: &mut Session, p: &Value) -> Result { if let Some(l) = p.get("landscape").and_then(Value::as_bool) { page.landscape = l; } + // A layout's saved page setup (plot window, scale to fit, scale, centring) applies unless the call says otherwise (#2493). + // An explicit `fit: false` without a `scale` asks for the plain 1:1 plot. + let plain = p.get("fit").and_then(Value::as_bool) == Some(false) && p.get("scale").is_none(); + let saved = if space.is_paper() && !plain { cadcraft_render::paper::saved_plot(&page) } else { Default::default() }; let sheet = Sheet::from_page(&page, paper::page_unit_mm(d, &page)); let lineweights = p.get("lineweights").and_then(Value::as_bool).unwrap_or(if space.is_paper() { page.lineweights } else { true }); let transparency = super::plotters::plot_transparency(s, p).unwrap_or(page.plot_transparency); - let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(matches!(space, Space::Model)); - let scale = p.get("scale").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0); + let given_scale = p.get("scale").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0); + // A saved scale to fit applies only when the call gives neither `fit` nor `scale`, as in the PDF. + let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(matches!(space, Space::Model) || (saved.fit && given_scale.is_none())); + let scale = given_scale.or(saved.scale); let width = p.get("width").and_then(Value::as_u64).unwrap_or(PREVIEW_PX).clamp(16, MAX_PREVIEW_PX); let height = ((width as f64) * sheet.size.y / sheet.size.x).round(); let height = if height.is_finite() { (height as u64).clamp(16, MAX_PREVIEW_PX) } else { width }; let px_per_paper_unit = width as f64 / sheet.size.x; // Curves are flattened to about half a pixel. - let est = plot_scale(&d.extents(&space), &sheet, fit, scale); + let est = plot_scale(&saved.window.unwrap_or_else(|| d.extents(&space)), &sheet, fit, scale); let tol = 0.5 / (px_per_paper_unit * est); let ropts = cadcraft_render::Options { tolerance: if tol.is_finite() && tol > 0.0 { tol } else { 0.01 }, @@ -352,9 +358,13 @@ fn run_preview(s: &mut Session, p: &Value) -> Result { ..Default::default() }; let list = cadcraft_render::build_plot(d, &space, &ropts); - let b = list.bounds; + let b = saved.window.unwrap_or(list.bounds); // Paper point q shows drawing point (q - to) / k + from. - let (from, k, to) = if fit || space == Space::Model { + let (from, k, to) = if saved.window.is_some() { + // A saved window, fitted or at a saved scale: its centre (or corner) on the printable area's. + let c = saved.center; + (if c { b.center() } else { b.min }, plot_scale(&b, &sheet, fit, scale), if c { sheet.printable.center() } else { sheet.printable.min }) + } else if fit || space == Space::Model { (if b.is_empty() { Vec2::ZERO } else { b.center() }, plot_scale(&b, &sheet, fit, scale), sheet.printable.center()) } else { (Vec2::ZERO, plot_scale(&b, &sheet, fit, scale), Vec2::ZERO) @@ -372,7 +382,20 @@ fn run_preview(s: &mut Session, p: &Value) -> Result { px_per_mm: if lineweights && px_per_mm.is_finite() { px_per_mm } else { 0.0 }, antialias: true, }; - let png = cadcraft_render::raster::render_png(&list, &view, &ro).ok_or_else(|| bad("preview", "rendering the preview failed"))?; + let mut pm = cadcraft_render::raster::render(&list, &view, &ro).ok_or_else(|| bad("preview", "rendering the preview failed"))?; + // A placed plot (fitted, or a saved window) shows only inside the printable area, as the PDF and PNG plots clip it. + if fit || saved.window.is_some() || space == Space::Model { + // The view may scale and centre the sheet (the height cap), so map the printable corners + // (paper point q shows drawing point (q - to) / k + from) through it. + let screen = |q: Vec2| { + let (x, y) = view.to_screen((q - to) / k + from); + (f64::from(x), f64::from(y)) + }; + let (min, max) = (sheet.printable.min, sheet.printable.max); + let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y))); + cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b); + } + let png = pm.encode_png().map_err(|_| bad("preview", "rendering the preview failed"))?; let layout = space.tab_name(); Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape })) } @@ -738,6 +761,140 @@ mod tests { assert_ne!(png(&mut s, json!({ "layout": "Layout1", "width": 200, "fit": false, "scale": 0.5 })), default, "scale 0.5 is not 1:1"); } + /// A layout's saved page setup (plot window, scale to fit) shapes its preview by default, as + /// it shapes the PDF; `fit: false` still gives the plain 1:1 sheet (#2493). + #[test] + fn preview_uses_the_layouts_saved_page_setup_by_default() { + let mut s = Session::new(); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + s.execute("line", &json!({ "points": [[20.0, 5.0], [836.0, 589.0]] })).unwrap(); + s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "A4", "landscape": true, "margins": [0, 0, 0, 0] })).unwrap(); + let png = |s: &mut Session, p: Value| s.execute("preview", &p).unwrap()["data"].as_str().unwrap_or_default().to_string(); + let unsaved = png(&mut s, json!({ "layout": "Layout1", "width": 200 })); + let page = &mut s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page; + page.plot_area = "window".into(); + page.plot_window = [20.0, 5.0, 836.0, 589.0]; + page.scale_to_fit = true; + let saved = png(&mut s, json!({ "layout": "Layout1", "width": 200 })); + assert_ne!(saved, unsaved, "the saved window and scale to fit change the preview"); + assert_eq!(png(&mut s, json!({ "layout": "Layout1", "width": 200, "fit": false })), unsaved, "fit: false is the plain 1:1 sheet"); + } + + /// With a saved plot window the preview follows the page setup's centring (fitted or not) and an + /// explicit `scale` beats a saved scale to fit, as in the PDF. + /// A placed saved window shows only inside the printable area, as the PDF and PNG plots clip it: + /// geometry in the margin leaves the preview unchanged. + #[test] + fn preview_clips_a_saved_window_to_the_printable_area() { + let build = |margin_line: bool| { + let mut s = Session::new(); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + s.execute("line", &json!({ "points": [[0.0, 30.0], [100.0, 30.0]] })).unwrap(); + if margin_line { + s.execute("line", &json!({ "points": [[-3.0, 0.0], [-3.0, 60.0]] })).unwrap(); + } + s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "A4", "landscape": true, "margins": [10, 10, 10, 10] })).unwrap(); + let page = &mut s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page; + page.plot_area = "window".into(); + page.plot_window = [0.0, 0.0, 100.0, 60.0]; + page.scale_to_fit = true; + page.center = true; + s.execute("preview", &json!({ "layout": "Layout1", "width": 600 })).unwrap()["data"].as_str().unwrap_or_default().to_string() + }; + assert_eq!(build(true), build(false), "a line in the margin is clipped away"); + } + + /// On a tall sheet the height cap makes the view scale and centre the sheet in the image; the + /// printable clip must follow it, so ink in the margin is still blanked. + #[test] + fn preview_clip_follows_the_view_when_the_height_cap_applies() { + let build = |margin_line: bool| { + let mut s = Session::new(); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + s.execute("line", &json!({ "points": [[0.0, 50.0], [100.0, 50.0]] })).unwrap(); + if margin_line { + s.execute("line", &json!({ "points": [[-2.6, 0.0], [-2.6, 100.0]] })).unwrap(); + } + s.execute("pagesetup", &json!({ "layout": "Layout1", "margins": [10, 10, 10, 10] })).unwrap(); + let page = &mut s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page; + page.width_mm = 210.0; + page.height_mm = 1200.0; + page.landscape = false; + page.plot_area = "window".into(); + page.plot_window = [0.0, 0.0, 100.0, 100.0]; + page.scale_to_fit = true; + page.center = true; + s.execute("preview", &json!({ "layout": "Layout1", "width": 1000 })).unwrap()["data"].as_str().unwrap_or_default().to_string() + }; + assert_eq!(build(true), build(false), "a line in the margin is clipped away on a tall sheet"); + } + + /// Hostile saved setups (a degenerate or far-away window, a scale of 0 or not finite) fall back + /// to the plain preview and never panic, and a layout with no saved setup previews exactly as + /// the plain 1:1 sheet does. + #[test] + fn preview_survives_hostile_saved_setups_and_default_is_unchanged() { + let mut s = Session::new(); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + s.execute("line", &json!({ "points": [[20.0, 5.0], [200.0, 100.0]] })).unwrap(); + s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "A4", "landscape": true })).unwrap(); + let png = |s: &mut Session, p: Value| s.execute("preview", &p).unwrap()["data"].as_str().unwrap_or_default().to_string(); + let call = json!({ "layout": "Layout1", "width": 200 }); + let plain = png(&mut s, json!({ "layout": "Layout1", "width": 200, "fit": false })); + assert_eq!(png(&mut s, call.clone()), plain, "no saved setup: the default preview is the plain sheet"); + let set = |s: &mut Session, window: [f64; 4], scale: f64, fit: bool| { + let page = &mut s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page; + page.plot_area = "window".into(); + page.plot_window = window; + page.scale = scale; + page.scale_to_fit = fit; + }; + let good = [0.0, 0.0, 100.0, 60.0]; + let (nan, inf) = (f64::NAN, f64::INFINITY); + for window in [[5.0, 5.0, 5.0, 40.0], [5.0, 5.0, 40.0, 5.0], [nan, 0.0, 10.0, 10.0], [0.0, 0.0, inf, 10.0]] { + set(&mut s, window, 1.0, true); + assert_eq!(png(&mut s, call.clone()), plain, "{window:?}: a degenerate window changes nothing"); + } + for scale in [0.0, -2.0, nan, inf] { + set(&mut s, good, scale, false); + let _ = png(&mut s, call.clone()); + set(&mut s, [5.0, 5.0, 5.0, 40.0], scale, false); + assert_eq!(png(&mut s, call.clone()), plain, "{scale}: an unusable saved scale is ignored"); + } + set(&mut s, [1e9, 1e9, 1e9 + 10.0, 1e9 + 10.0], 1.0, true); + let _ = png(&mut s, call.clone()); + set(&mut s, [-1e300, -1e300, 1e300, 1e300], 1.0, true); + let _ = png(&mut s, call.clone()); + } + + #[test] + fn preview_honours_saved_centering_and_an_explicit_scale() { + let mut s = Session::new(); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + s.execute("line", &json!({ "points": [[20.0, 5.0], [836.0, 589.0]] })).unwrap(); + s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "A4", "landscape": true, "margins": [0, 0, 0, 0] })).unwrap(); + let page = &mut s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page; + page.plot_area = "window".into(); + page.plot_window = [20.0, 5.0, 400.0, 200.0]; + page.scale_to_fit = true; + let png = |s: &mut Session, p: Value| s.execute("preview", &p).unwrap()["data"].as_str().unwrap_or_default().to_string(); + let set_center = |s: &mut Session, c: bool| s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page.center = c; + set_center(&mut s, true); + let centred = png(&mut s, json!({ "layout": "Layout1", "width": 200 })); + set_center(&mut s, false); + // The window is fitted by width, so only the other axis shows where it sits. + let corner = png(&mut s, json!({ "layout": "Layout1", "width": 200 })); + assert_ne!(corner, centred, "a saved centre: false puts the fitted window at the printable corner"); + let page = &mut s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page; + page.center = true; + let by_scale = png(&mut s, json!({ "layout": "Layout1", "width": 200, "scale": 0.5 })); + assert_ne!(by_scale, centred, "an explicit scale is not the fitted plot"); + assert_eq!( + by_scale, + png(&mut s, json!({ "layout": "Layout1", "width": 200, "fit": false, "scale": 0.5 })), + "scale decides, not the saved fit" + ); + } #[test] fn pdfbook_collects_frames_into_one_pdf_per_row() { our_hooks(); diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index b06580d53..ba9d65867 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -508,8 +508,37 @@ struct SheetPage { label: String, } +/// `o` with a layout's saved page setup filled in where the options don't say: its plot window, +/// scale to fit or saved scale, and centring (#2493). Explicit options win; model space has no +/// saved setup. +pub(crate) fn with_saved_setup(d: &Drawing, space: &Space, o: &PdfOptions) -> PdfOptions { + let mut o = o.clone(); + let Some(page) = space.layout().and_then(|n| d.layout(n)).map(|l| &l.page) else { return o }; + // An explicit `fit: false` without a `scale` asks for the plain 1:1 plot of the sheet. + if o.fit == Some(false) && o.scale.is_none() { + o.window = None; + return o; + } + let saved = paper::saved_plot(page); + // A layout is plotted over its own sheet: only its saved window applies, not one in the options. + o.window = saved.window; + // An explicit scale beats a saved scale to fit (the scale is ignored while fitting). + if o.fit.is_none() && o.scale.is_none() && saved.fit { + o.fit = Some(true); + } + if o.scale.is_none() { + o.scale = saved.scale; + } + if o.center.is_none() && saved.window.is_some() { + o.center = Some(saved.center); + } + o +} + /// Plot one space. fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String)]) -> Result { + let saved = with_saved_setup(d, space, o); + let o = &saved; let page = page_for(d, space, o)?; let unit_mm = paper::page_unit_mm(d, &page); let sheet = Sheet::from_page(&page, unit_mm); @@ -530,8 +559,8 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String cancel: None, }; let k = unit_mm * PT_PER_MM; - let window = o.window.filter(|w| matches!(space, Space::Model) && !w.is_empty()); - let fit = o.fit.unwrap_or(window.is_some() || matches!(space, Space::Model)); + let window = o.window.filter(|w| !w.is_empty()); + let fit = o.fit.unwrap_or(matches!(space, Space::Model)); // Chord tolerance: about 0.05 mm on paper. let est = plot_scale(&window.unwrap_or_else(|| d.extents(space)), &sheet, fit, o.scale); let tol = 0.05 / unit_mm / est.max(1e-300); @@ -541,8 +570,11 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String let list = cadcraft_render::build_plot(d, space, &cadcraft_render::Options { tolerance, view_height, ..ropts }); let b = window.unwrap_or(list.bounds); let s = plot_scale(&b, &sheet, fit, o.scale); - let map = if fit || matches!(space, Space::Model) { - let (from, to) = placement(space, &b, fit, &sheet, o); + // A layout plotted over a window is placed like model space: the window on the printable area. + let placed = fit || window.is_some() || matches!(space, Space::Model); + let map = if placed { + let by = if window.is_some() { &Space::Model } else { space }; + let (from, to) = placement(by, &b, fit, &sheet, o); Map { from, s, to, k } } else { Map { from: Vec2::ZERO, s, to: Vec2::ZERO, k } @@ -551,11 +583,7 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String let mut list = list; cadcraft_render::pen::apply(&mut list, map.s * unit_mm); let media = sheet.size * k; - let clip_pt = if fit || matches!(space, Space::Model) { - Bounds2::new(sheet.printable.min * k, sheet.printable.max * k) - } else { - Bounds2::new(Vec2::ZERO, media) - }; + let clip_pt = if placed { Bounds2::new(sheet.printable.min * k, sheet.printable.max * k) } else { Bounds2::new(Vec2::ZERO, media) }; // The layers drawn on, in order of first use. let mut layers: Vec = Vec::new(); if o.layers { @@ -989,3 +1017,86 @@ fn uri(url: &str) -> Option { } Some(out) } + +#[cfg(test)] +mod saved_setup_tests { + use super::*; + use cadcraft_doc::{Common, EntityKind, Layout, Line}; + use cadcraft_geom::Vec3; + use serde_json::json; + + /// A layout drawn in mm at A1 size (frame 20,5 - 836,589) whose page setup is A4 landscape + /// plotting that window, as in #2493. + fn drawing(scale_to_fit: bool, scale: f64) -> Drawing { + let mut d = Drawing::new_metric(); + let mut l = Layout::new("L1", 3); + l.page = PageSetup { + width_mm: 297.0, + height_mm: 210.0, + landscape: true, + margins_mm: [0.0; 4], + plot_area: "window".into(), + plot_window: [20.0, 5.0, 836.0, 589.0], + scale_to_fit, + scale, + center: true, + ..PageSetup::default() + }; + d.layouts.push(l); + let line = EntityKind::Line(Line { a: Vec3::new(20.0, 5.0, 0.0), b: Vec3::new(836.0, 589.0, 0.0) }); + d.add(&Space::Paper("L1".into()), Common::default(), line).unwrap(); + d + } + + fn map(d: &Drawing, opts: serde_json::Value) -> Map { + sheet(d, &Space::Paper("L1".into()), &PdfOptions::from_json(&opts), &[]).unwrap().map + } + + /// A layout plotted with no options uses its saved scale to fit and plot window, not 1:1. + #[test] + fn a_layout_plots_its_saved_window_scaled_to_fit_by_default() { + let d = drawing(true, 1.0); + let m = map(&d, json!({})); + let want = (297.0_f64 / 816.0).min(210.0 / 584.0); + assert!((m.s - want).abs() < 1e-9, "scale {} not {want}", m.s); + assert!(m.from.dist(Vec2::new(428.0, 297.0)) < 1e-9, "window centre, got {:?}", m.from); + assert!(m.to.dist(Vec2::new(148.5, 105.0)) < 1e-9, "page centre, got {:?}", m.to); + } + + /// The options still win: `fit: false` is the plain 1:1 plot, and a `scale` is used as given. + #[test] + fn explicit_options_override_the_saved_setup() { + let d = drawing(true, 1.0); + let m = map(&d, json!({"fit": false})); + assert_eq!((m.s, m.from, m.to), (1.0, Vec2::ZERO, Vec2::ZERO)); + let m = map(&d, json!({"fit": false, "scale": 0.25})); + assert!((m.s - 0.25).abs() < 1e-12, "{}", m.s); + } + + /// A saved scale (not scale to fit) is used by default, with the window centred on the page. + #[test] + fn a_layout_plots_at_its_saved_scale_by_default() { + let d = drawing(false, 0.3394); + let m = map(&d, json!({})); + assert!((m.s - 0.3394).abs() < 1e-12, "{}", m.s); + assert!(m.from.dist(Vec2::new(428.0, 297.0)) < 1e-9 && m.to.dist(Vec2::new(148.5, 105.0)) < 1e-9, "{:?} {:?}", m.from, m.to); + } + + /// A page setup with nothing saved to fit plots as it always did. + #[test] + fn a_layout_without_a_saved_window_or_scale_is_unchanged() { + let mut d = drawing(false, 1.0); + d.layouts.iter_mut().find(|l| l.name == "L1").unwrap().page.plot_area = "layout".into(); + let m = map(&d, json!({})); + assert_eq!((m.s, m.from, m.to), (1.0, Vec2::ZERO, Vec2::ZERO)); + } + + /// An explicit `scale` beats a saved scale to fit, in the PDF as in the preview. + #[test] + fn an_explicit_scale_overrides_the_saved_scale_to_fit() { + let d = drawing(true, 1.0); + let m = map(&d, json!({"scale": 0.25})); + assert!((m.s - 0.25).abs() < 1e-12, "{}", m.s); + assert!(m.from.dist(Vec2::new(428.0, 297.0)) < 1e-9 && m.to.dist(Vec2::new(148.5, 105.0)) < 1e-9, "still placed: {:?} {:?}", m.from, m.to); + } +} diff --git a/crates/io/src/plotter.rs b/crates/io/src/plotter.rs index 12da96c3b..f0a174ea1 100644 --- a/crates/io/src/plotter.rs +++ b/crates/io/src/plotter.rs @@ -63,7 +63,7 @@ fn fit_scale(b: &Bounds2, sheet: &Sheet, o: &PdfOptions) -> f64 { } fn png(d: &Drawing, space: &Space, opts: &Value) -> Result> { - let o = PdfOptions::from_json(opts); + let o = pdf::with_saved_setup(d, space, &PdfOptions::from_json(opts)); let (sheet, page) = sheet(d, space, &o)?; let dpi = opts.get("resolution").and_then(Value::as_f64).filter(|r| r.is_finite()).unwrap_or(300.0).clamp(50.0, 2400.0); // Pixels per paper unit, lowered so the image stays within the caps. @@ -78,10 +78,17 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result> { let (width, height) = (px(sheet.size.x), px(sheet.size.y)); let lineweights = o.lineweights.unwrap_or(if space.is_paper() { page.lineweights } else { true }); let table = cadcraft_doc::plot_style_table(d, &page.plot_style_table).map(Arc::new); - // Paper units per drawing unit: 1 for a layout at 1:1, the fitted scale for model space. + // Paper units per drawing unit: the fitted scale for model space or a fitted layout, else the + // `scale` option or 1:1, as PDF plots it. let fit = matches!(space, Space::Model) || o.fit == Some(true); - let window = o.window.filter(|w| matches!(space, Space::Model) && !w.is_empty()); - let est = if fit { fit_scale(&window.unwrap_or_else(|| d.extents(space)), &sheet, &o) } else { 1.0 }; + let window = o.window.filter(|w| !w.is_empty()); + // A layout over a saved window is placed like model space, the window on the printable area. + let placed = fit || window.is_some(); + let est = if fit { + fit_scale(&window.unwrap_or_else(|| d.extents(space)), &sheet, &o) + } else { + pdf::plot_scale(&Bounds2::EMPTY, &sheet, false, o.scale) + }; // Chord tolerance: a fifth of a pixel. let tolerance = (0.2 / (k * est)).max(1e-9); let transparency = o.plot_transparency.unwrap_or(page.plot_transparency); @@ -89,21 +96,27 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result> { let mut list = cadcraft_render::build_plot(d, space, &ropts); let half = Vec2::new(f64::from(width), f64::from(height)) / (2.0 * k); let b = window.unwrap_or(list.bounds); - let s = if fit { fit_scale(&b, &sheet, &o) } else { 1.0 }; + let s = if fit { fit_scale(&b, &sheet, &o) } else { est }; // Plot style ends, joins and fill patterns at the plot scale, as PDF draws them (a layout's // are already drawn). cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm); - let view = if fit { - let (from, to) = pdf::placement(space, &b, true, &sheet, &o); - // The world point at the image centre, mapped through the same paper origin as PDF. - let center = from + (half - to) / s; - raster::View { center, scale: k * s, width, height } + let (from, to) = if placed { + // A window is placed like model space, whatever the space (as in PDF). + pdf::placement(if window.is_some() { &Space::Model } else { space }, &b, fit, &sheet, &o) } else { - raster::View { center: half, scale: k, width, height } + (Vec2::ZERO, Vec2::ZERO) }; + // The world point at the image centre, mapped through the same paper origin as PDF. + let center = from + (half - to) / s; + let view = raster::View { center, scale: k * s, width, height }; let px_per_mm = if lineweights { (k / sheet.unit_mm) as f32 } else { 0.0 }; let ro = raster::RasterOptions { background: Rgb(255, 255, 255), hairline: 1.0, px_per_mm, antialias: true }; - raster::render_png(&list, &view, &ro).ok_or_else(|| IoError::Format("render failed".into())) + let mut pm = raster::render(&list, &view, &ro).ok_or_else(|| IoError::Format("render failed".into()))?; + if placed { + // PDF clips a placed plot to the printable area: blank the rest of the sheet. + raster::blank_outside_printable(&mut pm, &sheet.printable, k); + } + pm.encode_png().map_err(|_| IoError::Format("render failed".into())) } fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result> { @@ -237,4 +250,125 @@ mod tests { assert!(err.to_string().contains("not supported for SVG")); assert!(plot(&d, &model, &json!({"output": "svg", "center": true})).unwrap().starts_with(b" Drawing { + let mut d = Drawing::new_metric(); + let mut l = cadcraft_doc::Layout::new("L1", 3); + l.page = cadcraft_doc::PageSetup { + width_mm: 297.0, + height_mm: 210.0, + landscape: true, + margins_mm: [10.0; 4], + plot_area: "window".into(), + plot_window: [0.0, 0.0, 100.0, 60.0], + scale_to_fit, + scale: 1.0, + center: true, + ..cadcraft_doc::PageSetup::default() + }; + d.layouts.push(l); + let sp = Space::Paper("L1".into()); + let mut line = |a: (f64, f64), b: (f64, f64)| { + d.add(&sp, Common::default(), EntityKind::Line(Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) })).unwrap(); + }; + line((0.0, 30.0), (100.0, 30.0)); + line((-3.0, 0.0), (-3.0, 60.0)); + d + } + + /// Whether any pixel of the PNG in the column range `x0..=x1` (mm from the sheet's left edge) + /// at the row of `y_mm` (from the sheet's bottom edge, give or take 2 px) is not white. + fn inked(png: &[u8], x0_mm: f64, x1_mm: f64, y_mm: f64) -> bool { + let pm = tiny_skia::Pixmap::decode_png(png).unwrap(); + let px_per_mm = f64::from(pm.width()) / 297.0; + let row = (f64::from(pm.height()) - y_mm * px_per_mm).round() as i64; + let (c0, c1) = ((x0_mm * px_per_mm).round() as i64, (x1_mm * px_per_mm).round() as i64); + (row - 2..=row + 2).any(|r| (c0..=c1).any(|c| pm.pixel(c as u32, r as u32).is_some_and(|p| p.red() < 200))) + } + + const LAYOUT_PNG: &str = r#"{"output": "png", "resolution": 100}"#; + + /// Without scale to fit, a saved window is still placed (centred on the printable area, 1:1) as PDF + /// places it, not left at the sheet origin. + #[test] + fn png_places_the_saved_window_when_fit_is_off() { + let d = layout_drawing(false); + let png = plot(&d, &Space::Paper("L1".into()), &serde_json::from_str(LAYOUT_PNG).unwrap()).unwrap(); + // The 100 mm line is centred on the sheet: 98.5 to 198.5 mm. At the origin it would end at 100 mm. + assert!(inked(&png, 140.0, 160.0, 105.0), "the window's line crosses the sheet centre"); + assert!(!inked(&png, 10.0, 90.0, 105.0), "nothing at the sheet origin"); + } + + /// An explicit scale overrides a saved scale to fit, and the PNG uses it. + #[test] + fn png_explicit_scale_beats_saved_fit() { + let d = layout_drawing(true); + let sp = Space::Paper("L1".into()); + let fitted = plot(&d, &sp, &serde_json::from_str(LAYOUT_PNG).unwrap()).unwrap(); + assert!(inked(&fitted, 200.0, 280.0, 105.0), "fitted, the 100 unit line is 277 mm wide"); + let half = plot(&d, &sp, &json!({"output": "png", "resolution": 100, "scale": 0.5})).unwrap(); + assert!(inked(&half, 130.0, 170.0, 105.0)); + assert!(!inked(&half, 200.0, 280.0, 105.0), "at 0.5 the line is 50 mm wide, centred"); + } + + /// A placed window shows only inside the printable area, as PDF clips it. + #[test] + fn png_clips_a_placed_window_to_the_printable_area() { + let d = layout_drawing(true); + let png = plot(&d, &Space::Paper("L1".into()), &serde_json::from_str(LAYOUT_PNG).unwrap()).unwrap(); + // The line 3 units left of the window lands about 1.7 mm from the sheet edge, in the margin. + assert!(!inked(&png, 0.0, 9.0, 105.0), "the margin stays blank"); + } + + /// A layout with `window`/`scale` saved (any values, hostile ones included). + fn saved_drawing(window: [f64; 4], scale: f64, fit: bool) -> Drawing { + let mut d = layout_drawing(fit); + let page = &mut d.layouts.iter_mut().find(|l| l.name == "L1").unwrap().page; + page.plot_window = window; + page.scale = scale; + d + } + + /// Degenerate windows, a window off the drawing, and a saved scale of 0 or not finite fall back + /// to the plain plot: the setup resolves to no window or scale, and PDF and PNG still plot. + #[test] + fn hostile_saved_setups_fall_back_and_never_panic() { + let sp = Space::Paper("L1".into()); + let nan = f64::NAN; + let inf = f64::INFINITY; + for window in [[5.0, 5.0, 5.0, 40.0], [5.0, 5.0, 40.0, 5.0], [nan, 0.0, 10.0, 10.0], [0.0, 0.0, inf, 10.0]] { + let d = saved_drawing(window, 1.0, true); + let o = pdf::with_saved_setup(&d, &sp, &PdfOptions::from_json(&json!({}))); + assert!(o.window.is_none(), "{window:?}: a degenerate window is dropped, got {:?}", o.window); + assert!(plot(&d, &sp, &json!({})).unwrap().starts_with(b"%PDF"), "{window:?}"); + assert!(plot(&d, &sp, &serde_json::from_str(LAYOUT_PNG).unwrap()).is_ok(), "{window:?}"); + } + for scale in [0.0, -2.0, nan, inf] { + let d = saved_drawing([0.0, 0.0, 100.0, 60.0], scale, false); + let o = pdf::with_saved_setup(&d, &sp, &PdfOptions::from_json(&json!({}))); + assert!(o.scale.is_none(), "{scale}: an unusable saved scale is ignored"); + assert!(plot(&d, &sp, &json!({})).unwrap().starts_with(b"%PDF"), "{scale}"); + assert!(plot(&d, &sp, &serde_json::from_str(LAYOUT_PNG).unwrap()).is_ok(), "{scale}"); + } + // A window far from everything drawn is plotted (an empty sheet), not an error. + let d = saved_drawing([1e9, 1e9, 1e9 + 10.0, 1e9 + 10.0], 1.0, true); + assert!(plot(&d, &sp, &json!({})).unwrap().starts_with(b"%PDF")); + assert!(plot(&d, &sp, &serde_json::from_str(LAYOUT_PNG).unwrap()).is_ok()); + } + + /// A layout with no saved setup (`PageSetup::default()`) plots as the options say: nothing is + /// filled in from it. + #[test] + fn a_layout_without_saved_setup_changes_nothing() { + let mut d = Drawing::new_metric(); + d.layouts.push(cadcraft_doc::Layout::new("L1", 3)); + let sp = Space::Paper("L1".into()); + let given = PdfOptions::from_json(&json!({"scale": 0.5})); + let o = pdf::with_saved_setup(&d, &sp, &given); + assert_eq!((o.window, o.fit, o.scale, o.center), (None, None, Some(0.5), None)); + let o = pdf::with_saved_setup(&d, &sp, &PdfOptions::from_json(&json!({}))); + assert_eq!((o.window, o.fit, o.scale, o.center), (None, None, None, None)); + } } diff --git a/crates/render/src/paper.rs b/crates/render/src/paper.rs index 457a2a48d..ff4a027ba 100644 --- a/crates/render/src/paper.rs +++ b/crates/render/src/paper.rs @@ -155,3 +155,30 @@ mod tests { assert!(s.size.x > 0.0 && s.printable == s.bounds()); } } + +/// What a layout's saved page setup says about how to plot it, for a plot that was not given the +/// matching options (#2493): the plot window, whether to scale to fit, the saved scale, and +/// centring. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct SavedPlot { + /// The saved plot window, when the plot area is "window" and its corners are a real box. + pub window: Option, + /// Scale to fit the window (or the extents) on the printable area. + pub fit: bool, + /// The saved plot scale, paper units per drawing unit, when it isn't scale to fit or 1:1. + pub scale: Option, + /// Centre the plot on the printable area. + pub center: bool, +} + +/// The saved plot settings of `page`. A layout plotted over its whole sheet ("layout" plot area) +/// has nothing to fit, so scale to fit only counts for a window or the extents. +pub fn saved_plot(page: &PageSetup) -> SavedPlot { + let [x1, y1, x2, y2] = page.plot_window; + let window = (page.plot_area.eq_ignore_ascii_case("window") && [x1, y1, x2, y2].iter().all(|v| v.is_finite())) + .then(|| Bounds2::new(Vec2::new(x1, y1), Vec2::new(x2, y2))) + .filter(|w| w.width() > 0.0 && w.height() > 0.0); + let fit = page.scale_to_fit && (window.is_some() || page.plot_area.eq_ignore_ascii_case("extents")); + let scale = Some(page.scale).filter(|s| !page.scale_to_fit && s.is_finite() && *s > 0.0 && (*s - 1.0).abs() > 1e-9); + SavedPlot { window, fit, scale, center: page.center } +} diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 72ac821d0..a32818a38 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -222,6 +222,37 @@ impl Hairlines { } } +/// Blank (white) everything outside `printable`, a rectangle in paper units with the origin at the +/// sheet's bottom-left, on a pixmap showing the whole sheet at `px_per_unit` pixels per paper unit. +/// A placed plot is clipped to the printable area this way, in the PNG plot and in the preview. +pub fn blank_outside_printable(pm: &mut Pixmap, printable: &Bounds2, px_per_unit: f64) { + let ph = f64::from(pm.height()); + blank_outside_pixels( + pm, + (printable.min.x * px_per_unit, ph - printable.max.y * px_per_unit), + (printable.max.x * px_per_unit, ph - printable.min.y * px_per_unit), + ); +} + +/// Blank (white) everything outside the pixel rectangle from `top_left` to `bottom_right` (image +/// coordinates, y down; rounded and clamped to the image). For a pixmap whose view does not map +/// the sheet onto the whole image, map the printable corners through `View::to_screen`. +pub fn blank_outside_pixels(pm: &mut Pixmap, top_left: (f64, f64), bottom_right: (f64, f64)) { + let (pw, ph) = (pm.width(), pm.height()); + let col = |x: f64| x.round().clamp(0.0, f64::from(pw)) as usize; + let row = |y: f64| y.round().clamp(0.0, f64::from(ph)) as usize; + let (x0, x1) = (col(top_left.0), col(bottom_right.0)); + let (y0, y1) = (row(top_left.1), row(bottom_right.1)); + let stride = pw as usize * 4; + for (r, line) in pm.data_mut().chunks_exact_mut(stride.max(4)).enumerate() { + for (c, px) in line.as_chunks_mut::<4>().0.iter_mut().enumerate() { + if r < y0 || r >= y1 || c < x0 || c >= x1 { + px.copy_from_slice(&[255, 255, 255, 255]); + } + } + } +} + /// Render and encode as PNG. pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option> { render(list, view, o)?.encode_png().ok() From e8bcc38e34285c40c24ffc0513f81f7424a2c1f9 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:40:15 +0700 Subject: [PATCH 358/900] OOPS: bring back the last erase, each object where it was (#2605) There was no OOPS. It now brings back what the last ERASE removed (the Delete key too), or BLOCK deleting the objects it makes a block of, as AutoCAD 2024 does (accoreconsole, the drawing's entnext order read back): - Each object keeps its handle and goes back directly above the object that was under it, or under the one that was above it when that is gone. An erase records both neighbours (EntityStore::neighbours). - Only the last erase counts; entdel doesn't. OOPS says nothing and is one undo step. - An object stays out when it is already in the drawing, when an undo took the drawing back to before it was made, when its layer, block or layout is gone, and, during REFEDIT, when it isn't in the working set. REFCLOSE forgets the working copies; the Block Editor has an OOPS of its own. - The command's label is in the 17 interface catalogs. Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/doc/src/store.rs | 35 ++++ crates/engine/src/blockedit.rs | 4 +- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/blocks.rs | 13 +- crates/engine/src/cmd/blocks/refedit.rs | 2 + crates/engine/src/cmd/edit.rs | 8 +- crates/engine/src/cmd/modify.rs | 4 + crates/engine/src/cmd/modify/oops.rs | 171 ++++++++++++++++ crates/engine/src/cmd/modify/transform.rs | 13 +- crates/engine/src/doc_state.rs | 3 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/oops_command.rs | 232 ++++++++++++++++++++++ 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 + 29 files changed, 484 insertions(+), 20 deletions(-) create mode 100644 crates/engine/src/cmd/modify/oops.rs create mode 100644 crates/engine/tests/it/oops_command.rs diff --git a/crates/doc/src/store.rs b/crates/doc/src/store.rs index 3e9b440e1..00b04970e 100644 --- a/crates/doc/src/store.rs +++ b/crates/doc/src/store.rs @@ -189,6 +189,19 @@ impl EntityStore { None => false, } } + /// The objects directly under and above `h` in the draw order (None at the bottom or the + /// top), when `h` is here. + pub fn neighbours(&self, h: Handle) -> Option<(Option, Option)> { + let pos = self.chunk_pos(self.chunk_id(h)?)?; + let items = &self.chunks.get(pos)?.items; + let i = items.iter().position(|e| e.handle == h)?; + let below = match i.checked_sub(1) { + Some(j) => items.get(j), + None => pos.checked_sub(1).and_then(|p| self.chunks.get(p)).and_then(|c| c.items.last()), + }; + let above = items.get(i + 1).or_else(|| self.chunks.get(pos + 1).and_then(|c| c.items.first())); + Some((below.map(|e| e.handle), above.map(|e| e.handle))) + } /// Move `h` directly above (`above`) or under `anchor` in the draw order. False (and nothing /// moves) when either is absent or they are the same object. pub fn move_next_to(&mut self, h: Handle, anchor: Handle, above: bool) -> bool { @@ -364,4 +377,26 @@ mod tests { assert_eq!(s.get(Handle(h)).map(|e| e.handle.0), Some(h)); } } + + #[test] + fn neighbours_across_chunks() { + let mut s = EntityStore::new(); + for h in 1..=3000 { + s.push(ent(h)); + } + assert_eq!(s.neighbours(Handle(1)), Some((None, Some(Handle(2))))); + assert_eq!(s.neighbours(Handle(1500)), Some((Some(Handle(1499)), Some(Handle(1501))))); + // The first and last objects of a chunk look into the chunks next to it. + let k = CHUNK_MAX as u64; + assert_eq!(s.neighbours(Handle(k)), Some((Some(Handle(k - 1)), Some(Handle(k + 1))))); + assert_eq!(s.neighbours(Handle(k + 1)), Some((Some(Handle(k)), Some(Handle(k + 2))))); + assert_eq!(s.neighbours(Handle(3000)), Some((Some(Handle(2999)), None))); + assert_eq!(s.neighbours(Handle(9999)), None); + assert!(s.move_next_to(Handle(3000), Handle(1), false)); + assert_eq!(s.neighbours(Handle(1)), Some((Some(Handle(3000)), Some(Handle(2))))); + assert_eq!(s.neighbours(Handle(3000)), Some((None, Some(Handle(1))))); + let mut one = EntityStore::new(); + one.push(ent(7)); + assert_eq!(one.neighbours(Handle(7)), Some((None, None))); + } } diff --git a/crates/engine/src/blockedit.rs b/crates/engine/src/blockedit.rs index fae52757e..89da207f0 100644 --- a/crates/engine/src/blockedit.rs +++ b/crates/engine/src/blockedit.rs @@ -268,11 +268,12 @@ impl DocState { } /// Start editing in the Block Editor `be` (the drawing is already the editor's): a fresh - /// undo history, nothing selected, model space. + /// undo history, nothing selected, nothing for OOPS, model space. fn enter_block_editor(&mut self, be: BlockEdit) { self.undo.clear(); self.redo.clear(); self.undo_ctl = Default::default(); + self.erased = Default::default(); self.selection.clear(); self.previous_selection.clear(); self.space = cadcraft_doc::Space::Model; @@ -338,6 +339,7 @@ impl DocState { self.undo = host.undo; self.redo = host.redo; self.undo_ctl = host.undo_ctl; + self.erased = host.erased; // The drawing comes back with nothing selected; Previous is what was selected before. self.selection.clear(); self.previous_selection = if host.selection.is_empty() { host.previous_selection } else { host.selection }; diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 172e416d1..bc93b9f55 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -25,6 +25,7 @@ mod lisp; mod mleader_content; mod mleader_edit; mod modify; +pub(crate) use modify::Erased; mod modify2; mod mtext_opts; mod overkill; diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 81732a3f8..258594ff0 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -187,9 +187,16 @@ pub(crate) fn make_block(s: &mut Session, name: &str, base: Vec2, hs: &[Handle], b.entities.push(e); } doc.blocks.insert(name.to_string(), Arc::new(b)); - if keep != Keep::Retain { - for h in hs { - doc.remove_entity(*h); + match keep { + Keep::Retain => {} + Keep::Convert => { + for h in hs { + doc.remove_entity(*h); + } + } + // As after ERASE, OOPS brings them back. + Keep::Delete => { + super::modify::erase_kept(s, hs)?; } } s.set_selection(Vec::new()); diff --git a/crates/engine/src/cmd/blocks/refedit.rs b/crates/engine/src/cmd/blocks/refedit.rs index 0a61122a5..18d0d436b 100644 --- a/crates/engine/src/cmd/blocks/refedit.rs +++ b/crates/engine/src/cmd/blocks/refedit.rs @@ -281,6 +281,8 @@ fn close(s: &mut Session, save: bool) -> Result { } nd.end_refedit_discard(&r); *s.doc_mut()? = nd; + // The objects the edit managed were its own: OOPS doesn't bring them back after it. + s.state_mut()?.erased.forget(|h| r.owns(h)); s.set_selection(Vec::new()); Ok(json!({ "block": r.block, "saved": save, "objects": objects })) } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3a4c43e73..754248cd3 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -549,13 +549,7 @@ fn run_pasteorig(s: &mut Session, _p: &Value) -> Result { fn run_clear(s: &mut Session, _p: &Value) -> Result { let mut hs = s.selection(); hs.retain(|h| !super::curves::is_locked(s, *h)); - let d = s.doc_mut()?; - let mut n = 0; - for h in hs { - if d.remove_entity(h).is_some() { - n += 1; - } - } + let n = super::modify::erase_kept(s, &hs)?; s.set_selection(Vec::new()); Ok(json!({ "erased": n })) } diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 22126f900..828ce1c01 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -20,6 +20,7 @@ mod break_join; mod explode; mod fillet; mod offset; +mod oops; mod select_then; mod stretch; mod transform; @@ -30,6 +31,8 @@ use explode::run_explode; pub(crate) use explode::{explode_kind, explode_with}; use fillet::{FilletM, run_chamfer, run_fillet}; use offset::{OffsetM, run_offset}; +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::transform_entities; @@ -43,6 +46,7 @@ pub fn specs() -> Vec { .alias(&["e", "delete"]) .params("{handles?: [hex]} (default: selection)") .interactive(|_| Ok(Box::new(SelectThen::new(Op::Erase)))), + CommandSpec::new("oops", "Oops", run_oops).params("{} (brings back what the last ERASE or BLOCK removed)"), CommandSpec::new("move", "Move", run_move) .menu(&["Modify", "Move"]) .alias(&["m"]) diff --git a/crates/engine/src/cmd/modify/oops.rs b/crates/engine/src/cmd/modify/oops.rs new file mode 100644 index 000000000..217f57ae6 --- /dev/null +++ b/crates/engine/src/cmd/modify/oops.rs @@ -0,0 +1,171 @@ +//! OOPS: bring back the objects the last ERASE (or the Delete key) removed, or BLOCK deleting the +//! objects it makes a block of, with their handles and each where it was in the draw order, as +//! AutoCAD 2024 does (accoreconsole, the drawing's `entnext` order read back afterwards). + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use cadcraft_doc::{Drawing, Entity, EntityKind, EntityStore, Handle, Space}; +use serde_json::{Value, json}; + +use crate::{Result, Session}; + +/// One erased object, with the objects that were directly under and above it. +#[derive(Clone, Debug)] +struct Taken { + space: Space, + entity: Arc, + below: Option, + above: Option, +} + +/// What the drawing's last erase removed, for OOPS. +#[derive(Clone, Debug, Default)] +pub(crate) struct Erased(Vec); + +impl Erased { + /// Never bring back the objects `drop` picks. + pub(crate) fn forget(&mut self, drop: impl Fn(Handle) -> bool) { + self.0.retain(|t| !drop(t.entity.handle)); + } +} + +/// Remove the objects `hs` and keep them for OOPS in place of what an earlier erase kept. +/// Returns how many went; when none did, OOPS keeps what it had. +pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result { + let d = s.doc_mut()?; + // Every neighbour is read before anything goes: objects erased together may be neighbours. + let at: Vec<(Handle, Space, Option, Option)> = hs + .iter() + .filter_map(|&h| { + let space = d.space_of(h)?; + let (below, above) = d.space(&space)?.neighbours(h)?; + Some((h, space, below, above)) + }) + .collect(); + let mut taken = Vec::with_capacity(at.len()); + for (h, space, below, above) in at { + if let Some(entity) = d.space_mut(&space).and_then(|st| st.remove(h)) { + taken.push(Taken { space, entity, below, above }); + } + } + let n = taken.len(); + if n > 0 { + s.state_mut()?.erased = Erased(taken); + } + Ok(n) +} + +pub(super) fn run_oops(s: &mut Session, _p: &Value) -> Result { + let taken = s.state()?.erased.0.clone(); + let back: Vec = { + let d = s.doc()?; + let in_blocks = in_blocks(d, &taken); + taken.iter().map(|t| !in_blocks.contains(&t.entity.handle) && can_return(d, t)).collect() + }; + // Nothing to bring back leaves the drawing as it is: no undo step. + if !back.contains(&true) { + return Ok(json!({ "restored": 0 })); + } + let n = restore(s.doc_mut()?, &taken, &back); + Ok(json!({ "restored": n })) +} + +/// The handles of `taken` that a block's object has now (an undo can take the drawing back to +/// before an erased object was made, and a block's new object take its handle). +fn in_blocks(d: &Drawing, taken: &[Taken]) -> HashSet { + let hs: HashSet = taken.iter().map(|t| t.entity.handle).collect(); + let mut out = HashSet::new(); + for b in d.blocks.values() { + // Through whichever is smaller. + if b.entities.len() < hs.len() { + out.extend(b.entities.iter().map(|e| e.handle).filter(|h| hs.contains(h))); + } else { + out.extend(hs.iter().copied().filter(|h| b.entities.contains(*h))); + } + } + out +} + +/// Whether `t` can come back: it is not in the drawing (OOPS again, or an undo brought it back), +/// its handle is one the drawing has given out, a reference being edited in place (REFEDIT) +/// doesn't keep it out, and its layout, layer and block are still there. +fn can_return(d: &Drawing, t: &Taken) -> bool { + let h = t.entity.handle; + h.0 < d.handseed + && d.entity(h).is_none() + && !crate::cmd::blocks::refedit::locked(d, h) + && d.space(&t.space).is_some() + && d.layer(&t.entity.common.layer).is_some() + && match &t.entity.kind { + EntityKind::Insert(i) => d.block(&i.block).is_some(), + _ => true, + } +} + +/// Put back the objects `back` marks. Each run of objects that were neighbours comes back from +/// its bottom one up, so each goes directly above the one that was under it. +fn restore(d: &mut Drawing, taken: &[Taken], back: &[bool]) -> usize { + let index: HashMap = taken.iter().enumerate().map(|(i, t)| (t.entity.handle, i)).collect(); + let next: HashMap = taken.iter().enumerate().filter_map(|(i, t)| Some((t.below.filter(|b| index.contains_key(b))?, i))).collect(); + let mut done = vec![false; taken.len()]; + let mut n = 0; + for first in 0..taken.len() { + if taken[first].below.is_some_and(|b| index.contains_key(&b)) { + continue; + } + let mut at = Some(first); + while let Some(i) = at { + if std::mem::replace(&mut done[i], true) { + break; + } + if back[i] && put_back(d, taken, &index, i) { + n += 1; + } + at = next.get(&taken[i].entity.handle).copied(); + } + } + n +} + +/// Put `taken[i]` back directly above the nearest object that was under it and is here; when +/// those are gone, directly under the nearest one that was above it; else on top. +fn put_back(d: &mut Drawing, taken: &[Taken], index: &HashMap, i: usize) -> bool { + let t = &taken[i]; + let Some(store) = d.space_mut(&t.space) else { return false }; + let h = t.entity.handle; + store.push(Entity::clone(&t.entity)); + match nearest(store, taken, index, t.below, |t| t.below) { + Some(Some(b)) => { + store.move_next_to(h, b, true); + } + Some(None) => { + store.send_to_back(h); + } + None => { + if let Some(Some(a)) = nearest(store, taken, index, t.above, |t| t.above) { + store.move_next_to(h, a, false); + } + } + } + true +} + +/// From `h`, past objects erased with it that are not here, to the first object that is +/// (`Some(Some)`), the end of the draw order (`Some(None)`), or an object that is gone (`None`). +fn nearest( + store: &EntityStore, + taken: &[Taken], + index: &HashMap, + mut h: Option, + step: fn(&Taken) -> Option, +) -> Option> { + for _ in 0..=taken.len() { + let Some(x) = h else { return Some(None) }; + if store.contains(x) { + return Some(Some(x)); + } + h = step(taken.get(*index.get(&x)?)?); + } + None +} diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 9adc54ec1..11e52ea23 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -1,6 +1,6 @@ use cadcraft_geom::Vec3; -use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, f64_req, json, point_param, point_req, targets}; +use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, erase_kept, f64_req, json, point_param, point_req, targets}; // ---------------- core operations ---------------- @@ -54,14 +54,9 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut } pub(super) fn erase(s: &mut Session, hs: &[Handle]) -> Result { - let d = s.doc_mut()?; - let mut n = 0; - for h in hs { - let locked = d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked); - if !locked && d.remove_entity(*h).is_some() { - n += 1; - } - } + let d = s.doc()?; + let free: Vec = hs.iter().copied().filter(|h| !d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked)).collect(); + let n = erase_kept(s, &free)?; s.set_selection(Vec::new()); Ok(n) } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 97a1ede49..31d23a94e 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -35,6 +35,8 @@ 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, + /// What the last erase removed, for OOPS. + pub(crate) erased: crate::cmd::Erased, /// The fonts missing on Windows that a save last named: the next save names them again only /// when they change. pub(crate) fonts_noted: String, @@ -64,6 +66,7 @@ impl DocState { uid: NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), binary_dxf: false, block_edit: None, + erased: Default::default(), fonts_noted: String::new(), } } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 65b8e244f..f49d7bb7e 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -93,6 +93,7 @@ mod non_finite_edits; mod offset_closed_spline; mod offset_ellipse_side; mod offset_move; +mod oops_command; mod options_profile; mod overkill; mod parallel_display_list; diff --git a/crates/engine/tests/it/oops_command.rs b/crates/engine/tests/it/oops_command.rs new file mode 100644 index 000000000..465484e0f --- /dev/null +++ b/crates/engine/tests/it/oops_command.rs @@ -0,0 +1,232 @@ +//! OOPS, as AutoCAD 2024 runs it (accoreconsole: a line A, a line B, a circle C and a line D, these +//! scripts, then the drawing's `entnext` order read back). + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{EntityCodec, set_entity_codec}; +use cadcraft_engine::doc::{Common, EntityKind, Handle, Line, Space}; +use cadcraft_engine::geom::Vec3; +use serde_json::{Value, json}; + +/// A session that `entmake` works in. +fn session() -> Session { + set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups }); + Session::new() +} + +/// A session with A, B, C and D in draw order, and their handles. +fn drawing() -> (Session, Vec) { + let mut s = session(); + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + s.execute("line", &json!({ "points": [[0, 10], [10, 10]] })).unwrap(); + s.execute("circle", &json!({ "center": [5, 25], "radius": 3 })).unwrap(); + s.execute("line", &json!({ "points": [[0, 40], [10, 40]] })).unwrap(); + let hs = handles(&s); + (s, hs) +} + +fn handles(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.handle).collect() +} + +/// The drawing's objects in draw order: A to D by their handles, E for any other. +fn order(s: &Session, hs: &[Handle]) -> String { + let name = |h: &Handle| hs.iter().position(|x| x == h).map_or('E', |i| (b'A' + i as u8) as char); + handles(s).iter().map(|h| name(h).to_string()).collect::>().join(" ") +} + +/// Run `script` with `@A`…`@D` standing for the objects. +fn run(s: &mut Session, hs: &[Handle], script: &[&str]) { + for line in script { + let mut line = line.to_string(); + for (i, h) in hs.iter().enumerate() { + line = line.replace(&format!("@{}", (b'A' + i as u8) as char), &format!("(handent \"{}\")", h.hex())); + } + s.cmdline(&line).unwrap(); + assert!(s.running.is_none(), "{line}: {}", s.prompt_text()); + } +} + +fn oops(s: &mut Session) -> Value { + s.execute("oops", &json!({})).unwrap() +} + +#[test] +fn the_last_erase_comes_back_where_it_was() { + const LINE: &str = "(command \"_.LINE\" '(0.0 50.0) '(10.0 50.0) \"\")"; + const OOPS: &str = "(command \"_.OOPS\")"; + // (case, script, the drawing's order afterwards: E is the line drawn after the erase) + let cases: [(&str, &[&str], &str); 14] = [ + ("OOPS-000: nothing erased yet", &[OOPS], "A B C D"), + ("OOPS-001: two in the middle", &["(command \"_.ERASE\" @B @C \"\")", OOPS], "A B C D"), + ("OOPS-002: picked in reverse", &["(command \"_.ERASE\" @C @B \"\")", OOPS], "A B C D"), + ("OOPS-003: a new object after the erase", &["(command \"_.ERASE\" @B \"\")", LINE, OOPS], "A B C D E"), + ("OOPS-004: the bottom object", &["(command \"_.ERASE\" @A \"\")", LINE, OOPS], "A B C D E"), + ("OOPS-005: twice", &["(command \"_.ERASE\" @B \"\")", OOPS, OOPS], "A B C D"), + ("OOPS-006: after U", &["(command \"_.ERASE\" @B \"\")", "U", OOPS], "A B C D"), + ("OOPS-007: the last erase only", &["(command \"_.ERASE\" @B \"\")", "(command \"_.ERASE\" @C \"\")", OOPS], "A C D"), + ("OOPS-008: U after OOPS", &["(command \"_.ERASE\" @B \"\")", OOPS, "U"], "A C D"), + ("OOPS-009: entdel", &["(entdel @B)", OOPS], "A C D"), + ("OOPS-010: -BLOCK", &["(command \"_.-BLOCK\" \"BKO\" '(0.0 0.0) @A @C \"\")", OOPS], "A B C D"), + ("OOPS-011: U of another command", &["(command \"_.ERASE\" @B \"\")", LINE, "U", OOPS], "A B C D"), + ("OOPS-012: the object under it erased since", &["(command \"_.ERASE\" @B \"\")", "(entdel @A)", OOPS], "B C D"), + ("OOPS-013: everything", &["(command \"_.ERASE\" \"_ALL\" \"\")", OOPS], "A B C D"), + ]; + for (case, script, want) in cases { + let (mut s, hs) = drawing(); + run(&mut s, &hs, script); + assert_eq!(order(&s, &hs), want, "{case}"); + } +} + +#[test] +fn oops_says_nothing_and_counts_what_came_back() { + let (mut s, hs) = drawing(); + s.cmdline("oops").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Command: OOPS")); + s.execute("erase", &json!({ "handles": [hs[1].hex(), hs[3].hex()] })).unwrap(); + s.cmdline("oops").unwrap(); + assert_eq!(s.log.last().map(String::as_str), Some("Command: OOPS")); + assert_eq!(order(&s, &hs), "A B C D"); + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + s.execute("u", &json!({})).unwrap(); + assert_eq!(order(&s, &hs), "A C"); + assert_eq!(oops(&mut s), json!({ "restored": 2 })); + // They come back as they were. + let d = s.doc().unwrap(); + assert!(matches!(d.entity(hs[3]).map(|e| &e.kind), Some(EntityKind::Line(l)) if l.a.y == 40.0 && l.b.x == 10.0)); +} + +#[test] +fn the_delete_key_and_block_feed_oops_too() { + // Edit > Clear, the Delete key. + let (mut s, hs) = drawing(); + s.set_selection(vec![hs[2]]); + s.execute("erase.selection", &json!({})).unwrap(); + assert_eq!(order(&s, &hs), "A B D"); + assert_eq!(oops(&mut s), json!({ "restored": 1 })); + assert_eq!(order(&s, &hs), "A B C D"); + // BLOCK deleting its objects. + let (mut s, hs) = drawing(); + s.execute("block", &json!({ "name": "BK", "base": [0, 0], "handles": [hs[0].hex(), hs[3].hex()], "keep": "delete" })).unwrap(); + assert_eq!(order(&s, &hs), "B C"); + assert_eq!(oops(&mut s), json!({ "restored": 2 })); + assert_eq!(order(&s, &hs), "A B C D"); +} + +#[test] +fn an_object_an_undo_took_away_stays_away() { + // U past the line's creation: its handle is free again. + let mut s = session(); + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + let x = handles(&s)[0]; + s.execute("erase", &json!({ "handles": [x.hex()] })).unwrap(); + s.execute("u", &json!({})).unwrap(); + s.execute("u", &json!({})).unwrap(); + assert!(handles(&s).is_empty()); + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + assert!(handles(&s).is_empty()); + // A new object takes the handle. + s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap(); + assert_eq!(handles(&s), [x]); + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + assert!(matches!(s.doc().unwrap().entity(x).map(|e| &e.kind), Some(EntityKind::Circle(_)))); + // A block's object takes the handle: one erased object of two, one of a block's two. + for (erased, in_block) in [(2, 1), (1, 2)] { + let mut s = session(); + for y in 0..erased { + s.execute("line", &json!({ "points": [[0, y], [10, y]] })).unwrap(); + } + let hs = handles(&s); + s.execute("erase", &json!({ "handles": hs.iter().map(|h| h.hex()).collect::>() })).unwrap(); + for _ in 0..=erased { + s.execute("u", &json!({})).unwrap(); + } + assert!(handles(&s).is_empty()); + s.cmdline("(entmake '((0 . \"BLOCK\") (2 . \"BX\") (10 0.0 0.0 0.0) (70 . 0)))").unwrap(); + for _ in 0..in_block { + s.cmdline("(entmake '((0 . \"LINE\") (8 . \"0\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0)))").unwrap(); + } + s.cmdline("(entmake '((0 . \"ENDBLK\")))").unwrap(); + assert!(s.doc().unwrap().block("BX").is_some_and(|b| b.entities.contains(hs[0])), "{erased} {in_block}"); + assert_eq!(oops(&mut s), json!({ "restored": 0 }), "{erased} {in_block}"); + assert!(handles(&s).is_empty()); + } +} + +#[test] +fn an_object_whose_layer_or_block_is_gone_stays_away() { + // Its layer purged. + let (mut s, hs) = drawing(); + run(&mut s, &hs, &["(command \"_.-LAYER\" \"_M\" \"L1\" \"\")"]); + s.execute("line", &json!({ "points": [[0, 60], [10, 60]] })).unwrap(); + let on_l1 = *handles(&s).last().unwrap(); + run(&mut s, &hs, &["(setvar \"CLAYER\" \"0\")"]); + s.execute("erase", &json!({ "handles": [on_l1.hex()] })).unwrap(); + s.execute("purge", &json!({ "type": "layers", "names": "L1" })).unwrap(); + assert!(s.doc().unwrap().layer("L1").is_none()); + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + // Its block purged. + let (mut s, hs) = drawing(); + s.execute("block", &json!({ "name": "BK", "base": [0, 0], "handles": [hs[0].hex()], "keep": "retain" })).unwrap(); + s.execute("insert", &json!({ "name": "BK", "at": [50, 0] })).unwrap(); + let ins = *handles(&s).last().unwrap(); + s.execute("erase", &json!({ "handles": [ins.hex()] })).unwrap(); + s.execute("purge", &json!({ "type": "blocks", "names": "BK" })).unwrap(); + assert!(s.doc().unwrap().block("BK").is_none()); + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + assert_eq!(order(&s, &hs), "A B C D"); +} + +#[test] +fn the_block_editor_has_an_oops_of_its_own() { + let (mut s, hs) = drawing(); + s.execute("block", &json!({ "name": "BK", "base": [0, 0], "handles": [hs[0].hex()], "keep": "retain" })).unwrap(); + s.execute("erase", &json!({ "handles": [hs[1].hex()] })).unwrap(); + s.execute("bedit", &json!({ "name": "BK" })).unwrap(); + // The drawing's erased line doesn't come back into the block. + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + s.execute("bclose", &json!({ "save": false })).unwrap(); + // Back in the drawing, it does. + assert_eq!(oops(&mut s), json!({ "restored": 1 })); + assert_eq!(order(&s, &hs), "A B C D"); +} + +#[test] +fn a_layouts_objects_come_back_to_it() { + let mut s = session(); + let paper = Space::Paper("Layout1".into()); + let line = |y: f64| EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }); + let hs: Vec = (0..3).map(|y| s.doc_mut().unwrap().add(&paper, Common::default(), line(f64::from(y))).unwrap()).collect(); + s.execute("erase", &json!({ "handles": [hs[1].hex()] })).unwrap(); + assert_eq!(oops(&mut s), json!({ "restored": 1 })); + let d = s.doc().unwrap(); + assert!(d.model.is_empty()); + assert_eq!(d.space(&paper).unwrap().handles(), hs); +} + +#[test] +fn a_reference_edited_in_place_keeps_its_objects_and_the_drawings_apart() { + let (mut s, hs) = drawing(); + s.execute("block", &json!({ "name": "BK", "base": [0, 0], "handles": [hs[0].hex(), hs[1].hex()], "keep": "convert" })).unwrap(); + let ins = *handles(&s).last().unwrap(); + s.execute("erase", &json!({ "handles": [hs[3].hex()] })).unwrap(); + let r = s.execute("refedit", &json!({ "handle": ins.hex() })).unwrap(); + // The drawing's line stays out while the reference is edited... + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + // ...and a working copy comes back. + let copy = r["working"][0].as_str().unwrap().to_string(); + s.execute("erase", &json!({ "handles": [copy] })).unwrap(); + assert_eq!(oops(&mut s), json!({ "restored": 1 })); + // Once the edit is over, its copies don't come back into the drawing. + s.execute("erase", &json!({ "handles": [copy] })).unwrap(); + s.execute("refclose", &json!({ "save": true })).unwrap(); + assert_eq!(s.doc().unwrap().block("BK").unwrap().entities.len(), 1); + assert_eq!(oops(&mut s), json!({ "restored": 0 })); + assert_eq!(order(&s, &hs), "C E"); + // The drawing's own erased line does, after an edit that ends. + s.execute("erase", &json!({ "handles": [hs[2].hex()] })).unwrap(); + s.execute("refedit", &json!({ "handle": ins.hex() })).unwrap(); + s.execute("refclose", &json!({ "save": false })).unwrap(); + assert_eq!(oops(&mut s), json!({ "restored": 1 })); + assert_eq!(order(&s, &hs), "C E"); +} diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 026190729..ccc9b72d5 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -643,6 +643,7 @@ One of the Crafting Apps by the ArtCraft team and community. أحد تطبيقات Crafting من فريق ArtCraft والمجتمع. Only in this drawing: {n} في هذا الرسم فقط: {n} Only in {name}: {n} في {name} فقط: {n} + Oops استعادة الكائنات الممحوة Open فتح Open (⌘O) فتح (⌘O) Open Sample Drawing فتح رسم نموذجي diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 14565ce2f..460959a33 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -585,6 +585,7 @@ One of the Crafting Apps by the ArtCraft team and community. Jedna od Crafting aplikacija ArtCraft tima i zajednice. Only in this drawing: {n} Samo u ovom crtežu: {n} Only in {name}: {n} Samo u {name}: {n} + Oops Vrati obrisane objekte Open (⌘O) Otvori (⌘O) Open Sample Drawing Otvori primjer crteža Open sample drawing Otvori primjer crteža diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index c979cd786..2419bf41f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -583,6 +583,7 @@ One of the Crafting Apps by the ArtCraft team and community. Jedna z aplikací Crafting Apps od týmu ArtCraft a komunity. Only in this drawing: {n} Pouze v tomto výkresu: {n} Only in {name}: {n} Pouze v {name}: {n} + Oops Obnovit vymazané objekty Open (⌘O) Otevřít (⌘O) Open Sample Drawing Otevřít ukázkový výkres Open sample drawing Otevřít ukázku výkresu diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 84b944529..2186fc743 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -495,6 +495,7 @@ On Ein On/Off Ein/Aus One of the Crafting Apps by the ArtCraft team and community. Eine der Crafting Apps vom ArtCraft-Team und seiner Community. + Oops Gelöschte Objekte wiederherstellen Open (⌘O) Öffnen (⌘O) Open Sample Drawing Beispielzeichnung öffnen Open sample drawing Beispielzeichnung öffnen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2825e8fd2..16fcecfeb 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -702,6 +702,7 @@ One of the Crafting Apps by the ArtCraft team and community. Μία από τις εφαρμογές Crafting Apps της ομάδας και της κοινότητας ArtCraft. Only in this drawing: {n} Μόνο σε αυτό το σχέδιο: {n} Only in {name}: {n} Μόνο στο {name}: {n} + Oops Επαναφορά διαγραμμένων αντικειμένων Open Άνοιγμα Open (⌘O) Άνοιγμα (⌘O) Open a drawing first. Ανοίξτε πρώτα ένα σχέδιο. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b24970979..8c45b7f97 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -620,6 +620,7 @@ One of the Crafting Apps by the ArtCraft team and community. Una de las Crafting Apps del equipo y la comunidad de ArtCraft. Only in this drawing: {n} Solo en este dibujo: {n} Only in {name}: {n} Solo en {name}: {n} + Oops Restaurar objetos borrados Open Abrir Open (⌘O) Abrir (⌘O) Open Sample Drawing Abrir dibujo de ejemplo diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 42ad7ee48..548ed6a66 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -490,6 +490,7 @@ On Activé On/Off Activer/Désactiver One of the Crafting Apps by the ArtCraft team and community. L'une des applications Crafting Apps de l'équipe et de la communauté ArtCraft. + Oops Restaurer les objets effacés Open (⌘O) Ouvrir (⌘O) Open Sample Drawing Ouvrir un dessin d'exemple Open sample drawing Ouvrir un dessin d'exemple diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index fc27bd7ce..926ad0e6c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -711,6 +711,7 @@ One of the Crafting Apps by the ArtCraft team and community. Az ArtCraft csapata és közössége által készített Craft-alkalmazások egyike. Only in this drawing: {n} Csak ebben a rajzban: {n} Only in {name}: {n} Csak ebben: {name} – {n} + Oops Törölt objektumok visszaállítása Open Megnyitás Open (⌘O) Megnyitás (⌘O) Open Recent Legutóbbi megnyitása diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 634249093..3287ec077 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -594,6 +594,7 @@ menu Modify Edita One of the Crafting Apps by the ArtCraft team and community. Una delle Crafting App del team e della comunità ArtCraft. Only in this drawing: {n} Solo in questo disegno: {n} Only in {name}: {n} Solo in {name}: {n} + Oops Ripristina oggetti cancellati Open (⌘O) Apri (⌘O) Open Sample Drawing Apri disegno di esempio Open sample drawing Apri disegno di esempio diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 1bd7e0fd5..f41128ba1 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -585,6 +585,7 @@ One of the Crafting Apps by the ArtCraft team and community. ArtCraft 팀과 커뮤니티가 만드는 Crafting Apps 제품군의 하나입니다. Only in this drawing: {n} 이 도면에만 있음: {n}개 Only in {name}: {n} {name}에만 있음: {n}개 + Oops 지운 객체 복원 Open (⌘O) 열기(⌘O) Open Sample Drawing 예제 도면 열기 Open sample drawing 예제 도면 열기 diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 8f6533d51..3e16b65cf 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -616,6 +616,7 @@ One of the Crafting Apps by the ArtCraft team and community. Um dos Crafting Apps da equipe e da comunidade ArtCraft. Only in this drawing: {n} Somente neste desenho: {n} Only in {name}: {n} Somente em {name}: {n} + Oops Restaurar objetos apagados Open Abrir Open (⌘O) Abrir (⌘O) Open Sample Drawing Abrir desenho de exemplo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b8f97bf73..7e4ba21d5 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -490,6 +490,7 @@ On Включено On/Off Включить/выключить One of the Crafting Apps by the ArtCraft team and community. Одна из программ Crafting Apps от команды и сообщества ArtCraft. + Oops Восстановить стертые объекты Open (⌘O) Открыть (⌘O) Open Sample Drawing Открыть образец чертежа Open sample drawing Открыть образец чертежа diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6bea4c3da..96114f857 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -619,6 +619,7 @@ One of the Crafting Apps by the ArtCraft team and community. En av Crafting Apps, gjord av ArtCraft-teamet och dess community. Only in this drawing: {n} Bara i den här ritningen: {n} Only in {name}: {n} Bara i {name}: {n} + Oops Återställ raderade objekt Open Öppna Open (⌘O) Öppna (⌘O) Open Sample Drawing Öppna exempelritning diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2bf979f85..3fed6bc3b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -712,6 +712,7 @@ One of the Crafting Apps by the ArtCraft team and community. ArtCraft ekibi ve topluluğunun Crafting Apps uygulamalarından biri. Only in this drawing: {n} Yalnızca bu çizimde: {n} Only in {name}: {n} Yalnızca {name} içinde: {n} + Oops Silinen Nesneleri Geri Yükle Open Aç Open (⌘O) Aç (⌘O) Open Recent Son Kullanılanları Aç diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 714ce6c4c..bbb70e489 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -598,6 +598,7 @@ One of the Crafting Apps by the ArtCraft team and community. Одна з програм Crafting Apps від команди та спільноти ArtCraft. Only in this drawing: {n} Лише в цьому кресленні: {n} Only in {name}: {n} Лише в {name}: {n} + Oops Відновити стерті об'єкти Open (⌘O) Відкрити (⌘O) Open Sample Drawing Відкрити зразок креслення Open sample drawing Відкрити зразок креслення diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9b1493031..8887bb45b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -584,6 +584,7 @@ One of the Crafting Apps by the ArtCraft team and community. Một trong các ứng dụng Crafting của nhóm và cộng đồng ArtCraft. Only in this drawing: {n} Chỉ có trong bản vẽ này: {n} Only in {name}: {n} Chỉ có trong {name}: {n} + Oops Khôi phục đối tượng đã xóa Open (⌘O) Mở (⌘O) Open Sample Drawing Mở bản vẽ mẫu Open sample drawing Mở bản vẽ mẫu diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 2663105a2..21c86d1fe 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -489,6 +489,7 @@ On 开启 On/Off 开/关 One of the Crafting Apps by the ArtCraft team and community. 由 ArtCraft 团队和社区打造的 Crafting 系列应用之一。 + Oops 恢复已擦除对象 Open (⌘O) 打开 (⌘O) Open Sample Drawing 打开示例图形 Open sample drawing 打开示例图形 From 2034d6899eba72363028723ec75d4c36eacfceac Mon Sep 17 00:00:00 2001 From: Andrea Ficarra Date: Sun, 1 Nov 2026 20:40:30 +0100 Subject: [PATCH 359/900] Polyface meshes stay one object through DXF and DWG (#2600) * Polyface meshes stay one object through DXF and DWG A polyface mesh (POLYLINE flag 64) was read as loose 3D faces. It is now read, drawn, exploded into its 3D faces and written back as a POLYLINE. Hidden edges aren't drawn. A mesh too large for the 16-bit groups 71-74 is saved as 3D faces. Split from #1005. Co-Authored-By: Claude Opus 5.5 * A polyface face ends at its first zero index A face record with a gap ([1, 2, 0, 3]) has two corners and is dropped, not read as a triangle. Co-Authored-By: Claude Opus 5.5 * Polyface meshes: write only faces that name their vertices; ID gives their Z The writer drops the faces the reader would drop, so no record names a missing vertex, and the 16-bit check only needs the counts. ID and DIST give a mesh the Z of its nearest visible edge, as they do for 3D faces. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/doc/src/entity.rs | 16 ++- crates/doc/src/entity/curves.rs | 46 +++++++ crates/doc/tests/it/face3d_hidden_edges.rs | 19 +++ crates/doc/tests/it/main.rs | 1 + crates/engine/src/cmd/inquiry.rs | 8 ++ crates/engine/src/cmd/modify/explode.rs | 6 + crates/engine/src/cmd/modify2/selop.rs | 1 + crates/engine/src/grips.rs | 1 + crates/engine/tests/it/inquiry_z.rs | 12 +- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/polyface_explode.rs | 32 +++++ crates/engine/tests/it/scale_offset_z.rs | 13 +- crates/io/src/dxf_read.rs | 2 +- crates/io/src/dxf_read/document.rs | 2 +- crates/io/src/dxf_read/entities.rs | 48 +++----- crates/io/src/dxf_write.rs | 6 +- crates/io/src/dxf_write/entity.rs | 61 +++++++++- crates/io/tests/it/entity_props_roundtrip.rs | 16 ++- crates/io/tests/it/low_handseed.rs | 24 ++-- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/polyface_roundtrip.rs | 121 +++++++++++++++++++ 21 files changed, 376 insertions(+), 61 deletions(-) create mode 100644 crates/doc/tests/it/face3d_hidden_edges.rs create mode 100644 crates/engine/tests/it/polyface_explode.rs create mode 100644 crates/io/tests/it/polyface_roundtrip.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index b19d10961..a516137fa 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -48,7 +48,7 @@ mod wipeout; pub use block::{Attrib, AttribModes, AttribProps, Insert, MultilineAttrib, mtext_literal}; pub use common::{Common, Handle, Lineweight, RawTag, Transparency}; -pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyline3d, RayLine, Solid}; +pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid}; pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader}; pub use fill::{Gradient, Hatch, HatchLoop}; pub use layout::{Image, Table, TableCell, Viewport}; @@ -86,6 +86,7 @@ pub enum EntityKind { Solid(Solid), Trace(Solid), Face3d(Face3d), + PolyfaceMesh(PolyfaceMesh), Region(Region), Viewport(Viewport), Image(Image), @@ -140,6 +141,7 @@ impl EntityKind { EntityKind::Solid(_) => "2D Solid", EntityKind::Trace(_) => "Trace", EntityKind::Face3d(_) => "3D Face", + EntityKind::PolyfaceMesh(_) => "Polyface Mesh", EntityKind::Region(_) => "Region", EntityKind::Viewport(_) => "Viewport", EntityKind::Image(_) => "Raster Image", @@ -175,6 +177,7 @@ impl EntityKind { EntityKind::Solid(_) => "SOLID", EntityKind::Trace(_) => "TRACE", EntityKind::Face3d(_) => "3DFACE", + EntityKind::PolyfaceMesh(_) => "POLYLINE", EntityKind::Region(_) => "REGION", EntityKind::Viewport(_) => "VIEWPORT", EntityKind::Image(_) => "IMAGE", @@ -218,10 +221,10 @@ impl EntityKind { let c = &s.corners; vec![Prim::Fill(vec![c[0].xy(), c[1].xy(), c[3].xy(), c[2].xy()])] } - EntityKind::Face3d(f) => { - let c = &f.corners; - let pts = [c[0].xy(), c[1].xy(), c[2].xy(), c[3].xy(), c[0].xy()]; - pts.windows(2).filter_map(|w| Some(Prim::Seg(Segment::Line(GLine::new(*w.first()?, *w.get(1)?))))).collect() + EntityKind::Face3d(f) => f.visible_edges().into_iter().map(|(a, b)| Prim::Seg(Segment::Line(GLine::new(a.xy(), b.xy())))).collect(), + // Each face's visible edges (an edge flagged hidden, by a negative index, isn't drawn). + EntityKind::PolyfaceMesh(m) => { + m.faces3d().iter().flat_map(Face3d::visible_edges).map(|(a, b)| Prim::Seg(Segment::Line(GLine::new(a.xy(), b.xy())))).collect() } EntityKind::Region(r) => r.segments().into_iter().map(Prim::Seg).collect(), EntityKind::Hatch(h) => { @@ -424,6 +427,7 @@ impl EntityKind { } EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(t3), EntityKind::Face3d(f) => f.corners.iter_mut().for_each(t3), + EntityKind::PolyfaceMesh(pm) => pm.vertices.iter_mut().for_each(t3), EntityKind::Region(r) => { for v in r.loops.iter_mut().flat_map(|l| l.vertices.iter_mut()) { v.p = m.apply(v.p); @@ -542,6 +546,7 @@ impl EntityKind { EntityKind::Hatch(h) => scale(&mut h.elevation), EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(z), EntityKind::Face3d(fc) => fc.corners.iter_mut().for_each(z), + EntityKind::PolyfaceMesh(m) => m.vertices.iter_mut().for_each(z), EntityKind::Viewport(v) => z(&mut v.center), EntityKind::Image(i) => z(&mut i.insert), EntityKind::Table(t) => z(&mut t.insert), @@ -611,6 +616,7 @@ impl EntityKind { } EntityKind::Solid(s) | EntityKind::Trace(s) => s.corners.iter().map(|c| c.xy()).collect(), EntityKind::Face3d(f) => f.corners.iter().map(|c| c.xy()).collect(), + EntityKind::PolyfaceMesh(m) => m.vertices.iter().map(|v| v.xy()).collect(), EntityKind::Region(r) => vec![r.bounds().center()], EntityKind::Viewport(v) => { let c = v.center.xy(); diff --git a/crates/doc/src/entity/curves.rs b/crates/doc/src/entity/curves.rs index 8eeb556c4..f32319b02 100644 --- a/crates/doc/src/entity/curves.rs +++ b/crates/doc/src/entity/curves.rs @@ -69,6 +69,52 @@ pub struct Face3d { pub hidden_edges: u8, } +impl Face3d { + /// The edges drawn: side i (corner i to the next) unless bit i of `hidden_edges` hides it, + /// without the zero-length side of a triangle. + pub fn visible_edges(&self) -> Vec<(Vec3, Vec3)> { + let c = self.corners; + (0..4).filter(|i| self.hidden_edges & (1 << i) == 0).map(|i| (c[i], c[(i + 1) % 4])).filter(|(a, b)| a != b).collect() + } +} + +/// POLYLINE polyface mesh (DXF flag 64): its vertices, and faces naming three or four of them +/// by 1-based index as DXF stores them (0: no fourth vertex; a negative index hides the edge +/// that starts at that vertex). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct PolyfaceMesh { + pub vertices: Vec, + pub faces: Vec<[i32; 4]>, +} + +impl PolyfaceMesh { + /// The faces as 3D faces (what EXPLODE makes). Faces with fewer than three vertices or an + /// index outside the vertex list are skipped. + pub fn faces3d(&self) -> Vec { + self.faces.iter().filter_map(|f| self.face3d(f)).collect() + } + /// One face record as a 3D face: `None` when it names fewer than three vertices before a 0, + /// or one outside the vertex list. + pub fn face3d(&self, f: &[i32; 4]) -> Option { + let mut corners: Vec = Vec::with_capacity(4); + let mut hidden = 0u8; + for &ix in f.iter().take_while(|&&ix| ix != 0) { + let at = usize::try_from(ix.unsigned_abs()).ok().and_then(|n| n.checked_sub(1)); + let p = *at.and_then(|n| self.vertices.get(n))?; + if ix < 0 { + hidden |= 1 << corners.len(); + } + corners.push(p); + } + match corners.as_slice() { + // A triangle's closing edge is the 3DFACE's fourth (the third is degenerate). + [a, b, c] => Some(Face3d { corners: [*a, *b, *c, *c], hidden_edges: hidden | if hidden & 4 != 0 { 8 } else { 0 } }), + [a, b, c, d] => Some(Face3d { corners: [*a, *b, *c, *d], hidden_edges: hidden }), + _ => None, + } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RayLine { pub base: Vec3, diff --git a/crates/doc/tests/it/face3d_hidden_edges.rs b/crates/doc/tests/it/face3d_hidden_edges.rs new file mode 100644 index 000000000..ee49f462f --- /dev/null +++ b/crates/doc/tests/it/face3d_hidden_edges.rs @@ -0,0 +1,19 @@ +//! A 3D face draws only its visible edges: `hidden_edges` bit i hides the side from corner i to +//! the next, as DXF group 70 defines it, and a triangle's zero-length side isn't drawn. + +use cadcraft_doc::{EntityKind, Face3d, Prim}; +use cadcraft_geom::Vec3; + +fn sides(f: Face3d) -> usize { + EntityKind::Face3d(f).prims().iter().filter(|p| matches!(p, Prim::Seg(_))).count() +} + +#[test] +fn hidden_edges_are_not_drawn() { + let quad = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)]; + assert_eq!(sides(Face3d { corners: quad, hidden_edges: 0 }), 4); + assert_eq!(sides(Face3d { corners: quad, hidden_edges: 1 | 4 }), 2); + assert_eq!(sides(Face3d { corners: quad, hidden_edges: 15 }), 0); + let triangle = [quad[0], quad[1], quad[2], quad[2]]; + assert_eq!(sides(Face3d { corners: triangle, hidden_edges: 0 }), 3); +} diff --git a/crates/doc/tests/it/main.rs b/crates/doc/tests/it/main.rs index dcad121df..18d01e293 100644 --- a/crates/doc/tests/it/main.rs +++ b/crates/doc/tests/it/main.rs @@ -1,2 +1,3 @@ +mod face3d_hidden_edges; mod lin_pat_parse; mod sub_segment_alias; diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index 0fa342e23..119d727e1 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -285,6 +285,14 @@ fn entity_z(e: &Entity, p: Vec2) -> Option { EntityKind::MText(t) => Some(t.insert.z), EntityKind::Insert(i) => Some(i.insert.z), EntityKind::Face3d(f) => face_z(&f.corners, p).or_else(|| along(&f.corners, true)), + // Drawn as its faces' visible edges: the Z on the nearest one. + EntityKind::PolyfaceMesh(m) => m + .faces3d() + .iter() + .flat_map(cadcraft_doc::Face3d::visible_edges) + .map(|(a, b)| on_segment(a, b)) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(z, _)| z), _ => None, } } diff --git a/crates/engine/src/cmd/modify/explode.rs b/crates/engine/src/cmd/modify/explode.rs index 46ada655d..d7db29d35 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -151,6 +151,12 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option { + let faces = m.faces3d(); + (!faces.is_empty()) + .then(|| faces.into_iter().map(|f| Entity { handle: Handle(0), common: e.common.clone(), kind: EntityKind::Face3d(f) }).collect()) + } EntityKind::MLine(m) => Some(crate::cmd::draw2::mline::explode(e, m)), EntityKind::MText(m) => Some(explode_mtext(e, m)), // A region explodes into its boundary's lines and arcs. diff --git a/crates/engine/src/cmd/modify2/selop.rs b/crates/engine/src/cmd/modify2/selop.rs index f1b63e3ce..53939d4b6 100644 --- a/crates/engine/src/cmd/modify2/selop.rs +++ b/crates/engine/src/cmd/modify2/selop.rs @@ -103,6 +103,7 @@ pub(crate) fn flatten_kind(k: &mut EntityKind) { EntityKind::Hatch(h) => h.elevation = 0.0, EntityKind::Solid(so) | EntityKind::Trace(so) => so.corners.iter_mut().for_each(z), EntityKind::Face3d(f) => f.corners.iter_mut().for_each(z), + EntityKind::PolyfaceMesh(m) => m.vertices.iter_mut().for_each(z), EntityKind::Region(_) => {} EntityKind::Image(i) => { z(&mut i.insert); diff --git a/crates/engine/src/grips.rs b/crates/engine/src/grips.rs index 8c58e30b5..b0c1a1bca 100644 --- a/crates/engine/src/grips.rs +++ b/crates/engine/src/grips.rs @@ -226,6 +226,7 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option set_xy(s.corners.get_mut(index)?, to), EntityKind::Face3d(f) => set_xy(f.corners.get_mut(index)?, to), + EntityKind::PolyfaceMesh(m) => set_xy(m.vertices.get_mut(index)?, to), EntityKind::Region(_) => return Some(translated(kind, delta)), EntityKind::Viewport(v) => { let opposite = *grips.get((index + 2) % 4)?; diff --git a/crates/engine/tests/it/inquiry_z.rs b/crates/engine/tests/it/inquiry_z.rs index 17f44ac03..274eeacd0 100644 --- a/crates/engine/tests/it/inquiry_z.rs +++ b/crates/engine/tests/it/inquiry_z.rs @@ -3,7 +3,7 @@ //! all said Z = 0, so a topographic drawing's levels couldn't be read in CADCraft. use cadcraft_engine::Session; -use cadcraft_engine::doc::{EntityKind, Face3d, Handle, Line, LwPolyline, Point}; +use cadcraft_engine::doc::{EntityKind, Face3d, Handle, Line, LwPolyline, Point, PolyfaceMesh}; use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3}; use serde_json::json; @@ -56,6 +56,16 @@ fn id_reports_the_z_of_what_is_at_the_point() { assert!(s.log.iter().any(|l| l.contains("Z = 1883.5460")), "{:?}", s.log.iter().rev().take(3).collect::>()); } +#[test] +fn id_reports_the_z_on_a_polyface_mesh() { + let mut s = Session::new(); + // A sloped TIN as two triangles: z = 1000 + x / 10 over (0..100, 0..100). + let vertices = vec![Vec3::new(0.0, 0.0, 1000.0), Vec3::new(100.0, 0.0, 1010.0), Vec3::new(100.0, 100.0, 1010.0), Vec3::new(0.0, 100.0, 1000.0)]; + add(&mut s, EntityKind::PolyfaceMesh(PolyfaceMesh { vertices, faces: vec![[1, 2, -3, 0], [3, 4, -1, 0]] })); + s.cmdline("zoom e").ok(); + assert!((z(&mut s, [50.0, 0.0]) - 1005.0).abs() < 1e-9, "on the mesh's edge"); +} + fn z_given(s: &mut Session) -> f64 { s.execute("id", &json!({ "at": [10, 10, 3] })).unwrap()["z"].as_f64().unwrap() } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f49d7bb7e..54ea40675 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -104,6 +104,7 @@ mod pickdrag; mod pline_arc_xline_options; mod plot_styles; mod point_modifiers; +mod polyface_explode; mod post_command_passes; mod prompt_keywords; mod props_bad_lineweight; diff --git a/crates/engine/tests/it/polyface_explode.rs b/crates/engine/tests/it/polyface_explode.rs new file mode 100644 index 000000000..d6d850e88 --- /dev/null +++ b/crates/engine/tests/it/polyface_explode.rs @@ -0,0 +1,32 @@ +//! EXPLODE turns a polyface mesh into its 3D faces, as AutoCAD does; hidden edges stay hidden. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Common, EntityKind, PolyfaceMesh, Space}; +use cadcraft_geom::Vec3; +use serde_json::json; + +#[test] +fn exploding_a_polyface_mesh_gives_its_3d_faces() { + let mut s = Session::new(); + let mesh = PolyfaceMesh { + vertices: vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 2.0), Vec3::new(0.0, 10.0, 2.0)], + faces: vec![[1, 2, -3, 0], [3, 4, -1, 0]], + }; + let h = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::PolyfaceMesh(mesh)).unwrap(); + s.execute("explode", &json!({"handles": [h.hex()]})).unwrap(); + let faces: Vec<_> = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Face3d(f) => Some(f.clone()), + _ => None, + }) + .collect(); + assert_eq!(faces.len(), 2); + assert!(s.doc().unwrap().model.iter().all(|e| !matches!(e.kind, EntityKind::PolyfaceMesh(_)))); + // The diagonal starts at the third corner of the first triangle: edge 3 (and the closing 4th) hidden. + assert_eq!(faces[0].corners[2], Vec3::new(10.0, 10.0, 2.0)); + assert_eq!(faces[0].hidden_edges, 4 | 8); +} diff --git a/crates/engine/tests/it/scale_offset_z.rs b/crates/engine/tests/it/scale_offset_z.rs index a32cea081..d82d53ce0 100644 --- a/crates/engine/tests/it/scale_offset_z.rs +++ b/crates/engine/tests/it/scale_offset_z.rs @@ -5,7 +5,7 @@ //! has no thickness while a polyline's keeps it. use cadcraft_engine::Session; -use cadcraft_engine::doc::{Arc, Circle, Common, EntityKind, Handle, Line, LwPolyline, Point}; +use cadcraft_engine::doc::{Arc, Circle, Common, EntityKind, Handle, Line, LwPolyline, Point, PolyfaceMesh}; use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3}; use serde_json::json; @@ -182,3 +182,14 @@ fn offset_keeps_a_polylines_elevation_and_thickness() { let first = k.vertices.first().unwrap().p; assert!(close(first.x, 0.0) && close(first.y, 3.0), "{first:?}"); } + +#[test] +fn scale_scales_a_polyface_meshs_vertex_heights() { + let mut s = Session::new(); + let vertices = vec![Vec3::new(0.0, 0.0, 2.0), Vec3::new(10.0, 0.0, 2.0), Vec3::new(0.0, 10.0, 6.0)]; + let m = add(&mut s, EntityKind::PolyfaceMesh(PolyfaceMesh { vertices, faces: vec![[1, 2, 3, 0]] }), 0.0); + scale(&mut s, m, "0.0 0.0"); + let EntityKind::PolyfaceMesh(k) = get(&s, m).0 else { panic!() }; + let want = [Vec3::new(0.0, 0.0, 3.4), Vec3::new(17.0, 0.0, 3.4), Vec3::new(0.0, 17.0, 10.2)]; + assert!(k.vertices.iter().zip(want).all(|(a, b)| near3(*a, b)), "{:?}", k.vertices); +} diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 324caa361..341e72a77 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -93,7 +93,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { let mut objs = Objects::default(); // Every handle another program's file already uses is taken before anything gets a new one: // its $HANDSEED can be lower than its handles, and entities made while reading (the faces of - // a polyface mesh) would otherwise get handles that records further on still have. A file + // a polygon mesh) would otherwise get handles that records further on still have. A file // CADCraft wrote names its own next handle, above which its rebuilt records are numbered // (#495), so it is left to that. let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY)); diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index d732f4450..db935974a 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -23,7 +23,7 @@ pub(super) fn parse_entities( { c.plot_style = n; } - // More entities from this record (the faces of a polyface or polygon mesh). + // More entities from this record (the faces of a polygon mesh). let mut extra: Vec = Vec::new(); i += 1; match kind.as_str() { diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 394feb785..119d00bbd 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -7,6 +7,7 @@ use super::{ LwPolyline, MAX_FRAME_CHARS, Point, PolyVertex, Polyline3d, RawTag, RayLine, Rx, Solid, Spline, Table, TableCell, Tag, Tolerance, Unknown, Vec2, Vec3, Viewport, Wipeout, records, }; +use cadcraft_doc::PolyfaceMesh; /// Parse one entity record. POLYLINE/INSERT followers are handled by the caller. pub(super) fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> { @@ -514,11 +515,20 @@ pub(super) fn polyline_entity(recs: &[(String, Vec)], i: &mut usize, t: &T) } let c = common(t); let mut extra: Vec = Vec::new(); - let k = if flags & (16 | 64) != 0 { - // Polyface (64) and polygon (16) meshes become 3D faces; the first takes the - // polyline's place. + let k = if flags & 64 != 0 { + // Face records that name a missing vertex (or fewer than three) are dropped: they draw + // nothing and would be written back broken. A mesh left with no face is skipped. + let mut mesh = PolyfaceMesh { vertices: pts.iter().map(|p| p.0).collect(), faces: Vec::new() }; + let kept = faces.iter().map(|f| f.map(|ix| i32::try_from(ix).unwrap_or(i32::MAX))).filter(|f| mesh.face3d(f).is_some()).collect(); + mesh.faces = kept; + if mesh.faces.is_empty() { + return None; + } + EntityKind::PolyfaceMesh(mesh) + } else if flags & 16 != 0 { + // Polygon meshes become 3D faces; the first takes the polyline's place. let verts: Vec = pts.iter().map(|p| p.0).collect(); - let mut fs = if flags & 64 != 0 { polyface_faces(&verts, &faces) } else { mesh_faces(&verts, t, flags) }.into_iter().map(EntityKind::Face3d); + let mut fs = mesh_faces(&verts, t, flags).into_iter().map(EntityKind::Face3d); let first = fs.next()?; extra.extend(fs); first @@ -573,36 +583,6 @@ pub(super) fn insert_attribs(recs: &[(String, Vec)], i: &mut usize, ins_lay attribs } -/// Faces of a polyface mesh: each face record names three or four vertices by 1-based index; -/// a negative index hides the edge that starts at that vertex. Faces with fewer vertices or -/// an index outside the vertex list are skipped. -fn polyface_faces(verts: &[Vec3], faces: &[[i64; 4]]) -> Vec { - let mut out = Vec::new(); - for f in faces { - let mut corners: Vec = Vec::with_capacity(4); - let mut hidden = 0u8; - let mut ok = true; - for &ix in f.iter().filter(|&&ix| ix != 0) { - let at = usize::try_from(ix.unsigned_abs()).ok().and_then(|n| n.checked_sub(1)); - let Some(p) = at.and_then(|n| verts.get(n)) else { - ok = false; - break; - }; - if ix < 0 { - hidden |= 1 << corners.len(); - } - corners.push(*p); - } - match (ok, corners.as_slice()) { - // A triangle's closing edge is the 3DFACE's fourth (the third is degenerate). - (true, [a, b, c]) => out.push(Face3d { corners: [*a, *b, *c, *c], hidden_edges: hidden | if hidden & 4 != 0 { 8 } else { 0 } }), - (true, [a, b, c, d]) => out.push(Face3d { corners: [*a, *b, *c, *d], hidden_edges: hidden }), - _ => {} - } - } - out -} - /// Quads of an M×N polygon mesh (71/72, or the smoothed 73/74 when the vertex count matches /// those), closed in M by bit 1 and in N by bit 32. Vertices run row by row. fn mesh_faces(verts: &[Vec3], t: &T, flags: i64) -> Vec { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index b93471b01..411f1c4b2 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -68,7 +68,11 @@ impl W { self.f(c + 10, p.y); } fn h(&mut self) -> String { - let h = format!("{:X}", self.next); + format!("{:X}", self.next_handle()) + } + /// A new handle for a record the drawing doesn't hold (as [`W::h`]). + fn next_handle(&mut self) -> u64 { + let h = self.next; self.next = self.next.saturating_add(1); h } diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index f1e0a1d73..51b6b4388 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -32,6 +32,64 @@ pub(super) fn hatch_reactors(d: &Drawing) -> HashMap> { out } +/// A polyface mesh as one POLYLINE record: the vertices (flags 64 | 128), then one face record +/// (128) per face that names them (the others draw nothing and are dropped, as on read). Counts +/// and indices are 16-bit groups (71–74), and no index is above the vertex count: a mesh too large +/// for them is written as its 3D faces rather than with numbers cut short. +fn polyface(w: &mut W, d: &Drawing, e: &Entity, m: &cadcraft_doc::PolyfaceMesh, owner: &str, paper: bool, cx: &Ctx) { + let faces: Vec<&[i32; 4]> = m.faces.iter().filter(|f| m.face3d(f).is_some()).collect(); + let max = usize::try_from(i16::MAX).unwrap_or(usize::MAX); + if m.vertices.len() > max || faces.len() > max { + for (i, f) in m.faces3d().into_iter().enumerate() { + let handle = if i == 0 { e.handle } else { Handle(w.next_handle()) }; + let face = Entity { handle, common: e.common.clone(), kind: EntityKind::Face3d(f) }; + entity(w, d, &face, owner, paper, cx); + } + return; + } + w.s(0, "POLYLINE"); + common(w, e, owner, paper, "AcDbPolyFaceMesh"); + w.i(66, 1); + w.p(10, Vec3::ZERO); + w.i(70, 64); + w.i(71, m.vertices.len() as i64); + w.i(72, faces.len() as i64); + for q in &m.vertices { + let vh = w.h(); + w.s(0, "VERTEX"); + w.s(5, vh); + w.s(330, e.handle.hex()); + w.s(100, "AcDbEntity"); + w.s(8, &e.common.layer); + w.s(100, "AcDbVertex"); + w.s(100, "AcDbPolyFaceMeshVertex"); + w.p(10, *q); + w.i(70, 192); + } + for f in faces { + let vh = w.h(); + w.s(0, "VERTEX"); + w.s(5, vh); + w.s(330, e.handle.hex()); + w.s(100, "AcDbEntity"); + w.s(8, &e.common.layer); + w.s(100, "AcDbFaceRecord"); + w.p(10, Vec3::ZERO); + w.i(70, 128); + for (code, ix) in [71, 72, 73, 74].into_iter().zip(f) { + if *ix != 0 { + w.i(code, i64::from(*ix)); + } + } + } + let sh = w.h(); + w.s(0, "SEQEND"); + w.s(5, sh); + w.s(330, e.handle.hex()); + w.s(100, "AcDbEntity"); + w.s(8, &e.common.layer); +} + pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { write_basic_entity(w, d, e, owner, paper, cx); write_text_entity(w, d, e, owner, paper, cx); @@ -45,7 +103,7 @@ pub(super) fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: boo write_other_entity(w, d, e, owner, paper, cx); } -fn write_basic_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { +fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) { match &e.kind { EntityKind::Line(l) => { w.s(0, "LINE"); @@ -144,6 +202,7 @@ fn write_basic_entity(w: &mut W, _d: &Drawing, e: &Entity, owner: &str, paper: b w.s(100, "AcDbEntity"); w.s(8, &e.common.layer); } + EntityKind::PolyfaceMesh(m) => polyface(w, d, e, m, owner, paper, cx), EntityKind::Spline(s) => { w.s(0, "SPLINE"); common(w, e, owner, paper, "AcDbSpline"); diff --git a/crates/io/tests/it/entity_props_roundtrip.rs b/crates/io/tests/it/entity_props_roundtrip.rs index 38d325604..a5467d7cc 100644 --- a/crates/io/tests/it/entity_props_roundtrip.rs +++ b/crates/io/tests/it/entity_props_roundtrip.rs @@ -257,8 +257,16 @@ fn faces(d: &Drawing) -> Vec { .collect() } +/// The faces of the one polyface mesh in `d`, as 3D faces. +fn polyface_faces(d: &Drawing) -> Vec { + match d.model.iter().map(|e| &e.kind).collect::>().as_slice() { + [EntityKind::PolyfaceMesh(m)] => m.faces3d(), + ks => panic!("expected one polyface mesh, got {ks:?}"), + } +} + #[test] -fn polyface_and_polygon_mesh_polylines_become_faces_not_bogus_vertices() { +fn polyface_and_polygon_mesh_polylines_read_as_meshes_and_faces_not_bogus_vertices() { let p = |x: f64, y: f64, z: f64| Vec3::new(x, y, z); // Polyface: four vertices, a quad, a triangle whose third edge is hidden, and faces with an // out-of-range index or only two vertices (skipped). @@ -274,14 +282,14 @@ fn polyface_and_polygon_mesh_polylines_become_faces_not_bogus_vertices() { recs.push(vec![(0, "SEQEND"), (8, "0")]); let refs: Vec<&[(i32, &str)]> = recs.iter().map(Vec::as_slice).collect(); let d = read_dxf(dxf(&refs).as_bytes()).expect("read polyface"); - let fs = faces(&d); + let fs = polyface_faces(&d); assert_eq!(fs.len(), 2, "{fs:?}"); assert_eq!(fs[0].corners, [p(0.0, 0.0, 2.0), p(1.0, 0.0, 2.0), p(1.0, 1.0, 2.0), p(0.0, 1.0, 2.0)]); assert_eq!(fs[0].hidden_edges, 0); assert_eq!(fs[1].corners, [p(0.0, 0.0, 2.0), p(1.0, 1.0, 2.0), p(0.0, 1.0, 2.0), p(0.0, 1.0, 2.0)]); assert_eq!(fs[1].hidden_edges, 4 | 8, "the triangle's closing edge is hidden"); - // The faces survive a save and reopen as 3DFACEs. - assert_eq!(faces(&roundtrip(&d)), fs); + // The mesh survives a save and reopen. + assert_eq!(polyface_faces(&roundtrip(&d)), fs); // 3×2 polygon mesh: two quads. let mut recs: Vec> = diff --git a/crates/io/tests/it/low_handseed.rs b/crates/io/tests/it/low_handseed.rs index fbc1a77b6..26273f778 100644 --- a/crates/io/tests/it/low_handseed.rs +++ b/crates/io/tests/it/low_handseed.rs @@ -1,32 +1,32 @@ //! Another program's file can name a $HANDSEED below handles it uses. Entities CADCraft makes -//! while reading (the faces a polyface mesh becomes) must not take handles that records further +//! while reading (the faces a polygon mesh becomes) must not take handles that records further //! on still have: a DWG keeps one object per handle, so the duplicates were lost on save. use std::collections::HashSet; use cadcraft_doc::{Drawing, EntityKind, Handle}; -/// A block holding a polyface mesh of three triangles (handle 2000) and, in model space after it, +/// A block holding a 2×4 polygon mesh, three quads (handle 2000) and, in model space after it, /// lines with handles 2001–2003 (the next ones after the mesh's), under a $HANDSEED of 10. The /// collision is across separately read lists (a block and model space), as in the files it came /// from: within one list duplicates were already renumbered. fn dxf() -> String { - let vertex = |h: &str, x: f64, y: f64| format!("0\nVERTEX\n5\n{h}\n8\n0\n10\n{x}\n20\n{y}\n30\n0.0\n70\n192\n"); - let face = |h: &str, a: i32, b: i32, c: i32| format!("0\nVERTEX\n5\n{h}\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n70\n128\n71\n{a}\n72\n{b}\n73\n{c}\n"); + let vertex = |h: &str, x: f64, y: f64| format!("0\nVERTEX\n5\n{h}\n8\n0\n10\n{x}\n20\n{y}\n30\n0.0\n70\n64\n"); let line = |h: &str| format!("0\nLINE\n5\n{h}\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n1.0\n21\n1.0\n31\n0.0\n"); format!( "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n10\n0\nENDSEC\n\ 0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n5\n30\n8\n0\n2\nMESH\n70\n0\n10\n0.0\n20\n0.0\n30\n0.0\n\ - 0\nPOLYLINE\n5\n2000\n8\n0\n66\n1\n10\n0.0\n20\n0.0\n30\n0.0\n70\n64\n71\n4\n72\n3\n\ - {}{}{}{}{}{}{}0\nSEQEND\n5\n2010\n8\n0\n0\nENDBLK\n5\n31\n8\n0\n0\nENDSEC\n\ + 0\nPOLYLINE\n5\n2000\n8\n0\n66\n1\n10\n0.0\n20\n0.0\n30\n0.0\n70\n16\n71\n2\n72\n4\n\ + {}{}{}{}{}{}{}{}0\nSEQEND\n5\n2010\n8\n0\n0\nENDBLK\n5\n31\n8\n0\n0\nENDSEC\n\ 0\nSECTION\n2\nENTITIES\n{}{}{}0\nINSERT\n5\n60\n8\n0\n2\nMESH\n10\n0.0\n20\n0.0\n30\n0.0\n0\nENDSEC\n0\nEOF\n", vertex("2004", 0.0, 0.0), - vertex("2005", 1.0, 0.0), - vertex("2006", 1.0, 1.0), - vertex("2007", 0.0, 1.0), - face("2008", 1, 2, 3), - face("2009", 1, 3, 4), - face("200A", 2, 3, 4), + vertex("2005", 0.0, 1.0), + vertex("2006", 0.0, 2.0), + vertex("2007", 0.0, 3.0), + vertex("2008", 1.0, 0.0), + vertex("2009", 1.0, 1.0), + vertex("200A", 1.0, 2.0), + vertex("200B", 1.0, 3.0), line("2001"), line("2002"), line("2003"), diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 8442a7629..79c4e4b3e 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -54,6 +54,7 @@ mod pdf_read; mod plot_layout_scale; mod plot_model_png_scale; mod plot_styles; +mod polyface_roundtrip; mod portable_fonts; mod region_roundtrip; mod roundtrip; diff --git a/crates/io/tests/it/polyface_roundtrip.rs b/crates/io/tests/it/polyface_roundtrip.rs new file mode 100644 index 000000000..0ad05518d --- /dev/null +++ b/crates/io/tests/it/polyface_roundtrip.rs @@ -0,0 +1,121 @@ +//! A polyface mesh stays one object through DXF and DWG, instead of becoming loose 3D faces; +//! its hidden edges stay hidden. + +use cadcraft_doc::{Drawing, EntityKind, PolyfaceMesh, Prim}; +use cadcraft_geom::Vec3; +use cadcraft_io::{read_dxf, write_dxf}; + +/// A 10 × 10 square as two triangles; the diagonal (from vertex 3) is hidden in both. +const POLYFACE_DXF: &str = "0\nSECTION\n2\nENTITIES\n\ +0\nPOLYLINE\n5\n30\n100\nAcDbEntity\n8\n0\n100\nAcDbPolyFaceMesh\n66\n1\n10\n0\n20\n0\n30\n0\n70\n64\n71\n4\n72\n2\n\ +0\nVERTEX\n5\n31\n8\n0\n10\n0\n20\n0\n30\n0\n70\n192\n\ +0\nVERTEX\n5\n32\n8\n0\n10\n10\n20\n0\n30\n0\n70\n192\n\ +0\nVERTEX\n5\n33\n8\n0\n10\n10\n20\n10\n30\n2\n70\n192\n\ +0\nVERTEX\n5\n34\n8\n0\n10\n0\n20\n10\n30\n2\n70\n192\n\ +0\nVERTEX\n5\n35\n8\n0\n10\n0\n20\n0\n30\n0\n70\n128\n71\n1\n72\n2\n73\n-3\n\ +0\nVERTEX\n5\n36\n8\n0\n10\n0\n20\n0\n30\n0\n70\n128\n71\n3\n72\n4\n73\n-1\n\ +0\nSEQEND\n5\n37\n8\n0\n0\nENDSEC\n0\nEOF\n"; + +fn mesh(d: &Drawing) -> PolyfaceMesh { + let meshes: Vec<&PolyfaceMesh> = d + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::PolyfaceMesh(m) => Some(m), + _ => None, + }) + .collect(); + assert_eq!(meshes.len(), 1, "one polyface mesh"); + assert!(d.model.iter().all(|e| !matches!(e.kind, EntityKind::Face3d(_))), "no loose 3D faces"); + meshes[0].clone() +} + +fn expected() -> PolyfaceMesh { + PolyfaceMesh { + vertices: vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0), Vec3::new(10.0, 10.0, 2.0), Vec3::new(0.0, 10.0, 2.0)], + faces: vec![[1, 2, -3, 0], [3, 4, -1, 0]], + } +} + +#[test] +fn polyface_mesh_is_read_as_one_object_with_its_hidden_edges() { + let m = mesh(&read_dxf(POLYFACE_DXF.as_bytes()).unwrap()); + assert_eq!(m, expected()); + assert_eq!(m.faces3d().len(), 2); + // The square's four sides; the hidden diagonal isn't drawn. + let edges = EntityKind::PolyfaceMesh(m).prims().into_iter().filter(|p| matches!(p, Prim::Seg(_))).count(); + assert_eq!(edges, 4); +} + +#[test] +fn polyface_mesh_round_trips_through_dxf_and_dwg() { + let d = read_dxf(POLYFACE_DXF.as_bytes()).unwrap(); + let text = write_dxf(&d); + assert!(text.contains("AcDbPolyFaceMesh") && text.contains("AcDbFaceRecord")); + assert_eq!(mesh(&read_dxf(text.as_bytes()).unwrap()), expected()); + #[cfg(not(target_arch = "wasm32"))] + { + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + assert_eq!(mesh(&cadcraft_io::read(&dwg, "x.dwg").unwrap()), expected()); + } +} + +#[test] +fn a_polyface_mesh_too_large_for_its_record_is_saved_as_3d_faces() { + use cadcraft_doc::{Common, Space}; + use cadcraft_io::{SaveOptions, read, write_with}; + // 40,000 vertices: counts and indices past 32,767 don't fit the 16-bit groups 71–74. + let vertices: Vec = (0..40_000).map(|i| Vec3::new(f64::from(i), 0.0, f64::from(i % 7))).collect(); + let mesh = PolyfaceMesh { vertices, faces: vec![[1, 2, 39_999, 0], [39_998, -39_999, 40_000, 3]] }; + let mut d = Drawing::new_metric(); + let common = Common { layer: "0".into(), ..Common::default() }; + d.add(&Space::Model, common, EntityKind::PolyfaceMesh(mesh.clone())).unwrap(); + let want = mesh.faces3d(); + for binary in [false, true] { + let bytes = write_with(&d, "big.dxf", &SaveOptions { version: None, binary }).unwrap(); + let back = read(&bytes, "big.dxf").unwrap(); + let faces: Vec<_> = back + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Face3d(f) => Some(f.clone()), + _ => None, + }) + .collect(); + // Every face keeps its corners and hidden edges: no index was cut to 32,767. + assert_eq!(faces, want, "binary: {binary}"); + assert!(back.model.iter().all(|e| !matches!(e.kind, EntityKind::PolyfaceMesh(_))), "binary: {binary}"); + let mut handles: Vec<_> = back.model.iter().map(|e| e.handle).collect(); + handles.sort(); + handles.dedup(); + assert_eq!(handles.len(), back.model.iter().count(), "each face has its own handle"); + } +} + +#[test] +fn faces_naming_missing_vertices_are_dropped_on_read() { + // Added faces: one names vertex 9 of a 4-vertex mesh, one has only two corners, one has two + // before its first 0 (which ends the face). + let text = POLYFACE_DXF.replace( + "0\nSEQEND\n", + "0\nVERTEX\n5\n38\n8\n0\n10\n0\n20\n0\n30\n0\n70\n128\n71\n1\n72\n2\n73\n9\n\ +0\nVERTEX\n5\n39\n8\n0\n10\n0\n20\n0\n30\n0\n70\n128\n71\n1\n72\n2\n\ +0\nVERTEX\n5\n3A\n8\n0\n10\n0\n20\n0\n30\n0\n70\n128\n71\n1\n72\n2\n74\n3\n0\nSEQEND\n", + ); + let d = read_dxf(text.as_bytes()).unwrap(); + assert_eq!(mesh(&d), expected(), "only the faces that name its vertices"); + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(mesh(&back), expected()); +} + +#[test] +fn faces_naming_missing_vertices_are_not_written() { + use cadcraft_doc::{Common, Space}; + let mut m = expected(); + m.faces.push([1, 2, 9, 0]); + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common { layer: "0".into(), ..Common::default() }, EntityKind::PolyfaceMesh(m)).unwrap(); + let text = write_dxf(&d); + assert_eq!(text.matches("AcDbFaceRecord").count(), 2, "only the faces that name its vertices"); + assert_eq!(mesh(&read_dxf(text.as_bytes()).unwrap()), expected()); +} From 72e82c59d020670006f6a2df26df00ddc1bc4938 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:17:36 -0600 Subject: [PATCH 360/900] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/file-format-parity.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 894a70858..d85415123 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LAYOUT SAveas writes a layout as a DWT template) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** minor (R2000 DXF CLASS records without instance counts, so AutoCAD LT 2026 opens them) · **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,13 +31,11 @@ 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.6 crate and reading that DXF; it saves by writing its own R2000 DXF and +with the `acadrust` 0.6.3 crate 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 -title/header suppression. Since 0.6.5 it keeps the byte AutoCAD's DWG scale action (BLOCKSCALEACTION) -ends with, which DXF doesn't carry; before, AutoCAD refused every DWG CADCraft wrote with a dynamic -block that scales ("Error Decrypting Data"). +title/header suppression. | DWG version | Code | AutoCAD 2027 | CADCraft read | CADCraft write | Tested how | |---|---|---|---|---|---| @@ -66,9 +64,9 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | R12 (AC1009), ASCII | read, write | yes: no version gating; old-style POLYLINE/VERTEX read (polyface meshes flattened to 3D polylines) | **no** | | R12 binary | read, write | **no** (binary parser expects R13+ 2-byte group codes) | no | -| R13–R2018, ASCII | read, write each of 2000/2004/2007/2010/2013/2018 | yes, one reader for all versions | yes, each of 2000–2018 (#421): R2000 structure (later versions add only optional groups) with that `$ACADVER`; UTF-8 text from 2007; no CLASS instance counts (91) | +| R13–R2018, ASCII | read, write each of 2000/2004/2007/2010/2013/2018 | yes, one reader for all versions | yes, each of 2000–2018 (#421): R2000 structure with that `$ACADVER`; UTF-8 text from 2007; CLASS instance counts (91) from 2004 only (#635; with them, AutoCAD LT 2026 stops responding on an R2000 file) | | R13–R2018, binary | read, write | yes | yes, each of 2000–2018 (SAVEAS `binary`; a binary file stays binary on QSAVE) | -| Code pages (`$DWGCODEPAGE`, ANSI_932/936/949/950/125x) | yes | yes (#505): ASCII and binary DXF before 2007 decode from their code page (ANSI_874/932/936/949/950/1250–1258, DOS437/850/852/866, ISO 8859, Macintosh); a file that is valid UTF-8 reads as UTF-8; Johab and other DOS code pages read as ANSI_1252 (`dxf/src/codepage.rs`) | writes `\U+` escapes (#169), which is correct; declares `ANSI_1252` | +| Code pages (`$DWGCODEPAGE`, ANSI_932/936/949/950/125x) | yes | yes (#505): ASCII and binary DXF before 2007 decode from their code page (ANSI_874/932/936/949/950/1250–1258, DOS437/850/852/866, ISO 8859, Macintosh); a file that is valid UTF-8 reads as UTF-8; Johab and other DOS code pages read as ANSI_1252 (`dxf/src/codepage.rs`) | before 2007 writes text in the declared code page (the one read from the file, else `ANSI_1252`), characters outside it as `\U+` escapes; an unknown code page, or ASCII DXF whose code page bytes would also read as UTF-8, gives pure ASCII with escapes (#169); a double-byte character whose trail byte is `\` (Shift-JIS, Big5, GBK) is escaped where `U+` or `M+` follows it | | `\U+`/`\M+` escapes | yes | yes (`\M+` since #505; Johab `\M+4` stays literal) | `\U+` yes | ### DXF content: read and write by object type @@ -77,7 +75,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG |---|---|---|---| | LINE, POINT, CIRCLE, ARC, ELLIPSE, LWPOLYLINE (widths, bulges, elevation), SPLINE, RAY, XLINE | yes | yes | round-trip tests | | POLYLINE 2D/3D | yes | yes (as LWPOLYLINE / 3D POLYLINE) | polyface and polygon meshes flattened: lossy | -| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line) | ATTDEF prompt kept (#137) | +| TEXT, MTEXT, ATTDEF, INSERT + ATTRIB | yes; multiline attributes (embedded MTEXT) read and drawn | yes; multiline attributes written as embedded MTEXT (DXF 2007 and later; older versions: one line); 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) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written; angular block text honors DIMDSEP, including per-dimension overrides (#1646) | | DIMENSION (all 7 kinds) | yes | yes, with anonymous `*D` blocks; their text keeps the diameter sign as `%%c`, so SHX styles plot it (#1645) | a reopened dimension's `*D` block is regenerated under its name, unreferenced ones dropped (#495); DIMASSOC objects written | @@ -89,7 +87,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | ACAD_TABLE | yes | 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) | | +| WIPEOUT | yes | yes (#147, fixes #79) | Implicit or explicit closure in memory; explicit closing point on save. Same logical grips and edit results before/after DXF/DWG round trips (#2256). | | 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); a proxy entity's class number (group 91) is renumbered to its class's place in the written CLASSES (#1812); **dropped by DWG save** (acadrust) | only their layer follows edits | @@ -142,11 +140,13 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 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 | acadrust 0.6.6: a DWG with more than one layout gets unique `*Paper_SpaceN` names, so ACadSharp opens it (hakanaktt/acadrust#143); a dynamic block scale action keeps the DWG-only byte after its connections, so AutoCAD opens CADCraft's DWG of a drawing with one and its references still scale; dimension text-position flags now mapped by acadrust itself | | 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 | +| 2026-10-19 | minor | Pre-2007 DXF saves write text in the file's code page (`Ação` as ANSI_1252 bytes, not `A\U+00E7\U+00E3o`); characters outside it stay `\U+` escapes | | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | | 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) | 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 361/900] 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 362/900] 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 577aa81e8b0a655857aefdecc33cbcf0878de125 Mon Sep 17 00:00:00 2001 From: mo <131036780+mbolling@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:40:29 -0500 Subject: [PATCH 363/900] Leave docs/gaps.md and docs/localization-parity.md to the maintainers AGENTS.md asks PRs not to edit the parity and gaps documents: the affected rows are named in the PR description, and the maintainers update them in batches. The two files are back to main's version. Co-Authored-By: Claude Opus 5.5 --- docs/gaps.md | 3 +-- docs/localization-parity.md | 4 ---- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index ab68ccf69..f8ddac941 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -126,7 +126,7 @@ Detail: [localization-parity.md](localization-parity.md). | # | 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). Fonts outside /usr/share/fonts (NixOS, Guix, Flatpak) are found since 2026-10-20 (#674) | 6–10 | +| 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 | ## Ecosystem and automation @@ -157,7 +157,6 @@ Detail: [localization-parity.md](localization-parity.md). | 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 | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-20 | minor | Installed fonts are found where fontconfig looks (XDG font directories, fontconfig `

` entries, Flatpak host mounts), so NixOS, Guix and Flatpak get the CJK fallback and a system UI font (#674): P2 narrowed, hours unchanged | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 26f916ad0..c6f43ee4a 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -37,9 +37,6 @@ shaping and right-to-left text through TrueType, vertical SHX text styles. 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. - Installed fonts are found where fontconfig looks (the XDG font directories, the `` - entries of fontconfig's configuration, Flatpak's host font mounts), so NixOS, Guix and Flatpak - get the fallbacks too (#674); fontconfig's aliases and matching rules are not read. - **Text input:** egui/winit IME. The command line — which collects single-line TEXT edits and other prompt text — now enables the operating system IME while a prompt asks for text and shows composition (pre-edit) text until it is committed, so Chinese, Japanese and Korean input works @@ -95,7 +92,6 @@ each language, which needs humans. Translations parallelise fully once the catal |---|---|---| | 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-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-20 | minor | Installed fonts are found where fontconfig looks (XDG font directories, fontconfig `` entries, Flatpak host mounts): the CJK and Arabic fallbacks and the system UI font work on NixOS, Guix and Flatpak (#674) | | 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 | | 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 | From 0cbe1b7e503a74b7e1ee2cff69377583b676cfae Mon Sep 17 00:00:00 2001 From: mo <131036780+mbolling@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:42:44 -0500 Subject: [PATCH 364/900] Gate the fonts crate's HashSet import to the targets that walk font directories Only walk_font_dirs uses it, and that function is not built on wasm32, where the import was an unused-import warning. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/ttf.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 93659b715..9375ad64f 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -13,7 +13,9 @@ //! //! Both start empty; the host sets its starting values ([`set_font_alt`], [`set_fallback_fonts`]). -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; +#[cfg(not(target_arch = "wasm32"))] +use std::collections::HashSet; use std::path::PathBuf; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock}; 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 365/900] 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 366/900] 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 367/900] 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 368/900] 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 369/900] 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 b006110dc591c268ac558dc25c32705262d01503 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:31:14 +0700 Subject: [PATCH 370/900] OOPS: bring back what -WBLOCK erased; keep the last erase through REFEDIT; the Block Editor (#2625) * OOPS brings back what -WBLOCK erased -WBLOCK erases the objects it writes, and OOPS brings back what the last ERASE or BLOCK removed; the two landed separately, so OOPS never saw what -WBLOCK erased. -WBLOCK now erases through erase_kept, as ERASE and BLOCK do. As AutoCAD 2024 does (accoreconsole, the drawing's entnext order read back): OOPS after -WBLOCK brings its objects back, each where it was and with its handle; only the last erase counts, -WBLOCK's or ERASE's; and -WBLOCK * erases nothing, so OOPS still brings back the erase before it. Co-Authored-By: Claude Opus 5.5 * OOPS: keep the last erase through a refused REFEDIT command; Block Editor During REFEDIT, a command that removes an object outside the working set is undone (refedit::after_command), but erase_kept had already replaced what OOPS kept: the objects came back, and the erase before them was lost. erase_kept now leaves OOPS as it was when an object it removes is outside the working set. That covers BLOCK, -WBLOCK, ERASE and the Delete key. In the Block Editor, its objects keep the handles they have in the block definition, so in_blocks found them there and OOPS brought back nothing erased in the editor. in_blocks now skips the block open there. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/wblock.rs | 8 ++-- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/oops.rs | 22 +++++++--- crates/engine/tests/dash_wblock.rs | 59 ++++++++++++++++++++++++++ crates/engine/tests/it/oops_command.rs | 28 ++++++++++++ 5 files changed, 107 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 03356269e..98ab0c344 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -7,6 +7,7 @@ use serde_json::{Value, json}; use super::super::curves::KW; use super::super::machines::{SelOutcome, SelectPhase}; +use super::super::modify::erase_kept; use super::super::{CommandSpec, bad, point_param, str_param, targets}; use super::insert_file::stem; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; @@ -16,7 +17,7 @@ pub(super) fn wblock_spec() -> CommandSpec { } /// -WBLOCK erases the objects it writes, whatever its mOde option says: AutoCAD 2024 does, and -/// keeps "Object conversion=Delete" as the setting. +/// keeps "Object conversion=Delete" as the setting. OOPS brings them back, as after ERASE. pub(super) fn dash_wblock_spec() -> CommandSpec { CommandSpec::new("-wblock", "Write Block", run_dash_wblock) .params("{path, name? | handles?, base?} (the objects written are erased)") @@ -124,10 +125,7 @@ fn moved(e: &Entity, m: &Mat3) -> Entity { } fn erase(s: &mut Session, hs: &[Handle]) -> Result<()> { - let doc = s.doc_mut()?; - for h in hs { - doc.remove_entity(*h); - } + erase_kept(s, hs)?; s.set_selection(Vec::new()); Ok(()) } diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 828ce1c01..f68d08ebb 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -46,7 +46,7 @@ pub fn specs() -> Vec { .alias(&["e", "delete"]) .params("{handles?: [hex]} (default: selection)") .interactive(|_| Ok(Box::new(SelectThen::new(Op::Erase)))), - CommandSpec::new("oops", "Oops", run_oops).params("{} (brings back what the last ERASE or BLOCK removed)"), + CommandSpec::new("oops", "Oops", run_oops).params("{} (brings back what the last ERASE, BLOCK or -WBLOCK removed)"), CommandSpec::new("move", "Move", run_move) .menu(&["Modify", "Move"]) .alias(&["m"]) diff --git a/crates/engine/src/cmd/modify/oops.rs b/crates/engine/src/cmd/modify/oops.rs index 217f57ae6..6308cc615 100644 --- a/crates/engine/src/cmd/modify/oops.rs +++ b/crates/engine/src/cmd/modify/oops.rs @@ -1,6 +1,7 @@ //! OOPS: bring back the objects the last ERASE (or the Delete key) removed, or BLOCK deleting the -//! objects it makes a block of, with their handles and each where it was in the draw order, as -//! AutoCAD 2024 does (accoreconsole, the drawing's `entnext` order read back afterwards). +//! objects it makes a block of, or -WBLOCK the objects it writes, with their handles and each where +//! it was in the draw order, as AutoCAD 2024 does (accoreconsole, the drawing's `entnext` order read +//! back afterwards). use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -50,7 +51,10 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result { } } let n = taken.len(); - if n > 0 { + // During REFEDIT, removing an object outside the working set gets the command undone + // (`refedit::after_command`), so what OOPS had stays. + let refused = taken.iter().any(|t| crate::cmd::blocks::refedit::locked(d, t.entity.handle)); + if n > 0 && !refused { s.state_mut()?.erased = Erased(taken); } Ok(n) @@ -58,9 +62,10 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result { pub(super) fn run_oops(s: &mut Session, _p: &Value) -> Result { let taken = s.state()?.erased.0.clone(); + let editing = s.state()?.block_edit.as_ref().map(|b| b.name.clone()); let back: Vec = { let d = s.doc()?; - let in_blocks = in_blocks(d, &taken); + let in_blocks = in_blocks(d, &taken, editing.as_deref()); taken.iter().map(|t| !in_blocks.contains(&t.entity.handle) && can_return(d, t)).collect() }; // Nothing to bring back leaves the drawing as it is: no undo step. @@ -72,11 +77,16 @@ pub(super) fn run_oops(s: &mut Session, _p: &Value) -> Result { } /// The handles of `taken` that a block's object has now (an undo can take the drawing back to -/// before an erased object was made, and a block's new object take its handle). -fn in_blocks(d: &Drawing, taken: &[Taken]) -> HashSet { +/// before an erased object was made, and a block's new object take its handle). The block open +/// in the Block Editor (`editing`) doesn't count: its objects there keep the handles they have in +/// it. +fn in_blocks(d: &Drawing, taken: &[Taken], editing: Option<&str>) -> HashSet { let hs: HashSet = taken.iter().map(|t| t.entity.handle).collect(); let mut out = HashSet::new(); for b in d.blocks.values() { + if editing.is_some_and(|n| b.name.eq_ignore_ascii_case(n)) { + continue; + } // Through whichever is smaller. if b.entities.len() < hs.len() { out.extend(b.entities.iter().map(|e| e.handle).filter(|h| hs.contains(h))); diff --git a/crates/engine/tests/dash_wblock.rs b/crates/engine/tests/dash_wblock.rs index 348cde45a..52d456f42 100644 --- a/crates/engine/tests/dash_wblock.rs +++ b/crates/engine/tests/dash_wblock.rs @@ -242,3 +242,62 @@ fn the_json_form_of_dash_wblock_erases_what_it_writes() { assert!(s.execute("-wblock", &json!({ "path": none })).is_err()); assert!(!std::path::Path::new(&none).exists()); } + +#[test] +fn oops_brings_back_what_it_erased_where_it_was() { + // OOPSW-001 to OOPSW-005 (the drawing's `entnext` order read back): OOPS brings back what + // -WBLOCK erased, each where it was, as after ERASE. Only the last erase counts, and "*" (the + // whole drawing) erases nothing. + const OOPS: &str = "(command \"_.OOPS\")"; + // (script with @A to @D for the objects and @F for a new file, the order afterwards) + let cases: [(&[&str], &str); 5] = [ + (&["(command \"_.-WBLOCK\" @F \"\" '(0.0 0.0) @B @C \"\")", OOPS], "A B C D"), + (&["(command \"_.-WBLOCK\" @F \"\" '(0.0 0.0) @B \"\")", "(command \"_.ERASE\" @D \"\")", OOPS], "A C D"), + (&["(command \"_.ERASE\" @D \"\")", "(command \"_.-WBLOCK\" @F \"\" '(0.0 0.0) @B \"\")", OOPS], "A B C"), + (&["(command \"_.ERASE\" @D \"\")", "(command \"_.-WBLOCK\" @F \"*\")", OOPS], "A B C D"), + (&["(command \"_.-WBLOCK\" @F \"\" \"_O\" \"_R\" '(0.0 0.0) @A @C \"\")", OOPS], "A B C D"), + ]; + let dir = TempDir::new("dash-wblock"); + for (i, (script, want)) in cases.into_iter().enumerate() { + let (mut s, a, b, c) = drawing(); + let v = s.execute("line", &json!({ "points": [[0, 40], [10, 40]] })).unwrap(); + let d = Handle::parse_hex(v["handles"][0].as_str().or(v["handle"].as_str()).unwrap()).unwrap(); + let hs = [a, b, c, d]; + for line in script { + let mut line = line.to_string(); + for (n, h) in ["@A", "@B", "@C", "@D"].into_iter().zip(hs) { + line = line.replace(n, &ent(h)); + } + let line = line.replace("@F", &format!("\"{}\"", file(&dir, &format!("OOPSW{i}.dwg")))); + lisp(&mut s, &line); + assert!(s.running.is_none(), "{line}: {}", s.prompt_text()); + } + let order: Vec<&str> = + s.doc().unwrap().model.iter().map(|e| hs.iter().position(|h| *h == e.handle).map_or("E", |k| ["A", "B", "C", "D"][k])).collect(); + assert_eq!(order.join(" "), want, "{script:?}"); + } + // The JSON form too. + let (mut s, a, b, c) = drawing(); + s.execute("-wblock", &json!({ "path": file(&dir, "json.dwg"), "handles": [b.hex()] })).unwrap(); + assert!(!alive(&s, b)); + s.execute("oops", &json!({})).unwrap(); + let order: Vec = s.doc().unwrap().model.iter().map(|e| e.handle).collect(); + assert_eq!(order, [a, b, c]); +} + +#[test] +fn a_dash_wblock_refused_during_refedit_leaves_oops_as_it_was() { + let (mut s, a, b, c) = drawing(); + let dir = TempDir::new("dash-wblock"); + s.execute("block", &json!({ "name": "BK", "base": [0, 0], "handles": [a.hex()], "keep": "convert" })).unwrap(); + let ins = Handle::parse_hex(s.execute("entities", &json!({ "type": "INSERT" })).unwrap()["entities"][0]["handle"].as_str().unwrap()).unwrap(); + s.execute("erase", &json!({ "handles": [c.hex()] })).unwrap(); + s.execute("refedit", &json!({ "handle": ins.hex() })).unwrap(); + // B isn't in the working set: -WBLOCK is refused and the drawing put back. + assert!(s.execute("-wblock", &json!({ "path": file(&dir, "out.dwg"), "handles": [b.hex()] })).is_err()); + assert!(alive(&s, b)); + s.execute("refclose", &json!({ "save": false })).unwrap(); + // OOPS still has C, the last erase that stood. + s.execute("oops", &json!({})).unwrap(); + assert!(alive(&s, c)); +} diff --git a/crates/engine/tests/it/oops_command.rs b/crates/engine/tests/it/oops_command.rs index 465484e0f..f42564c6f 100644 --- a/crates/engine/tests/it/oops_command.rs +++ b/crates/engine/tests/it/oops_command.rs @@ -230,3 +230,31 @@ fn a_reference_edited_in_place_keeps_its_objects_and_the_drawings_apart() { assert_eq!(oops(&mut s), json!({ "restored": 1 })); assert_eq!(order(&s, &hs), "C E"); } + +#[test] +fn a_block_refused_during_refedit_leaves_oops_as_it_was() { + let (mut s, hs) = drawing(); + s.execute("block", &json!({ "name": "BK", "base": [0, 0], "handles": [hs[0].hex()], "keep": "convert" })).unwrap(); + let ins = *handles(&s).last().unwrap(); + s.execute("erase", &json!({ "handles": [hs[3].hex()] })).unwrap(); + s.execute("refedit", &json!({ "handle": ins.hex() })).unwrap(); + // B isn't in the working set: the block is refused and the drawing put back. + let r = s.execute("block", &json!({ "name": "BK2", "base": [0, 0], "handles": [hs[1].hex()], "keep": "delete" })); + assert!(r.is_err(), "{r:?}"); + s.execute("refclose", &json!({ "save": false })).unwrap(); + // OOPS still has D, the last erase that stood. + assert_eq!(oops(&mut s), json!({ "restored": 1 })); + assert!(s.doc().unwrap().entity(hs[3]).is_some()); +} + +#[test] +fn an_erase_in_the_block_editor_comes_back_there() { + let (mut s, hs) = drawing(); + s.execute("block", &json!({ "name": "BK", "base": [0, 0], "handles": [hs[0].hex(), hs[1].hex()], "keep": "retain" })).unwrap(); + s.execute("bedit", &json!({ "name": "BK" })).unwrap(); + let inside = handles(&s); + assert_eq!(inside.len(), 2); + s.execute("erase", &json!({ "handles": [inside[0].hex()] })).unwrap(); + assert_eq!(oops(&mut s), json!({ "restored": 1 })); + assert_eq!(handles(&s), inside); +} From fa03bf2a29b714e0832a120caa25b871e5f147d2 Mon Sep 17 00:00:00 2001 From: andrewbrake Date: Mon, 2 Nov 2026 23:31:18 +1300 Subject: [PATCH 371/900] feat(engine): INSERT of a drawing file keeps an attribute definition's field (#2619) * feat(engine): INSERT of a drawing file keeps an attribute definition's field The attribute definitions of a drawing file read by INSERT name=file lost their extension dictionary, so the ACAD_FIELD dictionary and the FIELD objects of an attribute whose value is a field (the file name in a title block) were gone from the block. adopt() now copies that object tree to the drawing under new handles, with the FIELD class and a field list if the drawing has none. Co-Authored-By: Claude Sonnet 5.5 * foreign: index the kept objects once when walking and copying a dictionary tree A file can keep many objects; a linear lookup per pointer grew with their product. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: andrewbrake <6925387+andrewbrake@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 Co-authored-by: Brandon Thomas --- crates/doc/src/foreign.rs | 88 +++++++++++++++- crates/engine/src/cmd/blocks/insert_file.rs | 17 +++- crates/engine/tests/insert_file_field.rs | 107 ++++++++++++++++++++ 3 files changed, 208 insertions(+), 4 deletions(-) create mode 100644 crates/engine/tests/insert_file_field.rs diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index e0ebb81a4..d732df261 100644 --- a/crates/doc/src/foreign.rs +++ b/crates/doc/src/foreign.rs @@ -6,7 +6,7 @@ //! named object dictionary, a table record, a block, an entity); references to objects that are //! gone are dropped. Commands don't edit it. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use crate::{Handle, RawTag}; @@ -94,3 +94,89 @@ impl Foreign { self.data_store.iter().filter(|t| t.code == 320).filter_map(|t| Handle::parse_hex(t.value.trim())).collect() } } + +impl Foreign { + /// The kept objects by handle (the first of any that share one). + fn object_index(&self) -> BTreeMap { + let mut m = BTreeMap::new(); + for o in &self.objects { + m.entry(o.handle).or_insert(o); + } + m + } + + /// The kept object `root` and the kept objects it owns, directly or not (dictionary entries + /// and child pointers, groups 350 and 360), `root` first. + pub fn tree(&self, root: Handle) -> Vec { + // Indexed once: a file can keep many objects, and a lookup per pointer would grow with + // their product. + let by_handle = self.object_index(); + let mut out = vec![root]; + let mut seen = BTreeSet::from([root]); + let mut i = 0; + while let Some(&h) = out.get(i) { + i += 1; + let Some(o) = by_handle.get(&h) else { continue }; + for c in o.tags.iter().filter(|t| matches!(t.code, 350 | 360)).filter_map(|t| Handle::parse_hex(t.value.trim())) { + if out.len() < 4096 && by_handle.contains_key(&c) && seen.insert(c) { + out.push(c); + } + } + } + out + } + + /// Copy the objects of `tree` (see [`Foreign::tree`]) of `src` into this one under the handles + /// `fresh` (the same order; two more follow for a field list), `owner` taking the place of the + /// root's owner. References to objects outside the tree become null. Fields keep a field + /// list: this one gets a copy of the source's if it has none. + pub fn adopt_tree(&mut self, src: &Foreign, tree: &[Handle], fresh: &[Handle], owner: Handle) { + if fresh.len() < tree.len() + 2 { + return; + } + let map: BTreeMap = tree.iter().copied().zip(fresh.iter().copied()).collect(); + let by_handle = src.object_index(); + let mut kinds = Vec::new(); + for (n, h) in tree.iter().enumerate() { + let Some(o) = by_handle.get(h) else { continue }; + let mut c = (*o).clone(); + let Some(&new) = fresh.get(n) else { continue }; + c.handle = new; + for t in &mut c.tags { + if t.code == 5 { + t.value = new.hex(); + } else if matches!(t.code, 320..=369 | 390..=399) { + let to = Handle::parse_hex(t.value.trim()).and_then(|h| map.get(&h).copied()).or((n == 0 && t.code == 330).then_some(owner)); + t.value = to.map_or_else(|| "0".to_string(), Handle::hex); + } + } + kinds.push(c.kind.clone()); + self.objects.push(c); + } + if let Some(list) = src.objects.iter().find(|o| o.kind == "FIELDLIST").filter(|_| !self.objects.iter().any(|o| o.kind == "FIELDLIST")) { + let (Some(&h), Some(&nod)) = (fresh.get(tree.len()), fresh.get(tree.len() + 1)) else { return }; + let mut c = list.clone(); + c.handle = h; + for t in &mut c.tags { + match t.code { + 5 => t.value = h.hex(), + 330 => t.value = "0".to_string(), + _ => {} + } + } + if let Some(t) = c.tags.iter_mut().find(|t| t.code == 330) { + t.value = nod.hex(); + } + self.targets.insert(nod, ("NOD".to_string(), String::new())); + self.dictionary.push(("ACAD_FIELDLIST".to_string(), h)); + kinds.push(c.kind.clone()); + self.objects.push(c); + } + for k in kinds { + let named = |c: &Vec| c.iter().any(|t| t.code == 1 && t.value.eq_ignore_ascii_case(&k)); + if !self.classes.iter().any(named) { + self.classes.extend(src.classes.iter().filter(|c| named(c)).cloned()); + } + } + } +} diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 1a90502b5..a00dbc64c 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -109,7 +109,7 @@ fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { nb.name = to.clone(); nb.entities = Default::default(); for e in b.entities.iter() { - let e = adopt(&mut d, e, &renames); + let e = adopt(&mut d, src, e, &renames); nb.entities.push(e); } d.blocks.insert(to.clone(), Arc::new(nb)); @@ -118,7 +118,7 @@ fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { b.base = src.header.point("INSBASE").filter(|p| p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).unwrap_or_default(); let mut ents = Vec::new(); for e in src.model.iter() { - let e = adopt(&mut d, e, &renames); + let e = adopt(&mut d, src, e, &renames); d.ensure_layer(&e.common.layer); ents.push(e); } @@ -183,9 +183,20 @@ fn block_names(d: &Drawing, src: &Drawing, defining: &str) -> BTreeMap) -> Entity { +fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &BTreeMap) -> Entity { let mut e = e.clone(); + let old = e.handle; e.handle = d.new_handle(); + // An attribute definition keeps its field: its extension dictionary and the objects in it. + if matches!(e.kind, EntityKind::AttDef(_)) + && let Some(root) = src.foreign.entities.get(&old).and_then(|x| x.xdict) + { + let tree = src.foreign.tree(root); + let fresh: Vec = (0..tree.len() + 2).map(|_| d.new_handle()).collect(); + let foreign = Arc::make_mut(&mut d.foreign); + foreign.adopt_tree(&src.foreign, &tree, &fresh, e.handle); + foreign.entities.entry(e.handle).or_default().xdict = fresh.first().copied(); + } match &mut e.kind { EntityKind::Insert(i) => { if let Some(n) = renames.get(&i.block) { diff --git a/crates/engine/tests/insert_file_field.rs b/crates/engine/tests/insert_file_field.rs new file mode 100644 index 000000000..1365f88b5 --- /dev/null +++ b/crates/engine/tests/insert_file_field.rs @@ -0,0 +1,107 @@ +//! `INSERT name=file` keeps the field of an attribute definition: the definition's extension +//! dictionary and the objects in it come along under new handles, so the attributes the block's +//! references get can carry the field when the drawing is saved. + +use std::sync::Arc; + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::foreign::{ForeignExtra, ForeignObject}; +use cadcraft_engine::doc::{Attrib, Drawing, Entity, EntityKind, Handle, RawTag, Text}; +use cadcraft_engine::geom::Vec3; +use serde_json::json; + +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +fn tag(code: i32, value: &str) -> RawTag { + RawTag { code, value: value.into() } +} + +fn object(handle: u64, kind: &str, tags: Vec) -> ForeignObject { + ForeignObject { handle: Handle(handle), kind: kind.into(), tags } +} + +/// A drawing file in a test format: model space holds a definition NUMBER (handle 0x50) whose +/// extension dictionary 0x60 owns the ACAD_FIELD dictionary 0x61, which owns the field 0x62 with +/// a child field 0x63. Handles 0x61..0x63 stand for the file's own; a second, unrelated object +/// 0x70 is not part of that tree. The bytes `plain` give the same definition without any of it. +fn read(bytes: &[u8], _name: &str) -> Result { + let mut d = Drawing::new_imperial(); + let text = Text { + insert: Vec3::ZERO, + align_pt: None, + height: 2.0, + value: "TEMPLATE".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }; + let def = Attrib { + tag: "NUMBER".into(), + text, + invisible: false, + constant: false, + prompt: String::new(), + props: Default::default(), + multiline: None, + modes: Default::default(), + }; + d.model.push(Entity::new(Handle(0x50), EntityKind::AttDef(def))); + if bytes == b"plain" { + return Ok(d); + } + let f = Arc::make_mut(&mut d.foreign); + f.entities.insert(Handle(0x50), ForeignExtra { xdict: Some(Handle(0x60)), ..Default::default() }); + f.objects.push(object(0x60, "DICTIONARY", vec![tag(5, "60"), tag(330, "50"), tag(3, "ACAD_FIELD"), tag(360, "61")])); + f.objects.push(object(0x61, "DICTIONARY", vec![tag(5, "61"), tag(330, "60"), tag(3, "TEXT"), tag(360, "62")])); + f.objects.push(object(0x62, "FIELD", vec![tag(5, "62"), tag(330, "61"), tag(1, "_text"), tag(360, "63")])); + f.objects.push(object(0x63, "FIELD", vec![tag(5, "63"), tag(330, "62"), tag(1, "AcVar")])); + f.objects.push(object(0x70, "XRECORD", vec![tag(5, "70"), tag(330, "0")])); + f.classes.push(vec![tag(1, "FIELD"), tag(2, "AcDbField")]); + Ok(d) +} + +fn hooks() { + set_io(IoHooks { read, write: |_, _| Err("no writer in this test".into()), plot: None }); +} + +#[test] +fn the_definition_of_an_inserted_file_keeps_its_field() { + hooks(); + let dir = TempDir::new("insert-file-field"); + let path = dir.file("border.dxf", ""); + let mut s = Session::new(); + s.execute("insert", &json!({ "name": "BORDER", "file": path, "at": [0, 0], "attribs": { "NUMBER": "A-1" } })).unwrap(); + let d = s.doc().unwrap(); + let def = d.block("BORDER").and_then(|b| b.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_)))).expect("the definition"); + assert_ne!(def.handle, Handle(0x50), "the definition has a handle of this drawing"); + let root = d.foreign.entities.get(&def.handle).and_then(|x| x.xdict).expect("the definition has an extension dictionary"); + let tree = d.foreign.tree(root); + assert_eq!(tree.len(), 4, "the dictionaries and both fields, not the unrelated object"); + assert!(tree.iter().all(|h| ![0x60, 0x61, 0x62, 0x63, 0x70].contains(&h.0)), "the copies have new handles"); + // The root's owner is the definition, the others point at each other. + let owner = + |h: Handle| d.foreign.objects.iter().find(|o| o.handle == h).and_then(|o| o.tags.iter().find(|t| t.code == 330)).map(|t| t.value.clone()); + assert_eq!(owner(tree[0]), Some(def.handle.hex())); + assert_eq!(owner(tree[1]), Some(tree[0].hex())); + assert_eq!(owner(tree[3]), Some(tree[2].hex())); + assert!(d.foreign.classes.iter().any(|c| c.iter().any(|t| t.code == 1 && t.value == "FIELD")), "the field class comes along"); +} + +#[test] +fn a_definition_without_a_field_gets_none() { + hooks(); + let dir = TempDir::new("insert-file-nofield"); + let path = dir.file("plain.dxf", "plain"); + let mut s = Session::new(); + s.execute("insert", &json!({ "name": "PLAIN", "file": path, "at": [0, 0] })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.block("PLAIN").is_some()); + assert!(d.foreign.is_empty(), "nothing is kept for a drawing without fields"); +} From ebc67fa81dccb0d89c157babb27e7d5c3a5c1177 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:31:22 +0700 Subject: [PATCH 372/900] Dynamic blocks: stretch the points inside the frame, as AutoCAD does (#2627) * Dynamic blocks: stretch the points inside the frame, as AutoCAD does A dynamic block made by a third-party tool came out distorted when a distance changed: its stretch action has distance multiplier 0 with angle offset 1, and stored vertex lists that don't match its objects. apply turned the 0 into 1 but kept the angle (a 57 degree slant), and moved exactly the listed points. AutoCAD 2024, on a copy of that drawing, moved the block straight along the parameter, and every point of its lines and polylines exactly when it was inside the frame, whatever the lists said. So: - a zero multiplier moves as 1, without its angle offset; - a line's or lightweight polyline's moving points are those inside the frame where the dynamic block has them; a selected one wholly outside the frame moves whole, as in AutoCAD's own stretched copies; - a frame of fewer than 2 or more than 1,000 points keeps the stored lists, so a huge frame can't make every point test every edge. Against AutoCAD's own anonymous copies in two library drawings (556 references set back to their block's distances), 249 come back exactly on main and 258 with this change; none stops matching. Co-Authored-By: Claude Opus 5.5 * Dynamic blocks: a point on a polygon frame's edge is inside it in_frame counted a point on a two-corner frame's edge as inside, but the even-odd test of a polygon frame put one on its right edge outside. A line whose end lay there, with its other end outside, then had no point inside the frame and moved whole instead of its end alone. A polygon frame now counts a point on an edge (within 1e-9, relative to the edge's length) as inside too, as the two-corner frame does. Co-Authored-By: Claude Opus 5.5 * Dynamic blocks: frame edge tolerance by the edge's length; tilted polylines keep their lists A point counted as on a polygon frame's edge within 1e-9 * (1 + the edge's length), so never less than 1e-9 drawing units: in a tiny frame, a point visibly outside was taken as inside. The tolerance is now a billionth of the edge's length. A lightweight polyline's vertices are in its own plane. The reader flips a mirrored one (extrusion along -z) into the block's plane, but leaves a tilted one's in its OCS, which the frame (block coordinates) can't be tested against. A tilted polyline keeps the stored vertex list, as before the frame test. Co-Authored-By: Claude Opus 5.5 * dynblock: only an exactly untilted polyline is tested against the frame; a tilted one keeps its stored list Co-Authored-By: Claude Opus 5.5 * fmt Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/doc/src/dynblock.rs | 4 +- crates/doc/src/dynblock/apply.rs | 38 ++++++- crates/io/tests/it/dynblock_read.rs | 154 ++++++++++++++++++++++++++++ 3 files changed, 192 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index ef0a88be2..392861388 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -194,7 +194,9 @@ pub struct Action { #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum ActionKind { - /// Moves the vertices inside `frame` of the objects listed (all of an object not listed). + /// Moves the points of its objects inside `frame`: a line's or polyline's points inside it + /// (the whole of one outside it), any other object whole. `vertices` are the point indices the + /// file lists for each object, used only when the frame can't be tested (see `apply`). Stretch { frame: Vec, #[serde(serialize_with = "hex_vertices")] diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index ed5281bf6..d5651faac 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -403,7 +403,20 @@ fn move_entity(e: &mut Entity, vertices: Option<&[i32]>, v: Vec2) { } } -/// Whether point `p` lies inside a stretch frame (two corners, or a polygon). +/// Most points of a stretch frame whose objects' points are tested against it one by one. A frame +/// is two corners or a short polygon; testing every point of every object against every edge of a +/// longer one would grow with their product, so the action's own vertex lists are used instead. +const MAX_FRAME_POINTS: usize = 1000; + +/// The indices of `points` inside stretch frame `frame`, or `None` when none is: an object the +/// action selects that lies outside its frame moves whole. +fn inside(frame: &[Vec2], points: impl Iterator) -> Option> { + let idx: Vec = points.enumerate().filter(|(_, p)| in_frame(frame, *p)).filter_map(|(i, _)| i32::try_from(i).ok()).collect(); + (!idx.is_empty()).then_some(idx) +} + +/// Whether point `p` lies inside a stretch frame (two corners, or a polygon). A point on its edge is +/// inside, for a polygon as for two corners: within a billionth of the edge's length of it. fn in_frame(frame: &[Vec2], p: Vec2) -> bool { match frame { [a, b] => p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x) && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y), @@ -412,6 +425,10 @@ fn in_frame(frame: &[Vec2], p: Vec2) -> bool { let mut j = f.len() - 1; for i in 0..f.len() { let (Some(pi), Some(pj)) = (f.get(i), f.get(j)) else { break }; + let edge = cadcraft_geom::Line { a: *pj, b: *pi }; + if edge.dist(p) <= 1e-9 * pi.dist(*pj) { + return true; + } if (pi.y > p.y) != (pj.y > p.y) && p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x { inside = !inside; } @@ -464,7 +481,10 @@ fn apply( _ => 0.0, }) }; - let mult = if mult == 0.0 { 1.0 } else { mult }; + // A zero multiplier would move nothing. AutoCAD 2024 moves such an action by the + // parameter's change and leaves its angle offset out (measured on a stretch action written + // with multiplier 0, angle offset 1 and group 280 = 1). + let (mult, angle) = if mult == 0.0 { (1.0, 0.0) } else { (mult, angle) }; let v = Vec2::new(comp(0), comp(1)).rotate(angle) * mult; if !(v.x.is_finite() && v.y.is_finite()) || (v.x == 0.0 && v.y == 0.0) { continue; @@ -473,6 +493,8 @@ fn apply( // this action's selection, so a selection that repeats a handle does not re-scan the // vertex list and re-clone its index vector per occurrence (CWE-400). let vtx_by_handle: HashMap> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect(); + // Whether the frame (two corners or a polygon) is tested point by point. + let framed = (2..=MAX_FRAME_POINTS).contains(&frame.len()); let mut handled: HashSet = HashSet::new(); for h in &a.selection { if !handled.insert(*h) { @@ -502,7 +524,17 @@ fn apply( continue; } let Some(c) = copy_of(h) else { continue }; - let idx = vtx_by_handle.get(h).map(|i| (*i).clone()); + // The points of a line or polyline that move are those inside the frame where the + // dynamic block has them, all of them when none is, as AutoCAD 2024 moves them. It + // doesn't go by the vertex lists the action stores, which a block from another program + // can get wrong. A polyline's vertices are in its own plane: in the block's when its + // extrusion is along z (a mirrored one is read flipped into it), so a tilted one keeps + // the stored list. + let idx = match def.entities.get(*h).map(|e| (&e.kind, e.common.extrusion)) { + Some((EntityKind::Line(l), _)) if framed => inside(frame, [l.a.xy(), l.b.xy()].into_iter()), + Some((EntityKind::LwPolyline(pl), n)) if framed && n.x == 0.0 && n.y == 0.0 => inside(frame, pl.vertices.iter().map(|v| v.p)), + _ => vtx_by_handle.get(h).map(|i| (*i).clone()), + }; moves.entry(c).or_default().push((idx, v)); } } diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index d265f9e70..bd9f2d1e1 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -406,6 +406,160 @@ fn parameters_in_a_stretch_selection_are_carried_along() { assert_eq!(tags[grip + 1..grip + 3], [(300, "GRIPLOC".to_string()), (11, "-15".to_string())]); } +/// A reference to Door at the origin with Door's own values, in a drawing read from `src`. +fn door_reference(src: &str) -> (cadcraft_doc::Drawing, Handle) { + let mut d = read_dxf(dxf(src).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: "Door".into(), + insert: cadcraft_doc::geom::Vec3::new(0.0, 0.0, 0.0), + scale: cadcraft_doc::geom::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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +/// The points of the lines and polylines of reference `r`'s block, in its order. +fn shapes(d: &cadcraft_doc::Drawing, r: Handle) -> Vec> { + let b = d.block(&block_of(d, &r.hex())).unwrap(); + b.entities + .iter() + .filter_map(|e| match &e.kind { + cadcraft_doc::EntityKind::Line(l) => Some(vec![(l.a.x, l.a.y), (l.b.x, l.b.y)]), + cadcraft_doc::EntityKind::LwPolyline(p) => Some(p.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()), + _ => None, + }) + .collect() +} + +#[test] +fn a_stretch_moves_the_points_inside_its_frame_not_the_listed_ones() { + // The stretch (frame (34,-2)-(38,2)) also acts on line 32, which is all outside the frame, and + // on a polyline whose last two vertices are inside it; and the vertex lists it stores are + // wrong for all three. AutoCAD 2024 moves the points inside the frame, measured on a dynamic + // block from another program whose lists didn't match its objects: every point of its lines and + // polylines moved exactly when it was inside the frame, whatever the lists said. A selected + // line or polyline all outside the frame moves whole, as in AutoCAD's own stretched copies. + let polyline = "0 LWPOLYLINE\n5 33\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbPolyline\n90 3\n70 0\n10 20\n20 1\n10 36\n20 1\n10 36\n20 -1\n"; + let src = fixture() + .replace("71 1\n330 30\n1010 40", "71 3\n330 30\n330 32\n330 33\n1010 40") + .replace("73 1\n331 30\n74 1\n94 1\n75 0", "73 3\n331 30\n74 1\n94 0\n331 32\n74 1\n94 1\n331 33\n74 1\n94 0\n75 0") + .replace("21 25\n31 0\n0 ENDBLK\n", &format!("21 25\n31 0\n{polyline}0 ENDBLK\n")); + let (mut d, r) = door_reference(&src); + let ActionKind::Stretch { vertices, .. } = &dynamic_block(&d, "Door").unwrap().actions[0].kind else { panic!("a stretch action") }; + assert_eq!(vertices, &[(h("30"), vec![0]), (h("32"), vec![1]), (h("33"), vec![0])]); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + let want: Vec> = vec![ + vec![(0.0, 0.0), (30.0, 0.0)], + vec![(0.0, 0.0), (0.0, 36.0)], + vec![(-6.0, 0.0), (19.0, 25.0)], + vec![(20.0, 1.0), (30.0, 1.0), (30.0, -1.0)], + ]; + assert_eq!(shapes(&d, r), want); +} + +#[test] +fn a_zero_distance_multiplier_moves_as_one_without_its_angle_offset() { + // A stretch written with multiplier 0 and angle offset 1 (radian), and group 280 = 1. AutoCAD + // 2024 moved such an action by the parameter's change, straight along it. + let src = fixture().replace("140 1\n141 0\n280 0", "140 0\n141 1\n280 1"); + assert_ne!(src, fixture()); + let (mut d, r) = door_reference(&src); + let ActionKind::Stretch { multiplier, angle_offset, .. } = &dynamic_block(&d, "Door").unwrap().actions[0].kind else { + panic!("a stretch action") + }; + assert_eq!((*multiplier, *angle_offset), (0.0, 1.0)); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + assert_eq!(shapes(&d, r)[0], [(0.0, 0.0), (30.0, 0.0)]); +} + +#[test] +fn a_point_on_the_edge_of_a_polygon_frame_is_inside_it() { + // Line 30 ends at (36, 0), and its start is outside every frame here. On the edge of the frame + // (34,-2)-(36,2) given as two corners, the end is inside and moves alone. The same frame as a + // polygon, and triangles whose slanted edge passes through (36, 0), exactly or up to rounding, + // take it the same way. + let frames = [ + "72 2\n1011 34\n1021 -2\n1011 36\n1021 2\n", + "72 4\n1011 34\n1021 -2\n1011 36\n1021 -2\n1011 36\n1021 2\n1011 34\n1021 2\n", + "72 3\n1011 34\n1021 -2\n1011 38\n1021 2\n1011 34\n1021 2\n", + "72 3\n1011 35.7\n1021 -0.3\n1011 36.7\n1021 0.7\n1011 30\n1021 10\n", + ]; + for frame in frames { + let src = fixture().replace("72 2\n1011 34\n1021 -2\n1011 38\n1021 2\n", frame); + assert_ne!(src, fixture()); + let (mut d, r) = door_reference(&src); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + assert_eq!(shapes(&d, r)[0], [(0.0, 0.0), (30.0, 0.0)], "{frame}"); + } +} + +#[test] +fn a_point_just_outside_a_tiny_frame_is_outside_it() { + // A frame 1e-8 across whose right edge is 5e-10 short of line 30's end (36, 0): the end is + // outside, so the line, with no point inside, moves whole. An edge's tolerance is a billionth of + // its length, not of a drawing unit. + let frame = "72 4\n1011 35.99999999\n1021 -1e-8\n1011 35.9999999995\n1021 -1e-8\n1011 35.9999999995\n1021 1e-8\n1011 35.99999999\n1021 1e-8\n"; + let src = fixture().replace("72 2\n1011 34\n1021 -2\n1011 38\n1021 2\n", frame); + assert_ne!(src, fixture()); + let (mut d, r) = door_reference(&src); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + assert_eq!(shapes(&d, r)[0], [(-6.0, 0.0), (30.0, 0.0)]); +} + +#[test] +fn a_tilted_polyline_keeps_the_stored_vertex_list() { + // Polyline 34 lies in a plane tilted about the y axis (extrusion (1,0,0)): its vertices are in + // that plane's coordinates, not the block's, so the frame isn't tested against them and the + // stored list (vertex 0) is used, as before. Polyline 35 is mirrored (extrusion (0,0,-1)): it + // is read flipped into the block's plane, (-20, 1) as (20, 1), so the frame is tested. + let polyline = |h: &str, [x0, x1]: [i32; 2], [ex, ey, ez]: [i32; 3]| { + format!( + "0 LWPOLYLINE\n5 {h}\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbPolyline\n90 2\n70 0\n10 {x0}\n20 1\n10 {x1}\n20 1\n210 {ex}\n220 {ey}\n230 {ez}\n" + ) + }; + let src = fixture() + .replace("71 1\n330 30\n1010 40", "71 3\n330 30\n330 34\n330 35\n1010 40") + .replace("73 1\n331 30\n74 1\n94 1\n75 0", "73 3\n331 30\n74 1\n94 1\n331 34\n74 1\n94 0\n331 35\n74 1\n94 0\n75 0") + .replace( + "21 25\n31 0\n0 ENDBLK\n", + &format!("21 25\n31 0\n{}{}0 ENDBLK\n", polyline("34", [20, 36], [1, 0, 0]), polyline("35", [-20, -36], [0, 0, -1])), + ); + let (mut d, r) = door_reference(&src); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + let s = shapes(&d, r); + assert_eq!(s[3], [(14.0, 1.0), (36.0, 1.0)]); + assert_eq!(s[4], [(20.0, 1.0), (30.0, 1.0)]); +} + +#[test] +fn a_frame_with_too_many_points_to_test_one_by_one_keeps_the_stored_lists() { + // The same frame as a polygon of `n` points (its four corners, the last repeated). Up to 1000 + // points each point of the objects is tested against it; past that the stored list (here the + // line's start, outside the frame) is used, so a huge frame doesn't make every point test every + // edge. + let frame = |n: usize| { + let mut f = format!("72 {n}\n1011 34\n1021 -2\n1011 38\n1021 -2\n1011 38\n1021 2\n"); + f.push_str(&"1011 34\n1021 2\n".repeat(n - 3)); + f + }; + for (n, want) in [(1000, [(0.0, 0.0), (30.0, 0.0)]), (1001, [(-6.0, 0.0), (36.0, 0.0)])] { + let src = fixture() + .replace("72 2\n1011 34\n1021 -2\n1011 38\n1021 2\n", &frame(n)) + .replace("73 1\n331 30\n74 1\n94 1\n75 0", "73 1\n331 30\n74 1\n94 0\n75 0"); + let (mut d, r) = door_reference(&src); + let ActionKind::Stretch { frame, .. } = &dynamic_block(&d, "Door").unwrap().actions[0].kind else { panic!("a stretch action") }; + assert_eq!(frame.len(), n); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + assert_eq!(shapes(&d, r)[0], want, "{n} frame points"); + } +} + /// The object entry `key` of dictionary `dict` refers to. fn dict_entry(d: &cadcraft_doc::Drawing, dict: Handle, key: &str) -> Option { let o = d.foreign.objects.iter().find(|o| o.handle == dict)?; 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 373/900] 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 374/900] 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 375/900] 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 376/900] 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 377/900] 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 378/900] 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 379/900] 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 380/900] 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 381/900] 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 382/900] 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 383/900] 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 384/900] 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 385/900] 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 386/900] 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 387/900] 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 388/900] 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 b17880ca89383c394b91a785937694e87923812c Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 01:27:15 -0700 Subject: [PATCH 389/900] dim: apply the style's DIMPOST to angular dimensions (#1653) --- crates/engine/tests/it/dim_vars.rs | 17 ++++ crates/io/tests/it/dim_block_text.rs | 95 ++++++++++++++++++++++- crates/render/src/dim/text.rs | 2 +- crates/render/src/dim/variants.rs | 7 +- crates/render/tests/it/dim_text_format.rs | 15 ++-- 5 files changed, 126 insertions(+), 10 deletions(-) diff --git a/crates/engine/tests/it/dim_vars.rs b/crates/engine/tests/it/dim_vars.rs index a2875ee07..4f2d6a835 100644 --- a/crates/engine/tests/it/dim_vars.rs +++ b/crates/engine/tests/it/dim_vars.rs @@ -299,6 +299,23 @@ fn tolerance_justification_angular_zeros_and_arc_symbol() { assert_eq!(dim_lines(&g1).len(), dim_lines(&g2).len() + 1, "the symbol drawn over the text"); } +/// DIMPOST frames the angle too, as AutoCAD 2026 does to its own angular dimensions (#1653). +#[test] +fn dimpost_applies_to_angular_dimensions() { + let mut s = Session::new(); + set(&mut s, "DIMPOST", json!("<> m")); + set(&mut s, "DIMADEC", json!(1)); + // Vertex and two points. + s.execute("dimangular", &json!({ "vertex": [0, 0], "p1": [10, 0], "p2": [0, 10], "at": [3, 3] })).unwrap(); + assert_eq!(last_dim(&s).1.value, "90.0° m"); + // Two lines picked: the same suffix. + s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + s.execute("line", &json!({ "points": [[0, 0], [5, 8.660254037844387]] })).unwrap(); + let h: Vec = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).map(|e| e.handle.hex()).collect(); + s.execute("dimangular", &json!({ "lines": h, "at": [4, 1] })).unwrap(); + assert_eq!(last_dim(&s).1.value, "60.0° m"); +} + #[test] fn linetypes_and_lineweights_of_dimension_and_extension_lines() { let mut s = Session::new(); diff --git a/crates/io/tests/it/dim_block_text.rs b/crates/io/tests/it/dim_block_text.rs index 0c5fa0cab..026e7d138 100644 --- a/crates/io/tests/it/dim_block_text.rs +++ b/crates/io/tests/it/dim_block_text.rs @@ -1,6 +1,7 @@ //! The anonymous `*D` block written for a dimension (what other programs draw) holds its text at //! the height it is drawn at: the dimension's overrides and DIMSCALE (0 = the drawing's) count -//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646). +//! (issue #367). Angular text also keeps its decimal separator in the stored block (#1646), and +//! the style's DIMPOST reaches angular dimensions' blocks too (#1653). use cadcraft_doc::{Common, DimKind, DimStyle, Dimension, Drawing, EntityKind, Space}; use cadcraft_geom::Vec3; @@ -127,3 +128,95 @@ fn dwg_angular_block_text_keeps_the_decimal_separator() { assert_eq!(texts, [expected], "DIMDSEP override: {separator_override:?}"); } } + +/// The group 1 (contents) values of every MTEXT in the BLOCKS section, in file order. +fn block_mtext_contents(dxf: &str) -> Vec { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let t: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect(); + let blocks = t.iter().position(|&(c, v)| c == "2" && v == "BLOCKS").unwrap(); + let end_blocks = blocks + t[blocks..].iter().position(|&(c, v)| c == "0" && v == "ENDSEC").unwrap(); + let mut out = Vec::new(); + let mut i = blocks; + while let Some(k) = t[i..end_blocks].iter().position(|&(c, v)| c == "0" && v == "MTEXT") { + let start = i + k; + let end = t[start + 1..end_blocks].iter().position(|&(c, _)| c == "0").map_or(end_blocks, |n| start + 1 + n); + // Contents are group 1 (the last chunk) after any 250-char group 3 chunks. + out.push(t[start + 1..end].iter().filter(|&&(c, _)| c == "3" || c == "1").map(|&(_, v)| v).collect()); + i = end; + } + out +} + +/// An angular dimension whose style sets DIMPOST `post` and one decimal place for angles. +fn posted_angular_drawing(kind: DimKind, points: [Vec3; 5], post: &str) -> Drawing { + let mut d = Drawing::new_metric(); + d.dim_styles.iter_mut().for_each(|s| { + s.post = post.into(); + s.angular_decimals = 1; + }); + let [p13, p14, p15, p16, defpt] = points; + let dm = Dimension { + kind, + defpt, + text_mid: Vec3::ZERO, + p13, + p14, + p15, + p16, + 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(), + }; + d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap(); + d +} + +/// The DXF text of the drawing's one dimension block. +fn dxf_block_text(d: &Drawing) -> String { + let mut texts = block_mtext_contents(&cadcraft_io::write_dxf(d)); + assert_eq!(texts.len(), 1, "{texts:?}"); + texts.remove(0) +} + +#[test] +fn dimpost_reaches_three_point_and_two_line_angular_dimension_blocks() { + // Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt. + let three_point = posted_angular_drawing( + DimKind::Angular3P, + [Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)], + "<> m", + ); + // The DXF is ASCII: the degree sign is its `\U+00B0` escape. + assert_eq!(dxf_block_text(&three_point), "90.0\\U+00B0 m"); + // Lines p13-p14 (along +X) and defpt-p15 (45°), the arc through p16. + let two_line = posted_angular_drawing( + DimKind::Angular, + [Vec3::ZERO, Vec3::new(10.0, 0.0, 0.0), Vec3::new(15.0, 15.0, 0.0), Vec3::new(4.0, 1.5, 0.0), Vec3::new(-5.0, -5.0, 0.0)], + "<> m", + ); + assert_eq!(dxf_block_text(&two_line), "45.0\\U+00B0 m"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dwg_angular_block_text_keeps_dimpost() { + use cadcraft_io::{SaveOptions, Version}; + + // Vertex p15 at the origin, legs through p13 (0°) and p14 (90°), the arc through defpt. + let d = posted_angular_drawing( + DimKind::Angular3P, + [Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::ZERO, Vec3::ZERO, Vec3::new(3.0, 3.0, 0.0)], + "<> m", + ); + let dwg = cadcraft_io::write_with(&d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap(); + let from_dwg = String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let mut texts = block_mtext_contents(&from_dwg); + assert_eq!(texts.len(), 1, "{texts:?}"); + assert_eq!(texts.remove(0), "90.0° m"); +} diff --git a/crates/render/src/dim/text.rs b/crates/render/src/dim/text.rs index 91e6b568c..b362eb706 100644 --- a/crates/render/src/dim/text.rs +++ b/crates/render/src/dim/text.rs @@ -67,7 +67,7 @@ fn tol_height_code(st: &DimStyle) -> String { } /// Apply measurement placeholders or append a dimension suffix, bounding the resulting UTF-8 text. -fn post(template: &str, meas: &str) -> String { +pub(super) fn post(template: &str, meas: &str) -> String { if template.contains("<>") { bounded_replace(template, meas) } else { diff --git a/crates/render/src/dim/variants.rs b/crates/render/src/dim/variants.rs index 948483a54..47b2464b8 100644 --- a/crates/render/src/dim/variants.rs +++ b/crates/render/src/dim/variants.rs @@ -1,4 +1,4 @@ -use super::text::{apply_override, inspected, linear_text}; +use super::text::{apply_override, inspected, linear_text, post}; use super::{Arrowhead, DimConfig, DimGeometry, DimKind, Vec2, ext_line, readable}; use crate::units::format_angle_with_separator; use cadcraft_geom::{Arc, ccw_sweep}; @@ -178,8 +178,9 @@ pub(super) fn draw_angular(config: &DimConfig<'_>, g: &mut DimGeometry, text_ang g.measurement = sweep; // DIMAZIN 1 / 2 suppress leading / trailing zeros (DIMZIN's bits 4 / 8). let azin = (st.angular_zero_suppression & 3) * 4; - let txt = format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator); - // DIMPOST is a linear-dimension prefix/suffix; angles have their own format only. + // DIMPOST wraps the angle too, as AutoCAD 2026 does to its own 2-line and 3-point + // angular dimensions ("36.9° m" for a style with "<> m"; issue #1653, after #376). + let txt = post(&st.post, &format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator)); g.mtext = inspected(apply_override(&txt, d), d); let mut pts = Vec::new(); arc.tessellate(r * 1e-3, &mut pts); diff --git a/crates/render/tests/it/dim_text_format.rs b/crates/render/tests/it/dim_text_format.rs index e70deea08..a4f451234 100644 --- a/crates/render/tests/it/dim_text_format.rs +++ b/crates/render/tests/it/dim_text_format.rs @@ -1,5 +1,5 @@ //! Dimension text formatting (issue #373): DIMRND rounds the measurement only, tolerances use -//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST is not added to angles. +//! DIMTZIN, alternate units DIMALTRND/DIMALTU/DIMALTZ, and DIMPOST wraps angles too (#1653). use cadcraft_doc::{DimKind, DimStyle, Dimension}; use cadcraft_geom::Vec3; @@ -59,18 +59,23 @@ fn dimrnd_rounds_neither_tolerances_nor_alternate_units() { } #[test] -fn dimpost_is_not_added_to_angular_dimensions() { +fn dimpost_applies_to_angular_dimensions_too() { let mut a = linear(0.0); a.kind = DimKind::Angular3P; a.p15 = Vec3::ZERO; a.p13 = Vec3::new(10.0, 0.0, 0.0); a.p14 = Vec3::new(0.0, 10.0, 0.0); a.defpt = Vec3::new(3.0, 3.0, 0.0); - assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°"); - // Linear dimensions keep it, and an angular text override still wraps the angle. + // AutoCAD 2026 applies the style's DIMPOST to angular dimensions it builds: with "<> m" + // its own 2-line and 3-point dimensions read "36.9° m" (#1653, follow-up to #373/#376). + assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm"); + // A prefix before `<>` works as on a linear dimension. + assert_eq!(text(&a, serde_json::json!({"DIMPOST": "A=<>"})), "A=90°"); + // Linear dimensions keep it, and an angular text override wraps the posted angle, as for + // a linear dimension. assert_eq!(text(&linear(10.0), serde_json::json!({"DIMPOST": "<>mm", "DIMDEC": 1})), "10.0mm"); a.text = "<> TYP".into(); - assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90° TYP"); + assert_eq!(text(&a, serde_json::json!({"DIMPOST": "<>mm"})), "90°mm TYP"); } fn angular(radians: f64) -> Dimension { From dc59a8e33cae3666f2f759379f642c8290768b80 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Mon, 2 Nov 2026 08:30:17 -0800 Subject: [PATCH 390/900] dim: note that DIMPOST wraps angles --- crates/render/src/dim.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index 967a2962c..becaaef3d 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -4,7 +4,8 @@ //! fixed-length extension lines (DIMFXL/DIMFXLON), text placement (DIMTAD, DIMTVP, DIMJUST, //! DIMTIH/DIMTOH, DIMGAP, DIMTMOVE) and text formatting (DIMLUNIT, DIMDEC, DIMZIN, DIMRND, //! DIMPOST, DIMTOL/DIMLIM with DIMTZIN and DIMTOLJ, DIMALT with DIMALTU/DIMALTZ/DIMALTRND, -//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL). +//! DIMAZIN, DIMARCSYM) with its background (DIMTFILL). DIMPOST wraps angles as well, as +//! AutoCAD does (#1653). use cadcraft_doc::{DimKind, DimStyle, Dimension}; use cadcraft_fonts::{MTextParams, TextFont}; From a3e82dc9ce0bf63708c381bcb48ff21fe73e3398 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Sat, 24 Oct 2026 18:50:06 -0700 Subject: [PATCH 391/900] 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 392/900] 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 393/900] 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 394/900] 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 395/900] 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 396/900] 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 3146b4765665eafe0e4c7d1c8d47a367140468c7 Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 15:25:41 -0600 Subject: [PATCH 397/900] fix(engine): WBLOCK writes only what the block or selection uses (#2423) (#2621) * fix(engine): WBLOCK writes only what the block or selection uses (#2423) WBLOCK of a block, or of selected objects, copied the source drawing's whole layer, linetype, style and block tables into the new file, so a 5-object symbol carried 40 unused layers and 20 blocks. The written drawing is now purged of what nothing in it uses, as AutoCAD's WBLOCK writes it: purge::purge_unused runs PURGE All's scan on a plain Drawing until a pass removes nothing (a block can free its layer), keeping the defaults and the current ones. Writing the entire drawing is unchanged. Co-Authored-By: Claude Opus 5.5 * fix(engine): PURGE's scan counts leaders' dimension styles and styles used by other styles From the review of #2621: PURGE (and now WBLOCK, which runs its scan) took as unused a dimension style only a LEADER used, a linetype only a dimension style or a dimension's override named (DIMLTYPE, DIMLTEX1, DIMLTEX2), and a text style only a complex linetype's text used, and removed them while the objects still named them. The scan counts all three now; text_styles_in_use, which STYLE's delete also asks, includes complex linetypes' text styles. Co-Authored-By: Claude Opus 5.5 * fix(engine): PURGE's scan counts multiline styles' linetypes and table styles' text styles From the review of #2621: a linetype only a multiline style's element used, and a text style only a table style's cell style used, were taken as unused and purged while the styles still named them. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/purge.rs | 52 +++++++- crates/engine/src/cmd/blocks/wblock.rs | 5 +- crates/engine/src/cmd/props.rs | 5 +- crates/engine/tests/wblock_purge.rs | 165 +++++++++++++++++++++++++ 4 files changed, 224 insertions(+), 3 deletions(-) create mode 100644 crates/engine/tests/wblock_purge.rs diff --git a/crates/engine/src/cmd/blocks/purge.rs b/crates/engine/src/cmd/blocks/purge.rs index 68aea3c36..b91507b15 100644 --- a/crates/engine/src/cmd/blocks/purge.rs +++ b/crates/engine/src/cmd/blocks/purge.rs @@ -197,7 +197,21 @@ pub(in crate::cmd) fn candidates(d: &Drawing, kind: Kind) -> Vec { .collect() } Kind::Linetypes => { - let used = lower(&mut entities(d).map(|e| e.common.linetype.clone()).chain(d.layers.iter().map(|l| l.linetype.clone()))); + // Objects and layers use linetypes, and so do dimension styles and a dimension's own + // overrides (DIMLTYPE, DIMLTEX1, DIMLTEX2), and multiline styles' elements. + let styles = d.dim_styles.iter().flat_map(|s| [s.dim_linetype.clone(), s.ext_linetype1.clone(), s.ext_linetype2.clone()]); + let overrides = entities(d).filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm) } else { None }).flat_map(|dm| { + ["dimLinetype", "extLinetype1", "extLinetype2"].into_iter().filter_map(|k| dm.overrides.get(k)?.as_str().map(str::to_string)) + }); + let mlines = d.mline_styles.iter().flat_map(|s| s.elements.iter().map(|el| el.linetype.clone())); + let used = lower( + &mut entities(d) + .map(|e| e.common.linetype.clone()) + .chain(d.layers.iter().map(|l| l.linetype.clone())) + .chain(styles) + .chain(overrides) + .chain(mlines), + ); let cur = d.header.str("CELTYPE", "ByLayer"); d.linetypes .iter() @@ -218,6 +232,7 @@ pub(in crate::cmd) fn candidates(d: &Drawing, kind: Kind) -> Vec { let used = lower(&mut entities(d).filter_map(|e| match &e.kind { EntityKind::Dimension(dm) => Some(dm.style.clone()), EntityKind::Tolerance(t) => Some(t.style.clone()), + EntityKind::Leader(l) => Some(l.style.clone()), _ => None, })); let cur = d.header.str("DIMSTYLE", "Standard"); @@ -299,6 +314,41 @@ fn retain(v: &mut Vec, name: impl Fn(&T) -> &String, n: &str) -> bool { v.len() != before } +/// Most passes [`purge_unused`] makes: each can free what the last one's objects used (a nested +/// block, its layer, that layer's linetype). +const MAX_PASSES: usize = 64; + +/// Remove every named object drawing `d` doesn't use, as PURGE All would, nested ones included; +/// the defaults and the current ones stay. For a drawing being written (WBLOCK's), not the one +/// being edited: nothing goes through the session or its undo. +pub(in crate::cmd) fn purge_unused(d: &mut Drawing) { + for _ in 0..MAX_PASSES { + let mut removed = false; + for kind in ALL { + for name in candidates(d, *kind) { + removed |= match kind { + Kind::Blocks => { + let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&name)).cloned(); + key.is_some_and(|k| d.blocks.remove(&k).is_some()) + } + Kind::Layers => retain(&mut d.layers, |l| &l.name, &name), + Kind::TextStyles => retain(&mut d.text_styles, |t| &t.name, &name), + Kind::Linetypes => retain(&mut d.linetypes, |t| &t.name, &name), + Kind::Dimstyles => retain(&mut d.dim_styles, |t| &t.name, &name), + Kind::MleaderStyles => retain(&mut d.mleader_styles, |t| &t.name, &name), + Kind::MlineStyles => retain(&mut d.mline_styles, |t| &t.name, &name), + Kind::TableStyles => retain(&mut d.table_styles, |t| &t.name, &name), + Kind::Groups => retain(&mut d.groups, |g| &g.name, &name), + Kind::ZeroLength | Kind::EmptyText | Kind::Absent | Kind::All => false, + }; + } + } + if !removed { + break; + } + } +} + /// Model-space and layout objects with no length, or text with no characters. fn degenerate(d: &Drawing, kind: Kind) -> Vec { let zero = |e: &EntityKind| match e { diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index 98ab0c344..bc2ff711a 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -97,7 +97,9 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi Ok((d.model.len(), bytes.len())) } -/// A new drawing of `ents`, with `src`'s settings, styles and blocks; its insertion base 0,0. +/// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks +/// they use, as AutoCAD's WBLOCK writes them (#2423): what nothing in it uses is purged, and +/// the defaults and the current ones stay. Its insertion base is 0,0. fn with_objects(src: &Drawing, ents: impl Iterator) -> Drawing { let mut d = Drawing::new_imperial(); d.header = src.header.clone(); @@ -115,6 +117,7 @@ fn with_objects(src: &Drawing, ents: impl Iterator) -> Drawing { e.handle = d.new_handle(); d.model.push(e); } + super::purge::purge_unused(&mut d); d } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 8afaddb3d..018e2dbf6 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -765,10 +765,13 @@ fn run_style_current(s: &mut Session, p: &Value) -> Result { ok() } -/// Text style names used by entities (in model, paper spaces and blocks) and dimension styles. +/// Text style names used by entities (in model, paper spaces and blocks), dimension, +/// multileader and table styles (their cell styles), and the text of complex linetypes. pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec { let mut out: Vec = d.dim_styles.iter().map(|s| s.text_style.clone()).collect(); out.extend(d.mleader_styles.iter().map(|s| s.text_style.clone())); + out.extend(d.table_styles.iter().flat_map(|s| s.cell_styles.iter().map(|c| c.text_style.clone()))); + out.extend(d.linetypes.iter().flat_map(|lt| lt.pattern.iter().filter_map(|el| el.style.clone()))); let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)); for st in stores { for e in st.iter() { diff --git a/crates/engine/tests/wblock_purge.rs b/crates/engine/tests/wblock_purge.rs new file mode 100644 index 000000000..3fc3bad5e --- /dev/null +++ b/crates/engine/tests/wblock_purge.rs @@ -0,0 +1,165 @@ +//! WBLOCK writes what the block or the selection uses, not the source drawing's whole tables +//! (#2423): AutoCAD's WBLOCK of a 5-object symbol writes its layer, its style and the defaults, +//! not the other 40 layers and 20 blocks of the drawing it came from. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::Drawing; +use serde_json::{Value, json}; + +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +/// Writes the written drawing's table names, one table a line: layers, text styles, blocks, +/// dimension styles, linetypes. One hook for every test here: `set_io` is process-wide and the +/// tests run in parallel. +fn write(d: &Drawing, _path: &str) -> Result, String> { + let mut blocks: Vec<&str> = d.blocks.values().map(|b| b.name.as_str()).collect(); + blocks.sort_unstable(); + let layers: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect(); + let styles: Vec<&str> = d.text_styles.iter().map(|t| t.name.as_str()).collect(); + let dims: Vec<&str> = d.dim_styles.iter().map(|t| t.name.as_str()).collect(); + let linetypes: Vec<&str> = d.linetypes.iter().map(|t| t.name.as_str()).collect(); + Ok(format!("{}\n{}\n{}\n{}\n{}", layers.join(","), styles.join(","), blocks.join(","), dims.join(","), linetypes.join(",")).into_bytes()) +} + +/// The layers, text styles and blocks of the file WBLOCK writes with `p`. +fn written(s: &mut Session, mut p: Value) -> (String, String, String) { + let dir = TempDir::new("wblock-purge"); + let path = dir.path_str("out.dxf"); + p["path"] = json!(path); + s.execute("wblock", &p).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let mut lines = text.lines().map(str::to_string); + (lines.next().unwrap_or_default(), lines.next().unwrap_or_default(), lines.next().unwrap_or_default()) +} + +fn line_on(s: &mut Session, layer: &str, y: f64) -> String { + let h = s.execute("line", &json!({ "points": [[0, y], [5, y]] })).unwrap()["handles"][0].as_str().unwrap().to_string(); + s.execute("properties.set", &json!({ "handles": [h], "layer": layer })).unwrap(); + h +} + +/// Block SYM: a line on SYM-LAYER and a reference to INNER, whose line is on INNER-LAYER. The +/// drawing also has a layer, a text style and a block that SYM doesn't use. +fn drawing() -> Session { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write, plot: None }); + let mut s = Session::new(); + for name in ["SYM-LAYER", "INNER-LAYER", "UNUSED-LAYER", "OTHER-LAYER"] { + s.execute("layer.new", &json!({ "name": name })).unwrap(); + } + s.execute("style", &json!({ "name": "UNUSED-STYLE" })).unwrap(); + s.execute("style.current", &json!({ "name": "Standard" })).unwrap(); + let inner = line_on(&mut s, "INNER-LAYER", 0.0); + s.execute("block", &json!({ "name": "INNER", "base": [0, 0], "handles": [inner], "keep": "delete" })).unwrap(); + let r = s.execute("insert", &json!({ "name": "INNER", "at": [0, 5] })).unwrap(); + let inner_ref = r["handle"].as_str().unwrap().to_string(); + let own = line_on(&mut s, "SYM-LAYER", 10.0); + s.execute("block", &json!({ "name": "SYM", "base": [0, 0], "handles": [own, inner_ref], "keep": "delete" })).unwrap(); + let other = line_on(&mut s, "OTHER-LAYER", 20.0); + s.execute("block", &json!({ "name": "OTHER", "base": [0, 0], "handles": [other], "keep": "delete" })).unwrap(); + s +} + +#[test] +fn a_block_is_written_with_what_it_uses() { + let mut s = drawing(); + let (layers, styles, blocks) = written(&mut s, json!({ "name": "SYM" })); + let layers: Vec<&str> = layers.split(',').collect(); + for used in ["0", "SYM-LAYER", "INNER-LAYER"] { + assert!(layers.contains(&used), "{used} in {layers:?}"); + } + for unused in ["UNUSED-LAYER", "OTHER-LAYER"] { + assert!(!layers.contains(&unused), "{unused} in {layers:?}"); + } + assert!(!styles.split(',').any(|n| n == "UNUSED-STYLE"), "{styles}"); + assert!(styles.split(',').any(|n| n == "Standard"), "{styles}"); + // The nested block comes along; the block being written is the file itself, and OTHER stays out. + assert_eq!(blocks, "INNER"); + // The source drawing is untouched. + let d = s.doc().unwrap(); + assert!(d.layer("UNUSED-LAYER").is_some() && d.block("OTHER").is_some()); +} + +#[test] +fn selected_objects_are_written_with_what_they_use() { + let mut s = drawing(); + let r = s.execute("insert", &json!({ "name": "INNER", "at": [50, 50] })).unwrap(); + let h = r["handle"].as_str().unwrap().to_string(); + let (layers, _, blocks) = written(&mut s, json!({ "handles": [h] })); + assert_eq!(blocks, "INNER", "only the block the selection references"); + let layers: Vec<&str> = layers.split(',').collect(); + assert!(layers.contains(&"INNER-LAYER") && !layers.contains(&"SYM-LAYER"), "{layers:?}"); +} + +/// What the block uses through its styles stays too: a leader's dimension style, the linetype a +/// dimension style draws its dimension line with, and the text style of a complex linetype's text. +#[test] +fn styles_used_through_other_styles_stay() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write, plot: None }); + let mut s = Session::new(); + s.execute("style", &json!({ "name": "LTEXT" })).unwrap(); + s.execute("style.current", &json!({ "name": "Standard" })).unwrap(); + let lin = "*TXT,Text --T--\nA,.5,-.2,[\"T\",LTEXT,S=.1,X=-.1,Y=-.05],-.2\n"; + s.execute("linetype", &json!({ "load": "TXT", "text": lin })).unwrap(); + s.execute("linetype", &json!({ "load": "DASHED" })).unwrap(); + s.execute("dimstyle", &json!({ "name": "LDR", "current": true })).unwrap(); + let leader = s.execute("leader", &json!({ "points": [[0, 0], [5, 5]], "text": "NOTE" })).unwrap()["handles"].clone(); + s.execute("dimstyle", &json!({ "name": "DS", "dimLinetype": "DASHED", "current": true })).unwrap(); + let dim = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, -3] })).unwrap()["handle"].clone(); + s.execute("dimstyle", &json!({ "name": "Standard", "current": true })).unwrap(); + let line = s.execute("line", &json!({ "points": [[0, 8], [9, 8]] })).unwrap()["handles"][0].clone(); + s.execute("properties.set", &json!({ "handles": [line], "linetype": "TXT" })).unwrap(); + let mut handles: Vec = leader.as_array().cloned().unwrap_or_default(); + handles.extend([dim, line]); + s.execute("block", &json!({ "name": "SYM", "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap(); + let dir = TempDir::new("wblock-purge-styles"); + let path = dir.path_str("out.dxf"); + s.execute("wblock", &json!({ "name": "SYM", "path": path })).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let table = |n: usize| text.lines().nth(n).unwrap_or("").split(',').map(str::to_string).collect::>(); + let (styles, dims, linetypes) = (table(1), table(3), table(4)); + for kept in ["LDR", "DS"] { + assert!(dims.iter().any(|n| n == kept), "dimension style {kept} kept: {dims:?}"); + } + for kept in ["DASHED", "TXT"] { + assert!(linetypes.iter().any(|n| n == kept), "linetype {kept} kept: {linetypes:?}"); + } + assert!(styles.iter().any(|n| n == "LTEXT"), "text style LTEXT kept: {styles:?}"); +} + +/// PURGE keeps a dimension style a leader uses (it only counted dimensions and tolerances). +#[test] +fn purge_keeps_a_leaders_dimension_style() { + let mut s = Session::new(); + s.execute("dimstyle", &json!({ "name": "LDR", "current": true })).unwrap(); + s.execute("leader", &json!({ "points": [[0, 0], [5, 5]], "text": "NOTE" })).unwrap(); + s.execute("dimstyle", &json!({ "name": "Standard", "current": true })).unwrap(); + s.execute("purge", &json!({ "type": "all" })).unwrap(); + assert!(s.doc().unwrap().dim_style("LDR").is_some(), "the leader's style stays"); +} + +/// PURGE keeps a linetype only a multiline style's element uses, and a text style only a table +/// style's cell style uses (from the review of #2621). +#[test] +fn purge_keeps_styles_used_by_multiline_and_table_styles() { + use cadcraft_engine::doc::{CellStyle, MLineElement, MLineStyle, TableStyle}; + let mut s = Session::new(); + s.execute("linetype", &json!({ "load": "DASHED" })).unwrap(); + s.execute("style", &json!({ "name": "CELLTEXT" })).unwrap(); + s.execute("style.current", &json!({ "name": "Standard" })).unwrap(); + let d = s.doc_mut().unwrap(); + let element = MLineElement { linetype: "DASHED".into(), ..MLineElement::default() }; + d.mline_styles.push(MLineStyle { name: "ML".into(), elements: vec![element], ..MLineStyle::default() }); + let cell = CellStyle { text_style: "CELLTEXT".into(), ..CellStyle::default() }; + d.table_styles.push(TableStyle { name: "TS".into(), cell_styles: vec![cell], ..TableStyle::default() }); + // Both styles are made current, so PURGE keeps them; what they use must stay with them. + d.header.set_str("CMLSTYLE", "ML"); + d.header.set_str("CTABLESTYLE", "TS"); + s.execute("purge", &json!({ "type": "all" })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.linetype("DASHED").is_some(), "the multiline style's linetype stays"); + assert!(d.text_style("CELLTEXT").is_some(), "the table style's text style stays"); +} From a277346c2f31385e7a76ace2952641df33d03df0 Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 15:25:46 -0600 Subject: [PATCH 398/900] fix(io): a viewport looks at its view target plus its centre (#2492) (#2508) * fix(io): a viewport looks at its view target plus its centre (#2492) A DXF stores a view's centre in display coordinates, whose origin is the view target (DXF Reference: VIEWPORT 12/22 and 17/27/37, VPORT 12/22 and 17/27/37, VIEW 10/20 and 12/22/32). The readers took the centre alone, so a file that keeps the location in the target with a centre of 0,0 (as ArchiCAD's AutoCAD 2018 export does) showed model point 0,0 in every layout viewport, on screen and when plotted. The VIEWPORT entity, VPORT tiles and named views now read the target plus the centre. A sum that overflows keeps the stored centre. The writers already store the whole location as the centre with a target of 0, so a save and reopen keeps the view, through DXF and DWG. Co-Authored-By: Claude Opus 5.5 * test(io): a viewport looking along another direction centres on its target Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/io/src/dxf_read/common.rs | 9 ++ crates/io/src/dxf_read/entities.rs | 3 +- crates/io/src/dxf_read/tables.rs | 6 +- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/view_target.rs | 181 +++++++++++++++++++++++++++++ 5 files changed, 197 insertions(+), 3 deletions(-) create mode 100644 crates/io/tests/it/view_target.rs diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index e46f3c09d..1dbabf6e9 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -19,6 +19,15 @@ impl T<'_> { pub(super) fn p(&self, code: i32) -> Vec3 { Vec3::new(self.fd(code, 0.0), self.fd(code + 10, 0.0), self.fd(code + 20, 0.0)) } + /// A view's centre in the drawing. The DXF stores it in display coordinates (`center`), whose + /// origin is the view target (`target`), so the point in the middle of a plan view is their + /// sum: a file whose view centre is 0,0 keeps the location in the target (#2492). A sum that + /// overflows leaves the stored centre. + pub(super) fn view_center(&self, center: i32, target: i32) -> Vec2 { + let c = self.p(center).xy(); + let sum = c + self.p(target).xy(); + if sum.is_finite() { sum } else { c } + } pub(super) fn all_f(&self, code: i32) -> Vec { self.0.iter().filter(|t| t.code == code).map(Tag::f64).collect() } diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 119d00bbd..980b1718c 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -246,7 +246,8 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef center: t.p(10), width: t.fd(40, 1.0), height: t.fd(41, 1.0), - view_center: Vec2::new(t.fd(12, 0.0), t.fd(22, 0.0)), + // 12/22 is in display coordinates, whose origin is the view target 17/27/37. + view_center: t.view_center(12, 17), view_height: t.fd(45, 1.0), id: t.i(69).unwrap_or(0) as u32, locked: t.i(90).unwrap_or(0) & 16384 != 0, diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index ee42b8a58..c914ea9f5 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -217,7 +217,8 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { if name.is_empty() || !(h.is_finite() && w.is_finite() && h > 0.0 && w > 0.0) || d.views.len() >= MAX_OBJECTS { continue; } - let center = t.p(10).xy(); + // The view centre 10/20 is in display coordinates, whose origin is the target 12/22/32. + let center = t.view_center(10, 12); if !(center.x.is_finite() && center.y.is_finite()) { continue; } @@ -316,7 +317,8 @@ const MAX_VPORT_TILES: usize = 64; /// are fractions of the drawing area; unusable tiles are skipped. 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()); + // The view centre 12/22 is in display coordinates, whose origin is the view target 17/27/37. + let (min, max, center) = (t.p(10).xy(), t.p(11).xy(), t.view_center(12, 17)); 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) diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 79c4e4b3e..aa77795fa 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -73,5 +73,6 @@ mod text_left_justify; mod tolerance_roundtrip; mod user_lin_pat_roundtrip; mod view_tables_roundtrip; +mod view_target; mod viewport_clip_roundtrip; mod xref_roundtrip; diff --git a/crates/io/tests/it/view_target.rs b/crates/io/tests/it/view_target.rs new file mode 100644 index 000000000..c6a2eea27 --- /dev/null +++ b/crates/io/tests/it/view_target.rs @@ -0,0 +1,181 @@ +//! A view's centre is stored in display coordinates, whose origin is the view target (DXF +//! Reference: VIEWPORT 12/22 and 17/27/37, VPORT 12/22 and 17/27/37, VIEW 10/20 and 12/22/32). +//! ArchiCAD's AutoCAD 2018 export puts each layout viewport's location in the target with a +//! centre of 0,0, so reading the centre alone showed model point 0,0 (#2492). + +use cadcraft_doc::geom::Vec2; +use cadcraft_doc::{Drawing, EntityKind, Viewport}; +use cadcraft_io::{read_dxf, write_dxf}; + +/// An ASCII DXF of `tags`. +fn dxf(tags: &[(i32, &str)]) -> String { + tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +/// A layout viewport with view centre `center` (12/22) and view target `target` (17/27/37). +fn with_viewport(center: [&str; 2], target: [&str; 3]) -> Drawing { + looking_along(center, target, ["0", "0", "1"]) +} + +/// The same, looking along view direction `dir` (16/26/36). +fn looking_along(center: [&str; 2], target: [&str; 3], dir: [&str; 3]) -> Drawing { + let tags: Vec<(i32, &str)> = vec![ + (0, "SECTION"), + (2, "ENTITIES"), + (0, "VIEWPORT"), + (5, "40"), + (67, "1"), + (8, "0"), + (10, "148.5"), + (20, "105"), + (30, "0"), + (40, "250"), + (41, "180"), + (68, "2"), + (69, "2"), + (12, center[0]), + (22, center[1]), + (16, dir[0]), + (26, dir[1]), + (36, dir[2]), + (17, target[0]), + (27, target[1]), + (37, target[2]), + (45, "48680.2"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + read_dxf(dxf(&tags).as_bytes()).expect("read") +} + +fn viewports(d: &Drawing) -> Vec { + d.layouts + .iter() + .flat_map(|l| l.entities.iter()) + .filter_map(|e| match &e.kind { + EntityKind::Viewport(v) if v.id > 1 => Some(v.clone()), + _ => None, + }) + .collect() +} + +fn view_center(d: &Drawing) -> Vec2 { + let vs = viewports(d); + assert_eq!(vs.len(), 1, "{vs:?}"); + vs[0].view_center +} + +/// `a` and `b` agree to within the rounding of adding two decimals. +fn close(a: Vec2, b: Vec2) -> bool { + (a - b).len() < 1e-6 +} + +#[test] +fn a_viewport_looks_at_its_target_plus_its_centre() { + // The issue's file: centre 0,0, the facade in the target. + let c = view_center(&with_viewport(["0", "0"], ["230748.7", "-867.4", "0"])); + assert_eq!(c, Vec2::new(230748.7, -867.4)); + // Both set: their sum. A target alone of 0 leaves the centre as it is. + assert_eq!(view_center(&with_viewport(["10", "5"], ["100", "50", "7"])), Vec2::new(110.0, 55.0)); + assert_eq!(view_center(&with_viewport(["10", "5"], ["0", "0", "0"])), Vec2::new(10.0, 5.0)); +} + +/// CADCraft draws every viewport as a plan view (the view direction, 16/26/36, isn't applied). A +/// viewport looking along another direction is centred on what it looks at, its target, as +/// AutoCAD's view of it is; its centre is in that view's own axes, so only the target is exact. +#[test] +fn a_viewport_looking_along_another_direction_centres_on_its_target() { + let c = view_center(&looking_along(["0", "0"], ["500", "-200", "30"], ["1", "1", "1"])); + assert_eq!(c, Vec2::new(500.0, -200.0)); +} + +/// Saved and reopened, the viewport still looks at the same place: CADCraft writes the whole +/// location as the centre with a target of 0. +#[test] +fn the_view_survives_a_save_and_reopen() { + let d = with_viewport(["3", "4"], ["84672.2", "25851.5", "0"]); + let back = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + let c = view_center(&back); + assert!(close(c, Vec2::new(84675.2, 25855.5)), "{c:?}"); +} + +/// A target coordinate that is not a finite number reads as 0, as any DXF real does, and a sum +/// that overflows leaves the centre. +#[test] +fn a_hostile_target_leaves_the_centre() { + for target in [["1e999", "0", "0"], ["nan", "0", "0"], ["1e308", "0", "0"]] { + assert_eq!(view_center(&with_viewport(["1e308", "2"], target)), Vec2::new(1e308, 2.0), "{target:?}"); + } + assert_eq!(view_center(&with_viewport(["1", "2"], ["inf", "5", "0"])), Vec2::new(1.0, 7.0)); +} + +/// The model viewport tiles of a saved configuration (VPORT 12/22 and 17/27/37) and named views +/// (VIEW 10/20 and 12/22/32) are read the same way. +#[test] +fn vport_tiles_and_named_views_add_their_targets() { + let tags: &[(i32, &str)] = &[ + (0, "SECTION"), + (2, "TABLES"), + (0, "TABLE"), + (2, "VPORT"), + (0, "VPORT"), + (2, "TWO"), + (70, "0"), + (10, "0"), + (20, "0"), + (11, "0.5"), + (21, "1"), + (12, "1"), + (22, "2"), + (17, "100"), + (27, "200"), + (37, "0"), + (40, "50"), + (41, "1"), + (0, "VPORT"), + (2, "TWO"), + (70, "0"), + (10, "0.5"), + (20, "0"), + (11, "1"), + (21, "1"), + (12, "0"), + (22, "0"), + (17, "-40"), + (27, "30"), + (37, "0"), + (40, "50"), + (41, "1"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "VIEW"), + (0, "VIEW"), + (2, "Facade"), + (70, "0"), + (40, "20"), + (41, "30"), + (10, "1"), + (20, "2"), + (11, "0"), + (21, "0"), + (31, "1"), + (12, "367097.3"), + (22, "-441.8"), + (32, "0"), + (0, "ENDTAB"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + let d = read_dxf(dxf(tags).as_bytes()).expect("read"); + let two = d.vports.iter().find(|c| c.name.eq_ignore_ascii_case("TWO")).expect("configuration TWO"); + let centers: Vec = two.tiles.iter().map(|t| t.center).collect(); + assert_eq!(centers, [Vec2::new(101.0, 202.0), Vec2::new(-40.0, 30.0)]); + let facade = d.views.iter().find(|v| v.name == "Facade").expect("view Facade"); + assert!(close(facade.center, Vec2::new(367098.3, -439.8)), "{:?}", facade.center); + // And again after a save and reopen. + let back = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + let two = back.vports.iter().find(|c| c.name.eq_ignore_ascii_case("TWO")).expect("configuration TWO"); + assert_eq!(two.tiles.iter().map(|t| t.center).collect::>(), centers); + let again = back.views.iter().find(|v| v.name == "Facade").map(|v| v.center).expect("view Facade"); + assert!(close(again, Vec2::new(367098.3, -439.8)), "{again:?}"); +} From c4ac8761e80df60d4bf9e9ab4ab91cc9c02c70f1 Mon Sep 17 00:00:00 2001 From: assamaral Date: Mon, 2 Nov 2026 18:25:51 -0300 Subject: [PATCH 399/900] fix(io): a ByBlock plot style (group 380 = 1) is written and read (#2242) (#2566) * test(io): a ByBlock plot style (group 380 = 1) survives a DXF round trip (#2242) Red: the writer leaves group 380 out and the reader maps it to ByLayer. Co-Authored-By: Claude Fable 5.1 * fix(io): a ByBlock plot style is group 380 = 1, written and read (#2242) The writer only knew named styles (group 390) and left ByBlock out like ByLayer; the reader mapped a record without 390 to ByLayer. Both now use the plot style name type. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Fable 5.1 --- crates/io/src/dxf_read/entities.rs | 16 +++++++++++----- crates/io/src/dxf_write/common.rs | 4 ++++ crates/io/tests/it/plot_styles.rs | 13 +++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 980b1718c..2011c3d63 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -411,20 +411,26 @@ pub(super) fn plot_style_names(secs: &[cadcraft_dxf::Section]) -> HashMap Option { let mut in_entity = false; + let mut by_block = false; for t in tags { if t.code == 100 { if in_entity { - return None; + break; } in_entity = t.str() == "AcDbEntity"; - } else if t.code == 390 && in_entity { - return rx.pstyles.get(&t.str().trim().to_ascii_uppercase()).cloned(); + } else if in_entity { + match t.code { + 390 => return rx.pstyles.get(&t.str().trim().to_ascii_uppercase()).cloned(), + 380 => by_block = t.i64() == 1, + _ => {} + } } } - None + by_block.then(|| "ByBlock".to_string()) } /// Dimension overrides and associativity, table references: data of an entity record that diff --git a/crates/io/src/dxf_write/common.rs b/crates/io/src/dxf_write/common.rs index 25d2bb074..ef2632665 100644 --- a/crates/io/src/dxf_write/common.rs +++ b/crates/io/src/dxf_write/common.rs @@ -101,6 +101,10 @@ pub(super) fn common_x(w: &mut W, e: &Entity, owner: &str, paper: bool, subclass if let Some(v) = transparency_440(e.common.transparency) { w.i(440, v); } + // ByBlock is the plot style name type 1 (ByLayer, 0, is the default and left out). + if e.common.plot_style.trim().eq_ignore_ascii_case("byblock") { + w.i(380, 1); + } // A named plot style (not ByLayer/ByBlock): its placeholder object. if let Some(h) = w.pstyles.get(&e.common.plot_style.trim().to_ascii_uppercase()).cloned() { w.s(390, h); diff --git a/crates/io/tests/it/plot_styles.rs b/crates/io/tests/it/plot_styles.rs index 679c167b9..73a5c8e5b 100644 --- a/crates/io/tests/it/plot_styles.rs +++ b/crates/io/tests/it/plot_styles.rs @@ -86,6 +86,19 @@ fn named_plot_styles_round_trip_through_the_plot_style_dictionary() { assert!(plain.contains("ACAD_PLOTSTYLENAME") && !plain.contains("CADCRAFT_PLOTSTYLES")); } +/// #2242: a ByBlock plot style is group 380 = 1 (AcDb::PlotStyleNameType); it was written like +/// ByLayer (no group at all) and read back as ByLayer. +#[test] +fn by_block_plot_style_round_trips() { + let mut d = Drawing::new_metric(); + let line = EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(1.0, 0.0, 0.0) }); + let h = d.add(&Space::Model, Common { plot_style: "ByBlock".into(), ..Default::default() }, line).unwrap(); + let text = write_dxf(&d); + let lines: Vec<&str> = text.lines().collect(); + assert!(lines.windows(2).any(|w| w[0].trim() == "380" && w[1].trim() == "1"), "group 380 = 1 written"); + assert_eq!(read_dxf(text.as_bytes()).unwrap().entity(h).unwrap().common.plot_style, "ByBlock"); +} + #[test] fn pdf_applies_a_named_table_from_the_drawing() { use cadcraft_doc::{PlotStyle, PlotStyleTable}; From ab15e42c6c12049f2c68e1c2715ca7183075703b Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 15:25:55 -0600 Subject: [PATCH 400/900] fix(io): a layout keeps its limits and paper image origin through a save (#2109) (#2623) Every LAYOUT was written with limits 0,0 to 12,9 (AcDbLayout groups 10/11) and paper image origin 0,0 (groups 148/149), whatever the file had, so another program drew the sheet elsewhere and a Layout plot came out shifted. Layout::limits and PageSetup::image_origin keep what the file had (finite, within 1e12) and a save writes it back; a layout without them writes the old defaults, which read back as none. Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/doc/src/tables.rs | 11 +++- crates/engine/src/cmd/layout.rs | 2 +- crates/io/src/dxf_read.rs | 3 +- crates/io/src/dxf_read/document.rs | 16 +++-- crates/io/src/dxf_read/objects.rs | 4 ++ crates/io/src/dxf_write/sections.rs | 17 +++-- crates/io/tests/it/layout_limits_roundtrip.rs | 64 +++++++++++++++++++ crates/io/tests/it/main.rs | 1 + 8 files changed, 106 insertions(+), 12 deletions(-) create mode 100644 crates/io/tests/it/layout_limits_roundtrip.rs diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index a2c63ca6a..a5f02454f 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -799,6 +799,10 @@ 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, + /// The paper image origin (DXF groups 148/149, in plot paper units) as the file had it, so a + /// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109). + #[serde(skip_serializing_if = "Option::is_none")] + pub image_origin: Option, } impl Default for PageSetup { @@ -820,6 +824,7 @@ impl Default for PageSetup { show_plot_styles: false, plot_transparency: false, paper_mm: false, + image_origin: None, } } } @@ -835,11 +840,15 @@ pub struct Layout { /// Saved paper-space view (centre, height). #[serde(default)] pub view: Option<(Vec2, f64)>, + /// The layout's limits (LAYOUT groups 10/11, lower left and upper right) as the file had + /// them; `None` for a layout CADCraft made, written as 0,0 to 12,9 (#2109). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limits: Option<(Vec2, Vec2)>, } 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, limits: None } } } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index a538d73b5..efe9bf13f 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -313,7 +313,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, limits: src.limits }); Ok(json!({ "name": to })) } diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 341e72a77..2dcb14fc0 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -73,7 +73,8 @@ pub fn read(bytes: &[u8]) -> Result { type BlockDef = (String, Vec3, String, Vec<(Option, bool, Entity)>, i64); /// A layout read from OBJECTS: name, tab order, paper block handle and page setup. -type LayoutDef = (String, u32, String, PageSetup); +/// A LAYOUT object: name, tab order, block record, page setup and its limits (groups 10/11). +type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>); /// Import DXF sections while sharing one materialized-table-cell budget across blocks and entity sections. fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index db935974a..6f61e3415 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -1,7 +1,7 @@ use super::common::T; use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity}; use super::objects::{MAX_OBJECTS, Objects, page_setup}; -use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, records}; +use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, records}; pub(super) fn parse_entities( recs: &[(String, Vec)], @@ -138,21 +138,29 @@ pub(super) fn read_objects(tags: &[Tag], objs: &mut Objects, layout_objs: &mut V // LAYOUT has two 330s: owner dict and the block record; take the last. let br = tg.iter().rfind(|x| x.code == 330).map(Tag::str).unwrap_or_default(); let plot = T(tg.get(..start).unwrap_or(&[])); - layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot))); + layout_objs.push((t.s(1).unwrap_or_default(), t.i(71).unwrap_or(0) as u32, br.to_ascii_uppercase(), page_setup(&plot), limits(&t))); } } } +/// A LAYOUT's limits (groups 10/20 and 11/21 after the AcDbLayout marker), when both corners +/// are there and usable, so a save writes back the file's own (#2109). The 0,0 to 12,9 a +/// layout without its own limits writes reads back as none. +fn limits(t: &T) -> Option<(Vec2, Vec2)> { + let corner = |x: i32, y: i32| Some(Vec2::new(t.f(x)?, t.f(y)?)).filter(|p| p.is_finite() && p.x.abs() < 1e12 && p.y.abs() < 1e12); + corner(10, 20).zip(corner(11, 21)).filter(|l| *l != (Vec2::ZERO, Vec2::new(12.0, 9.0))) +} + /// Add the drawing's layouts, and return the layout each paper-space block belongs to, and the /// layout that takes paper-space entities without an owner. pub(super) fn setup_layouts(d: &mut Drawing, layout_objs: &mut [LayoutDef], rx: &Rx) -> (HashMap, String) { let mut paper_block_for: HashMap = HashMap::new(); layout_objs.sort_by_key(|l| l.1); - for (name, order, br, page) in layout_objs.iter() { + for (name, order, br, page, limits) in layout_objs.iter() { if name.eq_ignore_ascii_case("Model") { continue; } - d.layouts.push(Layout { page: page.clone(), ..Layout::new(name, *order) }); + d.layouts.push(Layout { page: page.clone(), limits: *limits, ..Layout::new(name, *order) }); if let Some(bname) = rx.brs.get(br) { paper_block_for.insert(bname.to_ascii_uppercase(), name.clone()); } diff --git a/crates/io/src/dxf_read/objects.rs b/crates/io/src/dxf_read/objects.rs index 4d692ccee..359dc887a 100644 --- a/crates/io/src/dxf_read/objects.rs +++ b/crates/io/src/dxf_read/objects.rs @@ -274,6 +274,10 @@ pub(super) fn page_setup(t: &T) -> PageSetup { .into(); p.plot_window = [t.fd(48, 0.0), t.fd(49, 0.0), t.fd(140, 0.0), t.fd(141, 0.0)].map(|v| if v.is_finite() { v } else { 0.0 }); p.plot_style_table = t.s(7).unwrap_or_default(); + // Paper image origin: kept as the file has it, so a save puts the sheet back where it was (#2109). + // 0,0 is what a page without one writes, so it reads back as none. + p.image_origin = + t.f(148).zip(t.f(149)).map(|(x, y)| Vec2::new(x, y)).filter(|o| o.is_finite() && o.x.abs() < 1e12 && o.y.abs() < 1e12 && *o != Vec2::ZERO); p } diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index b2eff022d..0f93013a5 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -384,6 +384,8 @@ struct LayoutWriteData<'a> { flags: i64, page: &'a PageSetup, view: Option<(Vec2, f64)>, + /// The layout's limits as read (`None`: the default 0,0 to 12,9). + limits: Option<(Vec2, Vec2)>, } fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<'_>) { @@ -448,14 +450,18 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData< 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); + // The paper image origin the file had (#2109), else 0,0. + let origin = page.image_origin.filter(|o| o.is_finite()).unwrap_or(Vec2::ZERO); + w.f(148, origin.x); + w.f(149, origin.y); 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)); + // The layout's limits as the file had them (#2109), else 0,0 to 12,9. + let (lo, hi) = data.limits.filter(|(a, b)| a.is_finite() && b.is_finite()).unwrap_or((Vec2::ZERO, Vec2::new(12.0, 9.0))); + w.p2(10, lo); + w.p2(11, hi); w.p(12, Vec3::ZERO); w.p(14, Vec3::ZERO); w.p(15, Vec3::ZERO); @@ -524,7 +530,7 @@ 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 }, + LayoutWriteData { handle: model_layout, name: "Model", tab: 0, block_record: ms_br, flags: 1, page: &model_page, view: None, limits: None }, ); for (i, (_, brh, l)) in ps_brs.iter().enumerate() { let h = layout_handles.get(i).cloned().unwrap_or_default(); @@ -539,6 +545,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) { flags: 1, page: &l.page, view: l.view, + limits: l.limits, }, ); } diff --git a/crates/io/tests/it/layout_limits_roundtrip.rs b/crates/io/tests/it/layout_limits_roundtrip.rs new file mode 100644 index 000000000..31baea67d --- /dev/null +++ b/crates/io/tests/it/layout_limits_roundtrip.rs @@ -0,0 +1,64 @@ +//! A layout keeps its limits (LAYOUT groups 10/11) and its page's paper image origin +//! (groups 148/149) through a DXF and a DWG save, as the file had them, so another program puts +//! the sheet back where it was (#2109). A layout CADCraft made writes the defaults as before. + +use cadcraft_doc::geom::Vec2; +use cadcraft_doc::{Drawing, Layout}; +use cadcraft_io::{SaveOptions, Version, read, read_dxf, write_dxf, write_with}; + +/// A drawing whose layout has the limits and image origin of the ZWCAD file in #2109. +fn drawing() -> Drawing { + let mut d = Drawing::new_imperial(); + let mut layout = Layout::new("Sheet", 1); + layout.limits = Some((Vec2::new(1.038, 0.694), Vec2::new(9.506, 6.681))); + layout.page.image_origin = Some(Vec2::new(-1.054, -0.71)); + d.layouts = vec![layout]; + d +} + +fn sheet(d: &Drawing) -> &Layout { + d.layouts.iter().find(|l| l.name == "Sheet").expect("the layout") +} + +fn near(a: Vec2, b: Vec2) -> bool { + (a - b).len() < 1e-9 +} + +fn assert_kept(d: &Drawing, how: &str) { + let l = sheet(d); + let (lo, hi) = l.limits.unwrap_or_else(|| panic!("{how}: the limits are kept")); + assert!(near(lo, Vec2::new(1.038, 0.694)) && near(hi, Vec2::new(9.506, 6.681)), "{how}: {lo:?} {hi:?}"); + let origin = l.page.image_origin.unwrap_or_else(|| panic!("{how}: the image origin is kept")); + assert!(near(origin, Vec2::new(-1.054, -0.71)), "{how}: {origin:?}"); +} + +#[test] +fn a_layout_keeps_its_limits_and_image_origin_through_dxf() { + let back = read_dxf(write_dxf(&drawing()).as_bytes()).expect("reopen"); + assert_kept(&back, "DXF"); + // And again: a second save writes what the first read. + let again = read_dxf(write_dxf(&back).as_bytes()).expect("reopen"); + assert_kept(&again, "DXF twice"); +} + +#[test] +fn a_layout_keeps_its_limits_and_image_origin_through_dwg() { + let dwg = write_with(&drawing(), "t.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).expect("DWG"); + let back = read(&dwg, "t.dwg").expect("reopen"); + assert_kept(&back, "DWG"); +} + +#[test] +fn a_new_layout_writes_the_defaults() { + let text = write_dxf(&Drawing::new_imperial()); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + // The AcDbLayout limits after the layout's name, and the image origin before it. + let after = |code: &str| lines.windows(2).filter(|w| w[0] == code).map(|w| w[1]).collect::>(); + assert!(after("148").iter().all(|v| v.parse::() == Ok(0.0)), "{:?}", after("148")); + let back = read_dxf(text.as_bytes()).expect("reopen"); + let l = back.layouts.first().expect("a layout"); + // The defaults read back as none, so a drawing CADCraft made round-trips unchanged. + assert_eq!((l.limits, l.page.image_origin), (None, None)); + let limits = (after("10"), after("11")); + assert!(limits.0.iter().any(|v| v.parse::() == Ok(0.0)) && limits.1.iter().any(|v| v.parse::() == Ok(12.0)), "{limits:?}"); +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index aa77795fa..1601fc0ea 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -31,6 +31,7 @@ mod groups_roundtrip; mod hatch_assoc_roundtrip; mod hatch_pattern_def; mod helix_roundtrip; +mod layout_limits_roundtrip; mod layout_paper_units; mod layout_plot_window; mod leader_vertex_elevation; From ed08716f306f815a92d9c4a8ec6469403a249e2e Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 15:26:00 -0600 Subject: [PATCH 401/900] fix(io): the paper viewport a save adds is the sheet at the layout's plot scale (#2108) (#2624) A layout without a paper-space viewport (id 1) gets one on save, sized by the page alone; a custom plot scale (142/143) wasn't applied, so an A3 layout at 49.6 mm per unit got a 420 x 297 viewport around its 8.4 x 6 unit sheet, and its extents went wrong. paper_view divides the sheet by the layout's plot scale; a layout scaled to fit, at 1:1 or with an unusable scale writes what it did. Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/io/src/dxf_write/layout.rs | 11 ++++++++++- crates/io/tests/it/dwg_roundtrip_losses.rs | 23 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 4ad19ffbb..364648daf 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -33,12 +33,21 @@ pub(super) fn sheet_first(l: &Layout) -> Vec<&Entity> { all().filter(sheet).chain(all().filter(|e| !sheet(e))).collect() } +/// Paper units per paper-space unit of layout `l`: its custom plot scale (groups 142/143), so +/// the sheet is as large in paper space as it plots (a 420 mm sheet at 49.6 mm per unit is 8.47 +/// units wide, #2108). 1 when it is scaled to fit or the scale is unusable. +fn sheet_scale(l: &Layout) -> f64 { + let s = l.page.scale; + if l.page.scale_to_fit || !(s.is_finite() && (1e-6..=1e6).contains(&s)) { 1.0 } else { s } +} + /// The paper-space viewport (id 1) of the layout whose first viewport is `e`, if it needs one /// ([`paper_views`]): the whole sheet, viewed 1:1. Marked with CADCraft xdata so that our reader /// leaves it implicit again. pub(super) fn paper_view(w: &mut W, d: &Drawing, e: &Entity, owner: &str, cx: &Ctx) { let Some(l) = cx.paper_views.get(&e.handle).and_then(|i| d.layouts.get(*i)) else { return }; - let size = cadcraft_render::paper::sheet(d, &l.name).map(|s| s.size).unwrap_or(Vec2::new(12.0, 9.0)); + let paper = cadcraft_render::paper::sheet(d, &l.name).map(|s| s.size).unwrap_or(Vec2::new(12.0, 9.0)); + let size = paper / sheet_scale(l); let center = size * 0.5; let h = w.h(); w.s(0, "VIEWPORT"); diff --git a/crates/io/tests/it/dwg_roundtrip_losses.rs b/crates/io/tests/it/dwg_roundtrip_losses.rs index ec9c2b93d..aa00458a6 100644 --- a/crates/io/tests/it/dwg_roundtrip_losses.rs +++ b/crates/io/tests/it/dwg_roundtrip_losses.rs @@ -159,3 +159,26 @@ fn a_paper_viewport_behind_a_model_viewport_stays_id_1_through_dwg() { assert_eq!((id(model), id(sheet)), (Some(2), Some(1)), "layout {name}"); } } + +/// The paper-space viewport a save adds is the sheet as large as it plots: a layout with a custom +/// plot scale (here 49.6 mm of paper per unit, as in #2108's file) has an A3 sheet of 8.47 × 5.99 +/// units in paper space, not 420 × 297. A layout at 1:1 or scaled to fit keeps the page size. +#[test] +fn the_added_paper_viewport_follows_the_plot_scale() { + let sheet_width = |scale: f64, fit: bool| { + let mut d = Drawing::new_metric(); + let page = &mut d.layouts[0].page; + (page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, true); + (page.scale, page.scale_to_fit) = (scale, fit); + let first = Space::Paper(d.layouts[0].name.clone()); + d.add(&first, Common::default(), viewport(2)).unwrap(); + let text = cadcraft_io::write_dxf(&d); + let vps = records(&text, "VIEWPORT"); + assert_eq!(group(&vps[0], "1000"), Some("PAPERVIEW"), "{text}"); + group(&vps[0], "40").unwrap().parse::().unwrap() + }; + assert!((sheet_width(49.6, false) - 420.0 / 49.6).abs() < 1e-9, "{}", sheet_width(49.6, false)); + assert!((sheet_width(1.0, false) - 420.0).abs() < 1e-9); + assert!((sheet_width(49.6, true) - 420.0).abs() < 1e-9, "scaled to fit: the scale means nothing"); + assert!((sheet_width(f64::NAN, false) - 420.0).abs() < 1e-9, "an unusable scale is 1"); +} From f4c68e18fcd3e38d4122486c374e9d805cec8139 Mon Sep 17 00:00:00 2001 From: Elarionus <29511515+Elarionus@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:26:04 -0800 Subject: [PATCH 402/900] macOS: Quit (Cmd+Q), the Dock's Quit and logout ask to save unsaved drawings (#2157) (#2620) Quit CADCraft in the app menu, the Dock's Quit and logout end the app through AppKit's terminate, which skipped the "Save changes to ...?" prompt, so unsaved work was lost. The event loop now turns termination into a close request for the window (the storytold winit fork's opt-in, as DesignCraft does), so it asks first, as the close button does. Cancel keeps the app open; Force Quit can't be intercepted. Co-authored-by: Ethan Dale Co-authored-by: Claude Opus 5.5 --- apps/cadcraft/Cargo.toml | 3 +++ apps/cadcraft/src/main.rs | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index d8b4ef4c5..993668694 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -50,6 +50,9 @@ muda = { version = "0.21", default-features = false } # View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion # (system_animations.rs). Already in Cargo.lock through muda. objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] } +# The same winit eframe uses (the storytold fork, patched in the workspace): its opt-in that turns +# AppKit's terminate (Cmd+Q, Dock Quit) into a close request, so unsaved changes are asked about. +winit = { version = "0.30", default-features = false } # Rust HID backends: no proprietary SDK or C HID library. [target.'cfg(target_os = "windows")'.dependencies] diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index c591c10b3..98dd3c679 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -310,6 +310,16 @@ fn main() -> eframe::Result { b.with_x11(); })); } + // macOS: Quit CADCraft (Cmd+Q), the Dock's Quit and logout end the app through AppKit's + // terminate, which would skip the unsaved-changes prompt (#2157). winit turns each into a + // close request for the window instead, so it asks first, as the close button does. + #[cfg(target_os = "macos")] + { + options.event_loop_builder = Some(Box::new(|b| { + use winit::platform::macos::EventLoopBuilderExtMacOS; + b.with_close_requested_on_terminate(true); + })); + } eframe::run_native( "CADCraft", options, From 067439110048e717b5dc6598528994afeaea824d Mon Sep 17 00:00:00 2001 From: whaslbeck Date: Mon, 2 Nov 2026 22:26:09 +0100 Subject: [PATCH 403/900] fix(io): read drawings with many groups in linear time (#862) (#2645) * fix(io): read drawings with many groups in linear time (#862) Drawings can carry hundreds of thousands of empty anonymous groups (*A1, *A2, ...). Two places in the DXF reader were quadratic in their number: - apply_groups looked up each group by name with a linear search; it now uses an index keyed by the lower-case name, so the case-insensitive merge (the later definition wins) is unchanged. - retained_objects called is_xdict(parent) for every object before consulting its cache; for a group the parent is the ACAD_GROUP dictionary, which head() walks completely. is_xdict is now memoized per object index. Two drawings with 179,124 and 124,362 empty groups go from 388 s and 165 s (DWG to PDF) to 7.3 s and 8.0 s, with byte-identical output. * test(io): check that reading groups scales linearly (#862) The content test passes on the quadratic code as well, so add a scaling check: 16 times the groups (2,500 vs 40,000, best of three reads each) must take less than 64 times as long. With both fixes the ratio is about 21; without the name index it is about 218, without the is_xdict cache about 180. No wall-clock limit is involved. Also document apply_groups. --------- Co-authored-by: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> --- crates/io/src/dxf_raw.rs | 4 ++ crates/io/src/dxf_read/objects.rs | 17 +++++-- crates/io/tests/it/groups_roundtrip.rs | 62 ++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 16ea48b6c..ab18284ba 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -502,6 +502,10 @@ fn retained_objects( let modelled_entry = |tags: &[Tag], handle: &str| { entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && MODELLED_XDICT_KEYS.contains(&up(key).as_str())) }; + // is_xdict reads the whole record; a dictionary that owns many objects (ACAD_GROUP with + // hundreds of thousands of groups) would be read once per child (#862). + let mut xdict_memo: HashMap = HashMap::new(); + let mut is_xdict = |index: usize| *xdict_memo.entry(index).or_insert_with(|| is_xdict(index)); let mut retained = HashMap::new(); for index in 0..objects.len() { let mut path = Vec::new(); diff --git a/crates/io/src/dxf_read/objects.rs b/crates/io/src/dxf_read/objects.rs index 359dc887a..374313d48 100644 --- a/crates/io/src/dxf_read/objects.rs +++ b/crates/io/src/dxf_read/objects.rs @@ -153,8 +153,16 @@ impl Objects { } } + /// Add the groups named by the ACAD_GROUP dictionary entries, with the members that exist. + /// A name already present (compared case-insensitively) is replaced by the later definition. fn apply_groups(&self, d: &mut Drawing) { - // Groups (named by their ACAD_GROUP dictionary entries); members that exist. + // Names are matched through an index: a drawing can carry hundreds of thousands of + // (often empty) anonymous groups, and a linear search per group made loading quadratic + // (#862). + let mut by_name: HashMap = HashMap::new(); + for (i, g) in d.groups.iter().enumerate() { + by_name.entry(g.name.to_ascii_lowercase()).or_insert(i); + } for (h, tags) in &self.groups { let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue }; let t = T(tags); @@ -166,9 +174,12 @@ impl Objects { .take(MAX_OBJECTS) .collect(); let g = Group { name: name.clone(), description: t.s(300).unwrap_or_default(), selectable: t.i(71).unwrap_or(1) != 0, members }; - match d.groups.iter_mut().find(|x| x.name.eq_ignore_ascii_case(name)) { + match by_name.get(&name.to_ascii_lowercase()).and_then(|&i| d.groups.get_mut(i)) { Some(x) => *x = g, - None => d.groups.push(g), + None => { + by_name.insert(name.to_ascii_lowercase(), d.groups.len()); + d.groups.push(g); + } } } } diff --git a/crates/io/tests/it/groups_roundtrip.rs b/crates/io/tests/it/groups_roundtrip.rs index 394b3d482..8614dc757 100644 --- a/crates/io/tests/it/groups_roundtrip.rs +++ b/crates/io/tests/it/groups_roundtrip.rs @@ -29,3 +29,65 @@ fn groups_survive_dwg_round_trip() { .collect(); assert_eq!(got, vec![("Doors", "front", false, vec![5.0, 0.0]), ("*A1", "", true, vec![0.0])]); } + +/// A DXF with one LINE (handle 2A) and the given groups in ACAD_GROUP: `n` empty anonymous +/// groups `*A1`..`*An`, then the `named` ones `(name, handle, description)`, each holding the line. +fn groups_dxf(n: usize, named: &[(&str, &str, &str)]) -> String { + let mut dict = String::from("0\nDICTIONARY\n5\nC\n3\nACAD_GROUP\n350\nD\n0\nDICTIONARY\n5\nD\n330\nC\n"); + let mut groups = String::new(); + for i in 1..=n { + let h = format!("{:X}", 0x1000 + i); + dict.push_str(&format!("3\n*A{i}\n350\n{h}\n")); + groups.push_str(&format!("0\nGROUP\n5\n{h}\n330\nD\n300\n\n70\n1\n71\n1\n")); + } + for (name, h, text) in named { + dict.push_str(&format!("3\n{name}\n350\n{h}\n")); + groups.push_str(&format!("0\nGROUP\n5\n{h}\n330\nD\n300\n{text}\n70\n0\n71\n1\n340\n2A\n")); + } + format!( + "0\nSECTION\n2\nENTITIES\n0\nLINE\n5\n2A\n8\n0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n{dict}{groups}0\nENDSEC\n0\nEOF\n" + ) +} + +/// Drawings can carry hundreds of thousands of empty anonymous groups (#862). Every group +/// arrives, and a name repeated in another case still keeps one group, the later definition. +#[test] +fn many_anonymous_groups_read_and_names_merge_case_insensitively() { + const N: usize = 20_000; + let dxf = groups_dxf(N, &[("Doors", "100", "first"), ("DOORS", "101", "second")]); + let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read"); + assert_eq!(d.groups.len(), N + 1); + assert!(d.groups.iter().take(N).enumerate().all(|(i, g)| g.name == format!("*A{}", i + 1) && g.members.is_empty())); + let doors: Vec<(&str, &str, usize)> = d + .groups + .iter() + .filter(|g| g.name.eq_ignore_ascii_case("doors")) + .map(|g| (g.name.as_str(), g.description.as_str(), g.members.len())) + .collect(); + assert_eq!(doors, [("DOORS", "second", 1)]); +} + +/// Reading groups scales linearly (#862): 16 times the groups take about 16 to 20 times as long, +/// where the former quadratic lookups took about 256 times as long. The bound compares the two +/// sizes with each other, not with a wall-clock limit, and leaves room for timing noise; each +/// size is timed as the best of three reads. +#[test] +fn reading_groups_scales_linearly() { + let best_of_three = |n: usize| { + let dxf = groups_dxf(n, &[]); + (0..3) + .map(|_| { + let t = std::time::Instant::now(); + let d = cadcraft_io::read_dxf(dxf.as_bytes()).expect("read"); + assert_eq!(d.groups.len(), n); + t.elapsed() + }) + .min() + .unwrap_or_default() + }; + let small = best_of_three(2_500); + let large = best_of_three(40_000); + let ratio = large.as_secs_f64() / small.as_secs_f64().max(1e-6); + assert!(ratio < 64.0, "16x the groups took {ratio:.1}x as long ({small:?} -> {large:?})"); +} From fbd6e676f8353c9e46a67717d8bc39a4d2b813b3 Mon Sep 17 00:00:00 2001 From: CA Date: Tue, 3 Nov 2026 01:26:14 +0400 Subject: [PATCH 404/900] DWG save keeps OLE objects (OLE2FRAME): stop reporting them as not saved (#2582) * DWG save keeps OLE objects (OLE2FRAME): stop reporting them as not saved acadrust reads OLE2FRAME from our DXF into its own entity and writes it to DWG of every version we save, frame and embedded data unchanged; only the "Not saved in the DWG file" warning (and the QSAVE loss prompt) listed it. not_saved_as now skips the types the DWG bridge writes (DWG_WRITES). Tests: a synthetic OLE2FRAME through DWG (resaved, and as 2000 and 2010 DWG) keeps every byte; OLE objects are not reported at any version. Co-Authored-By: Claude Opus 5.5 * DWG_WRITES matches the type as stored, not case-insensitively The DXF given to the DWG bridge carries an unknown entity's type as stored, and acadrust reads only "OLE2FRAME" into its OLE entity: any other spelling becomes its Unknown and is dropped, so it must stay in the "Not saved" report. The test adds a lower-case "ole2frame" that is still listed. (Review comment on #2582.) Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/file.rs | 11 +- crates/engine/tests/save_reports_not_saved.rs | 20 ++++ crates/io/tests/it/main.rs | 2 + crates/io/tests/it/ole2frame_roundtrip.rs | 113 ++++++++++++++++++ 4 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 crates/io/tests/it/ole2frame_roundtrip.rs diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 234769ad4..3b24e87bd 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -742,8 +742,14 @@ 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"]; +/// Entity types CADCraft doesn't model that the DWG bridge writes all the same: acadrust reads +/// them from our DXF into entities of its own and writes them to DWG of every version we save, +/// an OLE object with its frame and its embedded object's bytes unchanged. Matched exactly: the +/// bridge gets the type as stored, and acadrust knows only this spelling of it. +const DWG_WRITES: [&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. +/// store has a record for keeps its geometry and is not counted; neither are [`DWG_WRITES`]. 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() }; @@ -753,6 +759,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 DWG_WRITES.contains(&u.dxf_type.as_str()) { + 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..24a2dff92 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -82,3 +82,23 @@ 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()); } + +/// The DWG bridge writes OLE objects (`ole2frame_roundtrip` in the io tests), so saving one as +/// DWG reports nothing for them, at any version, while other unmodelled types are still listed. +/// The type is matched as stored: the bridge gets it as stored too, and acadrust reads only the +/// upper-case spelling into its OLE entity, so any other spelling is still reported. +#[test] +fn ole_objects_are_not_reported() { + 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(); + d.add(&Space::Model, Common::default(), unknown("ole2frame")).unwrap(); + let mut b = Block::new("Logo"); + let h = d.new_handle(); + b.entities.push(cadcraft_engine::doc::Entity { handle: h, common: Common::default(), kind: unknown("OLE2FRAME") }); + d.blocks.insert("Logo".into(), std::sync::Arc::new(b)); + for v in [Version::R2000, Version::R2010, Version::R2018] { + assert_eq!(not_saved_as(&d, v), [("MLINE".to_string(), 1), ("ole2frame".to_string(), 1)].into_iter().collect(), "{v:?}"); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 1601fc0ea..7b49eb6bf 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -46,6 +46,8 @@ mod mtext_columns_roundtrip; mod mtext_embedded_object; mod mtext_line_spacing; mod multiline_attributes; +#[cfg(not(target_arch = "wasm32"))] +mod ole2frame_roundtrip; mod paperview_marker; mod passthrough_image_roundtrip; mod pdf_followups; diff --git a/crates/io/tests/it/ole2frame_roundtrip.rs b/crates/io/tests/it/ole2frame_roundtrip.rs new file mode 100644 index 000000000..2491d30d4 --- /dev/null +++ b/crates/io/tests/it/ole2frame_roundtrip.rs @@ -0,0 +1,113 @@ +//! OLE objects (OLE2FRAME: a picture, a spreadsheet or a document embedded in the drawing) +//! survive a DWG save. CADCraft doesn't model them and keeps them as read; the DWG bridge reads +//! them from our DXF into acadrust's own entity and writes them to DWG with their frame and the +//! embedded object's bytes, so a drawing saved as DWG and reopened still has them. + +use cadcraft_doc::EntityKind; + +/// Stand-in OLE data as a DWG carries it: a two-byte marker, the frame's four corners (upper +/// left, upper right, lower right, lower left; x, y, z doubles), then the object's bytes, here +/// opaque text long enough to take several 310 groups. +fn payload() -> Vec { + let mut data = vec![0x80, 0x00]; + for [x, y] in [[10.0f64, 40.0], [70.0, 40.0], [70.0, 5.0], [10.0, 5.0]] { + for v in [x, y, 0.0] { + data.extend_from_slice(&v.to_le_bytes()); + } + } + for i in 0..12u8 { + data.extend_from_slice(b"synthetic embedded object "); + data.push(i); + } + data +} + +fn hex(data: &[u8]) -> String { + data.iter().map(|b| format!("{b:02X}")).collect() +} + +/// A 2018 DXF with one embedded OLE object in model space on layer `Pictures`. +fn dxf() -> String { + let data = payload(); + let chunks: String = data.chunks(127).map(|c| format!("310\n{}\n", hex(c))).collect(); + format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n\ + 0\nOLE2FRAME\n5\n2A\n330\n1F\n100\nAcDbEntity\n8\nPictures\n100\nAcDbOle2Frame\n70\n2\n\ + 10\n10\n20\n40\n30\n0\n11\n70\n21\n5\n31\n0\n71\n2\n72\n0\n73\n2\n90\n{}\n{chunks}1\nOLE\n\ + 0\nENDSEC\n0\nEOF\n", + data.len() + ) +} + +/// Each OLE2FRAME of DXF text as its (code, value) pairs. +fn frames(text: &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 == "OLE2FRAME"; + 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()) +} + +fn number(rec: &[(String, String)], code: &str) -> Option { + group(rec, code).and_then(|v| v.parse().ok()) +} + +/// The embedded object's bytes: the 310 groups joined. +fn data(rec: &[(String, String)]) -> String { + rec.iter().filter(|(c, _)| c == "310").map(|(_, v)| v.as_str()).collect() +} + +/// The frame, its object's bytes, type and layer as the DWG keeps them. +fn assert_kept(rec: &[(String, String)]) { + assert_eq!(data(rec), hex(&payload()), "the embedded object's bytes changed"); + assert_eq!(number(rec, "90"), Some(payload().len() as f64)); + let corners: Vec> = ["10", "20", "11", "21"].iter().map(|c| number(rec, c)).collect(); + assert_eq!(corners, [Some(10.0), Some(40.0), Some(70.0), Some(5.0)]); + assert_eq!(group(rec, "71"), Some("2"), "an embedded object"); + assert_eq!(group(rec, "73"), Some("2")); + assert_eq!(group(rec, "8"), Some("Pictures")); +} + +#[test] +fn dwg_keeps_ole_objects() { + let d = cadcraft_io::read_dxf(dxf().as_bytes()).unwrap(); + let ole = |d: &cadcraft_doc::Drawing| d.model.iter().filter(|e| matches!(&e.kind, EntityKind::Unknown(u) if u.dxf_type == "OLE2FRAME")).count(); + assert_eq!(ole(&d), 1); + + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let got = frames(&back); + assert_eq!(got.len(), 1, "{got:?}"); + assert_kept(&got[0]); + + // Reopened in CADCraft it is in model space again, and a second DWG save keeps it too. + let again = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(ole(&again), 1); + let dwg = cadcraft_io::write(&again, "x.dwg").unwrap(); + let got = frames(&String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap()); + assert_eq!(got.len(), 1, "{got:?}"); + assert_kept(&got[0]); + + // Older DWG versions keep it the same way. + for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] { + let dwg = cadcraft_io::write_with(&d, "x.dwg", &cadcraft_io::SaveOptions { version: Some(version), binary: false }).unwrap(); + let got = frames(&String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap()); + assert_eq!(got.len(), 1, "{version:?}: {got:?}"); + assert_kept(&got[0]); + } +} From 25ca90581517a05eef4193fcb995836f91885124 Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 15:26:18 -0600 Subject: [PATCH 405/900] fix(fonts): single-line TEXT runs left to right, as AutoCAD lays it out (#2500) (#2618) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(fonts): single-line TEXT runs left to right, as AutoCAD lays it out (#2500) A TEXT "- פרוייקט" took its direction from its first strong character (Hebrew), so the leading dash went to the right of the word; AutoCAD shows it on the left. complex::shape now takes the base direction (shape_stroke_dir, ttf::shape_dir and shape_line_dir pass it on), and TEXT's layout (fonts::place and its frame) asks for left to right. MTEXT and the existing entry points keep taking the direction from the text. Co-Authored-By: Claude Opus 5.5 * fix(fonts): a right-to-left base reaches LTR-only lines; Fit TEXT is measured as placed From the review of #2618: shape_stroke_dir and ttf::shape_dir took the simple, left-to-right path whenever a line had no right-to-left letter, so an explicit right-to-left base did nothing there; such a line now takes the bidi path. And Fit/Aligned TEXT was measured with the direction from its content but placed left to right, so a line whose last glyph changed (a stroke-font gap) missed its second point; it is measured with the direction it is placed in. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: austin62jake <340374338+austin62jake@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/fonts/src/complex.rs | 23 +++++++------- crates/fonts/src/lib.rs | 60 ++++++++++++++++++++++++++++++++----- crates/fonts/src/ttf.rs | 12 ++++++-- 3 files changed, 73 insertions(+), 22 deletions(-) diff --git a/crates/fonts/src/complex.rs b/crates/fonts/src/complex.rs index 4a4ac461f..ce2fbcb61 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -64,20 +64,21 @@ impl Src { /// Shape one line containing right-to-left text in `primary` (None: the stroke font), with the /// same conventions as the left-to-right paths: baseline at y = 0, x from 0, text height = cap -/// height, `%%` codes decoded. `None` when the line is too long (the caller then lays it out one -/// glyph per character) or shaping failed. -pub(crate) fn shape(primary: Option<&Face>, s: &str, height: f64, width_factor: f64, oblique: f64) -> Option { +/// height, `%%` codes decoded. `base_rtl` is the line's direction (`None`: that of its first +/// strong character). `None` when the line is too long (the caller then lays it out one glyph +/// per character) or shaping failed. +pub(crate) fn shape(primary: Option<&Face>, s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Option { let chars = crate::decode_controls(s); if chars.is_empty() || chars.len() > MAX_CHARS { return None; } // A last-resort guard around the bidi and shaping libraries: a panic in them must not take // the drawing down with it (the line then falls back to one glyph per character). - catch_unwind(AssertUnwindSafe(|| shape_chars(primary, &chars, height, width_factor, oblique))).ok() + catch_unwind(AssertUnwindSafe(|| shape_chars(primary, &chars, height, width_factor, oblique, base_rtl))).ok() } /// Lay out decoded directional runs, keeping advances and decoration spans for empty glyphs. -fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64, width_factor: f64, oblique: f64) -> Shaped { +fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> 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 shear = oblique.tan().clamp(-10.0, 10.0); @@ -90,7 +91,7 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 let mut x = 0.0; // Whether the rightmost glyph so far is a stroke-font glyph. let mut stroke_last = false; - for (run, rtl) in bidi::visual_runs(&cs, None) { + for (run, rtl) in bidi::visual_runs(&cs, base_rtl) { let mut pieces = itemize(&cs, run, primary); if rtl { pieces.reverse(); @@ -325,13 +326,13 @@ mod tests { #[test] fn empty_complex_glyph_keeps_advance_without_geometry() { let face = empty_glyph_face(); - let shaped = shape(Some(&face), " ", 1.0, 1.0, 0.0).expect("shapes empty glyph"); + let shaped = shape(Some(&face), " ", 1.0, 1.0, 0.0, None).expect("shapes empty glyph"); assert!(shaped.width > 0.0, "the font's advance is retained"); assert!(shaped.is_empty()); assert!(shaped.glyphs.is_empty()); assert!(shaped.text.is_empty()); - let underlined = shape(Some(&face), "%%u ", 1.0, 1.0, 0.0).expect("shapes decorated empty glyph"); + let underlined = shape(Some(&face), "%%u ", 1.0, 1.0, 0.0, None).expect("shapes decorated empty glyph"); assert_eq!(underlined.width, shaped.width); assert!(underlined.glyphs.is_empty()); assert!(underlined.text.is_empty()); @@ -344,7 +345,7 @@ mod tests { // missing-glyph boxes, the digits stay stroke glyphs, in the middle of the line (between // the two words), and the measured width matches the shaped one. let s = "قیمت 25 تومان"; - let sh = shape(None, s, 1.0, 1.0, 0.0).unwrap_or_default(); + let sh = shape(None, s, 1.0, 1.0, 0.0, None).unwrap_or_default(); assert!(sh.width > 0.0); assert!((crate::line_width(s, 1.0, 1.0) - sh.width).abs() < 1e-9); let digits: Vec = sh.strokes.iter().filter(|st| !(st.len() == 5 && st.first() == st.last())).flatten().map(|p| p.x).collect(); @@ -535,7 +536,7 @@ mod tests { let marks = format!("ก{}", "\u{0E48}".repeat(MAX_CHARS - 1)); assert!(crate::shape_stroke(&marks, 1.0, 1.0, 0.0).width > 0.0); let long = "ก".repeat(MAX_CHARS + 1); - assert!(shape(None, &long, 1.0, 1.0, 0.0).is_none()); + assert!(shape(None, &long, 1.0, 1.0, 0.0, None).is_none()); assert!(crate::shape_stroke(&long, 1.0, 1.0, 0.0).width > 0.0); } @@ -546,7 +547,7 @@ mod tests { let _ = crate::line_width(s, 0.0, 0.0); } let long = "\u{05D0}b ".repeat(MAX_CHARS); - assert!(shape(None, &long, 1.0, 1.0, 0.0).is_none()); + assert!(shape(None, &long, 1.0, 1.0, 0.0, None).is_none()); assert!(crate::shape_stroke(&long, 1.0, 1.0, 0.0).width > 0.0); } } diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index beb8996ff..983110b4d 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -147,6 +147,12 @@ fn stroke_advance(c: char, h: f64, wf: f64) -> f64 { /// (radians). Characters the stroke font lacks are drawn from an installed font that has them /// (glyph outlines, sized like TrueType text), else as a missing-glyph box. pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Shaped { + shape_stroke_dir(s, height, width_factor, oblique, None) +} + +/// [`shape_stroke`] in the direction `base_rtl` (`None`: that of the line's first strong +/// character). +pub fn shape_stroke_dir(s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> 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 sc = h / stroke::CAP; @@ -156,8 +162,10 @@ pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Sh let mut under_start: Option = None; let mut over_start: Option = None; let mut gap = stroke::GAP * sc * wf; - if complex::needed(s) - && let Some(sh) = complex::shape(None, s, h, wf, oblique) + // The simple path lays a line out left to right: one asked to run right to left goes through + // the bidi path even without right-to-left letters. + if (complex::needed(s) || base_rtl == Some(true)) + && let Some(sh) = complex::shape(None, s, h, wf, oblique, base_rtl) { return sh; } @@ -250,7 +258,7 @@ pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { if complex::needed(s) { 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 }; - if let Some(sh) = complex::shape(None, s, h, wf, 0.0) { + if let Some(sh) = complex::shape(None, s, h, wf, 0.0, None) { return sh.width; } } @@ -417,14 +425,24 @@ pub(crate) fn decorations(spans: &[(f64, f64, bool, bool)], h: f64) -> Vec Shaped { + shape_line_dir(font, s, height, width_factor, oblique, None) +} + +/// [`shape_line`] in the direction `base_rtl` (`None`: that of the line's first strong +/// character). +pub fn shape_line_dir(font: &TextFont, s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Shaped { if let TextFont::Outline(face) = font - && let Some(sh) = ttf::shape(face, s, height, width_factor, oblique) + && let Some(sh) = ttf::shape_dir(face, s, height, width_factor, oblique, base_rtl) { return sh; } - shape_stroke(s, height, width_factor, oblique) + shape_stroke_dir(s, height, width_factor, oblique, base_rtl) } +/// Single-line TEXT (and attributes) runs left to right, as AutoCAD lays it out: neutral +/// characters before a right-to-left word ("- " in "- פרוייקט") stay on its left (#2500). +const TEXT_BASE_RTL: Option = Some(false); + /// Width of one line in `font`. pub fn text_width(font: &TextFont, s: &str, height: f64, width_factor: f64) -> f64 { if let TextFont::Outline(face) = font @@ -551,7 +569,7 @@ fn frame(font: &TextFont, s: &str, p: &TextParams) -> (Vec2, Vec2, f64, Vec2) { let rot = p.align_pt.map_or(rot, |p2| p.insert.angle_to(p2)); return (p.insert, Vec2::ZERO, rot, Vec2::new(1.0, 1.0)); } - let sh = shape_line(font, s, height, p.width_factor, p.oblique); + let sh = shape_line_dir(font, s, height, p.width_factor, p.oblique, TEXT_BASE_RTL); let origin = match (p.h, p.v) { (Align::Left, VAlign::Baseline) => p.insert, _ => p.align_pt.unwrap_or(p.insert), @@ -572,7 +590,9 @@ pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { { let len = insert.dist(p2); rot = insert.angle_to(p2); - let w = text_width(font, s, height, wf); + // Measured as it is placed, left to right: the stroke font's trailing gap follows the + // glyph that ends the line. + let w = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL).width; if w > 1e-12 && len > 1e-12 { let k = len / w; if p.h == Align::Aligned { @@ -582,7 +602,7 @@ pub fn place(font: &TextFont, s: &str, p: &TextParams) -> (Shaped, Bounds2) { } } } - let mut sh = shape_line(font, s, height, wf, p.oblique); + let mut sh = shape_line_dir(font, s, height, wf, p.oblique, TEXT_BASE_RTL); let width = sh.width; // Every justification but baseline-left (and aligned/fit, which span both points) is placed by // its alignment point (DXF group 11); the insertion point (group 10) is then a computed point. @@ -625,6 +645,30 @@ pub fn place_text( mod tests { use super::*; + /// A TEXT that starts with neutral characters before a Hebrew word ("- פרוייקט") keeps them + /// on the left, as AutoCAD draws it; the line's own direction (first strong character) would + /// put the dash on the right (#2500). + #[test] + fn text_runs_left_to_right_whatever_its_first_strong_character() { + let s = "- \u{05E4}\u{05E8}\u{05D5}\u{05D9}\u{05E7}\u{05D8}"; + let dash = shape_stroke("-", 1.0, 1.0, 0.0).strokes; + assert!(!dash.is_empty()); + let has_dash_first = |strokes: &[Vec]| dash.iter().all(|d| strokes.iter().any(|st| st == d)); + let (text, _) = place(&TextFont::Stroke, s, &TextParams::new(Vec2::ZERO, 1.0)); + assert!(has_dash_first(&text.strokes), "the dash starts the TEXT"); + // The line on its own (MTEXT pieces) still takes its direction from its first strong + // character: right to left here, the dash after the word. + let line = shape_stroke(s, 1.0, 1.0, 0.0); + assert!(!has_dash_first(&line.strokes), "the dash ends a right-to-left line"); + // A line asked to run right to left does so without right-to-left letters too. + assert!(has_dash_first(&shape_stroke_dir("- abc", 1.0, 1.0, 0.0, None).strokes)); + assert!(!has_dash_first(&shape_stroke_dir("- abc", 1.0, 1.0, 0.0, Some(true)).strokes), "the dash after the word"); + // Fit TEXT is measured as it is placed, so it spans its two points exactly. + let fit = TextParams { h: Align::Fit, align_pt: Some(Vec2::new(10.0, 0.0)), ..TextParams::new(Vec2::ZERO, 1.0) }; + let (text, _) = place(&TextFont::Stroke, s, &fit); + assert!((text.width - 10.0).abs() < 1e-9, "{}", text.width); + } + #[test] fn every_ascii_printable_has_a_glyph() { for c in ' '..='~' { diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index c426db243..fff4ecde7 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -894,9 +894,15 @@ pub(crate) fn place_glyph_at(g: &GlyphOutline, origin: Vec2, scale: f64, wf: f64 /// y = 0, x from 0) plus `%%u`/`%%o` decorations as strokes. Text height = cap height. /// Characters the face lacks come from a fallback font, scaled to its own cap height. pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) -> Option { + shape_dir(face, s, height, width_factor, oblique, None) +} + +/// [`shape`] in the direction `base_rtl` (`None`: that of the line's first strong character). +pub fn shape_dir(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64, base_rtl: Option) -> Option { face.font()?; - if crate::complex::needed(s) - && let Some(sh) = crate::complex::shape(Some(face), s, height, width_factor, oblique) + // As in [`crate::shape_stroke_dir`]: a line asked to run right to left takes the bidi path. + if (crate::complex::needed(s) || base_rtl == Some(true)) + && let Some(sh) = crate::complex::shape(Some(face), s, height, width_factor, oblique, base_rtl) { return Some(sh); } @@ -934,7 +940,7 @@ pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option { face.font()?; if crate::complex::needed(s) - && let Some(sh) = crate::complex::shape(Some(face), s, height, width_factor, 0.0) + && let Some(sh) = crate::complex::shape(Some(face), s, height, width_factor, 0.0, None) { return Some(sh.width); } From c0306b1af3d1f6f21c4563045a11963cc3d5dc59 Mon Sep 17 00:00:00 2001 From: Elarionus <29511515+Elarionus@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:26:23 -0800 Subject: [PATCH 406/900] Remember the main window's size, position and maximized state between sessions (#2595) (#2604) * Remember the main window's size, position and maximized state between sessions (#2595) The main window opened at its default size, centred, on every launch: eframe's window persistence was turned off (persist_window: false), and `centered` is applied over any saved position. The window state is now saved; on launch, if app.ron holds a saved window, it is restored (eframe keeps it on the connected monitors) and not centred. Only the first launch, with nothing saved, opens centred (#1129). Wayland places windows itself, so only size and maximized state return there. Co-Authored-By: Claude Opus 5.5 * Docs: leave the parity docs to the maintainers The affected rows are named in the PR description instead (CLAUDE.md: PRs do not edit the parity docs). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Ethan Dale Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 1 + apps/cadcraft/Cargo.toml | 3 ++ apps/cadcraft/src/main.rs | 61 +++++++++++++++++++++++++++++++-------- 3 files changed, 53 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 81a772f6e..b5210faea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -632,6 +632,7 @@ dependencies = [ "muda", "objc2-app-kit 0.3.2", "rfd", + "ron", "serde_json", "sys-locale", "thiserror 2.0.21", diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index 993668694..ee1b8b9c8 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -24,6 +24,9 @@ log = { workspace = true } clap = { workspace = true } thiserror = { workspace = true } chrono = { workspace = true } +# Reads eframe's app.ron to tell whether a window state was saved (main.rs `saved_window`). +# Already in Cargo.lock through eframe; same version so nothing is built twice. +ron = "0.12" [build-dependencies] winresource = "0.1" diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 98dd3c679..3454dc35f 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -127,7 +127,8 @@ impl eframe::App for App { self.cad.cancel_screenshots(); self.cad.shutdown_autosave(); } - /// Preferences (the interface theme) survive restarts; window and egui state are not kept. + /// Preferences (the interface theme) survive restarts; eframe saves the window state itself + /// (`persist_window`); egui state is not kept. fn save(&mut self, storage: &mut dyn eframe::Storage) { storage.set_string(cadcraft_ui_egui::options::PROFILE_KEY, self.cad.profile_json()); storage.set_string(cadcraft_ui_egui::PREFS_KEY, self.cad.prefs_json()); @@ -194,8 +195,20 @@ fn filters_for_save(name: &str) -> [(&'static str, &'static str); 6] { filters } -/// The main window: its size, title bar, placement and rendering needs. -fn window_options() -> eframe::NativeOptions { +/// Whether eframe's storage file (`app.ron`, a map of keys to strings) holds a saved main window +/// state. An unreadable or malformed file counts as none, as it does for eframe. +fn saved_window(app_ron: &str) -> bool { + ron::from_str::>(app_ron).is_ok_and(|kv| kv.contains_key(WINDOW_KEY)) +} + +/// The window state from the last session is saved and will be restored (#2595). +fn restores_window() -> bool { + eframe::storage_dir(APP_ID).and_then(|dir| std::fs::read_to_string(dir.join("app.ron")).ok()).is_some_and(|ron| saved_window(&ron)) +} + +/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state +/// saved by the last session is restored instead of opening centred. +fn window_options(restoring: bool) -> eframe::NativeOptions { eframe::NativeOptions { viewport: egui::ViewportBuilder::default() .with_title("CADCraft") @@ -206,10 +219,13 @@ fn window_options() -> eframe::NativeOptions { .with_titlebar_shown(false) .with_title_shown(false) .with_app_id(APP_ID), - persist_window: false, - // The window opens centred on its screen, not cascaded from the top-left corner (#1129). + // The size, position and maximized state are kept between sessions (#2595); eframe keeps a + // restored window on the monitors that are connected now. + persist_window: true, + // The first launch opens centred on its screen, not cascaded from the top-left corner + // (#1129); later launches go back where the window was (eframe would centre over that). // Wayland compositors place windows themselves. - centered: true, + centered: !restoring, // CADCraft installs its own capped font chain (`theme::install_fonts`); never run // system-font discovery as a hidden fallback. system_font_fallback: false, @@ -221,6 +237,9 @@ fn window_options() -> eframe::NativeOptions { const APP_ID: &str = "ai.storyteller.cadcraft"; +/// The key eframe saves the main window state under in its storage. +const WINDOW_KEY: &str = "window"; + /// Stencil bits of the window's render pass (see `NativeOptions::stencil_buffer`). const STENCIL_BITS: u8 = 8; @@ -281,7 +300,7 @@ fn main() -> eframe::Result { // The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11 // swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync). wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface), - ..window_options() + ..window_options(restores_window()) }; if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); @@ -403,7 +422,7 @@ fn main() -> eframe::Result { #[cfg(test)] mod tests { - use super::{filters_for_save, follow_desktop, window_options}; + use super::{filters_for_save, follow_desktop, saved_window, window_options}; #[test] fn save_dialog_offers_dwg_with_the_drawing_format_first() { @@ -421,12 +440,30 @@ mod tests { } } - /// #1129: the window opens centred, not cascaded from the top-left corner. + /// #1129: the first launch opens centred, not cascaded from the top-left corner. #[test] - fn the_window_opens_centred() { - let o = window_options(); + fn the_first_launch_opens_centred() { + let o = window_options(false); assert!(o.centered, "centred on launch"); - assert!(!o.persist_window, "no saved position to restore instead"); + assert!(o.persist_window, "the window state is saved for the next launch"); + } + + /// #2595: a saved window state (size, position, maximized) is restored, not centred over. + #[test] + fn a_saved_window_reopens_where_it_was() { + let o = window_options(true); + assert!(!o.centered, "centring would move a restored window"); + assert!(o.persist_window); + } + + /// Only a readable `app.ron` with a window entry counts as a saved window state. + #[test] + fn a_saved_window_is_read_from_app_ron() { + assert!(saved_window(r#"{"cadcraft.prefs": "{}", "window": "(maximized: true)"}"#)); + assert!(!saved_window(r#"{"cadcraft.prefs": "{\"window\":1}"}"#), "a value mentioning it is not the key"); + assert!(!saved_window("")); + assert!(!saved_window("{\"window\": "), "truncated"); + assert!(!saved_window("not ron at all")); } /// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in; From 4a17ee78c24407cfc1470bb6a336ea3432ca0a60 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:26:28 +0100 Subject: [PATCH 407/900] Reject invalid fill angles in JSON arraypolar (#2655) Found while testing crates/engine/src/cmd/array.rs:380 (run_arraypolar, `fill: f64_or(p, "angle", 360.0)`) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd/array.rs | 6 +++++- crates/engine/tests/it/array_commands.rs | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index 255555a28..da96ccfed 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -374,10 +374,14 @@ fn run_arraypolar(s: &mut Session, p: &Value) -> Result { 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 row_spacing = f64_or(p, "rowSpacing", 1.0); + let fill = f64_or(p, "angle", 360.0); + if !(fill.abs() >= 1e-9 && fill.abs() <= 360.0 + 1e-9) { + return Err(other("Requires a fill angle between -360 and 360 degrees (not 0).")); + } let kind = ArrayKind::Polar(PolarArray { center: c - base, items: count32(n), - fill: f64_or(p, "angle", 360.0), + fill: fill.clamp(-360.0, 360.0), rotate: bool_or(p, "rotate", true), rows: count32(rows), row_spacing, diff --git a/crates/engine/tests/it/array_commands.rs b/crates/engine/tests/it/array_commands.rs index d420c36d6..61d5a0d02 100644 --- a/crates/engine/tests/it/array_commands.rs +++ b/crates/engine/tests/it/array_commands.rs @@ -212,3 +212,20 @@ fn arrays_over_maxarray_are_refused_not_shrunk() { assert!(s.current_prompt().is_none(), "{}", prompt(&s)); assert_eq!(circle_centers(&s).len(), 2000); } + +#[test] +fn json_arraypolar_rejects_bad_fill_angles() { + let mut s = Session::new(); + let h = s.execute("circle", &json!({"center": [5, 0], "radius": 1})).unwrap()["handle"].clone(); + let before = s.doc().unwrap().model.iter().count(); + for bad in [0.0, 720.0, -400.0, 360.5] { + let p = json!({"handles": [h], "center": [0, 0], "count": 4, "angle": bad, "associative": false}); + let e = s.execute("arraypolar", &p).unwrap_err(); + assert!(e.to_string().contains("Requires a fill angle between -360 and 360 degrees"), "{bad}: {e}"); + assert_eq!(s.doc().unwrap().model.iter().count(), before, "{bad}"); + } + for ok in [360.0, -360.0] { + let p = json!({"handles": [h], "center": [0, 0], "count": 4, "angle": ok, "associative": false}); + s.execute("arraypolar", &p).unwrap(); + } +} From e6352d955ee4cc264fd5d26642d666c20cf8d062 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:26:33 +0100 Subject: [PATCH 408/900] Reject control characters in layer names (#2569) Found while testing crates/engine/src/cmd/layer.rs:184 (valid_name, used by run_new) Co-authored-by: Claude Haiku 5.5 --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/tests/layer_name_control_chars.rs | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 crates/engine/tests/layer_name_control_chars.rs diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 806641ef6..c5fa89403 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -182,7 +182,7 @@ fn loaded_linetype(d: &cadcraft_doc::Drawing, cmd: &str, p: &Value) -> Result bool { - !n.trim().is_empty() && n.len() <= 255 && !n.chars().any(|c| "<>/\\\":;?*|,=`".contains(c)) + !n.trim().is_empty() && n.len() <= 255 && !n.chars().any(|c| c.is_control() || "<>/\\\":;?*|,=`".contains(c)) } fn run_new(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/tests/layer_name_control_chars.rs b/crates/engine/tests/layer_name_control_chars.rs new file mode 100644 index 000000000..4e00a1454 --- /dev/null +++ b/crates/engine/tests/layer_name_control_chars.rs @@ -0,0 +1,14 @@ +//! `layer.new` refuses control characters in a layer name (the DXF writer would turn them into +//! spaces and the name would change on reopen). + +use cadcraft_engine::Session; +use serde_json::json; + +#[test] +fn layer_new_rejects_control_characters() { + let mut s = Session::new(); + for name in ["A\nB", "A\tB", "A\u{0}B"] { + assert!(s.execute("layer.new", &json!({"name": name})).is_err(), "{name:?} was accepted"); + } + assert!(s.execute("layer.new", &json!({"name": "A B"})).is_ok()); +} From ad95791c206a2722294bf3b397f82df90f026a6e Mon Sep 17 00:00:00 2001 From: Ashok Ram Date: Tue, 3 Nov 2026 02:56:38 +0530 Subject: [PATCH 409/900] SVG import: a transform on a shape element moves the shape (#2602) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SVG 1.1 §7.5 lets every graphics element carry a transform. Only groups' transforms were applied, so a rect, circle, path or other shape with its own transform came in where it would be without one. on_element now composes the element's transform after its groups' for that element only, the way a group around it would. https://www.w3.org/TR/SVG11/coords.html#TransformAttribute Co-authored-by: ashokram-si <347905169+ashokram-si@users.noreply.github.com> --- crates/io/src/svg_read.rs | 17 ++++++++++++++-- crates/io/src/tests.rs | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/crates/io/src/svg_read.rs b/crates/io/src/svg_read.rs index 21508fe7b..54ef9d846 100644 --- a/crates/io/src/svg_read.rs +++ b/crates/io/src/svg_read.rs @@ -1,8 +1,8 @@ //! SVG → Drawing: the static W3C SVG subset that drawing tools emit. //! //! Reads shapes (`rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`), `path` -//! outlines (`M L H V C S Q T A Z`, absolute and relative), `g` grouping with `transform` -//! attributes, `viewBox` and unit-bearing `width`/`height`, and Inkscape layers +//! outlines (`M L H V C S Q T A Z`, absolute and relative), `g` grouping, `transform` on groups +//! and shapes, `viewBox` and unit-bearing `width`/`height`, and Inkscape layers //! (`inkscape:groupmode="layer"`). Geometry becomes centre-line entities in millimetres with //! the page's top-left corner at the origin and Y pointing up — where a laser or pen job //! wants it. @@ -262,6 +262,19 @@ impl Parser { } return Ok(()); } + // A shape's own `transform` (SVG 1.1 §7.5) maps it after its groups', for this element only. + let local = attr(e, b"transform").as_deref().and_then(parse_transform); + if let Some(local) = local { + self.stack.push(self.cur().then_before(local)); + } + let read = self.shape(name, e); + if local.is_some() { + self.stack.pop(); + } + read + } + + fn shape(&mut self, name: &[u8], e: &BytesStart) -> Result<()> { match name { b"use" => { self.left_out(LeftOut::Use); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 12d9f0a12..4aa427bdd 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2299,6 +2299,48 @@ fn svg_group_transforms_apply() { assert!((l.b - Vec3::new(15.0, 8.0, 0.0)).len() < 1e-9, "{l:?}"); } +/// The geometry of everything read, for comparing two readings of one drawing. +fn geometry(d: &Drawing) -> String { + format!("{:?}", d.model.iter().map(|e| &e.kind).collect::>()) +} + +/// `transform` on a shape element (SVG 1.1 §7.5, every graphics element takes one) maps it as +/// the same transform on a group around it would: for every shape kind, composed after the +/// parent group's, and not passed on to the next sibling. +#[test] +fn svg_element_transforms_apply_like_a_group_around_the_element() { + let read_svg = |body: &str| read(format!("{SVG_PAGE}{body}").as_bytes(), "t.svg").unwrap(); + let shapes = [ + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + ]; + for t in ["translate(5,2)", "rotate(30 5 5)", "scale(2,1)", "skewX(20)", "matrix(1 0.2 0 1 3 -1)"] { + for shape in shapes { + let on_element = shape.replacen("/>", &format!(r#" transform="{t}"/>"#), 1); + let in_group = format!(r#"{shape}"#); + assert_eq!(geometry(&read_svg(&on_element)), geometry(&read_svg(&in_group)), "{t} on {shape}"); + } + } + // A rotated circle stays a circle; a skewed one is an ellipse. + assert_eq!(kinds(&read_svg(r#""#)), ["Circle"]); + assert_eq!(kinds(&read_svg(r#""#)), ["Ellipse"]); + // Inside a group: the group's transform, then the element's. + let nested = read_svg(r#""#); + let both = read_svg(r#""#); + assert_eq!(geometry(&nested), geometry(&both)); + // Written with an end tag too, and the next sibling keeps its own place. + let d = read_svg(r#""#); + let lines: Vec = d.model.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).collect(); + assert_eq!(lines.len(), 2); + assert!((lines[0].a - Vec3::new(5.0, 10.0, 0.0)).len() < 1e-9, "{:?}", lines[0]); + assert!((lines[1].a - Vec3::new(0.0, 10.0, 0.0)).len() < 1e-9, "{:?}", lines[1]); +} + #[test] fn svg_viewbox_scaling_and_mm_units() { let svg = r#""#; From ea127d470204b2618e9e0fed3bfec0e838910fc4 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:26:43 +0700 Subject: [PATCH 410/900] Dynamic blocks: a point on a frame edge of any length is on it (#2640) * Dynamic blocks: a point on a frame edge of any length is on it The frame edge test used Line::dist, which takes a segment shorter than EPS (1e-9) for its first point: a point halfway along a frame edge that short was neither on the edge nor, by the even-odd test, inside, so its line moved whole instead of stretching. The distance to an edge is now the exact one, clamped to the segment. Tests also cover two rules from #2627 that had none: a point on an edge's line but past its end is outside the frame, and a polyline tilted by only 5e-10 (about a unit off at an elevation of 2e9) keeps its stored vertex list. Co-Authored-By: Claude Opus 5.5 * Dynamic blocks: measure a frame edge's residual from its start segment_dist added the projection back to the edge's start before measuring, so near x = 36 the residual was rounded to that magnitude's spacing (7e-15). A point 1.4e-15 off an edge 5e-10 long, outside the frame, then came out 4e-20 away, within the edge's 5e-19 tolerance, and was taken as on it. The residual is now measured from the edge's start, where those digits are kept. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 19 ++++++++--- crates/io/tests/it/dynblock_read.rs | 50 ++++++++++++++++++++++++----- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index d5651faac..ecca36257 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -415,6 +415,17 @@ fn inside(frame: &[Vec2], points: impl Iterator) -> Option (!idx.is_empty()).then_some(idx) } +/// The distance from `p` to the segment `a`-`b`, however short (`Line::dist` takes one shorter than +/// `EPS` for its first point). It is measured from `a`, so a short segment far from the origin keeps +/// the digits rounding there would drop. +fn segment_dist(a: Vec2, b: Vec2, p: Vec2) -> f64 { + let d = b - a; + let w = p - a; + let l2 = d.len2(); + let t = if l2 > 0.0 { (w.dot(d) / l2).clamp(0.0, 1.0) } else { 0.0 }; + (w - d * t).len() +} + /// Whether point `p` lies inside a stretch frame (two corners, or a polygon). A point on its edge is /// inside, for a polygon as for two corners: within a billionth of the edge's length of it. fn in_frame(frame: &[Vec2], p: Vec2) -> bool { @@ -425,8 +436,7 @@ fn in_frame(frame: &[Vec2], p: Vec2) -> bool { let mut j = f.len() - 1; for i in 0..f.len() { let (Some(pi), Some(pj)) = (f.get(i), f.get(j)) else { break }; - let edge = cadcraft_geom::Line { a: *pj, b: *pi }; - if edge.dist(p) <= 1e-9 * pi.dist(*pj) { + if segment_dist(*pj, *pi, p) <= 1e-9 * pi.dist(*pj) { return true; } if (pi.y > p.y) != (pj.y > p.y) && p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x { @@ -528,8 +538,9 @@ fn apply( // dynamic block has them, all of them when none is, as AutoCAD 2024 moves them. It // doesn't go by the vertex lists the action stores, which a block from another program // can get wrong. A polyline's vertices are in its own plane: in the block's when its - // extrusion is along z (a mirrored one is read flipped into it), so a tilted one keeps - // the stored list. + // extrusion is exactly along z (a mirrored one is read flipped into it). Any tilt, however + // small, moves them by as much as the elevation times the tilt, so a tilted one keeps the + // stored list. let idx = match def.entities.get(*h).map(|e| (&e.kind, e.common.extrusion)) { Some((EntityKind::Line(l), _)) if framed => inside(frame, [l.a.xy(), l.b.xy()].into_iter()), Some((EntityKind::LwPolyline(pl), n)) if framed && n.x == 0.0 && n.y == 0.0 => inside(frame, pl.vertices.iter().map(|v| v.p)), diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index bd9f2d1e1..251029410 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -482,13 +482,14 @@ fn a_zero_distance_multiplier_moves_as_one_without_its_angle_offset() { fn a_point_on_the_edge_of_a_polygon_frame_is_inside_it() { // Line 30 ends at (36, 0), and its start is outside every frame here. On the edge of the frame // (34,-2)-(36,2) given as two corners, the end is inside and moves alone. The same frame as a - // polygon, and triangles whose slanted edge passes through (36, 0), exactly or up to rounding, - // take it the same way. + // polygon, triangles whose slanted edge passes through (36, 0), exactly or up to rounding, and a + // square 5e-10 across with (36, 0) halfway along its right edge, take it the same way. let frames = [ "72 2\n1011 34\n1021 -2\n1011 36\n1021 2\n", "72 4\n1011 34\n1021 -2\n1011 36\n1021 -2\n1011 36\n1021 2\n1011 34\n1021 2\n", "72 3\n1011 34\n1021 -2\n1011 38\n1021 2\n1011 34\n1021 2\n", "72 3\n1011 35.7\n1021 -0.3\n1011 36.7\n1021 0.7\n1011 30\n1021 10\n", + "72 4\n1011 35.9999999995\n1021 -2.5e-10\n1011 36\n1021 -2.5e-10\n1011 36\n1021 2.5e-10\n1011 35.9999999995\n1021 2.5e-10\n", ]; for frame in frames { let src = fixture().replace("72 2\n1011 34\n1021 -2\n1011 38\n1021 2\n", frame); @@ -512,29 +513,62 @@ fn a_point_just_outside_a_tiny_frame_is_outside_it() { assert_eq!(shapes(&d, r)[0], [(-6.0, 0.0), (30.0, 0.0)]); } +#[test] +fn a_point_less_than_a_rounding_off_a_short_edge_is_outside_it() { + // A triangle frame whose right edge runs from (35.99999999999999, -2e-10) to + // (36.00000000000001, 3e-10): line 30's end (36, 0) is 1.4e-15 off it, past a billionth of the + // edge's length (5e-19), and outside the frame, so the line moves whole. Measured from the + // edge's start, the distance keeps digits that rounding near x = 36 would drop. + let frame = "72 3\n1011 35.99999999999999\n1021 -2e-10\n1011 36.00000000000001\n1021 3e-10\n1011 35.999999999\n1021 0\n"; + let src = fixture().replace("72 2\n1011 34\n1021 -2\n1011 38\n1021 2\n", frame); + assert_ne!(src, fixture()); + let (mut d, r) = door_reference(&src); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + assert_eq!(shapes(&d, r)[0], [(-6.0, 0.0), (30.0, 0.0)]); +} + +#[test] +fn a_point_past_the_end_of_a_frame_edge_is_outside_it() { + // The frame's right edge runs along x = 36 from y = -2 to -1: line 30's end (36, 0) is on that + // edge's line but past its end, outside the frame, so the line moves whole. + let frame = "72 4\n1011 34\n1021 -2\n1011 36\n1021 -2\n1011 36\n1021 -1\n1011 34\n1021 -1\n"; + let src = fixture().replace("72 2\n1011 34\n1021 -2\n1011 38\n1021 2\n", frame); + assert_ne!(src, fixture()); + let (mut d, r) = door_reference(&src); + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + assert_eq!(shapes(&d, r)[0], [(-6.0, 0.0), (30.0, 0.0)]); +} + #[test] fn a_tilted_polyline_keeps_the_stored_vertex_list() { // Polyline 34 lies in a plane tilted about the y axis (extrusion (1,0,0)): its vertices are in // that plane's coordinates, not the block's, so the frame isn't tested against them and the - // stored list (vertex 0) is used, as before. Polyline 35 is mirrored (extrusion (0,0,-1)): it + // stored list (vertex 0) is used, as before; so is polyline 36's, tilted by only 5e-10 (at an + // elevation of 2e9 that moves it about a unit). Polyline 35 is mirrored (extrusion (0,0,-1)): it // is read flipped into the block's plane, (-20, 1) as (20, 1), so the frame is tested. - let polyline = |h: &str, [x0, x1]: [i32; 2], [ex, ey, ez]: [i32; 3]| { + let polyline = |h: &str, [x0, x1]: [i32; 2], [ex, ey, ez]: [f64; 3], elevation: f64| { format!( - "0 LWPOLYLINE\n5 {h}\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbPolyline\n90 2\n70 0\n10 {x0}\n20 1\n10 {x1}\n20 1\n210 {ex}\n220 {ey}\n230 {ez}\n" + "0 LWPOLYLINE\n5 {h}\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbPolyline\n90 2\n70 0\n38 {elevation}\n10 {x0}\n20 1\n10 {x1}\n20 1\n210 {ex}\n220 {ey}\n230 {ez}\n" ) }; let src = fixture() - .replace("71 1\n330 30\n1010 40", "71 3\n330 30\n330 34\n330 35\n1010 40") - .replace("73 1\n331 30\n74 1\n94 1\n75 0", "73 3\n331 30\n74 1\n94 1\n331 34\n74 1\n94 0\n331 35\n74 1\n94 0\n75 0") + .replace("71 1\n330 30\n1010 40", "71 4\n330 30\n330 34\n330 35\n330 36\n1010 40") + .replace("73 1\n331 30\n74 1\n94 1\n75 0", "73 4\n331 30\n74 1\n94 1\n331 34\n74 1\n94 0\n331 35\n74 1\n94 0\n331 36\n74 1\n94 0\n75 0") .replace( "21 25\n31 0\n0 ENDBLK\n", - &format!("21 25\n31 0\n{}{}0 ENDBLK\n", polyline("34", [20, 36], [1, 0, 0]), polyline("35", [-20, -36], [0, 0, -1])), + &format!( + "21 25\n31 0\n{}{}{}0 ENDBLK\n", + polyline("34", [20, 36], [1.0, 0.0, 0.0], 0.0), + polyline("35", [-20, -36], [0.0, 0.0, -1.0], 0.0), + polyline("36", [20, 36], [5e-10, 0.0, 1.0], 2e9) + ), ); let (mut d, r) = door_reference(&src); cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); let s = shapes(&d, r); assert_eq!(s[3], [(14.0, 1.0), (36.0, 1.0)]); assert_eq!(s[4], [(20.0, 1.0), (30.0, 1.0)]); + assert_eq!(s[5], [(14.0, 1.0), (36.0, 1.0)]); } #[test] From facae4a9a61ff8b894183cc2354e7d2246f6198d Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 3 Nov 2026 00:26:48 +0300 Subject: [PATCH 411/900] plot and exportpdf help name the `device` parameter (#2557) (#2567) * plot and exportpdf help name the `device` parameter (#2557) `cadcraft-cli commands plot` didn't list `device`, so the only way to find it was the `unknown plotter` error. PLOT's help now lists `device` with the built-in devices (CADCraft PDF, PNG, SVG), PLOTTERMANAGER plotters and "None". It also says the default is the page setup's device and that the device picks the output format and the papers. EXPORTPDF's help names `device` too, and notes that its output stays PDF. A test checks that both help texts name `device` and that PLOT's names every built-in device. * plot help: say what Model, "None" and an omitted paper do In model space, and with "None", no device is used and the plot is a PDF. When `paper` is omitted, a layout keeps its page setup's paper and model space takes the device's default. --- crates/engine/src/cmd/layout.rs | 4 ++-- crates/engine/src/cmd/layout/tests.rs | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index efe9bf13f..0c78e19cb 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -84,11 +84,11 @@ pub fn specs() -> Vec { .menu(&["File", "Print..."]) .key("Cmd+P") .alias(&["print"]) - .params("{path? (else returns base64 `data`), layout?: current|\"Model\", paper?, landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)") + .params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)") .noundo(), CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf")) .menu(&["File", "Export to PDF..."]) - .params("{path? (else returns base64 `data`), layout?, paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)") + .params("{path? (else returns base64 `data`), layout?, device? (its papers; the output stays PDF), paper?, landscape?, fit?, scale?, center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?, plotTransparency?, plotArea?, window?} (as PLOT)") .noundo(), CommandSpec::new("mspace", "Model Space (in viewport)", run_mspace) .alias(&["ms"]) diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 03356b892..4a631ccb0 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -293,3 +293,17 @@ fn mspace_edits_model_through_viewport() { s.execute("layout.set", &json!({"name": "Model"})).unwrap(); assert!(s.state().unwrap().mspace.is_none()); } + +/// PLOT and EXPORTPDF help name the `device` parameter, and PLOT's help every built-in device (#2557). +#[test] +fn plot_help_names_the_device_and_the_built_in_devices() { + for id in ["plot", "exportpdf"] { + let help = crate::find_command(id).map(|c| c.params).unwrap_or_default(); + assert!(help.contains("device?"), "{id}: {help}"); + } + let help = crate::find_command("plot").map(|c| c.params).unwrap_or_default(); + for name in ["CADCraft PDF", "CADCraft PNG", "CADCraft SVG"] { + assert!(super::super::plotters::find_device(name).is_some(), "{name} is not a device"); + assert!(help.contains(name), "plot help lacks {name}"); + } +} From 0e7c71759cede6da1b2c0df6660e94fdaccf64fe Mon Sep 17 00:00:00 2001 From: Tyler Chiriboga Date: Mon, 2 Nov 2026 15:26:53 -0600 Subject: [PATCH 412/900] test(ui): the IME double-click test passes without craft-fonts (#2652) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `double_clicked_text_takes_ime_composition_and_commit` commits 中文 at the command line. Without a CJK font (no CRAFT_FONTS_DIR, none installed, as on a plain Linux CI image) the kittest harness panics on the first missing glyph: "No glyph for 中 in Proportional". Code and tests must work without craft-fonts. The test now asks the harness's own fonts whether they can draw 中文 and, only when they can't, lets the command line draw boxes for it. The IME path it checks is unchanged: the pre-edit is shown and not saved, the commit is inserted once, Enter stores 中文 in the text. With a CJK font the harness still fails on any missing glyph. Co-authored-by: Tyler Chiriboga <18270301+Tyler-Chiriboga@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/tests/it/text_double_click.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/ui-egui/tests/it/text_double_click.rs b/crates/ui-egui/tests/it/text_double_click.rs index 5cedfbf61..f585ae46a 100644 --- a/crates/ui-egui/tests/it/text_double_click.rs +++ b/crates/ui-egui/tests/it/text_double_click.rs @@ -73,6 +73,16 @@ fn double_clicked_text_takes_ime_composition_and_commit() { let mut h = harness(); double_click(&mut h, Vec2::new(4.0, 1.2)); assert_eq!(h.state().session.current_prompt().unwrap().message, "Enter new text"); + // Without a CJK font (none installed, no craft-fonts) the command line draws 中文 as boxes, + // which the harness takes for a bug. The IME path below is the same either way. + let drawable = h.ctx.fonts_mut(|view| { + [egui::FontFamily::Proportional, egui::FontFamily::Monospace] + .into_iter() + .all(|family| view.has_glyphs(&egui::FontId::new(12.0, family), "中文")) + }); + if !drawable { + h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu); + } // Composition is shown, not saved; the commit is inserted exactly once (#1761). h.event(Event::Ime(ImeEvent::Preedit { text: "zhong".into(), active_range_chars: None })); h.run_steps(1); From f2cb7e6e8f704c37b299b42d64f8bb9a9724d632 Mon Sep 17 00:00:00 2001 From: Rahul Date: Tue, 3 Nov 2026 02:56:59 +0530 Subject: [PATCH 413/900] i18n(zh): translate the 74 strings the report listed as missing (#2638) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Chinese catalog lacked 74 interface strings: the block editor prompts and dialog, the alias editor sentences, the selection visual effects and preview filter, units of new drawings, and the menu names Dimension, Draw, Modify and View. Adds them in the catalog's TSV format with the AutoCAD zh-CN vocabulary the catalog already uses (夹点, 图案填充, 外部参照, 多行文字, 孤岛). After this the report lists nothing missing for zh. Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- crates/ui-egui/src/i18n/zh.tsv | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 21c86d1fe..9ca85fea7 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1381,3 +1381,79 @@ Save Layout as Template 将布局另存为样板 Set Dynamic Property 设置动态特性 Units 单位 + +# The strings the report listed as missing for zh. + Add… 添加… + Alias 别名 + Alias file: {file} 别名文件:{file} + Associative 关联 + AutoLISP (LSP) AutoLISP (LSP) + B B + Backup copy 备份副本 + Block to create or edit 要创建或编辑的块 + Choose the command the alias starts. 选择别名要启动的命令。 + Click the ruler to add a tab stop, right-click to remove one 单击标尺可添加制表位,右键单击可将其删除 + Command 命令 + Create backup copy with each save 每次保存时创建备份副本 + Crossing selection color: 交叉选择颜色: + Custom 自定义 + Define each corner of the selection window with a separate click. 分别单击以定义选择窗口的各个角点。 + Discard 放弃 + Edit Block Definition 编辑块定义 + Edit… 编辑… + Exclude: 排除: + Font 字体 + Grips 夹点 + Hatches 图案填充 + Imperial (inches) 英制(英寸) + Indicate selection area 指示选择区域 + Interface scale 界面缩放 + Island 孤岛 + Italic 斜体 + Metric (millimetres) 公制(毫米) + More than {n} aliases. 超过 {n} 个别名。 + Multiline text 多行文字 + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). 启动时的新建图形和第一个图形使用这些单位,除非设置了默认样板 (QNEWTEMPLATE)。 + New block 新建块 + No alias file loaded. REINIT replaces these aliases with a file's. 未加载别名文件。REINIT 将用文件中的别名替换这些别名。 + Object grouping 对象编组 + Object selection limit for display of grips 显示夹点时对象选择的数目上限 + Objects on locked layers 锁定图层上的对象 + Open in Block Editor 在块编辑器中打开 + Origin: {x}, {y} 原点:{x}, {y} + Overline 上划线 + Save alias 保存别名 + Save changes to block "{name}"? 保存对块“{name}”的更改吗? + Select boundaries to remove 选择要删除的边界 + Select using two clicks only 仅用两次单击选择 + Selection Area Effect 选择区域效果 + Selection Preview Filter 选择预览过滤器 + Selection area opacity: 选择区域不透明度: + Selection effect color 选择效果颜色 + Selection modes 选择模式 + Selection preview 选择预览 + Show grips 显示夹点 + Tables 表格 + Text color 文字颜色 + This drawing 此图形 + Type an alias name. 输入别名名称。 + Underline 下划线 + Units of new drawings 新图形的单位 + Unsaved changes 未保存的更改 + Visual Effect Settings 视觉效果设置 + Visual Effect Settings... 视觉效果设置... + When a command is active 命令处于活动状态时 + When no command is active 无活动命令时 + Window selection color: 窗口选择颜色: + X X + Xrefs 外部参照 + Y Y + built-in 内置 + contains authoring elements. Open in Block Editor? 包含编写元素。在块编辑器中打开吗? + overrides built-in 覆盖内置 + {alias} is already defined; select it and use Edit. {alias} 已定义;请选择它并使用编辑。 + {command} is an unknown command. {command} 是未知命令。 +menu Dimension 标注 +menu Draw 绘图 +menu Modify 修改 +menu View 视图 From a60d437f0a5c325e462daecaeaaf79f551b91366 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 14:27:33 -0700 Subject: [PATCH 414/900] WBLOCK: new handles start above those of the copied blocks (#1996) (#2659) Co-authored-by: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> --- crates/engine/src/cmd/blocks/wblock.rs | 5 ++ crates/engine/tests/wblock_units_handles.rs | 57 +++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 crates/engine/tests/wblock_units_handles.rs diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index bc2ff711a..e06e3a71a 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -113,6 +113,11 @@ fn with_objects(src: &Drawing, ents: impl Iterator) -> Drawing { d.scales = src.scales.clone(); d.blocks = src.blocks.clone(); d.header.set("INSBASE", cadcraft_doc::HVal::Point(Vec3::ZERO)); + // The copied blocks keep their objects' handles, so the new ones start above them. + let kept: Vec = d.blocks.values().flat_map(|b| b.entities.iter().map(|e| e.handle)).collect(); + for h in kept { + d.bump_handseed(h); + } for mut e in ents { e.handle = d.new_handle(); d.model.push(e); diff --git a/crates/engine/tests/wblock_units_handles.rs b/crates/engine/tests/wblock_units_handles.rs new file mode 100644 index 000000000..52a4d6053 --- /dev/null +++ b/crates/engine/tests/wblock_units_handles.rs @@ -0,0 +1,57 @@ +//! WBLOCK writes the source's units, only the blocks the written objects use, and handles that +//! never repeat. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::Drawing; +use serde_json::json; + +/// Writes "insunits;block names;handles;distinct handles" so the test can read what would be saved. +fn write(d: &Drawing, _path: &str) -> Result, String> { + let mut handles: Vec = d.model.iter().map(|e| e.handle.0).collect(); + let mut names = Vec::new(); + for b in d.blocks.values() { + names.push(b.name.clone()); + handles.extend(b.entities.iter().map(|e| e.handle.0)); + } + let total = handles.len(); + handles.sort_unstable(); + handles.dedup(); + Ok(format!("{};{};{};{}", d.header.i64("INSUNITS", -1), names.join(","), total, handles.len()).into_bytes()) +} + +fn written(s: &mut Session, p: serde_json::Value) -> String { + let path = std::env::temp_dir().join(format!("cadcraft-wblock-units-{}.dxf", std::process::id())); + let mut p = p; + p["path"] = json!(path.to_string_lossy()); + s.execute("wblock", &p).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let _ = std::fs::remove_file(&path); + text +} + +fn line(s: &mut Session, y: f64) -> String { + s.execute("line", &json!({ "points": [[0, y], [1, y]] })).unwrap()["handles"][0].as_str().unwrap().to_string() +} + +#[test] +fn wblock_keeps_units_drops_unused_blocks_and_repeats_no_handle() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write, plot: None }); + let mut s = Session::new(); + s.execute("units", &json!({ "insunits": 6 })).unwrap(); + // Block "Part" is made first, so its line has one of the drawing's lowest handles. + let p = line(&mut s, 0.0); + let ins = s.execute("block", &json!({ "name": "Part", "handles": [p], "keep": "convert" })).unwrap()["insert"].as_str().unwrap().to_string(); + let mut picked = vec![ins]; + for i in 1..300 { + picked.push(line(&mut s, f64::from(i) * 0.01)); + } + let u = line(&mut s, 5.0); + s.execute("block", &json!({ "name": "Unused", "handles": [u], "keep": "delete" })).unwrap(); + + // 300 objects (the insert and 299 lines) plus Part's line: the source's units, no Unused, + // and every handle distinct although the new objects are numbered from the start again. + assert_eq!(written(&mut s, json!({ "handles": picked })), "6;Part;301;301"); + // A block written by name: its objects go to model space, its definition stays behind. + assert_eq!(written(&mut s, json!({ "name": "Unused" })), "6;;1;1"); +} From 0f56c16d00902d7ea5475fc6858aea924c0e558e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 14:27:45 -0700 Subject: [PATCH 415/900] EXPORT and WBLOCK say what a DWG file leaves out (#2240) (#2660) Co-authored-by: assamaral <217119886+assamaral@users.noreply.github.com> --- crates/engine/src/cmd/blocks/wblock.rs | 40 ++++++++++++++----- crates/engine/src/cmd/exchange.rs | 14 ++++--- crates/engine/src/cmd/file.rs | 2 +- crates/engine/tests/save_reports_not_saved.rs | 32 +++++++++++++++ 4 files changed, 72 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/blocks/wblock.rs b/crates/engine/src/cmd/blocks/wblock.rs index e06e3a71a..fb03fe1af 100644 --- a/crates/engine/src/cmd/blocks/wblock.rs +++ b/crates/engine/src/cmd/blocks/wblock.rs @@ -1,11 +1,14 @@ //! WBLOCK (its JSON form) and -WBLOCK at the command line: objects, a block or the whole drawing //! written to a drawing file. +use std::collections::BTreeMap; + use cadcraft_doc::{Drawing, Entity, Handle}; use cadcraft_geom::{Mat3, Vec2, Vec3}; use serde_json::{Value, json}; use super::super::curves::KW; +use super::super::file::{drops_unknown, not_saved, not_saved_message, report_not_saved}; use super::super::machines::{SelOutcome, SelectPhase}; use super::super::modify::erase_kept; use super::super::{CommandSpec, bad, point_param, str_param, targets}; @@ -40,11 +43,13 @@ enum Source<'a> { fn run_wblock(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path").ok_or_else(|| bad("wblock", "`path` is required"))?.to_string(); let base = point_param(p, "base"); - let (entities, bytes) = match str_param(p, "name") { + let (entities, bytes, lost) = match str_param(p, "name") { Some(name) => write(s, "wblock", &path, Source::Block(name, base))?, None => write(s, "wblock", &path, Source::Objects(&targets(s, p)?, base.unwrap_or(Vec2::ZERO)))?, }; - Ok(json!({ "path": path, "entities": entities, "bytes": bytes })) + let mut r = json!({ "path": path, "entities": entities, "bytes": bytes }); + report_not_saved(s, &mut r, &lost); + Ok(r) } fn run_dash_wblock(s: &mut Session, p: &Value) -> Result { @@ -53,7 +58,7 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result { } let path = str_param(p, "path").ok_or_else(|| bad("-wblock", "`path` is required"))?.to_string(); let base = point_param(p, "base"); - let (entities, bytes) = match str_param(p, "name") { + let (entities, bytes, lost) = match str_param(p, "name") { Some(name) => write(s, "-wblock", &path, Source::Block(name, base))?, None => { let hs = targets(s, p)?; @@ -66,14 +71,17 @@ fn run_dash_wblock(s: &mut Session, p: &Value) -> Result { written } }; - Ok(json!({ "path": path, "entities": entities, "bytes": bytes })) + let mut r = json!({ "path": path, "entities": entities, "bytes": bytes }); + report_not_saved(s, &mut r, &lost); + Ok(r) } -/// Write `what` to `path` through the io hooks; the objects written and the file's size. The +/// Write `what` to `path` through the io hooks; the objects written, the file's size and what a +/// DWG file left out, for the caller to report as a save does. The /// written drawing keeps the source's settings and styles, as AutoCAD's -WBLOCK does: its units /// ($INSUNITS, $MEASUREMENT), so a block from a metric drawing is not declared in inches and /// scaled on insert, and its defaults (text size, current styles, annotation scales). -fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize)> { +fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usize, BTreeMap)> { let src = s.doc()?; // The base point becomes the written drawing's origin: by default 0,0 for objects and the // block's base point for a block. @@ -94,7 +102,15 @@ fn write(s: &Session, cmd: &str, path: &str, what: Source) -> Result<(usize, usi // Through a temporary file, as SAVE writes, so a failed write keeps the file it replaces. #[cfg(not(target_arch = "wasm32"))] crate::atomic_write::write_atomic(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - Ok((d.model.len(), bytes.len())) + let lost = if drops_unknown(path) { not_saved(&d) } else { BTreeMap::new() }; + Ok((d.model.len(), bytes.len(), lost)) +} + +/// Say on the command line what the written DWG file left out. +fn echo_not_saved(s: &mut Session, lost: &BTreeMap) { + if let Some(msg) = not_saved_message(lost) { + s.echo(msg); + } } /// A new drawing of `ents`, with `src`'s settings and the layers, linetypes, styles and blocks @@ -310,8 +326,9 @@ impl DashWblockM { } fn write(&self, s: &mut Session, what: Source) -> Result { - if let Err(e) = write(s, "-wblock", &self.path, what) { - s.echo(e.to_string()); + match write(s, "-wblock", &self.path, what) { + Ok((.., lost)) => echo_not_saved(s, &lost), + Err(e) => s.echo(e.to_string()), } Ok(Step::Done) } @@ -321,7 +338,10 @@ impl DashWblockM { return Ok(Step::Done); } match write(s, "-wblock", &self.path, Source::Objects(hs, self.base)) { - Ok(_) => erase(s, hs)?, + Ok((.., lost)) => { + echo_not_saved(s, &lost); + erase(s, hs)?; + } Err(e) => s.echo(e.to_string()), } Ok(Step::Done) diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index f6ce1e9b6..d4993566a 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -117,14 +117,18 @@ fn run_export(s: &mut Session, p: &Value) -> Result { if !EXPORT_FORMATS.contains(&format.as_str()) { return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)")); } - let bytes = (hooks.write)(s.doc()?, &format!("export.{format}")).map_err(|e| bad("export", e))?; - match path { + let file = format!("export.{format}"); + let lost = super::file::loss_on_save(s, &file); + let bytes = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?; + let mut r = match path { Some(path) => { write_file("export", path, &bytes)?; - Ok(json!({ "path": path, "format": format, "bytes": bytes.len(), "message": format!("Exported to {path}") })) + json!({ "path": path, "format": format, "bytes": bytes.len(), "message": format!("Exported to {path}") }) } - None => Ok(json!({ "data": base64_encode(&bytes), "format": format, "bytes": bytes.len() })), - } + None => json!({ "data": base64_encode(&bytes), "format": format, "bytes": bytes.len() }), + }; + super::file::report_not_saved(s, &mut r, &lost); + Ok(r) } // ---------- IMPORT ---------- diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 3b24e87bd..6a8d50384 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -801,7 +801,7 @@ fn is_drawing_file(path: impl AsRef) -> bool { } /// Say on the command line what the file couldn't keep, and list it in the result's `notSaved`. -fn report_not_saved(s: &mut Session, r: &mut Value, lost: &std::collections::BTreeMap) { +pub(super) fn report_not_saved(s: &mut Session, r: &mut Value, lost: &std::collections::BTreeMap) { let Some(msg) = not_saved_message(lost) else { return }; s.echo(msg); if let Some(o) = r.as_object_mut() { diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 24a2dff92..e31f2ec77 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -52,6 +52,38 @@ fn save_lists_the_entities_the_file_does_not_keep() { assert!(r.get("notSaved").is_none() && s.log.len() == n); } +#[test] +fn export_and_wblock_say_what_a_dwg_leaves_out() { + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + let mut d = Drawing::new_imperial(); + let h = d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET")).unwrap().hex(); + let mut s = Session::empty(); + s.open_drawing(d, "foreign.dxf", None); + let file = |ext: &str| std::env::temp_dir().join(format!("cadcraft-leaves-out-{}.{ext}", std::process::id())).to_string_lossy().into_owned(); + let msg = "Not saved in the DWG file (its writer can't write these object types yet; DXF keeps them): 1 ACME_WIDGET"; + + let (dwg, dxf) = (file("dwg"), file("dxf")); + for (cmd, p) in [("export", json!({ "path": dwg })), ("wblock", json!({ "path": dwg, "handles": [h] }))] { + s.log.clear(); + let r = s.execute(cmd, &p).unwrap(); + assert_eq!(r["notSaved"], json!({ "ACME_WIDGET": 1 }), "{cmd}"); + assert!(s.log.iter().any(|l| l == msg), "{cmd}: {:?}", s.log); + } + // -WBLOCK takes the objects out of the drawing, so last. + let r = s.execute("-wblock", &json!({ "path": dwg, "handles": [h] })).unwrap(); + assert_eq!(r["notSaved"], json!({ "ACME_WIDGET": 1 })); + let _ = std::fs::remove_file(&dwg); + + // DXF keeps them. + s.execute("undo", &json!({})).unwrap(); + for (cmd, p) in [("export", json!({ "path": dxf })), ("wblock", json!({ "path": dxf, "handles": [h] }))] { + s.log.clear(); + assert!(s.execute(cmd, &p).unwrap().get("notSaved").is_none(), "{cmd}"); + assert!(!s.log.iter().any(|l| l == msg), "{cmd}: {:?}", s.log); + } + let _ = std::fs::remove_file(&dxf); +} + #[test] fn templates_report_what_dwg_does_not_keep() { use cadcraft_engine::cmd::file::drops_unknown; From 97679d8cffa6d0d57b84d52eb25b18a14d429ebd Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 14:29:51 -0700 Subject: [PATCH 416/900] Ask before a save drops solids from a 2013+ DXF (#2334) The interactive save only knew about DWG, so overwriting a 2013+ DXF lost SAT-text solids on a command-line note. loss_on_save now lists them, and EXPORT reports them with the DXF wording. --- crates/engine/src/cmd/exchange.rs | 3 +- crates/engine/src/cmd/file.rs | 18 ++++++++++- crates/engine/tests/save_reports_not_saved.rs | 32 +++++++++++++++++++ crates/ui-egui/src/save_loss.rs | 10 ++++-- 4 files changed, 58 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index d4993566a..1be19a408 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -118,7 +118,6 @@ fn run_export(s: &mut Session, p: &Value) -> Result { return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)")); } let file = format!("export.{format}"); - let lost = super::file::loss_on_save(s, &file); let bytes = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?; let mut r = match path { Some(path) => { @@ -127,7 +126,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result { } None => json!({ "data": base64_encode(&bytes), "format": format, "bytes": bytes.len() }), }; - super::file::report_not_saved(s, &mut r, &lost); + super::file::report_loss(s, &mut r, &file); Ok(r) } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 80244bc21..012a1d381 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -794,13 +794,29 @@ pub fn not_saved_message(lost: &std::collections::BTreeMap) -> Op /// when the format keeps everything. The interactive save asks with this; [`save_reporting`] /// reports the same list afterwards to callers that never get a dialog. pub fn loss_on_save(s: &Session, path: &str) -> std::collections::BTreeMap { + let version = drawing_version(s, path); + if is_dxf_file(path) && version >= Version::R2013 { + // The drawing a file holds: the host while the Block Editor is open. + return s.state().map(|st| cadcraft_doc::foreign::sat_text_dropped(st.drawing())).unwrap_or_default(); + } if !drops_unknown(path) { return Default::default(); } - let version = drawing_version(s, path); s.doc().map(|d| not_saved_as(d, version)).unwrap_or_default() } +/// Report what the file `path`, just written at the drawing's own version, left out. +pub(super) fn report_loss(s: &mut Session, r: &mut Value, path: &str) { + if is_dxf_file(path) { + if drawing_version(s, path) >= Version::R2013 { + report_sat_text_dropped(s, r); + } + } else { + let lost = loss_on_save(s, path); + report_not_saved(s, r, &lost); + } +} + /// Whether saving to `path` leaves out the entities [`not_saved`] counts: DWG does (the DWG /// bridge drops types it doesn't know); DXF writes them back as read. pub fn drops_unknown(path: impl AsRef) -> bool { diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index cd73f637d..984d0d635 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -150,6 +150,38 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() { assert!(r.get("notSaved").is_none() && s.log.len() == n); } +/// The interactive save asks with the same list, and EXPORT reports it, so overwriting a 2013+ +/// DXF never drops solids on a command-line note alone (#2334). +#[test] +fn a_dxf_2013_loss_is_known_before_saving() { + use cadcraft_engine::cmd::file::loss_on_save; + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0 +EOF +".to_vec()), plot: None }); + let sat = |d: &mut Drawing| { + let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }]; + d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap(); + }; + let mut modern = Drawing::new_imperial(); + modern.header.set_str("ACADVER", "AC1032"); + sat(&mut modern); + let mut s = Session::empty(); + s.open_drawing(modern, "region.dxf", None); + assert_eq!(loss_on_save(&s, "region.dxf"), [("REGION".to_string(), 1)].into_iter().collect()); + + let path = std::env::temp_dir().join(format!("cadcraft-sat-export-{}.dxf", std::process::id())); + let r = s.execute("export", &json!({ "path": path.to_string_lossy() })).unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(r["notSaved"], json!({ "REGION": 1 })); + assert!(s.log.iter().any(|l| l.contains("Not saved in the DXF file")), "{:?}", s.log); + + let mut old = Drawing::new_imperial(); + old.header.set_str("ACADVER", "AC1024"); + sat(&mut old); + s.open_drawing(old, "region.dxf", None); + assert!(loss_on_save(&s, "region.dxf").is_empty(), "2010 keeps SAT text"); +} + /// In the Block Editor the file still holds the host drawing: its solids and version decide the /// note, not the edited block's (#2334). #[test] diff --git a/crates/ui-egui/src/save_loss.rs b/crates/ui-egui/src/save_loss.rs index 50e77978b..2b0a28c57 100644 --- a/crates/ui-egui/src/save_loss.rs +++ b/crates/ui-egui/src/save_loss.rs @@ -1,5 +1,6 @@ //! Asking before a save throws content away. DWG can't yet hold everything a drawing read from -//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), and QSAVE replaces the file +//! another program keeps (`cadcraft_engine::cmd::file::not_saved`), a DXF of 2013 or later can't +//! hold a solid's SAT text (`cadcraft_doc::foreign::sat_text_dropped`), and QSAVE replaces the file //! that still has it, so File ▸ Save, its shortcut or typing QSAVE says what would go first: //! Save Anyway / Save As... / Cancel. Agreeing lasts for that same loss on that same file, so //! later saves in the session don't ask again; the file no longer holds what was agreed to. @@ -120,7 +121,12 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) { ui.label(RichText::new(crate::tf!("Saving {name} will remove content", name = file)).strong()); ui.add_space(4.0); ui.label(crate::tf!("This format can't keep these objects yet: {objects}.", objects = pending.summary())); - ui.label(RichText::new(crate::tl!("DXF keeps them. Use Save As to keep them in the drawing.")).color(t.text_dim)); + let keeps = if path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dxf")) { + crate::tl!("DXF 2010 and earlier keep them. Use Save As to keep them in the drawing.") + } else { + crate::tl!("DXF keeps them. Use Save As to keep them in the drawing.") + }; + ui.label(RichText::new(keeps).color(t.text_dim)); let on_disk = if save_keeps_current(path) { crate::tf!("The current file is kept as {name} until the next save.", name = backup) } else if isavebak() { From 8de925e1d32b397073e50786ac84fa130896a814 Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:36:32 +0700 Subject: [PATCH 417/900] Write option prompts without "or", as AutoCAD does (#2540) * Write option prompts without "or", as AutoCAD does AutoCAD writes " or [" only when a prompt asks for something besides its keywords ("Enter block name or [?]"); a prompt asking for one of them has none ("Enter an option [...]", "Enter layout option [...]", "New color [Truecolor/COlorbook]"). The 27 messages read without "or" from AutoCAD 2024's command line are listed in NO_OR and displayed that way. Co-Authored-By: Claude Opus 5.5 * Address review: the window's command line drops "or" as the prompt does The command line in the window draws a prompt's keywords itself and wrote " or [" after every message, so -LAYER still read "Enter an option or [?/Make/...]" there, and questions such as AUDIT's had "or" too. Only the prompt text (the control channel, the state JSON, the tests) had dropped it. Prompt::keyword_lead gives what goes before the keywords; display() and the command line both use it, and the command line translates only " or [". A render test reads what the command line draws, in English and German, for -LAYER, LINE and AUDIT. Suggested in review. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/prompt.rs | 66 +++++++++++++++++++---- crates/engine/tests/it/assoc_array.rs | 2 +- crates/engine/tests/it/layout_prompts.rs | 2 +- crates/engine/tests/it/vplayer_prompts.rs | 4 +- crates/ui-egui/src/cmdline.rs | 7 ++- crates/ui-egui/src/i18n/tests.rs | 29 ++++++++++ 6 files changed, 96 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index 1563be702..e3498dcf0 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -26,6 +26,41 @@ impl Accept { pub const SELECT: Accept = Accept { point: true, number: false, text: false, select: true, enter: true }; } +/// Prompts that ask for one of their keywords, which AutoCAD 2024 writes without "or" before them: +/// "Enter an option [?/Make/Set/…]:", "Enter layout option [Copy/Delete/…/?] :", "New color +/// [Truecolor/COlorbook] :". A prompt asking for something else besides its keywords has +/// it: "Enter block name or [?]:", "Specify insertion base point or [Basepoint/…]:". Read from +/// AutoCAD's command line over measured runs, where no prompt was written both ways. +const NO_OR: [&str; 27] = [ + "Bring to front", + "Calculate rectangle dimensions based on", + "Choose mode for selected object conversion", + "Create annotative block", + "Enter a configuration option", + "Enter a plotting preference", + "Enter an annotation option", + "Enter an option", + "Enter an option to change", + "Enter attribute visibility setting", + "Enter justification", + "Enter layout option", + "Enter leader format option", + "Enter line spacing type", + "Enter object ordering option", + "Enter polyline linetype generation option", + "Enter property to change", + "Enter the type of array", + "Enter type of unused objects to purge", + "Enter viewport arrangement", + "Explode block", + "New color", + "Orient relative to sheet in paper space viewports", + "Select a content type", + "Select a leader type", + "Use landing", + "Viewport View Locking", +]; + /// A prompt shown on the command line. #[derive(Clone, Debug, Default, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -148,15 +183,7 @@ impl Prompt { } let mut s = self.message.clone(); if !self.keywords.is_empty() { - // A question offers its answers ("Fix any errors detected? [Yes/No]"); anything else - // offers options besides what it asks for ("Specify next point or [Undo]"). - s.push_str(if self.message.is_empty() { - "[" - } else if self.message.ends_with('?') { - " [" - } else { - " or [" - }); + s.push_str(self.keyword_lead()); s.push_str(&self.keywords.join("/")); s.push(']'); } @@ -166,6 +193,20 @@ impl Prompt { s.push(':'); s } + /// What goes between the message and its keywords. A question offers its answers ("Fix any + /// errors detected? [Yes/No]"), and so does a prompt for an option ([`NO_OR`]): " [". Anything + /// else offers options besides what it asks for ("Specify next point or [Undo]"): " or [". With + /// no message, "[". The command line in the window draws the keywords itself and takes this + /// too. + pub fn keyword_lead(&self) -> &'static str { + if self.message.is_empty() { + "[" + } else if self.message.ends_with('?') || NO_OR.contains(&self.message.as_str()) { + " [" + } else { + " or [" + } + } /// Match typed text against keywords: full word or the capitalised shortcut, case-insensitive. pub fn match_keyword(&self, text: &str) -> Option { let t = text.trim(); @@ -338,6 +379,13 @@ mod tests { assert_eq!(p.display(), "Specify next point or [Undo/Close]:"); let q = Prompt::new("Erase polyline?", Accept::TEXT).kw(&["Yes", "No"]).default("No"); assert_eq!(q.display(), "Erase polyline? [Yes/No] :"); + // A prompt for an option has no "or", as AutoCAD writes it. + let o = Prompt::new("Enter an option", Accept::TEXT).kw(&["Close", "Join"]); + assert_eq!(o.display(), "Enter an option [Close/Join]:"); + let c = Prompt::new("New color", Accept::TEXT).kw(&["Truecolor", "COlorbook"]).default("BYLAYER"); + assert_eq!(c.display(), "New color [Truecolor/COlorbook] :"); + let b = Prompt::new("Enter block name", Accept::TEXT).kw(&["?"]); + assert_eq!(b.display(), "Enter block name or [?]:"); assert_eq!(p.match_keyword("u").as_deref(), Some("Undo")); assert_eq!(p.match_keyword("CL").as_deref(), Some("Close")); assert_eq!(p.match_keyword("x"), None); diff --git a/crates/engine/tests/it/assoc_array.rs b/crates/engine/tests/it/assoc_array.rs index 131210fa1..f672176b3 100644 --- a/crates/engine/tests/it/assoc_array.rs +++ b/crates/engine/tests/it/assoc_array.rs @@ -336,7 +336,7 @@ fn typed_arrayedit() { let a = rect_array(&mut s); typed(&mut s, &["arrayedit", "l"]); let p = s.prompt_text(); - assert!(p.contains("Enter an option or [Source/REPlace/Base point/Rows/Columns/Levels/RESet/eXit] "), "{p}"); + assert!(p.contains("Enter an option [Source/REPlace/Base point/Rows/Columns/Levels/RESet/eXit] "), "{p}"); typed(&mut s, &["c", "4", "t", "9", "r", "2", "5", ""]); assert!(s.prompt_text().contains("Enter an option"), "{}", s.prompt_text()); assert_eq!(centres(&s, &a).len(), 8); diff --git a/crates/engine/tests/it/layout_prompts.rs b/crates/engine/tests/it/layout_prompts.rs index afa784e0b..8b6ea6637 100644 --- a/crates/engine/tests/it/layout_prompts.rs +++ b/crates/engine/tests/it/layout_prompts.rs @@ -17,7 +17,7 @@ fn typed_layout_options_prompt_for_names() { s.cmdline("LAYOUT").unwrap(); let p = s.current_prompt().expect("LAYOUT prompts").display(); - assert_eq!(p, "Enter layout option or [Copy/Delete/New/Template/Rename/SAveas/Set/?] :"); + assert_eq!(p, "Enter layout option [Copy/Delete/New/Template/Rename/SAveas/Set/?] :"); s.cmdline("n").unwrap(); assert_eq!(s.current_prompt().unwrap().display(), "Enter name of new layout :"); s.cmdline("Sheet9").unwrap(); diff --git a/crates/engine/tests/it/vplayer_prompts.rs b/crates/engine/tests/it/vplayer_prompts.rs index f7f7e4a1a..393ad0958 100644 --- a/crates/engine/tests/it/vplayer_prompts.rs +++ b/crates/engine/tests/it/vplayer_prompts.rs @@ -33,9 +33,9 @@ fn typed_vplayer_changes_layers_in_chosen_viewports() { // Freeze in the current viewport (the default inside a viewport). s.cmdline("VPLAYER").unwrap(); - assert_eq!(s.current_prompt().unwrap().display(), "Enter an option or [?/Color/Freeze/Thaw/Reset/Newfrz/Vpvisdflt]:"); + assert_eq!(s.current_prompt().unwrap().display(), "Enter an option [?/Color/Freeze/Thaw/Reset/Newfrz/Vpvisdflt]:"); s.script("F\n0\n").unwrap(); - assert_eq!(s.current_prompt().unwrap().display(), "Enter an option or [All/Select/Current/Except current] :"); + assert_eq!(s.current_prompt().unwrap().display(), "Enter an option [All/Select/Current/Except current] :"); s.script("\n").unwrap(); assert_eq!(frozen(&s, &a), ["0"]); assert!(frozen(&s, &b).is_empty()); diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 40397df99..fc25555e2 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -494,7 +494,12 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; if !pr.raw && !pr.keywords.is_empty() { - let g = p.layout_no_wrap(if pr.message.is_empty() { " [".into() } else { crate::tl!(" or [").into() }, font.clone(), t.text); + // As the engine's prompt text says it; only " or [" has words to translate. + let lead = match pr.keyword_lead() { + " or [" => crate::tl!(" or ["), + lead => lead, + }; + let g = p.layout_no_wrap(lead.into(), font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 034f261e1..492b9e595 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -357,6 +357,35 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> String { text } +/// The command line in the window draws a prompt's keywords itself; it puts the same words before +/// them as the engine's prompt text: " [" after a prompt for an option ("Enter an option [?/Make/…") +/// and after a question ("Fix any errors detected? [Yes/No]"), " or [" where the keywords are +/// offered besides what is asked ("Specify next point or [Undo]"), " or [" translated. +#[test] +fn the_command_line_says_or_before_keywords_as_the_prompt_does() { + let ctx = egui::Context::default(); + for lang in ["en", "de"] { + let mut app = CadApp::new(Session::new(), Services::default()); + app.run("ui.language", json!({ "lang": lang })).unwrap(); + app.logic(&ctx); + app.session.cmdline("-layer").unwrap(); + let text = render(&mut app, &ctx); + let option = format!("\n{}\n [\n", tr(lang, "Enter an option")); + assert!(text.contains(&option), "{lang}: {option:?} in {text:?}"); + app.session.cancel(); + app.session.cmdline("line").unwrap(); + app.session.cmdline("0,0").unwrap(); + let text = render(&mut app, &ctx); + let besides = format!("\n{}\n{}\n", tr(lang, "Specify next point"), tr(lang, " or [")); + assert!(text.contains(&besides), "{lang}: {besides:?} in {text:?}"); + app.session.cancel(); + app.session.cmdline("audit").unwrap(); + let text = render(&mut app, &ctx); + let question = format!("\n{}\n [\n", tr(lang, "Fix any errors detected?")); + assert!(text.contains(&question), "{lang}: {question:?} in {text:?}"); + } +} + #[test] fn live_switch_translates_the_shell_without_mutating_drawing_or_automation() { let mut app = CadApp::new(Session::new(), Services::default()); From 990ff2ce9f43b8e38fde9266c6975061a91348cd Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:36:37 +0700 Subject: [PATCH 418/900] Say "or" once in prompts that offer options (#2563) * Say "or" once in prompts that offer options Twelve prompt messages ended in "or", and the command line adds "or" before a prompt's options, so they read "or or": HELIX height, XLINE angle and offset, BLEND, four LENGTHEN prompts, two NCOPY prompts, PEDIT and table breaks. They now read as AutoCAD's do. The interface catalogs are keyed by these messages: each key loses its "or" and each translation its trailing word for "or"; where the shorter key already had a translation, the longer row is removed. Co-Authored-By: Claude Opus 5.5 * Say "or" once in HELIX's radius prompts; rename the Vietnamese keys HELIX's base and top radius prompts ended in "or" before their Diameter option too, so they read "Specify base radius or or [Diameter]". They now read "Specify base radius or [Diameter] <1.0000>:", and their keys lose "or" in all 17 catalogs, as the other twelve did. The Vietnamese catalog, merged from main, gets the same renames as the other catalogs; where the shorter key already had a translation, the longer row goes. The unused "Specify rotation angle or" row goes from every catalog too: RECTANG has asked "Specify rotation angle" since #2554. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/draw2/curves3d.rs | 14 ++--- crates/engine/src/cmd/draw2/xline.rs | 4 +- crates/engine/src/cmd/modify2/blend.rs | 2 +- crates/engine/src/cmd/modify2/lengthen.rs | 8 +-- crates/engine/src/cmd/modify2/ncopy.rs | 4 +- crates/engine/src/cmd/modify2/pedit.rs | 2 +- crates/engine/src/cmd/table/breaks.rs | 2 +- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/prompt_or_once.rs | 77 +++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.tsv | 24 +++---- crates/ui-egui/src/i18n/bs.tsv | 24 +++---- crates/ui-egui/src/i18n/cs.tsv | 24 +++---- crates/ui-egui/src/i18n/de.tsv | 24 +++---- crates/ui-egui/src/i18n/el.tsv | 24 +++---- crates/ui-egui/src/i18n/es.tsv | 24 +++---- crates/ui-egui/src/i18n/fr.tsv | 24 +++---- crates/ui-egui/src/i18n/hu.tsv | 24 +++---- crates/ui-egui/src/i18n/it.tsv | 24 +++---- crates/ui-egui/src/i18n/ko.tsv | 24 +++---- crates/ui-egui/src/i18n/pt_br.tsv | 24 +++---- crates/ui-egui/src/i18n/ru.tsv | 24 +++---- crates/ui-egui/src/i18n/sv.tsv | 24 +++---- crates/ui-egui/src/i18n/tests.rs | 11 ++++ crates/ui-egui/src/i18n/tr.tsv | 24 +++---- crates/ui-egui/src/i18n/uk.tsv | 24 +++---- crates/ui-egui/src/i18n/vi.tsv | 24 +++---- crates/ui-egui/src/i18n/zh.tsv | 24 +++---- 27 files changed, 276 insertions(+), 257 deletions(-) create mode 100644 crates/engine/tests/it/prompt_or_once.rs diff --git a/crates/engine/src/cmd/draw2/curves3d.rs b/crates/engine/src/cmd/draw2/curves3d.rs index 005c49f07..faad5442c 100644 --- a/crates/engine/src/cmd/draw2/curves3d.rs +++ b/crates/engine/src/cmd/draw2/curves3d.rs @@ -153,19 +153,17 @@ impl Interactive for HelixM { } match (self.center, self.rb, self.rt) { (None, ..) => Prompt::new("Specify center point of base", Accept::POINT), - (Some(c), None, _) => { - Prompt::new(if self.diameter { "Specify base diameter" } else { "Specify base radius or" }, Accept::POINT_OR_NUMBER) - .kw(if self.diameter { &[] } else { &["Diameter"] }) - .default("1.0000") - .base(c) - } + (Some(c), None, _) => Prompt::new(if self.diameter { "Specify base diameter" } else { "Specify base radius" }, Accept::POINT_OR_NUMBER) + .kw(if self.diameter { &[] } else { &["Diameter"] }) + .default("1.0000") + .base(c), (Some(c), Some(rb), None) => { - Prompt::new(if self.diameter { "Specify top diameter" } else { "Specify top radius or" }, Accept::POINT_OR_NUMBER) + Prompt::new(if self.diameter { "Specify top diameter" } else { "Specify top radius" }, Accept::POINT_OR_NUMBER) .kw(if self.diameter { &[] } else { &["Diameter"] }) .default(format!("{rb:.4}")) .base(c) } - (Some(c), Some(_), Some(_)) => Prompt::new("Specify helix height or", Accept::POINT_OR_NUMBER) + (Some(c), Some(_), Some(_)) => Prompt::new("Specify helix height", Accept::POINT_OR_NUMBER) .kw(&["Axis endpoint", "Turns", "turn Height", "tWist"]) .default("1.0000") .base(c), diff --git a/crates/engine/src/cmd/draw2/xline.rs b/crates/engine/src/cmd/draw2/xline.rs index 31f152d16..78ab5c610 100644 --- a/crates/engine/src/cmd/draw2/xline.rs +++ b/crates/engine/src/cmd/draw2/xline.rs @@ -119,7 +119,7 @@ impl Interactive for XlineM2 { Some(b) => Prompt::new("Specify through point", Accept::POINT).base(b), }, XMode::Fixed(_) => Prompt::new("Specify through point", Accept::POINT), - XMode::AngAsk => Prompt::new("Enter angle of xline (0) or", Accept::NUMBER).kw(&["Reference"]), + XMode::AngAsk => Prompt::new("Enter angle of xline (0)", Accept::NUMBER).kw(&["Reference"]), XMode::RefSelect => Prompt::new("Select a line object", Accept::POINT), XMode::RefAngle(_) => Prompt::new("Enter angle of xline", Accept::NUMBER).default("0"), XMode::Bisect => match self.bis.len() { @@ -129,7 +129,7 @@ impl Interactive for XlineM2 { }, XMode::OffDist => { let d = s.doc().map(|d| d.header.f64("OFFSETDIST", 1.0)).unwrap_or(1.0); - Prompt::new("Specify offset distance or", Accept::NUMBER).kw(&["Through"]).default(if d < 0.0 { + Prompt::new("Specify offset distance", Accept::NUMBER).kw(&["Through"]).default(if d < 0.0 { "Through".into() } else { format!("{d:.4}") diff --git a/crates/engine/src/cmd/modify2/blend.rs b/crates/engine/src/cmd/modify2/blend.rs index 32b477eea..ef2258969 100644 --- a/crates/engine/src/cmd/modify2/blend.rs +++ b/crates/engine/src/cmd/modify2/blend.rs @@ -81,7 +81,7 @@ impl Interactive for BlendM { return Prompt::new("Enter continuity", curves::KW).kw(&["Tangent", "Smooth"]).default("Tangent"); } match self.first { - None => Prompt::new("Select first object or", Accept::POINT).kw(&["CONtinuity"]), + None => Prompt::new("Select first object", Accept::POINT).kw(&["CONtinuity"]), Some(_) => Prompt::new("Select second point", Accept::POINT), } } diff --git a/crates/engine/src/cmd/modify2/lengthen.rs b/crates/engine/src/cmd/modify2/lengthen.rs index 0c86c2c9c..7597ca771 100644 --- a/crates/engine/src/cmd/modify2/lengthen.rs +++ b/crates/engine/src/cmd/modify2/lengthen.rs @@ -194,14 +194,14 @@ impl Interactive for LengthenM { fn prompt(&self, _s: &Session) -> Prompt { match self.phase { LPhase::Main => { - Prompt::new("Select an object to measure or", Accept::POINT).kw(&["DElta", "Percent", "Total", "DYnamic"]).default("DYnamic") + Prompt::new("Select an object to measure", Accept::POINT).kw(&["DElta", "Percent", "Total", "DYnamic"]).default("DYnamic") } - LPhase::Delta => Prompt::new("Enter delta length or", Accept::NUMBER).kw(&["Angle"]).default("0.0000"), + LPhase::Delta => Prompt::new("Enter delta length", Accept::NUMBER).kw(&["Angle"]).default("0.0000"), LPhase::DeltaAngle => Prompt::new("Enter delta angle", Accept::NUMBER).default("0"), LPhase::Percent => Prompt::new("Enter percentage length", Accept::NUMBER).default("100.0000"), - LPhase::Total => Prompt::new("Specify total length or", Accept::NUMBER).kw(&["Angle"]).default("1.0000"), + LPhase::Total => Prompt::new("Specify total length", Accept::NUMBER).kw(&["Angle"]).default("1.0000"), LPhase::TotalAngle => Prompt::new("Specify total angle", Accept::NUMBER).default("57"), - LPhase::Change => Prompt::new("Select an object to change or", Accept::POINT).kw(&["Undo"]), + LPhase::Change => Prompt::new("Select an object to change", Accept::POINT).kw(&["Undo"]), LPhase::DynEnd(..) => Prompt::new("Specify new end point", Accept::POINT), } } diff --git a/crates/engine/src/cmd/modify2/ncopy.rs b/crates/engine/src/cmd/modify2/ncopy.rs index 475256e84..9b6f9eeb2 100644 --- a/crates/engine/src/cmd/modify2/ncopy.rs +++ b/crates/engine/src/cmd/modify2/ncopy.rs @@ -87,8 +87,8 @@ impl Interactive for NcopyM { } fn prompt(&self, _s: &Session) -> Prompt { match (self.selecting_done, self.base) { - (false, _) => Prompt::new("Select nested objects to copy or", Accept::POINT).kw(&["Settings"]), - (true, None) => Prompt::new("Specify base point or", Accept::POINT).kw(&["Displacement", "Multiple"]).default("Displacement"), + (false, _) => Prompt::new("Select nested objects to copy", Accept::POINT).kw(&["Settings"]), + (true, None) => Prompt::new("Specify base point", Accept::POINT).kw(&["Displacement", "Multiple"]).default("Displacement"), (true, Some(b)) => Prompt::new("Specify second point or ", Accept::POINT).base(b), } } diff --git a/crates/engine/src/cmd/modify2/pedit.rs b/crates/engine/src/cmd/modify2/pedit.rs index 0c1b64879..59d614323 100644 --- a/crates/engine/src/cmd/modify2/pedit.rs +++ b/crates/engine/src/cmd/modify2/pedit.rs @@ -398,7 +398,7 @@ impl Interactive for PeditM { fn prompt(&self, s: &Session) -> Prompt { match self.phase { PPhase::MSelect | PPhase::MConvert | PPhase::MMain | PPhase::MWidth | PPhase::MFuzz => self.multi_prompt(), - PPhase::Select => Prompt::new("Select polyline or", Accept::POINT).kw(&["Multiple"]), + PPhase::Select => Prompt::new("Select polyline", Accept::POINT).kw(&["Multiple"]), PPhase::Convert => { Prompt::new("Object selected is not a polyline. Do you want to turn it into one?", curves::KW).kw(&["Yes", "No"]).default("Y") } diff --git a/crates/engine/src/cmd/table/breaks.rs b/crates/engine/src/cmd/table/breaks.rs index 38ed33bce..6f207ec50 100644 --- a/crates/engine/src/cmd/table/breaks.rs +++ b/crates/engine/src/cmd/table/breaks.rs @@ -112,7 +112,7 @@ impl Interactive for BreakM { fn prompt(&self, _s: &Session) -> Prompt { match self.table { None => Prompt::new("Select a table", Accept::SELECT), - Some(_) => Prompt::new("Enter maximum part height or", Accept::POINT_OR_NUMBER).kw(&["Off"]), + Some(_) => Prompt::new("Enter maximum part height", Accept::POINT_OR_NUMBER).kw(&["Off"]), } } fn input(&mut self, s: &mut Session, i: Input) -> Result { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 54ea40675..d3c8d030d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -107,6 +107,7 @@ mod point_modifiers; mod polyface_explode; mod post_command_passes; mod prompt_keywords; +mod prompt_or_once; mod props_bad_lineweight; mod props_insert_scale_attribs; mod purge_mlinestyles; diff --git a/crates/engine/tests/it/prompt_or_once.rs b/crates/engine/tests/it/prompt_or_once.rs new file mode 100644 index 000000000..c84c58b1c --- /dev/null +++ b/crates/engine/tests/it/prompt_or_once.rs @@ -0,0 +1,77 @@ +//! Prompts that offer options say "or" once, as AutoCAD 2024's do: "Enter angle of xline (0) or +//! [Reference]:". The prompt adds "or" before its options, so a message that ended in "or" read +//! "or or". + +use cadcraft_engine::Session; +use serde_json::json; + +fn shows(s: &Session, text: &str) { + let p = s.prompt_text(); + assert!(p.ends_with(text), "{p}"); + assert!(!p.contains(" or or "), "{p}"); +} + +#[test] +fn xline_angle_and_offset() { + let mut s = Session::new(); + s.cmdline("xline").unwrap(); + s.cmdline("a").unwrap(); + shows(&s, "Enter angle of xline (0) or [Reference]:"); + s.cancel(); + s.cmdline("xline").unwrap(); + s.cmdline("o").unwrap(); + shows(&s, "Specify offset distance or [Through] <1.0000>:"); +} + +#[test] +fn helix_radii_and_height() { + let mut s = Session::new(); + s.script("helix\n0,0\n").unwrap(); + shows(&s, "Specify base radius or [Diameter] <1.0000>:"); + s.cmdline("5").unwrap(); + shows(&s, "Specify top radius or [Diameter] <5.0000>:"); + s.cmdline("").unwrap(); + shows(&s, "Specify helix height or [Axis endpoint/Turns/turn Height/tWist] <1.0000>:"); +} + +#[test] +fn blend_first_object() { + let mut s = Session::new(); + s.cmdline("blend").unwrap(); + shows(&s, "Select first object or [CONtinuity]:"); +} + +#[test] +fn lengthen_options() { + let mut s = Session::new(); + s.cmdline("lengthen").unwrap(); + shows(&s, "Select an object to measure or [DElta/Percent/Total/DYnamic] :"); + s.cmdline("de").unwrap(); + shows(&s, "Enter delta length or [Angle] <0.0000>:"); + s.cmdline("2").unwrap(); + shows(&s, "Select an object to change or [Undo]:"); + s.cancel(); + s.cmdline("lengthen").unwrap(); + s.cmdline("t").unwrap(); + shows(&s, "Specify total length or [Angle] <1.0000>:"); +} + +#[test] +fn ncopy_pedit_and_table_break() { + let mut s = Session::new(); + s.script("line 25,-5 25,5\n\nline 0,0 10,0\n\n-block B 0,0 L\n\n").unwrap(); + s.execute("insert", &json!({ "name": "B", "at": [20, 0] })).unwrap(); + s.cmdline("zoom e").unwrap(); + s.cmdline("ncopy").unwrap(); + shows(&s, "Select nested objects to copy or [Settings]:"); + s.script("22,0\n\n").unwrap(); + shows(&s, "Specify base point or [Displacement/Multiple] :"); + s.cancel(); + s.cmdline("pedit").unwrap(); + shows(&s, "Select polyline or [Multiple]:"); + s.cancel(); + s.execute("table", &json!({ "at": [0, 20], "cells": [["1", ""], ["2", ""]], "rowHeight": 1.0, "colWidth": 3.0 })).unwrap(); + s.cmdline("table.break").unwrap(); + s.cmdline("1,19.5").unwrap(); + shows(&s, "Enter maximum part height or [Off]:"); +} diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index ccc9b72d5..7713378d9 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -305,7 +305,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 أدخل اسم وسم السمة @@ -316,7 +316,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] @@ -852,8 +852,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. حدد خطاً مفتوحاً أو قوساً أو متعدد خطوط أو قوس إهليلج أو سبلاين. @@ -867,9 +867,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 حدد كائناً لتقسيمه @@ -886,7 +885,7 @@ Select one polyline (Multiple is available through the JSON form). حدد متعدد خطوط واحداً (يتوفر الوضع المتعدد عبر نموذج 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 حدد الكائن الثاني @@ -956,9 +955,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 حدد مركز المضلع @@ -1000,7 +998,7 @@ Specify first point on circle: _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 حدد نقطة الإدراج @@ -1019,7 +1017,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 حدد نقطة النهاية الأخرى للمحور @@ -1032,7 +1029,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 حدد نقطة الفصل الثانية @@ -1065,9 +1061,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 سبلاين diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 460959a33..b349db278 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -281,7 +281,7 @@ Enter a vertex editing option Unesite opciju uređivanja tjemena Enter an option Unesite opciju Enter angle of xline Unesite ugao konstrukcijske linije - Enter angle of xline (0) or Unesite ugao konstrukcijske linije (0) ili + Enter angle of xline (0) Unesite ugao konstrukcijske linije (0) Enter area of rectangle in current units Unesite površinu pravougaonika u trenutnim jedinicama Enter attribute prompt Unesite upit atributa Enter attribute tag name Unesite naziv oznake atributa @@ -292,7 +292,7 @@ Enter default attribute value Unesite zadanu vrijednost atributa Enter degree of spline Unesite stepen splajna Enter delta angle Unesite delta ugao - Enter delta length or Unesite delta dužinu ili + Enter delta length Unesite delta dužinu Enter dimension text Unesite tekst kote Enter dimension text (<> = measurement) Unesite tekst kote (<> = mjera) Enter dimension value or [name=expression] Unesite vrijednost kote ili [naziv=izraz] @@ -788,8 +788,8 @@ Select an arc or circle Odaberite luk ili krug Select an arc. Odaberite luk. Select an object Odaberite objekat - Select an object to change or Odaberite objekat za promjenu ili - Select an object to measure or Odaberite objekat za mjerenje ili + Select an object to change Odaberite objekat za promjenu + Select an object to measure Odaberite objekat za mjerenje Select an object. Odaberite objekat. Select an open curve. Odaberite otvorenu krivu. Select an open line, arc, polyline, ellipse arc or spline. Odaberite otvorenu liniju, luk, poliliniju, eliptični luk ili splajn. @@ -803,14 +803,13 @@ Select first line Odaberite prvu liniju Select first line or arc Odaberite prvu liniju ili luk Select first object Odaberite prvi objekat - Select first object or Odaberite prvi objekat ili Select first point Odaberite prvu tačku Add to Working Set Dodaj u radni skup Edit Reference In-Place Uredi referencu na mjestu Save Reference Edits Sačuvaj izmjene reference Working Set Radni skup Xref and Block In-place Editing Uređivanje vanjskih referenci i blokova na mjestu - Select nested objects to copy or Odaberite ugniježđene objekte za kopiranje ili + Select nested objects to copy Odaberite ugniježđene objekte za kopiranje Select object Odaberite objekat Select object to dimension Odaberite objekat za kotiranje Select object to divide Odaberite objekat za dijeljenje @@ -826,7 +825,7 @@ Select one polyline (Multiple is available through the JSON form). Odaberite jednu poliliniju (Višestruko je dostupno putem JSON oblika). Select path curve Odaberite krivu putanje Select point or object Odaberite tačku ili objekat - Select polyline or Odaberite poliliniju ili + Select polyline Odaberite poliliniju Select second line Odaberite drugu liniju Select second line or shift-select to apply corner Odaberite drugu liniju ili Shift+odabir za primjenu ugla Select second object Odaberite drugi objekat @@ -884,9 +883,8 @@ Specify axis endpoint of ellipse Navedite krajnju tačku ose elipse Specify base diameter Navedite prečnik baze Specify base point Navedite baznu tačku - Specify base point or Navedite baznu tačku ili Specify base point or displacement (drag with the middle mouse button for realtime pan) Navedite baznu tačku ili pomak (prevucite srednjim dugmetom miša za pomicanje pogleda u stvarnom vremenu) - Specify base radius or Navedite poluprečnik baze ili + Specify base radius Navedite poluprečnik baze Specify center of donut Navedite središte prstena Specify center of ellipse Navedite središte elipse Specify center of polygon Navedite središte mnogougla @@ -928,7 +926,7 @@ Specify first point on circle: _tan to Navedite prvu tačku na krugu: _tan na Specify first source point Navedite prvu izvornu tačku Specify height Navedite visinu - Specify helix height or Navedite visinu spirale ili + Specify helix height Navedite visinu spirale Specify included angle Navedite obuhvaćeni ugao Specify insertion base point Navedite baznu tačku umetanja Specify insertion point Navedite tačku umetanja @@ -982,7 +980,6 @@ Specify new width for all segments Navedite novu širinu za sve segmente Specify next point Navedite sljedeću tačku Specify offset distance Navedite udaljenost odmaka - Specify offset distance or Navedite udaljenost odmaka ili Specify opposite corner Navedite suprotni ugao Specify other corner point Navedite tačku drugog ugla Specify other endpoint of axis Navedite drugu krajnju tačku ose @@ -995,7 +992,6 @@ Specify radius of circle Navedite poluprečnik kruga Specify rotation angle Navedite ugao rotacije Specify rotation angle of text Navedite ugao rotacije teksta - Specify rotation angle or Navedite ugao rotacije ili Specify scale factor Navedite faktor skale Specify second angle endpoint Navedite drugu krajnju tačku ugla Specify second break point Navedite drugu tačku prekida @@ -1028,9 +1024,9 @@ Specify third source point or Navedite treću izvornu tačku ili Specify through point Navedite tačku kroz koju prolazi Specify top diameter Navedite gornji prečnik - Specify top radius or Navedite gornji poluprečnik ili + Specify top radius Navedite gornji poluprečnik Specify total angle Navedite ukupni ugao - Specify total length or Navedite ukupnu dužinu ili + Specify total length Navedite ukupnu dužinu Specify width for rectangles Navedite širinu za pravougaonike Sphere Sfera Spline Splajn diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2419bf41f..61dc1b2b6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -279,7 +279,7 @@ Enter a vertex editing option Zadejte možnost úpravy vrcholů Enter an option Zadejte možnost Enter angle of xline Zadejte úhel přímky - Enter angle of xline (0) or Zadejte úhel přímky (0) nebo + Enter angle of xline (0) Zadejte úhel přímky (0) Enter area of rectangle in current units Zadejte plochu obdélníku v aktuálních jednotkách Enter attribute prompt Zadejte výzvu atributu Enter attribute tag name Zadejte označení atributu @@ -290,7 +290,7 @@ Enter default attribute value Zadejte výchozí hodnotu atributu Enter degree of spline Zadejte stupeň spline Enter delta angle Zadejte změnu úhlu - Enter delta length or Zadejte změnu délky nebo + Enter delta length Zadejte změnu délky Enter dimension text Zadejte text kóty Enter dimension text (<> = measurement) Zadejte text kóty (<> = naměřená hodnota) Enter dimension value or [name=expression] Zadejte hodnotu kóty nebo [name=expression] @@ -786,8 +786,8 @@ Select an arc or circle Vyberte oblouk nebo kružnici Select an arc. Vyberte oblouk. Select an object Vyberte objekt - Select an object to change or Vyberte objekt ke změně nebo - Select an object to measure or Vyberte objekt k měření nebo + Select an object to change Vyberte objekt ke změně + Select an object to measure Vyberte objekt k měření Select an object. Vyberte objekt. Select an open curve. Vyberte otevřenou křivku. Select an open line, arc, polyline, ellipse arc or spline. Vyberte otevřenou úsečku, oblouk, křivku, eliptický oblouk nebo spline. @@ -801,14 +801,13 @@ Select first line Vyberte první úsečku Select first line or arc Vyberte první úsečku nebo oblouk Select first object Vyberte první objekt - Select first object or Vyberte první objekt nebo Select first point Vyberte první bod Add to Working Set Přidat do pracovní sady Edit Reference In-Place Upravit referenci na místě Save Reference Edits Uložit úpravy reference Working Set Pracovní sada Xref and Block In-place Editing Úpravy xref a bloků na místě - Select nested objects to copy or Vyberte vnořené objekty ke kopírování nebo + Select nested objects to copy Vyberte vnořené objekty ke kopírování Select object Vyberte objekt Select object to dimension Vyberte objekt ke kótování Select object to divide Vyberte objekt k dělení @@ -824,7 +823,7 @@ Select one polyline (Multiple is available through the JSON form). Vyberte jednu křivku (možnost Multiple je dostupná ve formě JSON). Select path curve Vyberte křivku trajektorie Select point or object Vyberte bod nebo objekt - Select polyline or Vyberte křivku nebo + Select polyline Vyberte křivku Select second line Vyberte druhou úsečku Select second line or shift-select to apply corner Vyberte druhou úsečku; s klávesou Shift vytvoříte roh Select second object Vyberte druhý objekt @@ -882,9 +881,8 @@ Specify axis endpoint of ellipse Určete koncový bod osy elipsy Specify base diameter Určete průměr základny Specify base point Určete základní bod - Specify base point or Určete základní bod nebo Specify base point or displacement (drag with the middle mouse button for realtime pan) Určete základní bod nebo posunutí (tažením prostředním tlačítkem myši posunete pohled v reálném čase) - Specify base radius or Určete poloměr základny nebo + Specify base radius Určete poloměr základny Specify center of donut Určete střed prstence Specify center of ellipse Určete střed elipsy Specify center of polygon Určete střed mnohoúhelníku @@ -926,7 +924,7 @@ Specify first point on circle: _tan to Určete první bod na kružnici: _tan k Specify first source point Určete první zdrojový bod Specify height Určete výšku - Specify helix height or Určete výšku šroubovice nebo + Specify helix height Určete výšku šroubovice Specify included angle Určete středový úhel Specify insertion base point Určete základní bod vložení Specify insertion point Určete bod vložení @@ -980,7 +978,6 @@ Specify new width for all segments Určete novou šířku všech segmentů Specify next point Určete další bod Specify offset distance Určete vzdálenost ekvidistanty - Specify offset distance or Určete vzdálenost ekvidistanty nebo Specify opposite corner Určete protilehlý roh Specify other corner point Určete bod druhého rohu Specify other endpoint of axis Určete druhý koncový bod osy @@ -993,7 +990,6 @@ Specify radius of circle Určete poloměr kružnice Specify rotation angle Určete úhel otočení Specify rotation angle of text Určete úhel otočení textu - Specify rotation angle or Určete úhel otočení nebo Specify scale factor Určete faktor měřítka Specify second angle endpoint Určete druhý koncový bod úhlu Specify second break point Určete druhý bod přerušení @@ -1026,9 +1022,9 @@ Specify third source point or Určete třetí zdrojový bod nebo Specify through point Určete bod, kterým má procházet Specify top diameter Určete horní průměr - Specify top radius or Určete horní poloměr nebo + Specify top radius Určete horní poloměr Specify total angle Určete celkový úhel - Specify total length or Určete celkovou délku nebo + Specify total length Určete celkovou délku Specify width for rectangles Určete šířku obdélníků Sphere Koule Spline Spline diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2186fc743..f36e9ed02 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -222,7 +222,7 @@ Enter a vertex editing option Geben Sie eine Option zur Scheitelpunktbearbeitung ein Enter an option Geben Sie eine Option ein Enter angle of xline Geben Sie den Winkel der Konstruktionslinie ein - Enter angle of xline (0) or Geben Sie den Winkel der Konstruktionslinie ein (0) oder + Enter angle of xline (0) Geben Sie den Winkel der Konstruktionslinie ein (0) Enter area of rectangle in current units Geben Sie die Fläche des Rechtecks in den aktuellen Einheiten ein Enter attribute prompt Geben Sie die Attributaufforderung ein Enter attribute tag name Geben Sie den Attribut-Tag-Namen ein @@ -233,7 +233,7 @@ Enter default attribute value Geben Sie den Standard-Attributwert ein Enter degree of spline Geben Sie den Grad des Splines ein Enter delta angle Geben Sie den Delta-Winkel ein - Enter delta length or Geben Sie die Delta-Länge ein oder + Enter delta length Geben Sie die Delta-Länge ein Enter dimension text Geben Sie den Bemaßungstext ein Enter dimension text (<> = measurement) Geben Sie den Bemaßungstext ein (<> = Messwert) Enter dimension value or [name=expression] Geben Sie einen Bemaßungswert oder [name=expression] ein @@ -676,8 +676,8 @@ Select an arc or circle Wählen Sie einen Bogen oder Kreis Select an arc. Wählen Sie einen Bogen. Select an object Wählen Sie ein Objekt - Select an object to change or Wählen Sie ein zu änderndes Objekt oder - Select an object to measure or Wählen Sie ein zu messendes Objekt oder + Select an object to change Wählen Sie ein zu änderndes Objekt + Select an object to measure Wählen Sie ein zu messendes Objekt Select an object. Wählen Sie ein Objekt. Add to Working Set Zum Arbeitssatz hinzufügen Edit Reference In-Place Referenz an Ort und Stelle bearbeiten @@ -696,9 +696,8 @@ Select first line Wählen Sie die erste Linie Select first line or arc Wählen Sie die erste Linie oder den ersten Bogen Select first object Wählen Sie das erste Objekt - Select first object or Wählen Sie das erste Objekt oder Select first point Wählen Sie den ersten Punkt - Select nested objects to copy or Wählen Sie zu kopierende verschachtelte Objekte oder + Select nested objects to copy Wählen Sie zu kopierende verschachtelte Objekte Select object Wählen Sie ein Objekt Select object to dimension Wählen Sie das zu bemaßende Objekt Select object to divide Wählen Sie das zu teilende Objekt @@ -714,7 +713,7 @@ Select one polyline (Multiple is available through the JSON form). Wählen Sie eine Polylinie (Multiple ist über die JSON-Form verfügbar). Select path curve Wählen Sie die Pfadkurve Select point or object Wählen Sie einen Punkt oder ein Objekt - Select polyline or Wählen Sie eine Polylinie oder + Select polyline Wählen Sie eine Polylinie Select second line Wählen Sie die zweite Linie Select second line or shift-select to apply corner Wählen Sie die zweite Linie oder wählen Sie mit der Umschalttaste, um eine Ecke anzuwenden Select second object Wählen Sie das zweite Objekt @@ -767,9 +766,8 @@ Specify axis endpoint of ellipse Geben Sie den Achsenendpunkt der Ellipse an Specify base diameter Geben Sie den Basisdurchmesser an Specify base point Geben Sie den Basispunkt an - Specify base point or Geben Sie den Basispunkt an oder Specify base point or displacement (drag with the middle mouse button for realtime pan) Geben Sie den Basispunkt oder die Verschiebung an (ziehen Sie mit der mittleren Maustaste zum Schwenken in Echtzeit) - Specify base radius or Geben Sie den Basisradius an oder + Specify base radius Geben Sie den Basisradius an Specify center of donut Geben Sie den Mittelpunkt des Rings an Specify center of ellipse Geben Sie den Mittelpunkt der Ellipse an Specify center of polygon Geben Sie den Mittelpunkt des Polygons an @@ -811,7 +809,7 @@ Specify first point on circle: _tan to Geben Sie den ersten Punkt auf dem Kreis an: _tan zu Specify first source point Geben Sie den ersten Quellpunkt an Specify height Geben Sie die Höhe an - Specify helix height or Geben Sie die Höhe der Helix an oder + Specify helix height Geben Sie die Höhe der Helix an Specify included angle Geben Sie den eingeschlossenen Winkel an Specify insertion base point Geben Sie den Einfügebasispunkt an Specify insertion point Geben Sie den Einfügepunkt an @@ -830,7 +828,6 @@ Specify new width for all segments Geben Sie die neue Breite für alle Segmente an Specify next point Geben Sie den nächsten Punkt an Specify offset distance Geben Sie den Versatzabstand an - Specify offset distance or Geben Sie den Versatzabstand an oder Specify opposite corner Geben Sie die gegenüberliegende Ecke an Specify other corner point Geben Sie den anderen Eckpunkt an Specify other endpoint of axis Geben Sie den anderen Endpunkt der Achse an @@ -843,7 +840,6 @@ Specify radius of circle Geben Sie den Radius des Kreises an Specify rotation angle Geben Sie den Drehwinkel an Specify rotation angle of text Geben Sie den Drehwinkel des Textes an - Specify rotation angle or Geben Sie den Drehwinkel an oder Specify scale factor Geben Sie den Skalierfaktor an Specify second angle endpoint Geben Sie den zweiten Endpunkt des Winkels an Specify second break point Geben Sie den zweiten Unterbrechungspunkt an @@ -876,9 +872,9 @@ Specify third source point or Geben Sie den dritten Quellpunkt an oder Specify through point Geben Sie den Durchgangspunkt an Specify top diameter Geben Sie den oberen Durchmesser an - Specify top radius or Geben Sie den oberen Radius an oder + Specify top radius Geben Sie den oberen Radius an Specify total angle Geben Sie den Gesamtwinkel an - Specify total length or Geben Sie die Gesamtlänge an oder + Specify total length Geben Sie die Gesamtlänge an Specify width for rectangles Geben Sie die Breite für Rechtecke an Sphere Kugel Spline Spline diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 16fcecfeb..528dacf55 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -337,7 +337,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 Εισαγάγετε όνομα ετικέτας ιδιότητας @@ -348,7 +348,7 @@ Enter default attribute value Εισαγάγετε προεπιλεγμένη τιμή ιδιότητας Enter degree of spline Εισαγάγετε βαθμό καμπύλης spline Enter delta angle Εισαγάγετε μεταβολή γωνίας - Enter delta length or Εισαγάγετε μεταβολή μήκους ή + Enter delta length Εισαγάγετε μεταβολή μήκους Enter dimension text Εισαγάγετε κείμενο διάστασης Enter dimension text (<> = measurement) Εισαγάγετε κείμενο διάστασης (<> = μέτρηση) Enter dimension value or [name=expression] Εισαγάγετε τιμή διάστασης ή [όνομα=έκφραση] @@ -919,8 +919,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. Επιλέξτε ανοικτή γραμμή, τόξο, πολυγραμμή, ελλειπτικό τόξο ή καμπύλη spline. @@ -934,9 +934,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 Επιλέξτε αντικείμενο για διαίρεση @@ -954,7 +953,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 Επιλέξτε δεύτερο αντικείμενο @@ -1036,9 +1035,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 Καθορίστε κέντρο πολυγώνου @@ -1080,7 +1078,7 @@ Specify first point on circle: _tan to Καθορίστε πρώτο σημείο επάνω στον κύκλο: _tan προς Specify first source point Καθορίστε πρώτο σημείο προέλευσης Specify height Καθορίστε ύψος - Specify helix height or Καθορίστε ύψος έλικας ή + Specify helix height Καθορίστε ύψος έλικας Specify included angle Καθορίστε περιεχόμενη γωνία Specify insertion base point Καθορίστε σημείο βάσης εισαγωγής Specify insertion point Καθορίστε σημείο εισαγωγής @@ -1099,7 +1097,6 @@ Specify new width for all segments Καθορίστε νέο πλάτος για όλα τα τμήματα Specify next point Καθορίστε επόμενο σημείο Specify offset distance Καθορίστε απόσταση παράλληλης μετατόπισης (Offset) - Specify offset distance or Καθορίστε απόσταση παράλληλης μετατόπισης ή Specify opposite corner Καθορίστε απέναντι γωνία Specify other corner point Καθορίστε το άλλο γωνιακό σημείο Specify other endpoint of axis Καθορίστε το άλλο τελικό σημείο άξονα @@ -1112,7 +1109,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 Καθορίστε δεύτερο σημείο διακοπής @@ -1145,9 +1141,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 Σφαίρα Spherical Σφαιρικό diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8c45b7f97..457341c36 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -295,7 +295,7 @@ Enter a vertex editing option Introduce una opción de edición de vértices Enter an option Introduce una opción Enter angle of xline Introduce el ángulo de la línea auxiliar - Enter angle of xline (0) or Introduce el ángulo de la línea auxiliar (0) o + Enter angle of xline (0) Introduce el ángulo de la línea auxiliar (0) Enter area of rectangle in current units Introduce el área del rectángulo en las unidades actuales Enter attribute prompt Introduce la solicitud del atributo Enter attribute tag name Introduce la etiqueta del atributo @@ -306,7 +306,7 @@ Enter default attribute value Introduce el valor predeterminado del atributo Enter degree of spline Introduce el grado de la spline Enter delta angle Introduce el incremento angular - Enter delta length or Introduce el incremento de longitud o + Enter delta length Introduce el incremento de longitud Enter dimension text Introduce el texto de cota Enter dimension text (<> = measurement) Introduce el texto de cota (<> = medida) Enter dimension value or [name=expression] Introduce el valor de cota o [nombre=expresión] @@ -885,8 +885,8 @@ Select an arc or circle Selecciona un arco o círculo Select an arc. Selecciona un arco. Select an object Selecciona un objeto - Select an object to change or Selecciona un objeto que modificar o - Select an object to measure or Selecciona un objeto que medir o + Select an object to change Selecciona un objeto que modificar + Select an object to measure Selecciona un objeto que medir Select an object. Selecciona un objeto. Select an open curve. Selecciona una curva abierta. Select an open line, arc, polyline, ellipse arc or spline. Selecciona una línea, arco, polilínea, arco elíptico o spline abierta. @@ -900,9 +900,8 @@ Select first line Selecciona la primera línea Select first line or arc Selecciona la primera línea o arco Select first object Selecciona el primer objeto - Select first object or Selecciona el primer objeto o Select first point Selecciona el primer punto - Select nested objects to copy or Selecciona objetos anidados para copiar o + Select nested objects to copy Selecciona objetos anidados para copiar Select object Selecciona un objeto Select object to dimension Selecciona un objeto para acotar Select object to divide Selecciona un objeto para dividir @@ -918,7 +917,7 @@ Select one polyline (Multiple is available through the JSON form). Selecciona una polilínea (la opción Multiple está disponible en la forma JSON). Select path curve Selecciona la curva del camino Select point or object Selecciona un punto u objeto - Select polyline or Selecciona una polilínea o + Select polyline Selecciona una polilínea Select second line Selecciona la segunda línea Select second line or shift-select to apply corner Selecciona la segunda línea o usa Mayús para aplicar una esquina Select second object Selecciona el segundo objeto @@ -971,9 +970,8 @@ Specify axis endpoint of ellipse Indica el extremo del eje de la elipse Specify base diameter Indica el diámetro de la base Specify base point Indica el punto base - Specify base point or Indica el punto base o Specify base point or displacement (drag with the middle mouse button for realtime pan) Indica el punto base o el desplazamiento (arrastra con el botón central para encuadrar) - Specify base radius or Indica el radio de la base o + Specify base radius Indica el radio de la base Specify center of donut Indica el centro de la arandela Specify center of ellipse Indica el centro de la elipse Specify center of polygon Indica el centro del polígono @@ -1015,7 +1013,7 @@ Specify first point on circle: _tan to Indica el primer punto del círculo: _tan a Specify first source point Indica el primer punto de origen Specify height Indica la altura - Specify helix height or Indica la altura de la hélice o + Specify helix height Indica la altura de la hélice Specify included angle Indica el ángulo incluido Specify insertion base point Indica el punto base de inserción Specify insertion point Indica el punto de inserción @@ -1034,7 +1032,6 @@ Specify new width for all segments Indica la nueva anchura de todos los segmentos Specify next point Indica el siguiente punto Specify offset distance Indica la distancia de desfase - Specify offset distance or Indica la distancia de desfase o Specify opposite corner Indica la esquina opuesta Specify other corner point Indica el punto de la otra esquina Specify other endpoint of axis Indica el otro extremo del eje @@ -1047,7 +1044,6 @@ Specify radius of circle Indica el radio del círculo Specify rotation angle Indica el ángulo de giro Specify rotation angle of text Indica el ángulo de giro del texto - Specify rotation angle or Indica el ángulo de giro o Specify scale factor Indica el factor de escala Specify second angle endpoint Indica el segundo extremo del ángulo Specify second break point Indica el segundo punto de ruptura @@ -1080,9 +1076,9 @@ Specify third source point or Indica el tercer punto de origen o Specify through point Indica el punto a atravesar Specify top diameter Indica el diámetro superior - Specify top radius or Indica el radio superior o + Specify top radius Indica el radio superior Specify total angle Indica el ángulo total - Specify total length or Indica la longitud total o + Specify total length Indica la longitud total Specify width for rectangles Indica la anchura de los rectángulos Sphere Esfera Spline Spline diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 548ed6a66..62c77c3f9 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -221,7 +221,7 @@ Enter a vertex editing option Entrez une option d'édition de sommet Enter an option Entrez une option Enter angle of xline Entrez l'angle de la ligne de construction - Enter angle of xline (0) or Entrez l'angle de la ligne de construction (0) ou + Enter angle of xline (0) Entrez l'angle de la ligne de construction (0) Enter area of rectangle in current units Entrez l'aire du rectangle dans les unités courantes Enter attribute prompt Entrez l'invite de l'attribut Enter attribute tag name Entrez le nom de l'étiquette d'attribut @@ -232,7 +232,7 @@ Enter default attribute value Entrez la valeur par défaut de l'attribut Enter degree of spline Entrez le degré de la spline Enter delta angle Entrez l'écart d'angle - Enter delta length or Entrez l'écart de longueur ou + Enter delta length Entrez l'écart de longueur Enter dimension text Entrez le texte de cotation Enter dimension text (<> = measurement) Entrez le texte de cotation (<> = mesure) Enter dimension value or [name=expression] Entrez la valeur de cotation ou [name=expression] @@ -675,8 +675,8 @@ Select an arc or circle Sélectionner un arc ou un cercle Select an arc. Sélectionner un arc. Select an object Sélectionner un objet - Select an object to change or Sélectionner un objet à modifier ou - Select an object to measure or Sélectionner un objet à mesurer ou + Select an object to change Sélectionner un objet à modifier + Select an object to measure Sélectionner un objet à mesurer Select an object. Sélectionner un objet. Select an open curve. Sélectionner une courbe ouverte. Select an open line, arc, polyline, ellipse arc or spline. Sélectionner une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts. @@ -690,9 +690,8 @@ Select first line Sélectionner la première ligne Select first line or arc Sélectionner la première ligne ou le premier arc Select first object Sélectionner le premier objet - Select first object or Sélectionner le premier objet ou Select first point Sélectionner le premier point - Select nested objects to copy or Sélectionner des objets imbriqués à copier ou + Select nested objects to copy Sélectionner des objets imbriqués à copier Select object Sélectionner un objet Select object to dimension Sélectionner un objet à coter Select object to divide Sélectionner un objet à diviser @@ -708,7 +707,7 @@ Select one polyline (Multiple is available through the JSON form). Sélectionner une polyligne (l'option Multiple est disponible via le formulaire JSON). Select path curve Sélectionner la courbe de trajectoire Select point or object Sélectionner un point ou un objet - Select polyline or Sélectionner une polyligne ou + Select polyline Sélectionner une polyligne Select second line Sélectionner la deuxième ligne Select second line or shift-select to apply corner Sélectionner la deuxième ligne ou sélectionner avec Maj pour former le coin Select second object Sélectionner le deuxième objet @@ -761,9 +760,8 @@ Specify axis endpoint of ellipse Spécifier l'extrémité de l'axe de l'ellipse Specify base diameter Spécifiez le diamètre de la base Specify base point Spécifiez le point de base - Specify base point or Spécifiez le point de base ou Specify base point or displacement (drag with the middle mouse button for realtime pan) Spécifiez le point de base ou le déplacement (faites glisser avec le bouton central de la souris pour un panoramique en temps réel) - Specify base radius or Spécifiez le rayon de base ou + Specify base radius Spécifiez le rayon de base Specify center of donut Spécifiez le centre de l'anneau Specify center of ellipse Spécifiez le centre de l'ellipse Specify center of polygon Spécifiez le centre du polygone @@ -805,7 +803,7 @@ Specify first point on circle: _tan to Spécifiez le premier point sur le cercle : _tan à Specify first source point Spécifiez le premier point source Specify height Spécifiez la hauteur - Specify helix height or Spécifiez la hauteur de l'hélice ou + Specify helix height Spécifiez la hauteur de l'hélice Specify included angle Spécifiez l'angle inclus Specify insertion base point Spécifiez le point de base d'insertion Specify insertion point Spécifiez le point d'insertion @@ -824,7 +822,6 @@ Specify new width for all segments Spécifiez la nouvelle largeur de tous les segments Specify next point Spécifiez le point suivant Specify offset distance Spécifiez la distance de décalage - Specify offset distance or Spécifiez la distance de décalage ou Specify opposite corner Spécifiez le coin opposé Specify other corner point Spécifiez l'autre point d'angle Specify other endpoint of axis Spécifiez l'autre point final de l'axe @@ -837,7 +834,6 @@ Specify radius of circle Spécifiez le rayon du cercle Specify rotation angle Spécifiez l'angle de rotation Specify rotation angle of text Spécifiez l'angle de rotation du texte - Specify rotation angle or Spécifiez l'angle de rotation ou Specify scale factor Spécifiez le facteur d'échelle Specify second angle endpoint Spécifiez le deuxième point final de l'angle Specify second break point Spécifiez le deuxième point de rupture @@ -870,9 +866,9 @@ Specify third source point or Spécifiez le troisième point source ou Specify through point Spécifiez le point de passage Specify top diameter Spécifiez le diamètre supérieur - Specify top radius or Spécifiez le rayon supérieur ou + Specify top radius Spécifiez le rayon supérieur Specify total angle Spécifiez l'angle total - Specify total length or Spécifiez la longueur totale ou + Specify total length Spécifiez la longueur totale Specify width for rectangles Spécifiez la largeur des rectangles Sphere Sphère Spline Spline diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 926ad0e6c..e486f6337 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -350,7 +350,7 @@ Enter a vertex editing option Válassz egy csúcspont-szerkesztési lehetőséget Enter an option Válassz egy lehetőséget Enter angle of xline Add meg a szerkesztővonal szögét - Enter angle of xline (0) or Add meg a szerkesztővonal szögét (0) + Enter angle of xline (0) Add meg a szerkesztővonal szögét (0) Enter area of rectangle in current units Add meg a téglalap területét az aktuális mértékegységben Enter attribute prompt Add meg az attribútum bekérő szövegét Enter attribute tag name Add meg az attribútum címkéjét @@ -361,7 +361,7 @@ Enter default attribute value Add meg az attribútum alapértelmezett értékét Enter degree of spline Add meg a spline fokszámát Enter delta angle Add meg a szögváltozást - Enter delta length or Add meg a hosszváltozást + Enter delta length Add meg a hosszváltozást Enter dimension text Add meg a méretszámot Enter dimension text (<> = measurement) Add meg a méretszámot (<> = mért érték) Enter dimension value or [name=expression] Add meg a méret értékét vagy [név=kifejezés] @@ -931,8 +931,8 @@ Select an arc or circle Válassz egy ívet vagy kört Select an arc. Válassz egy ívet. Select an object Válassz egy objektumot - Select an object to change or Válaszd ki a módosítandó objektumot - Select an object to measure or Válaszd ki a mérendő objektumot + Select an object to change Válaszd ki a módosítandó objektumot + Select an object to measure Válaszd ki a mérendő objektumot Select an object. Válassz egy objektumot. Select an open curve. Válassz egy nyitott görbét. Select an open line, arc, polyline, ellipse arc or spline. Válassz egy nyitott vonalat, ívet, vonalláncot, ellipszisívet vagy spline-t. @@ -946,9 +946,8 @@ Select first line Válaszd ki az első vonalat Select first line or arc Válaszd ki az első vonalat vagy ívet Select first object Válaszd ki az első objektumot - Select first object or Válaszd ki az első objektumot Select first point Válaszd ki az első pontot - Select nested objects to copy or Válaszd ki a másolandó beágyazott objektumokat + Select nested objects to copy Válaszd ki a másolandó beágyazott objektumokat Select object Válassz objektumot Select object to dimension Válaszd ki a méretezendő objektumot Select object to divide Válaszd ki a felosztandó objektumot @@ -965,7 +964,7 @@ Select one polyline (Multiple is available through the JSON form). Egyetlen vonalláncot válassz (a Multiple a parancs JSON-hívásával érhető el). Select path curve Válaszd ki az útvonalgörbét Select point or object Válassz pontot vagy objektumot - Select polyline or Válassz vonalláncot + Select polyline Válassz vonalláncot Select second line Válaszd ki a második vonalat Select second line or shift-select to apply corner Válaszd ki a második vonalat, Shift+kijelöléssel éles sarkot képezhetsz Select second object Válaszd ki a második objektumot @@ -1046,9 +1045,8 @@ Specify axis endpoint of ellipse Add meg az ellipszis tengelyének végpontját Specify base diameter Add meg az alap átmérőjét Specify base point Add meg a bázispontot - Specify base point or Add meg a bázispontot Specify base point or displacement (drag with the middle mouse button for realtime pan) Add meg a bázispontot vagy az elmozdulást (a középső egérgombbal húzva a nézetet valós időben mozgathatod) - Specify base radius or Add meg az alap sugarát + Specify base radius Add meg az alap sugarát Specify center of donut Add meg a gyűrű középpontját Specify center of ellipse Add meg az ellipszis középpontját Specify center of polygon Add meg a sokszög középpontját @@ -1090,7 +1088,7 @@ Specify first point on circle: _tan to Add meg a kör első pontját: _tan to Specify first source point Add meg az első forráspontot Specify height Add meg a magasságot - Specify helix height or Add meg a csavarvonal magasságát + Specify helix height Add meg a csavarvonal magasságát Specify included angle Add meg a középponti szöget Specify insertion base point Add meg a beszúrási bázispontot Specify insertion point Add meg a beszúrási pontot @@ -1109,7 +1107,6 @@ Specify new width for all segments Add meg az összes szakasz új szélességét Specify next point Add meg a következő pontot Specify offset distance Add meg az eltolási távolságot - Specify offset distance or Add meg az eltolási távolságot Specify opposite corner Add meg az átellenes sarkot Specify other corner point Add meg a másik sarokpontot Specify other endpoint of axis Add meg a tengely másik végpontját @@ -1122,7 +1119,6 @@ Specify radius of circle Add meg a kör sugarát Specify rotation angle Add meg az elforgatási szöget Specify rotation angle of text Add meg a szöveg elforgatási szögét - Specify rotation angle or Add meg az elforgatási szöget Specify scale factor Add meg a léptéktényezőt Specify second angle endpoint Add meg a szög második végpontját Specify second break point Add meg a második megszakítási pontot @@ -1155,9 +1151,9 @@ Specify third source point or Add meg a harmadik forráspontot vagy Specify through point Add meg az átmenő pontot Specify top diameter Add meg a felső átmérőt - Specify top radius or Add meg a felső sugarat + Specify top radius Add meg a felső sugarat Specify total angle Add meg a teljes szöget - Specify total length or Add meg a teljes hosszt + Specify total length Add meg a teljes hosszt Specify width for rectangles Add meg a téglalapok szélességét Sphere Gömb Spherical Gömbszerű diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cec28d857..b437397b6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -288,7 +288,7 @@ menu Modify Edita Enter a vertex editing option Digitare un'opzione di modifica dei vertici Enter an option Digitare un'opzione Enter angle of xline Digitare l'angolo della linea di costruzione - Enter angle of xline (0) or Digitare l'angolo della linea di costruzione (0) o + Enter angle of xline (0) Digitare l'angolo della linea di costruzione (0) Enter area of rectangle in current units Digitare l'area del rettangolo nelle unità correnti Enter attribute prompt Digitare il messaggio dell'attributo Enter attribute tag name Digitare il nome dell'etichetta dell'attributo @@ -299,7 +299,7 @@ menu Modify Edita Enter default attribute value Digitare il valore predefinito dell'attributo Enter degree of spline Digitare il grado della spline Enter delta angle Digitare la variazione dell'angolo - Enter delta length or Digitare la variazione di lunghezza o + Enter delta length Digitare la variazione di lunghezza Enter dimension text Digitare il testo della quota Enter dimension text (<> = measurement) Digitare il testo della quota (<> = misura) Enter dimension value or [name=expression] Digitare il valore della quota o [nome=espressione] @@ -797,8 +797,8 @@ menu Modify Edita Select an arc or circle Selezionare un arco o un cerchio Select an arc. Selezionare un arco. Select an object Selezionare un oggetto - Select an object to change or Selezionare l'oggetto da modificare o - Select an object to measure or Selezionare l'oggetto da misurare o + Select an object to change Selezionare l'oggetto da modificare + Select an object to measure Selezionare l'oggetto da misurare Select an object. Selezionare un oggetto. Select an open curve. Selezionare una curva aperta. Select an open line, arc, polyline, ellipse arc or spline. Selezionare una linea, un arco, una polilinea, un arco ellittico o una spline aperti. @@ -811,9 +811,8 @@ menu Modify Edita Select first line Selezionare la prima linea Select first line or arc Selezionare la prima linea o il primo arco Select first object Selezionare il primo oggetto - Select first object or Selezionare il primo oggetto o Select first point Selezionare il primo punto - Select nested objects to copy or Selezionare gli oggetti nidificati da copiare o + Select nested objects to copy Selezionare gli oggetti nidificati da copiare Select object Selezionare l'oggetto Select object to dimension Selezionare l'oggetto da quotare Select object to divide Selezionare l'oggetto da dividere @@ -829,7 +828,7 @@ menu Modify Edita Select one polyline (Multiple is available through the JSON form). Selezionare una polilinea (Multiple è disponibile tramite il modulo JSON). Select path curve Selezionare la curva della traiettoria Select point or object Selezionare un punto o un oggetto - Select polyline or Selezionare la polilinea o + Select polyline Selezionare la polilinea Select second line Selezionare la seconda linea Select second line or shift-select to apply corner Selezionare la seconda linea o selezionare con Maiusc per applicare l'angolo Select second object Selezionare il secondo oggetto @@ -889,9 +888,8 @@ menu Modify Edita Specify axis endpoint of ellipse Specificare l'estremo dell'asse dell'ellisse Specify base diameter Specificare il diametro di base Specify base point Specificare il punto base - Specify base point or Specificare il punto base o Specify base point or displacement (drag with the middle mouse button for realtime pan) Specificare il punto base o lo spostamento (trascinare con il tasto centrale del mouse per il pan in tempo reale) - Specify base radius or Specificare il raggio di base o + Specify base radius Specificare il raggio di base Specify center of donut Specificare il centro dell'anello Specify center of ellipse Specificare il centro dell'ellisse Specify center of polygon Specificare il centro del poligono @@ -933,7 +931,7 @@ menu Modify Edita Specify first point on circle: _tan to Specificare il primo punto sul cerchio: _tan a Specify first source point Specificare il primo punto di origine Specify height Specificare l'altezza - Specify helix height or Specificare l'altezza dell'elica o + Specify helix height Specificare l'altezza dell'elica Specify included angle Specificare l'angolo compreso Specify insertion base point Specificare il punto base di inserimento Specify insertion point Specificare il punto di inserimento @@ -987,7 +985,6 @@ menu Modify Edita Specify new width for all segments Specificare la nuova larghezza di tutti i segmenti Specify next point Specificare il punto successivo Specify offset distance Specificare la distanza di offset - Specify offset distance or Specificare la distanza di offset o Specify opposite corner Specificare l'angolo opposto Specify other corner point Specificare l'altro angolo Specify other endpoint of axis Specificare l'altro estremo dell'asse @@ -1000,7 +997,6 @@ menu Modify Edita Specify radius of circle Specificare il raggio del cerchio Specify rotation angle Specificare l'angolo di rotazione Specify rotation angle of text Specificare l'angolo di rotazione del testo - Specify rotation angle or Specificare l'angolo di rotazione o Specify scale factor Specificare il fattore di scala Specify second angle endpoint Specificare il secondo estremo dell'angolo Specify second break point Specificare il secondo punto di interruzione @@ -1033,9 +1029,9 @@ menu Modify Edita Specify third source point or Specificare il terzo punto di origine o Specify through point Specificare il punto di passaggio Specify top diameter Specificare il diametro superiore - Specify top radius or Specificare il raggio superiore o + Specify top radius Specificare il raggio superiore Specify total angle Specificare l'angolo totale - Specify total length or Specificare la lunghezza totale o + Specify total length Specificare la lunghezza totale Specify width for rectangles Specificare la larghezza dei rettangoli Sphere Sfera Spline Spline diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index f41128ba1..2f269b051 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -281,7 +281,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 속성 태그 이름 입력 @@ -292,7 +292,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] 입력 @@ -788,8 +788,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. 열린 선, 호, 폴리선, 타원 호 또는 스플라인을 선택하세요. @@ -803,9 +803,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 등분할할 객체 선택 @@ -821,7 +820,7 @@ Select one polyline (Multiple is available through the JSON form). 폴리선 하나를 선택하세요(다중 선택은 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 두 번째 객체 선택 @@ -881,9 +880,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 다각형 중심 지정 @@ -925,7 +923,7 @@ Specify first point on circle: _tan to 원 위의 첫 번째 점 지정: _tan 접점 Specify first source point 첫 번째 원본점 지정 Specify height 높이 지정 - Specify helix height or 나선 높이 지정 또는 + Specify helix height 나선 높이 지정 Specify included angle 사이각 지정 Specify insertion base point 삽입 기준점 지정 Specify insertion point 삽입점 지정 @@ -979,7 +977,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 축의 다른 끝점 지정 @@ -992,7 +989,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 두 번째 끊기점 지정 @@ -1025,9 +1021,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 스플라인 diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 3e16b65cf..a000d9b09 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -291,7 +291,7 @@ Enter a vertex editing option Digite uma opção de edição de vértice Enter an option Digite uma opção Enter angle of xline Digite o ângulo da linha infinita - Enter angle of xline (0) or Digite o ângulo da linha infinita (0) ou + Enter angle of xline (0) Digite o ângulo da linha infinita (0) Enter area of rectangle in current units Digite a área do retângulo nas unidades atuais Enter attribute prompt Digite o texto de solicitação do atributo Enter attribute tag name Digite o nome do rótulo do atributo @@ -302,7 +302,7 @@ Enter default attribute value Digite o valor padrão do atributo Enter degree of spline Digite o grau da spline Enter delta angle Digite o ângulo delta - Enter delta length or Digite o comprimento delta ou + Enter delta length Digite o comprimento delta Enter dimension text Digite o texto da cota Enter dimension text (<> = measurement) Digite o texto da cota (<> = medida) Enter dimension value or [name=expression] Digite o valor da cota ou [nome=expressão] @@ -880,8 +880,8 @@ Select an arc or circle Selecione um arco ou círculo Select an arc. Selecione um arco. Select an object Selecione um objeto - Select an object to change or Selecione um objeto para alterar ou - Select an object to measure or Selecione um objeto para medir ou + Select an object to change Selecione um objeto para alterar + Select an object to measure Selecione um objeto para medir Select an object. Selecione um objeto. Select an open curve. Selecione uma curva aberta. Select an open line, arc, polyline, ellipse arc or spline. Selecione uma linha aberta, arco, polilinha, arco elíptico ou spline. @@ -895,9 +895,8 @@ Select first line Selecione a primeira linha Select first line or arc Selecione a primeira linha ou arco Select first object Selecione o primeiro objeto - Select first object or Selecione o primeiro objeto ou Select first point Selecione o primeiro ponto - Select nested objects to copy or Selecione objetos aninhados para copiar ou + Select nested objects to copy Selecione objetos aninhados para copiar Select object Selecione o objeto Select object to dimension Selecione o objeto a cotar Select object to divide Selecione o objeto a dividir @@ -913,7 +912,7 @@ Select one polyline (Multiple is available through the JSON form). Selecione uma polilinha (a opção Multiple está disponível pela forma JSON). Select path curve Selecione a curva da trajetória Select point or object Selecione um ponto ou objeto - Select polyline or Selecione uma polilinha ou + Select polyline Selecione uma polilinha Select second line Selecione a segunda linha Select second line or shift-select to apply corner Selecione a segunda linha ou use Shift para aplicar o canto Select second object Selecione o segundo objeto @@ -966,9 +965,8 @@ Specify axis endpoint of ellipse Especifique a extremidade do eixo da elipse Specify base diameter Especifique o diâmetro da base Specify base point Especifique o ponto base - Specify base point or Especifique o ponto base ou Specify base point or displacement (drag with the middle mouse button for realtime pan) Especifique o ponto base ou o deslocamento (arraste com o botão do meio do mouse para pan em tempo real) - Specify base radius or Especifique o raio da base ou + Specify base radius Especifique o raio da base Specify center of donut Especifique o centro do anel Specify center of ellipse Especifique o centro da elipse Specify center of polygon Especifique o centro do polígono @@ -1010,7 +1008,7 @@ Specify first point on circle: _tan to Especifique o primeiro ponto no círculo: _tan para Specify first source point Especifique o primeiro ponto de origem Specify height Especifique a altura - Specify helix height or Especifique a altura da hélice ou + Specify helix height Especifique a altura da hélice Specify included angle Especifique o ângulo incluído Specify insertion base point Especifique o ponto base de inserção Specify insertion point Especifique o ponto de inserção @@ -1029,7 +1027,6 @@ Specify new width for all segments Especifique a nova largura para todos os segmentos Specify next point Especifique o próximo ponto Specify offset distance Especifique a distância de offset - Specify offset distance or Especifique a distância de offset ou Specify opposite corner Especifique o canto oposto Specify other corner point Especifique o outro ponto de canto Specify other endpoint of axis Especifique a outra extremidade do eixo @@ -1042,7 +1039,6 @@ Specify radius of circle Especifique o raio do círculo Specify rotation angle Especifique o ângulo de rotação Specify rotation angle of text Especifique o ângulo de rotação do texto - Specify rotation angle or Especifique o ângulo de rotação ou Specify scale factor Especifique o fator de escala Specify second angle endpoint Especifique a segunda extremidade do ângulo Specify second break point Especifique o segundo ponto de quebra @@ -1075,9 +1071,9 @@ Specify third source point or Especifique o terceiro ponto de origem ou Specify through point Especifique o ponto de passagem Specify top diameter Especifique o diâmetro superior - Specify top radius or Especifique o raio superior ou + Specify top radius Especifique o raio superior Specify total angle Especifique o ângulo total - Specify total length or Especifique o comprimento total ou + Specify total length Especifique o comprimento total Specify width for rectangles Especifique a largura para retângulos Sphere Esfera Spline Spline diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7e4ba21d5..619988f45 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -221,7 +221,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 Введите имя тега атрибута @@ -232,7 +232,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] Введите размерное значение или [имя=выражение] @@ -675,8 +675,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. Выберите незамкнутый отрезок, дугу, полилинию, эллиптическую дугу или сплайн. @@ -690,9 +690,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 Выберите объект для деления @@ -708,7 +707,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 Выберите второй объект @@ -761,9 +760,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 Укажите центр многоугольника @@ -805,7 +803,7 @@ Specify first point on circle: _tan to Укажите первую точку на круге: _tan к Specify first source point Укажите первую исходную точку Specify height Укажите высоту - Specify helix height or Укажите высоту спирали или + Specify helix height Укажите высоту спирали Specify included angle Укажите угол между сторонами Specify insertion base point Укажите базовую точку вставки Specify insertion point Укажите точку вставки @@ -824,7 +822,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 Укажите другую конечную точку оси @@ -837,7 +834,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 Укажите вторую точку разрыва @@ -870,9 +866,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 Сплайн diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 96114f857..ecfe35b40 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -295,7 +295,7 @@ Enter a vertex editing option Ange ett alternativ för hörnpunktsredigering Enter an option Ange ett alternativ Enter angle of xline Ange konstruktionslinjens vinkel - Enter angle of xline (0) or Ange konstruktionslinjens vinkel (0) eller + Enter angle of xline (0) Ange konstruktionslinjens vinkel (0) Enter area of rectangle in current units Ange rektangelns area i aktuella enheter Enter attribute prompt Ange attributets fråga Enter attribute tag name Ange attributets taggnamn @@ -306,7 +306,7 @@ Enter default attribute value Ange attributets standardvärde Enter degree of spline Ange splinens grad Enter delta angle Ange vinkeländring - Enter delta length or Ange längdändring eller + Enter delta length Ange längdändring Enter dimension text Ange måttal Enter dimension text (<> = measurement) Ange måttal (<> = mätvärde) Enter dimension value or [name=expression] Ange måttvärde eller [namn=uttryck] @@ -878,8 +878,8 @@ Select an arc or circle Markera en båge eller cirkel Select an arc. Markera en båge. Select an object Markera ett objekt - Select an object to change or Markera ett objekt att ändra eller - Select an object to measure or Markera ett objekt att mäta eller + Select an object to change Markera ett objekt att ändra + Select an object to measure Markera ett objekt att mäta Select an object. Markera ett objekt. Select an open curve. Markera en öppen kurva. Select an open line, arc, polyline, ellipse arc or spline. Markera en öppen linje, båge, polylinje, ellipsbåge eller spline. @@ -893,9 +893,8 @@ Select first line Markera första linjen Select first line or arc Markera första linjen eller bågen Select first object Markera första objektet - Select first object or Markera första objektet eller Select first point Ange första punkten - Select nested objects to copy or Markera nästlade objekt att kopiera eller + Select nested objects to copy Markera nästlade objekt att kopiera Select object Markera objekt Select object to dimension Markera objekt att måttsätta Select object to divide Markera objekt att dela in @@ -911,7 +910,7 @@ Select one polyline (Multiple is available through the JSON form). Markera en polylinje (Multiple finns i JSON-formen). Select path curve Markera banans kurva Select point or object Ange punkt eller markera objekt - Select polyline or Markera polylinje eller + Select polyline Markera polylinje Select second line Markera andra linjen Select second line or shift-select to apply corner Markera andra linjen, eller Shift-markera för att skapa hörn Select second object Markera andra objektet @@ -964,9 +963,8 @@ Specify axis endpoint of ellipse Ange ellipsens axeländpunkt Specify base diameter Ange basdiameter Specify base point Ange baspunkt - Specify base point or Ange baspunkt eller Specify base point or displacement (drag with the middle mouse button for realtime pan) Ange baspunkt eller förskjutning (dra med mittenknappen för att panorera i realtid) - Specify base radius or Ange basradie eller + Specify base radius Ange basradie Specify center of donut Ange ringens centrum Specify center of ellipse Ange ellipsens centrum Specify center of polygon Ange polygonens centrum @@ -1008,7 +1006,7 @@ Specify first point on circle: _tan to Ange första punkten på cirkeln: _tan to Specify first source point Ange första källpunkten Specify height Ange höjd - Specify helix height or Ange helixens höjd eller + Specify helix height Ange helixens höjd Specify included angle Ange medelpunktsvinkel Specify insertion base point Ange insättningens baspunkt Specify insertion point Ange insättningspunkt @@ -1027,7 +1025,6 @@ Specify new width for all segments Ange ny bredd för alla segment Specify next point Ange nästa punkt Specify offset distance Ange förskjutningsavstånd - Specify offset distance or Ange förskjutningsavstånd eller Specify opposite corner Ange motsatt hörn Specify other corner point Ange andra hörnpunkten Specify other endpoint of axis Ange axelns andra ändpunkt @@ -1040,7 +1037,6 @@ Specify radius of circle Ange cirkelns radie Specify rotation angle Ange rotationsvinkel Specify rotation angle of text Ange textens rotationsvinkel - Specify rotation angle or Ange rotationsvinkel eller Specify scale factor Ange skalfaktor Specify second angle endpoint Ange vinkelns andra ändpunkt Specify second break point Ange andra brytpunkten @@ -1073,9 +1069,9 @@ Specify third source point or Ange tredje källpunkten eller Specify through point Ange genomgångspunkt Specify top diameter Ange toppdiameter - Specify top radius or Ange toppradie eller + Specify top radius Ange toppradie Specify total angle Ange total vinkel - Specify total length or Ange total längd eller + Specify total length Ange total längd Specify width for rectangles Ange bredd för rektanglar Sphere Sfär Spline Spline diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 492b9e595..24fac6a79 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -40,6 +40,17 @@ fn catalog_is_valid_and_preserves_placeholders_and_ellipses() { assert_eq!(tr("unknown", "Open"), "Open"); } +/// A prompt with options is translated without its own "or": the command line adds the +/// translated " or [" before the options ("Select polyline or [Multiple]"). +#[test] +fn prompts_with_options_leave_or_to_the_command_line() { + assert_eq!(format!("{}{}", tr("de", "Select polyline"), tr("de", " or [")), "Wählen Sie eine Polylinie oder ["); + assert_eq!(format!("{}{}", tr("ko", "Specify helix height"), tr("ko", " or [")), "나선 높이 지정 또는 ["); + assert_eq!(format!("{}{}", tr("zh", "Enter delta length"), tr("zh", " or [")), "输入增量长度 或 ["); + assert_eq!(format!("{}{}", tr("vi", "Select polyline"), tr("vi", " or [")), "Chọn polyline hoặc ["); + assert_eq!(format!("{}{}", tr("vi", "Specify base radius"), tr("vi", " or [")), "Chỉ định bán kính đáy hoặc ["); +} + /// What each language shows in English for now. Missing translations never fail a build: /// `cargo xtask i18n`, a step of `cargo xtask ci`, runs this to print the list. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3fed6bc3b..cc8576aa7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -351,7 +351,7 @@ Enter a vertex editing option Bir köşe noktası düzenleme seçeneği girin Enter an option Bir seçenek girin Enter angle of xline Yapı çizgisinin açısını girin - Enter angle of xline (0) or Yapı çizgisinin açısını girin (0) veya + Enter angle of xline (0) Yapı çizgisinin açısını girin (0) Enter area of rectangle in current units Dikdörtgenin alanını geçerli birimlerle girin Enter attribute prompt Öznitelik istemini girin Enter attribute tag name Öznitelik etiket adını girin @@ -362,7 +362,7 @@ Enter default attribute value Varsayılan öznitelik değerini girin Enter degree of spline Spline derecesini girin Enter delta angle Açı farkını girin - Enter delta length or Uzunluk farkını girin veya + Enter delta length Uzunluk farkını girin Enter dimension text Ölçü metnini girin Enter dimension text (<> = measurement) Ölçü metnini girin (<> = ölçülen değer) Enter dimension value or [name=expression] Ölçü değerini girin veya [name=expression] @@ -932,8 +932,8 @@ Select an arc or circle Bir yay veya daire seçin Select an arc. Bir yay seçin. Select an object Bir nesne seçin - Select an object to change or Değiştirilecek nesneyi seçin veya - Select an object to measure or Ölçülecek nesneyi seçin veya + Select an object to change Değiştirilecek nesneyi seçin + Select an object to measure Ölçülecek nesneyi seçin Select an object. Bir nesne seçin. Select an open curve. Açık bir eğri seçin. Select an open line, arc, polyline, ellipse arc or spline. Açık bir çizgi, yay, çoklu çizgi, elips yayı veya spline seçin. @@ -947,9 +947,8 @@ Select first line İlk çizgiyi seçin Select first line or arc İlk çizgiyi veya yayı seçin Select first object İlk nesneyi seçin - Select first object or İlk nesneyi seçin veya Select first point İlk noktayı seçin - Select nested objects to copy or Kopyalanacak iç içe nesneleri seçin veya + Select nested objects to copy Kopyalanacak iç içe nesneleri seçin Select object Nesne seçin Select object to dimension Ölçülendirilecek nesneyi seçin Select object to divide Bölünecek nesneyi seçin @@ -966,7 +965,7 @@ Select one polyline (Multiple is available through the JSON form). Bir çoklu çizgi seçin (Multiple seçeneği JSON biçimiyle kullanılabilir). Select path curve Yol eğrisini seçin Select point or object Nokta veya nesne seçin - Select polyline or Çoklu çizgi seçin veya + Select polyline Çoklu çizgi seçin Select second line İkinci çizgiyi seçin Select second line or shift-select to apply corner İkinci çizgiyi seçin ya da köşe uygulamak için Shift ile seçin Select second object İkinci nesneyi seçin @@ -1047,9 +1046,8 @@ Specify axis endpoint of ellipse Elipsin eksen uç noktasını belirtin Specify base diameter Taban çapını belirtin Specify base point Taban noktasını belirtin - Specify base point or Taban noktasını belirtin veya Specify base point or displacement (drag with the middle mouse button for realtime pan) Taban noktasını veya yer değiştirmeyi belirtin (gerçek zamanlı kaydırma için orta fare düğmesiyle sürükleyin) - Specify base radius or Taban yarıçapını belirtin veya + Specify base radius Taban yarıçapını belirtin Specify center of donut Halkanın merkezini belirtin Specify center of ellipse Elipsin merkezini belirtin Specify center of polygon Çokgenin merkezini belirtin @@ -1091,7 +1089,7 @@ Specify first point on circle: _tan to Daire üzerindeki ilk noktayı belirtin: _tan to Specify first source point İlk kaynak noktayı belirtin Specify height Yüksekliği belirtin - Specify helix height or Helezon yüksekliğini belirtin veya + Specify helix height Helezon yüksekliğini belirtin Specify included angle İç açıyı belirtin Specify insertion base point Ekleme taban noktasını belirtin Specify insertion point Ekleme noktasını belirtin @@ -1110,7 +1108,6 @@ Specify new width for all segments Tüm parçalar için yeni genişliği belirtin Specify next point Sonraki noktayı belirtin Specify offset distance Öteleme uzaklığını belirtin - Specify offset distance or Öteleme uzaklığını belirtin veya Specify opposite corner Karşı köşeyi belirtin Specify other corner point Diğer köşe noktasını belirtin Specify other endpoint of axis Eksenin diğer uç noktasını belirtin @@ -1123,7 +1120,6 @@ Specify radius of circle Dairenin yarıçapını belirtin Specify rotation angle Döndürme açısını belirtin Specify rotation angle of text Metnin döndürme açısını belirtin - Specify rotation angle or Döndürme açısını belirtin veya Specify scale factor Ölçek faktörünü belirtin Specify second angle endpoint Açının ikinci uç noktasını belirtin Specify second break point İkinci kırma noktasını belirtin @@ -1156,9 +1152,9 @@ Specify third source point or Üçüncü kaynak noktayı belirtin veya Specify through point Geçiş noktasını belirtin Specify top diameter Üst çapı belirtin - Specify top radius or Üst yarıçapı belirtin veya + Specify top radius Üst yarıçapı belirtin Specify total angle Toplam açıyı belirtin - Specify total length or Toplam uzunluğu belirtin veya + Specify total length Toplam uzunluğu belirtin Specify width for rectangles Dikdörtgenler için genişliği belirtin Sphere Küre Spherical Küresel diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bbb70e489..8d8c6b875 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -286,7 +286,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 Введіть ім'я тегу атрибута @@ -297,7 +297,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] @@ -803,8 +803,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. Виберіть незамкнений відрізок, дугу, полілінію, еліптичну дугу або сплайн. @@ -818,9 +818,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 Виберіть об'єкт для поділу @@ -841,7 +840,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 Виберіть другий об'єкт @@ -901,9 +900,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 Укажіть центр багатокутника @@ -945,7 +943,7 @@ Specify first point on circle: _tan to Укажіть першу точку на колі: _tan до Specify first source point Укажіть першу вихідну точку Specify height Укажіть висоту - Specify helix height or Укажіть висоту спіралі або + Specify helix height Укажіть висоту спіралі Specify included angle Укажіть кут між сторонами Specify insertion base point Укажіть базову точку вставлення Specify insertion point Укажіть точку вставлення @@ -1029,7 +1027,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 Укажіть іншу кінцеву точку осі @@ -1042,7 +1039,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 Укажіть другу точку розриву @@ -1075,9 +1071,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 Сплайн diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8887bb45b..f1b8dca7b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -280,7 +280,7 @@ Enter a vertex editing option Nhập tùy chọn sửa đỉnh Enter an option Nhập một tùy chọn Enter angle of xline Nhập góc của đường dựng - Enter angle of xline (0) or Nhập góc của đường dựng (0) hoặc + Enter angle of xline (0) Nhập góc của đường dựng (0) Enter area of rectangle in current units Nhập diện tích hình chữ nhật theo đơn vị hiện hành Enter attribute prompt Nhập lời nhắc attribute Enter attribute tag name Nhập tên thẻ attribute @@ -291,7 +291,7 @@ Enter default attribute value Nhập giá trị attribute mặc định Enter degree of spline Nhập bậc của spline Enter delta angle Nhập góc chênh lệch - Enter delta length or Nhập chiều dài chênh lệch hoặc + Enter delta length Nhập chiều dài chênh lệch Enter dimension text Nhập chữ kích thước Enter dimension text (<> = measurement) Nhập chữ kích thước (<> = số đo) Enter dimension value or [name=expression] Nhập giá trị kích thước hoặc [name=expression] @@ -787,8 +787,8 @@ Select an arc or circle Chọn một cung tròn hoặc đường tròn Select an arc. Chọn một cung tròn. Select an object Chọn một đối tượng - Select an object to change or Chọn một đối tượng để thay đổi hoặc - Select an object to measure or Chọn một đối tượng để đo hoặc + Select an object to change Chọn một đối tượng để thay đổi + Select an object to measure Chọn một đối tượng để đo Select an object. Chọn một đối tượng. Select an open curve. Chọn một đường cong hở. Select an open line, arc, polyline, ellipse arc or spline. Chọn một đoạn thẳng, cung tròn, polyline, cung elip hoặc spline hở. @@ -802,14 +802,13 @@ Select first line Chọn đoạn thẳng thứ nhất Select first line or arc Chọn đoạn thẳng hoặc cung tròn thứ nhất Select first object Chọn đối tượng thứ nhất - Select first object or Chọn đối tượng thứ nhất hoặc Select first point Chọn điểm thứ nhất Add to Working Set Thêm vào Working Set Edit Reference In-Place Chỉnh sửa tham chiếu tại chỗ Save Reference Edits Lưu chỉnh sửa tham chiếu Working Set Working Set Xref and Block In-place Editing Chỉnh sửa Xref và Block tại chỗ - Select nested objects to copy or Chọn đối tượng lồng nhau để sao chép hoặc + Select nested objects to copy Chọn đối tượng lồng nhau để sao chép Select object Chọn đối tượng Select object to dimension Chọn đối tượng để ghi kích thước Select object to divide Chọn đối tượng để chia @@ -825,7 +824,7 @@ Select one polyline (Multiple is available through the JSON form). Chọn một polyline (có thể chọn nhiều qua dạng JSON). Select path curve Chọn đường cong làm đường dẫn Select point or object Chọn điểm hoặc đối tượng - Select polyline or Chọn polyline hoặc + Select polyline Chọn polyline Select second line Chọn đoạn thẳng thứ hai Select second line or shift-select to apply corner Chọn đoạn thẳng thứ hai hoặc chọn kèm Shift để áp dụng góc Select second object Chọn đối tượng thứ hai @@ -883,9 +882,8 @@ Specify axis endpoint of ellipse Chỉ định điểm cuối trục của elip Specify base diameter Chỉ định đường kính đáy Specify base point Chỉ định điểm gốc - Specify base point or Chỉ định điểm gốc hoặc Specify base point or displacement (drag with the middle mouse button for realtime pan) Chỉ định điểm gốc hoặc độ dời (kéo bằng nút giữa chuột để pan theo thời gian thực) - Specify base radius or Chỉ định bán kính đáy hoặc + Specify base radius Chỉ định bán kính đáy Specify center of donut Chỉ định tâm vành tròn Specify center of ellipse Chỉ định tâm elip Specify center of polygon Chỉ định tâm đa giác @@ -927,7 +925,7 @@ Specify first point on circle: _tan to Chỉ định điểm thứ nhất trên đường tròn: _tan to Specify first source point Chỉ định điểm nguồn thứ nhất Specify height Chỉ định chiều cao - Specify helix height or Chỉ định chiều cao đường xoắn ốc hoặc + Specify helix height Chỉ định chiều cao đường xoắn ốc Specify included angle Chỉ định góc chắn của cung Specify insertion base point Chỉ định điểm gốc chèn Specify insertion point Chỉ định điểm chèn @@ -981,7 +979,6 @@ Specify new width for all segments Chỉ định bề rộng mới cho tất cả các đoạn Specify next point Chỉ định điểm tiếp theo Specify offset distance Chỉ định khoảng cách offset - Specify offset distance or Chỉ định khoảng cách offset hoặc Specify opposite corner Chỉ định góc đối diện Specify other corner point Chỉ định điểm góc đối diện Specify other endpoint of axis Chỉ định đầu kia của trục @@ -994,7 +991,6 @@ Specify radius of circle Chỉ định bán kính đường tròn Specify rotation angle Chỉ định góc xoay Specify rotation angle of text Chỉ định góc xoay của chữ - Specify rotation angle or Chỉ định góc xoay hoặc Specify scale factor Chỉ định hệ số tỉ lệ Specify second angle endpoint Chỉ định đầu thứ hai của góc Specify second break point Chỉ định điểm ngắt thứ hai @@ -1027,9 +1023,9 @@ Specify third source point or Chỉ định điểm nguồn thứ ba hoặc Specify through point Chỉ định điểm đi qua Specify top diameter Chỉ định đường kính trên - Specify top radius or Chỉ định bán kính trên hoặc + Specify top radius Chỉ định bán kính trên Specify total angle Chỉ định tổng góc - Specify total length or Chỉ định tổng chiều dài hoặc + Specify total length Chỉ định tổng chiều dài Specify width for rectangles Chỉ định bề rộng cho hình chữ nhật Sphere Hình cầu Spline Spline diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 9ca85fea7..de4e6a633 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -222,7 +222,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 输入属性标记名称 @@ -233,7 +233,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] 输入标注值或 [名称=表达式] @@ -669,8 +669,8 @@ Select an arc or circle 选择圆弧或圆 Select an arc. 选择一段圆弧。 Select an object 选择对象 - Select an object to change or Select an object to change or - Select an object to measure or Select an object to measure or + Select an object to change Select an object to change + Select an object to measure Select an object to measure Add to Working Set 添加到工作集 Edit Reference In-Place 就地编辑参照 Save Reference Edits 保存参照编辑 @@ -689,9 +689,8 @@ Select first line 选择第一条直线 Select first line or arc 选择第一条直线或圆弧 Select first object 选择第一个对象 - Select first object or Select first object or Select first point 指定第一点 - Select nested objects to copy or Select nested objects to copy or + Select nested objects to copy Select nested objects to copy Select object 选择对象 Select object to dimension 选择要标注的对象 Select object to divide 选择要定数等分的对象 @@ -707,7 +706,7 @@ Select one polyline (Multiple is available through the JSON form). 选择一条多段线(可通过 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 选择第二个对象 @@ -760,9 +759,8 @@ Specify axis endpoint of ellipse 指定椭圆的轴端点 Specify base diameter 指定底面直径 Specify base point 指定基点 - Specify base point or 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 or + Specify base radius Specify base radius Specify center of donut 指定圆环中心 Specify center of ellipse 指定椭圆中心 Specify center of polygon 指定多边形中心 @@ -804,7 +802,7 @@ Specify first point on circle: _tan to 指定圆上的第一点: _tan 到 Specify first source point 指定第一个源点 Specify height 指定高度 - Specify helix height or Specify helix height or + Specify helix height Specify helix height Specify included angle 指定夹角 Specify insertion base point 指定插入基点 Specify insertion point 指定插入点 @@ -823,7 +821,6 @@ Specify new width for all segments 指定所有段的新宽度 Specify next point 指定下一点 Specify offset distance 指定偏移距离 - Specify offset distance or Specify offset distance or Specify opposite corner 指定对角点 Specify other corner point 指定另一角点 Specify other endpoint of axis 指定轴的另一端点 @@ -836,7 +833,6 @@ Specify radius of circle 指定圆半径 Specify rotation angle 指定旋转角度 Specify rotation angle of text 指定文字旋转角度 - Specify rotation angle or Specify rotation angle or Specify scale factor 指定比例因子 Specify second angle endpoint 指定第二角度端点 Specify second break point 指定第二打断点 @@ -869,9 +865,9 @@ Specify third source point or 指定第三个源点或 <继续> Specify through point 指定通过点 Specify top diameter 指定顶面直径 - Specify top radius or Specify top radius or + Specify top radius Specify top radius Specify total angle 指定总角度 - Specify total length or Specify total length or + Specify total length Specify total length Specify width for rectangles 指定矩形宽度 Sphere 球体 Spline 样条曲线 From beb6c48a591d499f3b6125147ca550eeb4ae546a Mon Sep 17 00:00:00 2001 From: 2ez4gcx <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:36:42 +0700 Subject: [PATCH 419/900] AREA, PERIMETER and DISTANCE system variables, as AutoCAD sets them (#2552) * feat(inquiry): AREA, PERIMETER and DISTANCE system variables, as AutoCAD sets them AREA, DIST and MEASUREGEOM now leave AREA, PERIMETER and DISTANCE for getvar, read-only and not saved: the area just measured (the running total in Add and Subtract mode) with the last area's perimeter, and the distance (the total of Multiple points). After DIST's two points LASTPOINT stays at the first point, as measured. AREA's Object option measures splines, closed by their chord like open polylines. Co-Authored-By: Claude Opus 5.5 * Address review: spline area over narrow spans, finite distances, list order - AREA of a spline samples it span by span (Spline::tessellate_spans), so a narrow knot span no longer drops out of the area. The spread over the spans is one helper shared with Spline::bounds, whose boxes are unchanged. - DIST refuses a distance that isn't finite on all three paths and leaves DISTANCE as it was. - sysvars::list puts the session's values after the drawing's header, so it shows what get returns (AREA, ORTHOMODE, LWDISPLAY...). - LASTPOINT after DIST's Multiple points is pinned to AutoCAD 2024's measured behaviour: the last point entered, also after Length and Undo. Co-Authored-By: Claude Opus 5.5 * Address review: measure every knot span of a spline in AREA A spline with more knot spans than half the sample cap fell back to an even grid over the domain, which can step over a narrow span and measure the wrong area: a 100 x 100 square as a degree-1 spline, its right and top edges two spans a millionth wide after 4,500 spans along the bottom, measured 4,998.75. Spread the samples over the spans at any span count: at least one segment per span, within the cap up to MAX_SAMPLES spans and one each past it, as Spline::length integrates every span. One evaluation per span costs 85-285 ms on a million spans in a release build, against 32-52 s for the length AREA already takes. Co-Authored-By: Claude Opus 5.5 * Address review: share AREA's spline samples by how much each span bends Past the sample cap, tessellate_spans gave each knot span one segment, so a bent span among many straight ones was measured by its chord. Example: a quadratic spline along the x-axis, one control point 1000 above it, past 4,500 spans. It measured 750; the area is 1750/3. Each span now keeps one segment. A span whose control points are collinear is straight, so its chord is exact. tessellate's count is shared among the spans that bend, by the cube root of a measure of their control points' convex hull, which holds the span and its chord. The shares are rounded on the running total, so they use the whole count however many spans share it. The example now measures 583.33343, below the cap and past it. The spreading by parameter width that this replaces goes, and span_params with it: bounds is main's code again. Co-Authored-By: Claude Opus 5.5 * DIST: a measurement refused as too large leaves LASTPOINT at the first point Session::feed sets LASTPOINT to the second point before DIST checks the distance, and the refusal returned before DIST put the first point back, as it does after a measurement. It now does so before refusing. Co-Authored-By: Claude Opus 5.5 * AREA: a spline too long to measure is too large, not a perimeter of 0 Spline::length reads a length past f64's range as 0, and AREA took that as the spline's perimeter. Spline::checked_length returns None there, and AREA reports the perimeter too large, as it does a polyline's. The overflow was hidden twice: in the sum, and before it in the derivative, which read as zero speed once past f64's range. The length integral now takes the derivative before that (Spline::velocity), so an overflowing speed counts too. param_at_length keeps the speed it had, and finite lengths are unchanged. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/inquiry.rs | 37 ++- crates/engine/src/lib.rs | 9 + crates/engine/src/sysvars.rs | 21 +- crates/engine/tests/it/inquiry_variables.rs | 271 ++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/geom/src/nurbs.rs | 68 +++-- crates/geom/src/spline.rs | 61 ++++- crates/geom/src/spline/tests.rs | 77 ++++++ 8 files changed, 521 insertions(+), 24 deletions(-) create mode 100644 crates/engine/tests/it/inquiry_variables.rs diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index 119d727e1..364fa6796 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -217,6 +217,11 @@ fn run_dist(s: &mut Session, p: &Value) -> Result { let a = point3_req(s, "dist", p, "p1")?; let b = point3_req(s, "dist", p, "p2")?; let d = b - a; + if !d.len().is_finite() { + return Err(bad("dist", "the distance is too large")); + } + s.distance = d.len(); + s.last_point = a.xy(); Ok(json!({ "distance": d.len(), "angle": d.xy().angle().to_degrees(), @@ -430,6 +435,8 @@ fn run_area(s: &mut Session, p: &Value) -> Result { if let Some(what) = too_large(a, per) { return Err(bad("area", format!("the {what} is too large"))); } + s.area = a; + s.perimeter = per; Ok(json!({ "area": a, "perimeter": per, "message": area_text(s, a, per) })) } @@ -516,6 +523,13 @@ pub(super) fn object_area(s: &Session, h: Handle) -> Result<(f64, f64)> { total } EntityKind::Region(r) => (r.area(), r.perimeter()), + // Like an open polyline: the area closed by the chord, the perimeter its own length. + EntityKind::Spline(sp) if sp.is_valid() => { + let b = sp.bounds(); + let pts = sp.tessellate_spans((b.min.dist(b.max) * 1e-7).max(1e-12)); + // A length past f64's range is too large to report, as a polyline's is, not 0. + (cadcraft_geom::shoelace(&pts).abs(), sp.checked_length().unwrap_or(f64::INFINITY)) + } _ => return Err(bad("area", "object has no area")), }) } @@ -872,16 +886,25 @@ impl Interactive for DistM { self.first_source = s.picked_viewport; Ok(Step::Continue) } - (Some(a), Input::Point(b)) => { + (Some(first), Input::Point(b)) => { let (a, b) = match (self.first_source, s.picked_viewport) { (Some(first), Some(second)) if first.viewport == second.viewport => (first.point, second.point), - _ => (a, b), + _ => (first, b), }; let (za, zb) = if self.first_source.is_some() || s.picked_viewport.is_some() { (0.0, 0.0) } else { (z_at(s, a), z_at(s, b)) }; - let t = dist_text(s, Vec3::new(a.x, a.y, za), Vec3::new(b.x, b.y, zb)); + let (a, b) = (Vec3::new(a.x, a.y, za), Vec3::new(b.x, b.y, zb)); + if !(b - a).len().is_finite() { + // The first point stays LASTPOINT, as after a measurement. + s.last_point = first; + return Err(bad("dist", "the distance is too large")); + } + let t = dist_text(s, a, b); for l in t.lines() { s.echo(l.to_string()); } + // As in AutoCAD, the second point doesn't become LASTPOINT: the first stays. + s.distance = (b - a).len(); + s.last_point = first; Ok(Step::Done) } (Some(a), Input::Keyword(k)) if k == "Multiple points" => { @@ -909,7 +932,11 @@ impl DistM { .as_deref() .or(self.multi.as_deref()) .map_or(0.0, |pts| if closed { arcs::polyline(pts, &self.bulges, true).len() } else { path_len(pts, &self.bulges) }); + if !d.is_finite() { + return Err(bad("dist", "the distance is too large")); + } s.echo(format!("Distance = {}", fmt_d(s, d))); + s.distance = d; Ok(Step::Done) } } @@ -1123,10 +1150,14 @@ impl AreaM { return if self.mode == AreaMode::Single { Step::Done } else { Step::Continue }; } s.echo(area_text(s, a, per)); + // AREA: this area, or in Add and Subtract mode the running total; PERIMETER: this area's. + s.perimeter = per; if self.mode == AreaMode::Single { + s.area = a; return Step::Done; } self.total = total; + s.area = total; s.echo(format!("Total area = {}", fmt_d(s, self.total))); Step::Continue } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8f84b35d7..d1fa2b03d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -92,6 +92,12 @@ pub struct Session { pub last_command: Option, /// LASTPOINT. pub last_point: Vec2, + /// AREA and PERIMETER: the last area AREA or MEASUREGEOM measured (in their Add and Subtract + /// modes the running total) and that area's perimeter. Not saved, as in AutoCAD. + pub area: f64, + pub perimeter: f64, + /// DISTANCE: the last distance DIST or MEASUREGEOM measured (with Multiple points, the total). + pub distance: f64, /// The last segment given at a point prompt (its base point and the point): polar angles /// relative to the last segment (POLARMODE bit 1) are measured from it. pub last_segment: Option<(Vec2, Vec2)>, @@ -173,6 +179,9 @@ impl Session { log: Vec::new(), last_command: None, last_point: Vec2::ZERO, + area: 0.0, + perimeter: 0.0, + distance: 0.0, last_segment: None, last_polar: None, point_mods: Vec::new(), diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 3fe47c052..fcecbd2cf 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -67,6 +67,9 @@ const SESSION_VARS: &[&str] = &[ "ZOOMFACTOR", "MEASUREINIT", "LASTPOINT", + "AREA", + "PERIMETER", + "DISTANCE", "FONTALT", "FONTFALLBACK", "SAVETIME", @@ -145,6 +148,9 @@ pub fn get(s: &Session, name: &str) -> Option { "ZOOMFACTOR" => json!(st.zoomfactor), "MEASUREINIT" => json!(i32::from(st.measureinit)), "LASTPOINT" => json!([s.last_point.x, s.last_point.y, 0.0]), + "AREA" => json!(s.area), + "PERIMETER" => json!(s.perimeter), + "DISTANCE" => json!(s.distance), // Held in radians (`$ANGBASE` in DXF is in degrees); reported in degrees, like POLARANG. "ANGBASE" => json!(s.doc().ok()?.header.f64("ANGBASE", 0.0).to_degrees()), "CONSTRAINTINFER" => json!(i32::from(s.doc().ok()?.parametric.settings.infer)), @@ -249,6 +255,9 @@ const READ_ONLY: &[&str] = &[ "BLOCKEDITOR", "CTAB", "LASTPOINT", + "AREA", + "PERIMETER", + "DISTANCE", "VIEWCTR", "VIEWSIZE", "EXTMIN", @@ -464,11 +473,6 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { pub fn list(s: &Session) -> Value { let mut m = serde_json::Map::new(); - for n in SESSION_VARS { - if let Some(v) = get(s, n) { - m.insert((*n).to_string(), v); - } - } if let Ok(d) = s.doc() { for (k, v) in &d.header.vars { if matches!(k.as_str(), "ANGBASE" | "SNAPUNIT" | "GRIDUNIT" | "CECOLOR") { @@ -478,6 +482,13 @@ pub fn list(s: &Session) -> Value { } } } + // The session's values last: a drawing's header can carry the same names (ORTHOMODE, + // LWDISPLAY, an AREA), and `get` reads the session's. + for n in SESSION_VARS { + if let Some(v) = get(s, n) { + m.insert((*n).to_string(), v); + } + } table::list(s, &mut m); Value::Object(m) } diff --git a/crates/engine/tests/it/inquiry_variables.rs b/crates/engine/tests/it/inquiry_variables.rs new file mode 100644 index 000000000..f42749458 --- /dev/null +++ b/crates/engine/tests/it/inquiry_variables.rs @@ -0,0 +1,271 @@ +//! AREA, PERIMETER and DISTANCE as AutoCAD 2024 leaves them after AREA, DIST and MEASUREGEOM +//! (measured with accoreconsole, running these scripts on these drawings): AREA is the area just +//! measured, or the running total in Add and Subtract mode, PERIMETER the perimeter of the last +//! area; DISTANCE the distance measured, or the total of DIST's Multiple points. After DIST's two +//! points LASTPOINT is still the first; after Multiple points it is the last. + +use cadcraft_engine::doc::{Common, EntityKind, Handle}; +use cadcraft_engine::geom::{Spline, Vec2}; +use cadcraft_engine::{Input, Session, sysvars}; +use serde_json::{Value, json}; + +fn var(s: &Session, name: &str) -> f64 { + sysvars::get(s, name).and_then(|v| v.as_f64()).unwrap_or_else(|| panic!("{name} not a number")) +} + +fn lastpoint(s: &Session) -> (f64, f64) { + let v = sysvars::get(s, "LASTPOINT").unwrap(); + (v[0].as_f64().unwrap(), v[1].as_f64().unwrap()) +} + +fn close(got: f64, want: f64) -> bool { + (got - want).abs() <= 1e-9 * (1.0 + want.abs()) +} + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +fn lisp(s: &mut Session, expr: &str) { + s.cmdline(expr).unwrap(); + assert!(s.running.is_none(), "{expr}: {}", s.prompt_text()); +} + +/// The closed polyline with an arc and the circle the Add-mode scripts pick. +fn p_and_c(s: &mut Session) -> (Handle, Handle) { + let p = handle(&s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [40, 0], "bulge": 0.5 }, [40, 30], [0, 30]], "closed": true })).unwrap()); + let c = handle(&s.execute("circle", &json!({ "center": [150, 15], "radius": 10 })).unwrap()); + (p, c) +} + +#[test] +fn area_of_points_sets_area_and_perimeter() { + let mut s = Session::new(); + lisp(&mut s, "(command \"_.AREA\" '(0.0 0.0) '(40.0 0.0) '(40.0 30.0) '(0.0 30.0) \"\")"); + assert!(close(var(&s, "AREA"), 1200.0) && close(var(&s, "PERIMETER"), 140.0)); +} + +#[test] +fn add_mode_totals_the_area_and_keeps_the_last_perimeter() { + // Points, then the circle as an object. + let mut s = Session::new(); + let (_, c) = p_and_c(&mut s); + lisp( + &mut s, + &format!( + "(command \"_.AREA\" \"_A\" '(0.0 0.0) '(40.0 0.0) '(40.0 30.0) '(0.0 30.0) \"\" \"_O\" (list (handent \"{}\") '(160.0 15.0)) \"\" \"\")", + c.hex() + ), + ); + assert!(close(var(&s, "AREA"), 1514.159265358979), "{}", var(&s, "AREA")); + assert!(close(var(&s, "PERIMETER"), 62.83185307179586), "{}", var(&s, "PERIMETER")); + // Both as objects. + let mut s = Session::new(); + let (p, c) = p_and_c(&mut s); + lisp( + &mut s, + &format!( + "(command \"_.AREA\" \"_A\" \"_O\" (list (handent \"{}\") '(0.0 15.0)) (list (handent \"{}\") '(160.0 15.0)) \"\" \"\")", + p.hex(), + c.hex() + ), + ); + assert!(close(var(&s, "AREA"), 1671.411490437671), "{}", var(&s, "AREA")); + assert!(close(var(&s, "PERIMETER"), 62.83185307179586), "{}", var(&s, "PERIMETER")); +} + +#[test] +fn subtract_mode_takes_the_area_off_the_total() { + // At large coordinates: the polyline added, the circle subtracted. + let mut s = Session::new(); + let p = handle( + &s.execute( + "pline", + &json!({ "vertices": [[-35000, 81000], { "p": [-33000, 81000], "bulge": 0.5 }, [-33000, 82500], [-35000, 82500]], "closed": true }), + ) + .unwrap(), + ); + let c = handle(&s.execute("circle", &json!({ "center": [-27000, 81750], "radius": 500 })).unwrap()); + lisp( + &mut s, + &format!( + "(command \"_.AREA\" \"_A\" \"_O\" (list (handent \"{}\") '(-35000.0 81750.0)) \"\" \"_S\" \"_O\" (list (handent \"{}\") '(-27000.0 81750.0)) \"\" \"\")", + p.hex(), + c.hex() + ), + ); + assert!(close(var(&s, "AREA"), 2607732.399299283), "{}", var(&s, "AREA")); + assert!(close(var(&s, "PERIMETER"), 3141.592653589793), "{}", var(&s, "PERIMETER")); +} + +#[test] +fn area_of_an_open_spline_closes_it_by_its_chord() { + let control = [(0.8, 0.25), (0.82, 0.24), (0.84, 0.25), (0.84, 0.28), (0.82, 0.29), (0.8, 0.28), (0.8, 0.25)]; + let spline = Spline { + degree: 3, + knots: vec![0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 4.0, 4.0], + control: control.iter().map(|&(x, y)| Vec2::new(x, y)).collect(), + weights: Vec::new(), + fit: Vec::new(), + closed: false, + fit_opts: Default::default(), + }; + let mut s = Session::new(); + let space = s.space(); + let h = s.doc_mut().unwrap().add(&space, Common::default(), EntityKind::Spline(spline)).unwrap(); + lisp(&mut s, &format!("(command \"_.AREA\" \"_O\" (list (handent \"{}\") '(0.8 0.265)))", h.hex())); + assert!(close(var(&s, "AREA"), 0.001308333333333334), "{}", var(&s, "AREA")); + // The spline's length, 0.13046952991870 by an independent integration. AutoCAD reported + // 0.1304733129441191, 2.9e-5 longer than that: its own approximation of the length. + assert!(close(var(&s, "PERIMETER"), 0.1304695299187), "{}", var(&s, "PERIMETER")); +} + +#[test] +fn area_of_a_spline_counts_its_narrow_knot_spans() { + // A degree-1 spline is its control polygon, here the triangle (0,0) (1,0) (0,1): area 0.5, + // perimeter 2 + sqrt(2), though two of its three knot spans are a billionth of the domain. + let control = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]; + let spline = Spline { + degree: 1, + knots: vec![0.0, 0.0, 1e-9, 2e-9, 1.0, 1.0], + control: control.iter().map(|&(x, y)| Vec2::new(x, y)).collect(), + ..Spline::default() + }; + let mut s = Session::new(); + let space = s.space(); + let h = s.doc_mut().unwrap().add(&space, Common::default(), EntityKind::Spline(spline)).unwrap(); + lisp(&mut s, &format!("(command \"_.AREA\" \"_O\" (list (handent \"{}\") '(0.5 0.0)))", h.hex())); + assert!(close(var(&s, "AREA"), 0.5), "{}", var(&s, "AREA")); + assert!(close(var(&s, "PERIMETER"), 2.0 + 2f64.sqrt()), "{}", var(&s, "PERIMETER")); +} + +#[test] +fn area_of_a_spline_with_more_spans_than_samples_counts_each() { + // The square (0,0) (100,0) (100,100) (0,100) as a degree-1 spline: 5000 spans along the bottom, + // then two a millionth wide up the right side and across the top. Area 10000, perimeter (the + // open spline's length) 300. + let mut control: Vec = (0..=5000).map(|i| Vec2::new(i as f64 / 50.0, 0.0)).collect(); + control.extend([Vec2::new(100.0, 100.0), Vec2::new(0.0, 100.0)]); + let mut knots: Vec = (0..=5000).map(f64::from).collect(); + knots.insert(0, 0.0); + knots.extend([5000.0 + 1e-6, 5000.0 + 2e-6, 5000.0 + 2e-6]); + let spline = Spline { degree: 1, knots, control, ..Spline::default() }; + let mut s = Session::new(); + let space = s.space(); + let h = s.doc_mut().unwrap().add(&space, Common::default(), EntityKind::Spline(spline)).unwrap(); + lisp(&mut s, &format!("(command \"_.AREA\" \"_O\" (list (handent \"{}\") '(50.0 0.0)))", h.hex())); + assert!(close(var(&s, "AREA"), 1e4), "{}", var(&s, "AREA")); + assert!(close(var(&s, "PERIMETER"), 300.0), "{}", var(&s, "PERIMETER")); +} + +#[test] +fn a_spline_too_long_to_measure_is_refused_and_not_kept() { + let mut s = Session::new(); + lisp(&mut s, "(command \"_.AREA\" '(0.0 0.0) '(10.0 0.0) '(10.0 10.0) \"\")"); + // Finite ends 2e308 apart: its chord closes no area, but its length is past f64's range. That is + // too large to report, as a polyline's is, not a perimeter of 0. + let spline = Spline::from_line(Vec2::new(-1e308, 0.0), Vec2::new(1e308, 0.0), 1); + let space = s.space(); + let h = s.doc_mut().unwrap().add(&space, Common::default(), EntityKind::Spline(spline)).unwrap(); + let err = s.execute("area", &json!({ "handle": h.hex() })).unwrap_err(); + assert!(err.to_string().contains("the perimeter is too large"), "{err}"); + lisp(&mut s, &format!("(command \"_.AREA\" \"_O\" (list (handent \"{}\") '(0.0 0.0)))", h.hex())); + assert!(s.log.iter().any(|l| l.contains("The perimeter is too large.")), "{:?}", s.log); + assert!(close(var(&s, "AREA"), 50.0), "{}", var(&s, "AREA")); + assert!(close(var(&s, "PERIMETER"), 20.0 + 200f64.sqrt()), "{}", var(&s, "PERIMETER")); +} + +#[test] +fn dist_sets_the_distance_and_leaves_lastpoint_at_the_first_point() { + let mut s = Session::new(); + lisp(&mut s, "(command \"_.DIST\" '(0.5 0.25) '(0.53 0.29))"); + assert!(close(var(&s, "DISTANCE"), 0.05), "{}", var(&s, "DISTANCE")); + let (x, y) = lastpoint(&s); + assert!(close(x, 0.5) && close(y, 0.25), "{x}, {y}"); +} + +#[test] +fn dist_with_multiple_points_sets_the_total_and_lastpoint_at_the_last() { + let mut s = Session::new(); + lisp(&mut s, "(command \"_.DIST\" '(0.0 0.0) \"_M\" '(40.0 0.0) '(40.0 30.0) '(0.0 30.0) \"\")"); + assert!(close(var(&s, "DISTANCE"), 110.0), "{}", var(&s, "DISTANCE")); + let (x, y) = lastpoint(&s); + assert!(close(x, 0.0) && close(y, 30.0), "{x}, {y}"); +} + +#[test] +fn measuregeom_sets_them_as_dist_and_area_do() { + let mut s = Session::new(); + // (AutoCAD's MEASUREGEOM asks for the next option after each measurement until eXit; here it + // ends after one.) + lisp(&mut s, "(command \"_.MEASUREGEOM\" \"_D\" '(0.0 0.0) '(30.0 40.0))"); + assert!(close(var(&s, "DISTANCE"), 50.0), "{}", var(&s, "DISTANCE")); + lisp(&mut s, "(command \"_.MEASUREGEOM\" \"_AR\" '(0.5 0.25) '(0.54 0.25) '(0.54 0.28) '(0.5 0.28) \"\")"); + assert!(close(var(&s, "AREA"), 0.0012) && close(var(&s, "PERIMETER"), 0.14), "{} {}", var(&s, "AREA"), var(&s, "PERIMETER")); +} + +#[test] +fn the_json_forms_set_them_too_and_they_are_read_only() { + let mut s = Session::new(); + s.execute("area", &json!({ "points": [[0, 0], [40, 0], [40, 30], [0, 30]] })).unwrap(); + s.execute("dist", &json!({ "p1": [0, 0], "p2": [30, 40] })).unwrap(); + assert_eq!((var(&s, "AREA"), var(&s, "PERIMETER"), var(&s, "DISTANCE")), (1200.0, 140.0, 50.0)); + for name in ["AREA", "PERIMETER", "DISTANCE"] { + assert!(s.execute("setvar", &json!({ "name": name, "value": 1 })).is_err(), "{name}"); + } +} + +#[test] +fn lastpoint_after_multiple_points_is_the_last_point_entered() { + // A length typed with Length extends the path, but LASTPOINT stays at the last point picked; + // after Undo it stays at the point undone (AutoCAD 2024 leaves LASTPOINT at 10,0 and 10,10). + let mut s = Session::new(); + lisp(&mut s, "(command \"_.DIST\" '(0.0 0.0) \"_M\" '(10.0 0.0) \"_L\" 5.0 \"\")"); + assert!(close(var(&s, "DISTANCE"), 15.0), "{}", var(&s, "DISTANCE")); + let (x, y) = lastpoint(&s); + assert!(close(x, 10.0) && close(y, 0.0), "{x}, {y}"); + let mut s = Session::new(); + lisp(&mut s, "(command \"_.DIST\" '(0.0 0.0) \"_M\" '(10.0 0.0) '(10.0 10.0) \"_U\" \"_T\")"); + assert!(close(var(&s, "DISTANCE"), 10.0), "{}", var(&s, "DISTANCE")); + let (x, y) = lastpoint(&s); + assert!(close(x, 10.0) && close(y, 10.0), "{x}, {y}"); +} + +#[test] +fn a_distance_too_large_to_measure_is_refused_and_not_kept() { + let mut s = Session::new(); + lisp(&mut s, "(command \"_.DIST\" '(0.5 0.25) '(0.53 0.29))"); + assert!(close(var(&s, "DISTANCE"), 0.05)); + // Finite points whose distance overflows: the JSON form, two picked points, Multiple points. + assert!(s.execute("dist", &json!({ "p1": [-1e308, 0], "p2": [1e308, 0] })).is_err()); + s.cmdline("dist").unwrap(); + s.input(Input::Point(Vec2::new(-1e308, 0.0))).unwrap(); + s.input(Input::Point(Vec2::new(1e308, 0.0))).unwrap(); + assert!(s.log.last().is_some_and(|l| l.contains("the distance is too large")), "{:?}", s.log.last()); + // LASTPOINT stays at the first point, as after a measurement. + assert_eq!(lastpoint(&s), (-1e308, 0.0)); + s.cancel(); + s.cmdline("dist").unwrap(); + s.input(Input::Point(Vec2::new(-1e308, 0.0))).unwrap(); + s.cmdline("m").unwrap(); + s.input(Input::Point(Vec2::new(1e308, 0.0))).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.log.last().is_some_and(|l| l.contains("the distance is too large")), "{:?}", s.log.last()); + s.cancel(); + assert!(close(var(&s, "DISTANCE"), 0.05), "{}", var(&s, "DISTANCE")); +} + +#[test] +fn the_variable_list_shows_the_sessions_values() { + // A drawing's header can carry these names; GETVAR reads the session's, and so does the list. + let mut s = Session::new(); + s.doc_mut().unwrap().header.set_f64("AREA", 99.0); + // Every DXF header carries ORTHOMODE; the session's ortho is off. + s.doc_mut().unwrap().header.set_i64("ORTHOMODE", 1); + lisp(&mut s, "(command \"_.AREA\" '(0.0 0.0) '(10.0 0.0) '(10.0 10.0) \"\")"); + let list = s.execute("sysvars", &json!({})).unwrap(); + assert!(close(var(&s, "AREA"), 50.0)); + assert_eq!(list["AREA"].as_f64(), Some(var(&s, "AREA")), "{}", list["AREA"]); + assert_eq!(list["ORTHOMODE"], sysvars::get(&s, "ORTHOMODE").unwrap()); + assert_eq!(list["ORTHOMODE"], 0); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index d3c8d030d..38fb4d005 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -60,6 +60,7 @@ mod hatch_numeric_validation; mod hatch_options; mod helix; mod inquiry_keywords; +mod inquiry_variables; mod inquiry_z; mod insert_attribute_prompts; mod insert_prompts; diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 104ba8d3c..e07852340 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -131,6 +131,12 @@ impl Spline { /// [`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). fn derivative_unchecked(&self, t: f64) -> Vec2 { + let d = self.velocity(t); + if d.is_finite() { d } else { Vec2::ZERO } + } + + /// [`Spline::derivative_unchecked`] before a value past f64's range is read as zero. + fn velocity(&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(); @@ -158,8 +164,7 @@ impl Spline { if w.abs() < 1e-300 { return Vec2::ZERO; } - let d = (da - a / w * dw) / w; - if d.is_finite() { d } else { Vec2::ZERO } + (da - a / w * dw) / w } /// Unit tangent at `t` in the direction of increasing parameter; a central difference stands @@ -477,22 +482,18 @@ impl Spline { out } - /// Arc length of one integration panel. The spline is validated once by the public callers - /// ([`Spline::length_between`]/[`Spline::length`]) before any panel is measured, so the speed - /// closure uses the unchecked derivative to avoid re-scanning the knots per sample. - fn panel_length(&self, a: f64, b: f64) -> f64 { - let speed = |t: f64| self.derivative_unchecked(t).len(); + /// Arc length of one integration panel, at the speed of `derivative`. The spline is validated + /// once by the callers ([`Spline::integrated_length`]/[`Spline::param_at_length`]) before any + /// panel is measured, so the derivative is an unchecked one, to avoid re-scanning the knots per + /// sample. + fn panel_length(&self, a: f64, b: f64, derivative: fn(&Spline, f64) -> Vec2) -> f64 { + let speed = |t: f64| derivative(self, t).len(); adaptive_gauss(a, b, gauss(a, b, speed), &speed, MAX_GAUSS_DEPTH) } /// Arc length between parameters `a` and `b` (adaptive Gauss–Legendre over each knot span). pub fn length_between(&self, a: f64, b: f64) -> f64 { - if !(self.is_valid() && a.is_finite() && b.is_finite()) { - return 0.0; - } - let (lo, hi) = self.domain(); - let (a, b) = (a.min(b).clamp(lo, hi), a.max(b).clamp(lo, hi)); - let l: f64 = self.length_intervals(a, b).into_iter().map(|(x, y)| self.panel_length(x, y)).sum(); + let l = self.integrated_length(a, b); if l.is_finite() { l } else { 0.0 } } @@ -502,6 +503,25 @@ impl Spline { self.length_between(lo, hi) } + /// Arc length of the whole spline, or `None` when it is past f64's range, where + /// [`Spline::length`] reads 0. An invalid spline's is 0. + pub fn checked_length(&self) -> Option { + let (lo, hi) = self.domain(); + let l = self.integrated_length(lo, hi); + l.is_finite().then_some(l) + } + + /// Arc length between `a` and `b`, infinite or NaN when it overflows (the length, or the speed + /// along the way); 0 for an invalid spline or a non-finite parameter. + fn integrated_length(&self, a: f64, b: f64) -> f64 { + if !(self.is_valid() && a.is_finite() && b.is_finite()) { + return 0.0; + } + let (lo, hi) = self.domain(); + let (a, b) = (a.min(b).clamp(lo, hi), a.max(b).clamp(lo, hi)); + self.length_intervals(a, b).into_iter().map(|(x, y)| self.panel_length(x, y, Spline::velocity)).sum() + } + /// The parameter `len` along the curve from parameter `from` (forward for positive `len`, /// backward for negative), clamped to the domain. pub fn param_at_length(&self, from: f64, len: f64) -> f64 { @@ -521,7 +541,7 @@ impl Spline { } let mut acc = 0.0; for (x0, x1) in ivs { - let l = self.panel_length(x0, x1); + let l = self.panel_length(x0, x1, Spline::derivative_unchecked); if acc + l >= target && l > 0.0 { // Bisect inside this interval, measuring from its near end. let rest = target - acc; @@ -529,7 +549,7 @@ impl Spline { let (mut s0, mut s1) = (near, far); for _ in 0..60 { let m = (s0 + s1) / 2.0; - let lm = self.panel_length(near.min(m), near.max(m)); + let lm = self.panel_length(near.min(m), near.max(m), Spline::derivative_unchecked); if lm < rest { s0 = m; } else { @@ -735,6 +755,24 @@ mod tests { assert_eq!(q.param_at_length(lo, 1e9), hi); } + #[test] + fn checked_length_tells_an_overflow_from_a_zero_length() { + let l = Spline::from_line(Vec2::ZERO, Vec2::new(3.0, 4.0), 3); + assert_eq!(l.checked_length(), Some(l.length())); + let dot = Spline::from_line(Vec2::new(1.0, 1.0), Vec2::new(1.0, 1.0), 1); + assert_eq!((dot.length(), dot.checked_length()), (0.0, Some(0.0))); + // Finite ends 2e308 apart: over a knot span of 4 the speed is in f64's range and the length + // past it; over a span of 1 the speed is past it too. `length` reads both as 0. + let ends = vec![Vec2::new(-1e308, 0.0), Vec2::new(1e308, 0.0)]; + for span in [4.0, 1.0] { + let huge = Spline { degree: 1, knots: vec![0.0, 0.0, span, span], control: ends.clone(), ..Spline::default() }; + assert_eq!((huge.length(), huge.checked_length()), (0.0, None), "{span}"); + } + let mut invalid = l.clone(); + invalid.knots.reverse(); + assert_eq!(invalid.checked_length(), Some(0.0)); + } + #[test] fn spline_arc_length_on_a_tight_bend() { // One Bezier span that turns sharply: four fixed Gauss panels come out 0.3% short, and diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index d954e66b1..1d5922d37 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -205,10 +205,69 @@ impl Spline { out } + /// Points along the curve for measuring it (AREA). Each knot span has a segment, so a narrow + /// span, which one grid over the whole domain can step over entirely, is measured too. The + /// count [`Spline::tessellate`] takes at `tol` is then shared out among the spans that bend + /// ([`Spline::span_bend`]), by the cube root of their bend: a span's chord error falls with + /// the square of its segments, so that share keeps the total error least. A straight span + /// keeps its one segment, which measures it exactly. The points number one per span plus + /// that count, past `MAX_SAMPLES` when the spans are that many, as [`Spline::length`] + /// integrates every span. An invalid spline gives its control points, as `tessellate` does. + pub fn tessellate_spans(&self, tol: f64) -> Vec { + if !self.is_valid() { + return self.control.clone(); + } + let (lo, hi) = self.domain(); + let n = self.sample_count(tol); + let spans: Vec<(f64, f64, f64)> = self.indexed_knot_spans().map(|(j, a, b)| (a, b, self.span_bend(j).cbrt())).collect(); + if spans.is_empty() { + return self.samples(n).collect(); + } + let total: f64 = spans.iter().map(|s| s.2).sum(); + let shared = total.is_finite() && total > 0.0; + let mut out = Vec::with_capacity(spans.len() + n + 1); + let (mut acc, mut used) = (0.0, 0); + for (a, b, share) in spans { + // Rounded on the running total, so the extra samples add up to `n` however thinly the + // shares are spread; the fraction first, at most 1, so a huge bend can't overflow. + acc += share; + let upto = if shared { (n as f64 * (acc / total).min(1.0)) as usize } else { 0 }; + let seg = 1 + upto.saturating_sub(used); + used = used.max(upto); + out.extend((0..seg).map(|i| self.eval_valid(a + (b - a) * i as f64 / seg as f64, lo, hi))); + } + out.push(self.eval_valid(hi, lo, hi)); + out + } + + /// How far knot span `j` (as [`Spline::indexed_knot_spans`] numbers it) can stray from its + /// chord, as an area: twice the largest triangle its first control point, the one farthest + /// from it and another make. That is between a quarter of the area of their convex hull and + /// twice it. With positive weights the span and its chord lie in that hull, so the area + /// between them is no more; it is zero when the points are collinear, and then the span is + /// straight. A weight that isn't positive lets the span leave the hull, so the square of the + /// points' polygon length counts instead. + fn span_bend(&self, j: usize) -> f64 { + let Some(pts) = self.control.get(j..=j + self.degree) else { return 0.0 }; + let Some(&a) = pts.first() else { return 0.0 }; + if !self.weights.get(j..=j + self.degree).is_none_or(|w| w.iter().all(|w| *w > 0.0)) { + let len: f64 = pts.windows(2).filter_map(|w| w.first().zip(w.get(1)).map(|(p, q)| p.dist(*q))).sum(); + return len * len; + } + let far = pts.iter().copied().max_by(|p, q| a.dist(*p).total_cmp(&a.dist(*q))).unwrap_or(a); + pts.iter().map(|p| (*p - a).cross(far - a).abs()).fold(0.0, f64::max) + } + /// The non-empty knot spans the curve is defined over, in parameter order. fn knot_spans(&self) -> impl Iterator + '_ { + self.indexed_knot_spans().map(|(_, a, b)| (a, b)) + } + + /// The non-empty knot spans with the index of the first of the `degree + 1` control points + /// that shape each. + fn indexed_knot_spans(&self) -> impl Iterator + '_ { let knots = self.knots.get(self.degree..=self.control.len()).unwrap_or(&[]); - knots.windows(2).filter_map(|w| w.first().zip(w.get(1)).map(|(a, b)| (*a, *b)).filter(|(a, b)| b > a)) + knots.windows(2).enumerate().filter_map(|(j, w)| w.first().zip(w.get(1)).map(|(a, b)| (j, *a, *b)).filter(|(_, a, b)| b > a)) } } diff --git a/crates/geom/src/spline/tests.rs b/crates/geom/src/spline/tests.rs index d953cfabd..820490d89 100644 --- a/crates/geom/src/spline/tests.rs +++ b/crates/geom/src/spline/tests.rs @@ -202,6 +202,83 @@ fn bounds_keep_their_cap_over_huge_knot_spans() { } } +#[test] +fn tessellate_spans_measures_narrow_knot_spans() { + // A degree-1 spline is its control polygon: the triangle (0,0) (1,0) (0,1), though two of its + // three spans are a billionth of the domain. One grid over the domain steps over them and + // sees no area; spread over the spans, the corners are there. + let control = vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0), Vec2::ZERO]; + let s = Spline { degree: 1, knots: vec![0.0, 0.0, 1e-9, 2e-9, 1.0, 1.0], control, ..Spline::default() }; + assert!(s.is_valid()); + assert!(crate::shoelace(&s.tessellate(1e-3)).abs() < 1e-6); + let pts = s.tessellate_spans(1e-3); + assert!(pts.iter().any(|p| p.near(Vec2::new(1.0, 0.0), 1e-12)), "{pts:?}"); + assert!((crate::shoelace(&pts).abs() - 0.5).abs() < 1e-12); + // An ordinary spline measures as `tessellate` does, within the sampling's sag. + let w = wiggly(false); + let (a, b) = (crate::shoelace(&w.tessellate(1e-4)), crate::shoelace(&w.tessellate_spans(1e-4))); + assert!((a - b).abs() <= 1e-4 * a.abs().max(1.0), "{a} {b}"); +} + +/// The square (0,0) (100,0) (100,100) (0,100) as a degree-1 spline: `edge` spans of width 1 +/// along the bottom, then two spans a millionth wide up the right side and across the top. +fn square_with_narrow_spans(edge: usize) -> Spline { + let mut control: Vec = (0..=edge).map(|i| Vec2::new(100.0 * i as f64 / edge as f64, 0.0)).collect(); + control.extend([Vec2::new(100.0, 100.0), Vec2::new(0.0, 100.0)]); + let end = edge as f64; + let mut knots: Vec = (0..=edge).map(|i| i as f64).collect(); + knots.insert(0, 0.0); + knots.extend([end + 1e-6, end + 2e-6, end + 2e-6]); + Spline { degree: 1, knots, control, ..Spline::default() } +} + +#[test] +fn tessellate_spans_covers_every_span_however_many() { + // A degree-1 spline's spans are straight: one segment each, its control points, however many + // there are. The narrow spans are measured, not stepped over by a grid. + for edge in [3000, MAX_SAMPLES + 500] { + let s = square_with_narrow_spans(edge); + assert!(s.is_valid()); + let pts = s.tessellate_spans(1e-9); + assert_eq!(pts.len(), s.control.len()); + assert!(pts.iter().zip(&s.control).all(|(p, c)| p.near(*c, 1e-9))); + assert!((crate::shoelace(&pts).abs() - 1e4).abs() < 1e-6, "{}", crate::shoelace(&pts)); + } + let s = square_with_narrow_spans(MAX_SAMPLES + 500); + assert!(crate::shoelace(&s.samples(MAX_SAMPLES).collect::>()).abs() < 0.6e4); +} + +#[test] +fn tessellate_spans_samples_where_the_curve_bends() { + // A quadratic spline along the x-axis but for one control point 1000 above it: three spans + // bend, and the area under them is 1750/3 (a fine grid gives 583.3333334). Their chords alone + // would give 750. Below the sample cap and past it, the straight spans keep one segment each + // (their samples are the only ones on the axis but the curve's end) and the bent spans take + // all the rest. + for edge in [40, MAX_SAMPLES + 500] { + let mut control: Vec = (0..=edge).map(|i| Vec2::new(i as f64, 0.0)).collect(); + control.extend([Vec2::new(edge as f64 + 0.5, 1000.0), Vec2::new(edge as f64 + 1.0, 0.0), Vec2::new(edge as f64 + 2.0, 0.0)]); + let s = Spline::from_control(control, 2); + let pts = s.tessellate_spans(1e-9); + let area = crate::shoelace(&pts).abs(); + assert!((area - 1750.0 / 3.0).abs() < 1e-6 * area, "{edge}: {area}"); + assert_eq!(pts.iter().filter(|p| p.y == 0.0).count(), edge + 1, "{edge}"); + assert_eq!(pts.len(), s.control.len() - 2 + s.sample_count(1e-9) + 1, "{edge}"); + } +} + +#[test] +fn span_bend_bounds_the_area_off_the_chord() { + let mut s = Spline::from_control(vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(3.0, 0.0), Vec2::new(4.0, 2.0)], 2); + // Collinear control points: a straight span. + assert_eq!(s.span_bend(0), 0.0); + // (1,0) (3,0) (4,2): twice their triangle's area. + assert!((s.span_bend(1) - 4.0).abs() < 1e-12, "{}", s.span_bend(1)); + // A weight that isn't positive: the polygon's length squared. + s.weights = vec![1.0, -0.5, 1.0, 1.0]; + assert!((s.span_bend(0) - 9.0).abs() < 1e-12, "{}", s.span_bend(0)); +} + fn scaled(s: &Spline, k: f64) -> Spline { Spline { control: s.control.iter().map(|c| *c * k).collect(), fit: s.fit.iter().map(|c| *c * k).collect(), ..s.clone() } } From 6660d887855f872314151a61c6898a321b3e8de7 Mon Sep 17 00:00:00 2001 From: RicSchonfelder Date: Mon, 2 Nov 2026 18:36:48 -0300 Subject: [PATCH 420/900] i18n(pt-BR): translate the rows the sibling catalogs cover (#2581) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * i18n(pt-BR): translate the rows the sibling catalogs cover The Brazilian Portuguese catalog covered the reference catalog and every marked UI literal, but 191 strings that the German, French, Swedish and Ukrainian catalogs already translate still fell back to English: the Hatch and Gradient dialog, the Block Editor and dynamic-block grips, the plot and drawing units dialogs, multileader editing, selection preview settings and the unit names. Rows follow the catalog's vocabulary (dimension = cota, hatch = hachura, grip = pinça, layout = apresentação, multileader = multilinha, xref = referência externa), keep the prompt keywords, SPDX tokens and technology names in English, and are appended after the existing entries. * docs: leave localization parity updates to maintainers --- crates/ui-egui/src/i18n/pt_br.tsv | 197 ++++++++++++++++++++++++++++++ docs/localization.md | 4 +- 2 files changed, 199 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index a000d9b09..3d8f03449 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -1253,3 +1253,200 @@ 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. +# Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31). + Add: Pick points Adicionar: indicar pontos + Add: Select objects Adicionar: selecionar objetos + Add… Adicionar… + Alias Alias + Alias file: {file} Arquivo de aliases: {file} + Align Multileaders Alinhar multilinhas + Analyze Usage Analisar uso + Angstroms Angströms + Apply to Layout Aplicar à apresentação + Architectural Arquitetônico + Arrow size Tamanho da seta + Associate Associar + Associative Associativo + Astronomical Units Unidades astronômicas + AutoLISP (LSP) AutoLISP (LSP) + Backup copy Cópia de backup + Block to create or edit Bloco a criar ou editar + Bottom left Inferior esquerdo + Bottom right Inferior direito + Boundaries Contornos + Boundaries picked: {n} Contornos selecionados: {n} + Break-line Symbol Símbolo de linha de quebra + built-in integrado + Center the plot Centralizar a plotagem + Centered Centralizado + Centimeters Centímetros + Change Properties Alterar propriedades + Choose the command the alias starts. Escolha o comando que o alias inicia. + Clear Recent Files Limpar arquivos recentes + Click the ruler to add a tab stop, right-click to remove one Clique na régua para adicionar uma parada de tabulação; clique com o botão direito para remover + Click to set new origin Clique para definir a nova origem + Close Block Editor Fechar o editor de blocos + Collect Coletar + Collect Multileaders Coletar multilinhas + Color 1 Cor 1 + Color 2 Cor 2 + Command Comando + contains authoring elements. Open in Block Editor? contém elementos de autoria. Abrir no editor de blocos? + Convert Text to Mtext Converter texto em Mtexto + Create backup copy with each save Criar cópia de backup a cada salvamento + Create separate hatches Criar hachuras separadas + Crossing selection color: Cor da seleção por cruzamento: + Curved Curvo + Custom Personalizado + Customize Personalizar + Decameters Decâmetros + Decimal Decimal + Decimal Degrees Graus decimais + Decimeters Decímetros + Default to boundary extents Padrão para a extensão do contorno + Deg/Min/Sec Gra/Min/Seg + Dim scale overall Escala geral de cotas + Discard Descartar + Don't Save Não salvar + Drag Dynamic Grip Arrastar pinça dinâmica + Drawing Units Unidades do desenho + Dynamic Block Data Dados de bloco dinâmico + Dynamic Block Grips Pinças de bloco dinâmico + Dynamic Block Reference Referência de bloco dinâmico + Edit Block Definition Editar definição de bloco + Edit Command Aliases (PGP)... Editar aliases de comandos (PGP)... + Edit Multileader Editar multilinha + Edit… Editar… + Engineering Engenharia + Enter block names to extract Insira os nomes dos blocos a extrair + Enter geometric characteristic Insira a característica geométrica + Enter name of LISP file to load Insira o nome do arquivo LISP a carregar + Evaluate LISP Avaliar LISP + Exclude: Excluir: + Explode Attributes to Text Explodir atributos em texto + Express Tools Ferramentas Express + Feet Pés + First corner Primeiro canto + Fit to paper Ajustar ao papel + Font Fonte + Fractional Fracionário + Gigameters Gigâmetros + Grads Grados + Grips Pinças + Groups Grupos + Hatch and Gradient Hachura e gradiente + Hatch origin Origem da hachura + Hatch Pick Seleção de hachura + Hatches Hachuras + Hectometers Hectômetros + Hemispherical Hemisférico + Ignore Ignorar + Imperial (inches) Imperial (polegadas) + Implied Loops Laços implícitos + Inches Polegadas + Indicate selection area Indicar área de seleção + Insertion scale Escala de inserção + Interface scale Escala da interface + Inverted Invertido + Island Ilha + Island detection Detecção de ilhas + Italic Itálico + Justify Justificar + Kilometers Quilômetros + Landscape Paisagem + Layouts Apresentações + Light Years Anos-luz + Limits Limites + Load Application... Carregar aplicativo... + Meters Metros + Metric (millimetres) Métrico (milímetros) + Microinches Micropolegadas + Microns Mícrons + Miles Milhas + Millimeters Milímetros + Mils Mils + More than {n} aliases. Mais de {n} aliases. + Move/Copy/Rotate Mover/Copiar/Girar + Multiline text Texto multilinha + Nanometers Nanômetros + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). Novos desenhos e o primeiro desenho na inicialização usam estas unidades, a menos que um modelo padrão esteja definido (QNEWTEMPLATE). + New block Novo bloco + No alias file loaded. REINIT replaces these aliases with a file's. Nenhum arquivo de aliases carregado. O REINIT substitui estes aliases pelos de um arquivo. + Object grouping Agrupamento de objetos + Object selection limit for display of grips Limite de seleção de objetos para exibir pinças + Objects on locked layers Objetos em camadas bloqueadas + Open in Block Editor Abrir no editor de blocos + Open Recent Abrir recentes + Opposite corner Canto oposto + Orientation Orientação + Origin: {x}, {y} Origem: {x}, {y} + Outer Externo + Overline Sobrelinha + overrides built-in substitui o integrado + Paper size Tamanho do papel + Parsecs Parsecs + Plot area Área de plotagem + Plot object lineweights Plotar espessuras de linha dos objetos + Plot offset Deslocamento da plotagem + Plot transparency Plotar transparência + Portrait Retrato + Precision Precisão + Preview Visualizar + Printer/plotter Impressora/plotter + Radians Radianos + Sample output Amostra de saída + Save alias Salvar alias + Save Block Salvar bloco + Save Block As Salvar bloco como + Save changes to block "{name}"? Salvar alterações no bloco "{name}"? + Save changes to {name}? Salvar alterações em {name}? + Save Layout as Template Salvar apresentação como modelo + Scientific Científico + Select boundaries to remove Selecione contornos para remover + Selection Area Effect Efeito da área de seleção + Selection area opacity: Opacidade da área de seleção: + Selection effect color Cor do efeito de seleção + Selection modes Modos de seleção + Selection preview Visualização da seleção + Selection Preview Filter Filtro de visualização da seleção + Set Dynamic Property Definir propriedade dinâmica + Shape Forma + Sheet Books to PDF... Livros de folhas em PDF... + Show grips Mostrar pinças + Specified origin Origem especificada + Spherical Esférico + Surveyor's Units Unidades de topografia + Tables Tabelas + Text color Cor do texto + This drawing Este desenho + Top left Superior esquerdo + Top right Superior direito + Type an alias name. Digite um nome de alias. + Underline Sublinhado + Unitless Adimensional + Units of new drawings Unidades de novos desenhos + Units to scale inserted content Unidades para dimensionar conteúdo inserido + Unsaved changes Alterações não salvas + US Survey Feet Pés topográficos norte-americanos + US Survey Inch Polegada topográfica norte-americana + US Survey Mile Milha topográfica norte-americana + US Survey Yard Jarda topográfica norte-americana + Use current origin Usar origem atual + Visual Effect Settings Configurações de efeitos visuais + Visual Effect Settings... Configurações de efeitos visuais... + When a command is active Quando um comando está ativo + When no command is active Quando nenhum comando está ativo + Window < Janela < + Window selection color: Cor da seleção por janela: + X offset (mm) Deslocamento X (mm) + Xrefs Referências externas + Y offset (mm) Deslocamento Y (mm) + Yards Jardas + Your changes will be lost if you don't save them. Suas alterações serão perdidas se você não salvá-las. + {alias} is already defined; select it and use Edit. {alias} já está definido; selecione-o e use Editar. + {command} is an unknown command. {command} é um comando desconhecido. +# Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31). +menu Dimension Cota +menu Draw Desenho +menu Modify Modificar +menu View Exibir diff --git a/docs/localization.md b/docs/localization.md index 909fad9f8..998fbe0a0 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -46,8 +46,8 @@ 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 +Brazilian Portuguese has 1,447 catalog rows and also covers the reference catalog, every marked UI +literal and the strings the sibling catalogs translate: 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 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 From 7bc76f94ca080275eb866567e45f3110a6525c6c Mon Sep 17 00:00:00 2001 From: Tyler Chiriboga Date: Mon, 2 Nov 2026 15:36:53 -0600 Subject: [PATCH 421/900] OVERKILL: objects within the tolerance are duplicates wherever their numbers fall (#2653) * OVERKILL: objects within the tolerance are duplicates wherever their numbers fall OVERKILL compared objects by rounding every number to a multiple of the tolerance. Two numbers closer than the tolerance on either side of a rounding step round apart, so the objects were kept: at 0.01, circles at x = 80.001 and 80.003 were merged but circles at 50.004 and 50.006 were not. Arcs on one circle were bucketed the same way. Duplicates are now found by shape (the JSON without its floating-point numbers; counts and flags must match exactly) and a weighted sum of the numbers on a grid of the tolerance, looking in the neighbouring cells too, then compared pairwise to within the tolerance. Arcs and circles look in the neighbouring cells of centre and radius and are grouped with a union-find. Lines were already grouped by sorting and are unchanged. Co-Authored-By: Claude Opus 5.5 * OVERKILL: within the tolerance doesn't chain Arcs and circles were grouped with a union-find over pairwise matches, so A ~ B and B ~ C put A and C in one group even when A and C are farther apart than the tolerance: a circle C was deleted for matching only the arc between it and the kept circle A, and arcs were combined across the chain. Each object now joins the first group whose every member is within the tolerance of it, or starts its own. In the duplicates pass, a followed object displaced an earlier keeper that later objects had already matched, leaving them deleted up to twice the tolerance from what stays. Followed objects are now looked at first, so every deletion is within the tolerance of an object that stays. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Tyler Chiriboga <18270301+Tyler-Chiriboga@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/overkill.rs | 142 +++++++++++++++++++++-------- crates/engine/tests/it/overkill.rs | 86 +++++++++++++++++ 2 files changed, 190 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/overkill.rs b/crates/engine/src/cmd/overkill.rs index abfdff2eb..632001461 100644 --- a/crates/engine/src/cmd/overkill.rs +++ b/crates/engine/src/cmd/overkill.rs @@ -146,20 +146,49 @@ impl Opts { } } -/// Round every number of a JSON value to a multiple of `q`. -fn quantize(v: &mut Value, q: f64) { +/// Take the measurements (floating-point numbers) out of a JSON value, in order, leaving a marker +/// in their place: two objects are equal when what is left matches, counts and flags included, +/// and each pair of measurements is within the tolerance. +fn split_numbers(v: &mut Value, nums: &mut Vec) { match v { Value::Number(n) => { - if let Some(x) = n.as_f64() { - *v = json!((x / q).round()); + if n.is_f64() + && let Some(x) = n.as_f64() + { + nums.push(x); + *v = Value::String(NUMBER.into()); } } - Value::Array(a) => a.iter_mut().for_each(|x| quantize(x, q)), - Value::Object(o) => o.values_mut().for_each(|x| quantize(x, q)), + Value::Array(a) => a.iter_mut().for_each(|x| split_numbers(x, nums)), + Value::Object(o) => o.values_mut().for_each(|x| split_numbers(x, nums)), _ => {} } } +/// What [`split_numbers`] leaves where a number was. +const NUMBER: &str = "\u{0}#"; + +/// Whether two lists of numbers match pairwise to within `tol`. +fn within(a: &[f64], b: &[f64], tol: f64) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol) +} + +/// The numbers summed with weights in [1, 2) that no simple pattern shares (golden-ratio steps), +/// so points on a diagonal of a grid don't all get the same sum; and the sum of the weights. +fn weighted_sum(nums: &[f64]) -> (f64, f64) { + nums.iter().enumerate().fold((0.0, 0.0), |(sum, total), (j, x)| { + let w = 1.0 + (j as f64 * 0.618_033_988_749_895).fract(); + (sum + w * x, total + w) + }) +} + +/// The cell of `x` on a grid of `step`. Values within one step of each other land in the same or +/// neighbouring cells; values too large for the grid share the outermost ones. +fn cell_of(x: f64, step: f64) -> i64 { + let k = (x / step).floor(); + if k.is_finite() { k.clamp(-9e15, 9e15) as i64 } else { i64::MIN } +} + #[derive(Default)] struct Report { duplicates: usize, @@ -234,33 +263,37 @@ fn overkill(s: &mut Session, hs: Option>, o: &Opts) -> Result = HashMap::new(); - for (i, c) in cands.iter().enumerate() { + // Keepers so far: (properties, shape) → cell of the sum → their numbers. + type Keepers = HashMap>>; + let mut seen: HashMap<(u32, String), Keepers> = HashMap::new(); + // Followed objects first, so a keeper is never displaced: everything deleted is within the + // tolerance of an object that stays. + let (followed, rest): (Vec, Vec) = (0..cands.len()).partition(|i| cands.get(*i).is_some_and(|c| c.protected)); + for i in followed.into_iter().chain(rest) { + let Some(c) = cands.get(i) else { continue }; let Ok(mut v) = serde_json::to_value(&c.e.kind) else { continue }; - if o.tol > 0.0 { - quantize(&mut v, o.q()); + let mut nums = Vec::new(); + split_numbers(&mut v, &mut nums); + let (sum, weights) = weighted_sum(&nums); + let cell = cell_of(sum, o.q() * weights.max(1.0)); + let cells = seen.entry((c.prop, v.to_string())).or_default(); + let found = [cell.saturating_sub(1), cell, cell.saturating_add(1)] + .into_iter() + .any(|k| cells.get(&k).is_some_and(|keepers| keepers.iter().any(|n| within(n, &nums, o.tol)))); + if !found || c.protected { + // A followed object stays even when it matches another. + cells.entry(cell).or_default().push(nums); + continue; } - let key = (c.prop, v.to_string()); - match seen.get(&key).copied() { - None => { - seen.insert(key, i); - } - Some(k) => { - let keeper_protected = cands.get(k).is_some_and(|x| x.protected); - let victim = match (keeper_protected, c.protected) { - (_, false) => i, - (false, true) => { - seen.insert(key, i); - k - } - (true, true) => continue, - }; - if let Some(g) = gone.get_mut(victim) { - *g = true; - rep.duplicates += 1; - } - } + if let Some(g) = gone.get_mut(i) { + *g = true; + rep.duplicates += 1; } } } @@ -421,8 +454,8 @@ fn collinear(members: &[&LineRec], cands: &[Cand], o: &Opts, gone: &mut [bool], fn arcs(cands: &[Cand], o: &Opts, gone: &mut [bool], changed: &mut HashMap, rep: &mut Report) { let q = o.q(); let g = q.max(1e-9); - let cell = |x: f64| (x / g).round() as i64; - let mut buckets: HashMap<(u32, i64, i64, i64, i64), Vec> = HashMap::new(); + // (index, properties, centre and radius); cells of `g` hold them. + let mut recs: Vec<(usize, u32, [f64; 4])> = Vec::new(); for (i, c) in cands.iter().enumerate() { if gone.get(i).copied().unwrap_or(true) || c.protected { continue; @@ -442,12 +475,45 @@ fn arcs(cands: &[Cand], o: &Opts, gone: &mut [bool], changed: &mut HashMap = buckets.keys().copied().collect(); - keys.sort_unstable(); - for key in keys { - let Some(group) = buckets.get(&key) else { continue }; + // Those within `g` of each other in centre and radius are on one circle. Each object joins the + // first group whose every member is within `g` of it, or starts one: matches don't chain, so + // nothing is deleted for matching only an object that itself matches the keeper. Members are + // looked for in the neighbouring cells too, so values on either side of a cell boundary meet. + let mut grid: HashMap<(u32, [i64; 4]), Vec> = HashMap::new(); + let mut group_of: Vec = Vec::with_capacity(recs.len()); + // Each group's records, in draw order; groups in the order of their first object. + let mut members: Vec> = Vec::new(); + for (ri, (_, prop, v)) in recs.iter().enumerate() { + let cells = v.map(|x| cell_of(x, g)); + let mut near_groups: Vec = Vec::new(); + for n in 0..81_i64 { + let near = [n % 3 - 1, n / 3 % 3 - 1, n / 9 % 3 - 1, n / 27 % 3 - 1]; + let mut key = cells; + for (k, d) in key.iter_mut().zip(near) { + *k = k.saturating_add(d); + } + near_groups.extend(grid.get(&(*prop, key)).map(Vec::as_slice).unwrap_or_default().iter().filter_map(|rj| group_of.get(*rj))); + } + near_groups.sort_unstable(); + near_groups.dedup(); + let fits = |gi: &usize| members.get(*gi).is_some_and(|m| m.iter().all(|rk| recs.get(*rk).is_some_and(|(_, _, w)| within(v, w, g)))); + let gi = match near_groups.into_iter().find(fits) { + Some(gi) => gi, + None => { + members.push(Vec::new()); + members.len() - 1 + } + }; + if let Some(m) = members.get_mut(gi) { + m.push(ri); + } + group_of.push(gi); + grid.entry((*prop, cells)).or_default().push(ri); + } + let groups = members.iter().map(|m| m.iter().filter_map(|ri| recs.get(*ri).map(|r| r.0)).collect::>()); + for group in groups { if group.len() < 2 { continue; } @@ -465,7 +531,7 @@ fn arcs(cands: &[Cand], o: &Opts, gone: &mut [bool], changed: &mut HashMap>(); + let mut s = Session::new(); + circle(&mut s, 50.0); + arc_at(&mut s, 50.008, 0.0, 90.0); + circle(&mut s, 50.016); + let r = ok(&mut s, json!({ "tolerance": 0.01 })); + assert_eq!((r["duplicates"].as_u64(), r["overlapping"].as_u64()), (Some(0), Some(1)), "{r}"); + assert_eq!(kinds(&s), ["Circle", "Circle"]); + let mut s = Session::new(); + arc_at(&mut s, 50.008, 0.0, 90.0); + circle(&mut s, 50.0); + circle(&mut s, 50.016); + let r = ok(&mut s, json!({ "tolerance": 0.01 })); + assert_eq!(r["deleted"], 1, "{r}"); + assert_eq!(kinds(&s), ["Circle", "Circle"]); + // Arcs alone: the third is 0.016 from the first, so it is not combined with it. + let mut s = Session::new(); + arc_at(&mut s, 0.0, 0.0, 90.0); + arc_at(&mut s, 0.008, 45.0, 180.0); + arc_at(&mut s, 0.016, 100.0, 200.0); + let r = ok(&mut s, json!({ "tolerance": 0.01 })); + assert_eq!(r["overlapping"], 1, "{r}"); + assert_eq!(kinds(&s), ["Arc", "Arc"]); + // A followed line displaces the first one, which a third line matched: the third is 0.016 from + // the followed line, so it stays. + let mut s = Session::new(); + let first = line(&mut s, [0.0, 0.0], [10.0, 0.0]); + let third = line(&mut s, [0.0, 0.008], [10.0, 0.008]); + let followed = line(&mut s, [0.0, -0.008], [10.0, -0.008]); + s.execute("dimlinear", &json!({ "object": followed.hex(), "at": [5, 5] })).unwrap(); + let r = ok(&mut s, json!({ "tolerance": 0.01 })); + assert_eq!(r["deleted"], 1, "{r}"); + let d = s.doc().unwrap(); + assert!(d.entity(first).is_none() && d.entity(third).is_some() && d.entity(followed).is_some()); +} From 7690d36bb0aa43c73d266c56af828e985f2afb10 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 14:31:06 -0700 Subject: [PATCH 422/900] fmt --- crates/engine/tests/save_reports_not_saved.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 984d0d635..d38e13e0b 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -155,9 +155,16 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() { #[test] fn a_dxf_2013_loss_is_known_before_saving() { use cadcraft_engine::cmd::file::loss_on_save; - set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0 + set_io(IoHooks { + read: |_, _| Err("no reader in this test".into()), + write: |_, _| { + Ok(b"0 EOF -".to_vec()), plot: None }); +" + .to_vec()) + }, + plot: None, + }); let sat = |d: &mut Drawing| { let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }]; d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap(); From 86f3fdc9e99454fe096f94b33e8aa864d62fc158 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 14:34:47 -0700 Subject: [PATCH 423/900] Test: the DWG note's wording, and one-line fake bytes --- crates/engine/tests/save_reports_not_saved.rs | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index d38e13e0b..80192bf53 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -60,14 +60,14 @@ fn export_and_wblock_say_what_a_dwg_leaves_out() { let mut s = Session::empty(); s.open_drawing(d, "foreign.dxf", None); let file = |ext: &str| std::env::temp_dir().join(format!("cadcraft-leaves-out-{}.{ext}", std::process::id())).to_string_lossy().into_owned(); - let msg = "Not saved in the DWG file (its writer can't write these object types yet; DXF keeps them): 1 ACME_WIDGET"; + let said = |l: &String| l.starts_with("Not saved in the DWG file") && l.ends_with(": 1 ACME_WIDGET"); let (dwg, dxf) = (file("dwg"), file("dxf")); for (cmd, p) in [("export", json!({ "path": dwg })), ("wblock", json!({ "path": dwg, "handles": [h] }))] { s.log.clear(); let r = s.execute(cmd, &p).unwrap(); assert_eq!(r["notSaved"], json!({ "ACME_WIDGET": 1 }), "{cmd}"); - assert!(s.log.iter().any(|l| l == msg), "{cmd}: {:?}", s.log); + assert!(s.log.iter().any(said), "{cmd}: {:?}", s.log); } // -WBLOCK takes the objects out of the drawing, so last. let r = s.execute("-wblock", &json!({ "path": dwg, "handles": [h] })).unwrap(); @@ -79,7 +79,7 @@ fn export_and_wblock_say_what_a_dwg_leaves_out() { for (cmd, p) in [("export", json!({ "path": dxf })), ("wblock", json!({ "path": dxf, "handles": [h] }))] { s.log.clear(); assert!(s.execute(cmd, &p).unwrap().get("notSaved").is_none(), "{cmd}"); - assert!(!s.log.iter().any(|l| l == msg), "{cmd}: {:?}", s.log); + assert!(!s.log.iter().any(said), "{cmd}: {:?}", s.log); } let _ = std::fs::remove_file(&dxf); } @@ -155,16 +155,7 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() { #[test] fn a_dxf_2013_loss_is_known_before_saving() { use cadcraft_engine::cmd::file::loss_on_save; - set_io(IoHooks { - read: |_, _| Err("no reader in this test".into()), - write: |_, _| { - Ok(b"0 -EOF -" - .to_vec()) - }, - plot: None, - }); + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); let sat = |d: &mut Drawing| { let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }]; d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap(); From 0bc025965ae80d09ecb6ec1ebd487ce901585b64 Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Mon, 2 Nov 2026 22:01:21 +0000 Subject: [PATCH 424/900] fix(dwg): preserve MTEXT caret-adjacent whitespace (#2250) (#2314) * fix(dwg): preserve literal spaces after MTEXT carets (#2250) * test(dwg): fix MTEXT fixture ownership and boxed entity --------- Co-authored-by: Zaxaerith <189452125+Zaxaerith@users.noreply.github.com> --- crates/dwg/src/lib.rs | 95 +++++++++++++++++- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/mtext_caret_spaces.rs | 118 +++++++++++++++++++++++ 3 files changed, 212 insertions(+), 2 deletions(-) create mode 100644 crates/io/tests/it/mtext_caret_spaces.rs diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 037aa26b5..ffde17ee8 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -110,8 +110,11 @@ mod native { notes.push(format!("DWG: {orphans} DGN line style component{s} that no line style definition uses {were} left out")); } let mut out = CappedWriter { buf: Vec::new(), limit: limits.max_dxf_bytes, exceeded: false }; - let written = std::panic::catch_unwind(AssertUnwindSafe(|| acadrust::DxfWriter::new(&doc).write_to_writer(&mut out))) - .map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?; + let written = std::panic::catch_unwind(AssertUnwindSafe(|| { + acadrust::DxfWriter::new(&doc).write_to_writer(&mut out)?; + mtext_contents(&doc, &mut out) + })) + .map_err(|_| "the DWG→DXF conversion failed on this file".to_string())?; if out.exceeded { return Err(format!( "DWG: converting this {} file produced more than {} of drawing data (the limit); \ @@ -124,6 +127,94 @@ mod native { Ok((add_header_vars(out.buf, &doc.header), notes)) } + /// acadrust 0.6.6's ASCII writer treats a caret followed by a literal space as already + /// escaped, and turns line feeds into paragraph codes. Serialize affected MTEXT contents + /// from the native values instead, using its lossless string writer. All other groups, + /// including embedded-object data, remain byte-for-byte as the DXF writer emitted them. + fn mtext_contents(doc: &acadrust::CadDocument, out: &mut CappedWriter) -> acadrust::Result<()> { + use acadrust::io::dxf::{DxfStreamWriter, DxfTextWriter}; + let contents: std::collections::HashMap<_, _> = doc + .entities() + .filter_map(|e| match e { + acadrust::EntityType::MText(t) if t.value.contains(['^', '\t', '\n']) => Some((t.common.handle.value(), t.value.as_str())), + _ => None, + }) + .collect(); + if contents.is_empty() { + return Ok(()); + } + let dxf = std::mem::take(&mut out.buf); + let mut lines = dxf.split_inclusive(|b| *b == b'\n'); + let (mut mtext, mut text, mut written) = (false, None, false); + while let Some(code) = lines.next() { + let value = lines.next().ok_or_else(|| std::io::Error::other("incomplete DWG bridge DXF pair"))?; + match code.trim_ascii() { + b"0" => { + mtext = value.trim_ascii() == b"MTEXT"; + text = None; + written = false; + } + b"5" if mtext => { + text = std::str::from_utf8(value.trim_ascii()).ok().and_then(|s| u64::from_str_radix(s, 16).ok()).and_then(|h| contents.get(&h)); + } + b"101" => mtext = false, + b"1" | b"3" if mtext && text.is_some() => { + if let Some(&text) = text + && !written + { + let mut writer = DxfTextWriter::new(&mut *out); + if doc.version < acadrust::DxfVersion::AC1021 + && let Some(encoding) = acadrust::io::dxf::code_page::encoding_from_code_page(&doc.header.code_page) + { + writer.set_encoding(encoding); + } + // Each character can expand to two caret-escape characters. Keep + // those pairs together and each group within 250 characters. + let mut rest = text; + while let Some((end, _)) = rest.char_indices().nth(125) { + let (chunk, tail) = rest.split_at(end); + writer.write_xrecord_string(3, chunk)?; + rest = tail; + } + writer.write_xrecord_string(1, rest)?; + written = true; + } + continue; + } + _ => {} + } + out.write_all(code)?; + out.write_all(value)?; + } + Ok(()) + } + + #[cfg(test)] + #[test] + fn mtext_contents_keeps_other_groups_and_the_output_limit() -> acadrust::Result<()> { + for version in [acadrust::DxfVersion::AC1015, acadrust::DxfVersion::AC1032] { + let mut doc = acadrust::CadDocument::new(); + doc.version = version; + doc.header.code_page = "ANSI_1252".into(); + let mut t = acadrust::MText::with_value("é ^ C", acadrust::Vector3::ZERO); + t.common.handle = acadrust::Handle::new(0x10); + doc.add_entity(acadrust::EntityType::MText(Box::new(t)))?; + // Only the MTEXT's own 1/3 groups change. The embedded object's groups and the + // following TEXT record must survive byte-for-byte, including their spaces. + let prefix = b" 0\r\nMTEXT\r\n 5\r\n10\r\n 8\r\n0\r\n"; + let suffix = b"101\r\nEmbedded Object\r\n 1\r\n^ embedded\r\n 3\r\n^ tail\r\n 0\r\nTEXT\r\n 1\r\n^ plain\r\n"; + let raw = [prefix.as_slice(), b" 3\r\nold\r\n 1\r\ntext\r\n", suffix.as_slice()].concat(); + let mut out = CappedWriter { buf: raw.clone(), limit: 4096, exceeded: false }; + mtext_contents(&doc, &mut out)?; + let value: &[u8] = if version == acadrust::DxfVersion::AC1015 { b"\xe9 ^ C" } else { "é ^ C".as_bytes() }; + assert_eq!(out.buf, [prefix.as_slice(), b" 1\r\n", value, b"\r\n", suffix.as_slice()].concat()); + let mut limited = CappedWriter { buf: raw, limit: 1, exceeded: false }; + assert!(mtext_contents(&doc, &mut limited).is_err()); + assert!(limited.exceeded); + } + Ok(()) + } + /// Most record types named in the skipped-records note. const NOTE_TYPES: usize = 6; diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 7b49eb6bf..289e87806 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -42,6 +42,7 @@ mod mleader_roundtrip; mod mline_roundtrip; #[cfg(not(target_arch = "wasm32"))] mod model_layout_plot_type; +mod mtext_caret_spaces; mod mtext_columns_roundtrip; mod mtext_embedded_object; mod mtext_line_spacing; diff --git a/crates/io/tests/it/mtext_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs new file mode 100644 index 000000000..8bb1ed071 --- /dev/null +++ b/crates/io/tests/it/mtext_caret_spaces.rs @@ -0,0 +1,118 @@ +//! Literal MTEXT carets and their adjacent whitespace survive DXF and DWG saves (#2250). + +use cadcraft_doc::{Common, Drawing, EntityKind, Handle, MText, Space}; +use cadcraft_geom::Vec3; +use cadcraft_io::{SaveOptions, Version, read, write_with}; + +type TestResult = Result<(), Box>; + +fn drawing() -> Result<(Drawing, Vec<(Handle, String)>), Box> { + let mut d = Drawing::new_metric(); + let mut expected = Vec::new(); + let mut cases: Vec = [ + "ordinary text", + "^ C", + "A ^ C B", + "^ C", + "A ^ C B", + "^ ", + "^^ C ^ ^ D^", + "^I ^J ^ C", + "\t^ C\nD\tE", + "^\t ^\n C", + r"A\P^ C\P^I ^J", + r"\S+0.1^-0.1; ^ C", + ] + .into_iter() + .map(str::to_string) + .collect(); + // Exercise multiple group-3 chunks and a caret at the output chunk boundary. + cases.push(format!("{}^ C", "A".repeat(124))); + cases.push(format!("{}^ C B", "A".repeat(260))); + for contents in cases { + let kind = EntityKind::MText(MText { + insert: Vec3::new(1.0, 2.0, 0.0), + height: 0.5, + width: 12.5, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: contents.clone(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }); + let handle = d.add(&Space::Model, Common::default(), kind)?; + expected.push((handle, contents)); + } + Ok((d, expected)) +} + +fn assert_contents(d: &Drawing, expected: &[(Handle, String)], context: &str) -> TestResult { + assert_eq!(d.model.len(), expected.len(), "{context}: entity count"); + for (handle, contents) in expected { + let e = d.entity(*handle).ok_or("MTEXT handle lost")?; + let EntityKind::MText(t) = &e.kind else { return Err("MTEXT entity type changed".into()) }; + assert_eq!(&t.contents, contents, "{context}: {handle:?}"); + } + Ok(()) +} + +#[test] +fn dxf_mtext_caret_spaces_round_trip() -> TestResult { + let (original, expected) = drawing()?; + for version in Version::ALL { + for binary in [false, true] { + let mut d = original.clone(); + for pass in 1..=2 { + let bytes = write_with(&d, "carets.dxf", &SaveOptions { version: Some(version), binary })?; + d = read(&bytes, "carets.dxf")?; + assert_contents(&d, &expected, &format!("{version:?}, binary={binary}, pass={pass}"))?; + } + } + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dwg_mtext_caret_spaces_round_trip() -> TestResult { + let (original, expected) = drawing()?; + for version in Version::ALL { + let mut d = original.clone(); + for pass in 1..=2 { + let bytes = write_with(&d, "carets.dwg", &SaveOptions { version: Some(version), binary: false })?; + assert_eq!(cadcraft_dwg::version(&bytes).as_deref(), Some(version.code())); + // Inspect the stored DWG text before its DXF rendition: a compensating reader + // must not hide corruption on save. This uses the same codec, not an external oracle. + let native = acadrust::DwgReader::from_stream(std::io::Cursor::new(&bytes)).read()?; + for (handle, contents) in &expected { + let text = native.entities().find_map(|e| match e { + acadrust::EntityType::MText(t) if t.common.handle.value() == handle.0 => Some(&t.value), + _ => None, + }); + assert_eq!(text, Some(contents), "native DWG {version:?}, pass={pass}, {handle:?}"); + } + let dxf = cadcraft_dwg::dwg_to_dxf(&bytes)?; + let converted = read(&dxf, "bridge.dxf")?; + assert_contents(&converted, &expected, &format!("DWG bridge DXF {version:?}, pass={pass}"))?; + d = read(&bytes, "carets.dwg")?; + assert_contents(&d, &expected, &format!("DWG {version:?}, pass={pass}"))?; + } + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn bridge_caret_space_is_escaped_once_in_each_direction() -> TestResult { + let (d, _) = drawing()?; + let dxf = cadcraft_io::write_dxf(&d); + assert!(dxf.contains(" 1\r\n^ C\r\n"), "literal caret plus authored space needs two wire spaces"); + let native = acadrust::DxfReader::from_reader(std::io::Cursor::new(dxf.into_bytes()))?.read()?; + assert!(native.entities().any(|e| matches!(e, acadrust::EntityType::MText(t) if t.value == "^ C"))); + let dwg = write_with(&d, "carets.dwg", &SaveOptions { version: Some(Version::R2018), binary: false })?; + let returned = String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg)?)?; + assert!(returned.contains(" 1\r\n^ C\r\n"), "the return bridge must encode the separator independently of authored whitespace"); + Ok(()) +} From 03101e8d77b49a4c847f182dd8c98c0cbaca0b25 Mon Sep 17 00:00:00 2001 From: Rahul Date: Tue, 3 Nov 2026 03:31:26 +0530 Subject: [PATCH 425/900] fix(io): a moved DIMENSION draws its block at its insertion point (group 12) (#2634) (#2636) A DIMENSION moved by an older AutoCAD keeps its *D block contents where they were and the move in DXF group 12, and is drawn translated by the insertion point. Group 12 was never read into Dimension, so the block rendered at its pre-move position and the extents reached there too. Read group 12 into a new Dimension::insertion_point, draw the block translated by it, move its bounds with it in the extents, test the block's text where it draws, and write group 12 back whenever the block written is the one read from the file. Regenerated geometry (edits drop the block link) sits at its definition points, so no offset is kept or written for it. Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- crates/doc/src/entity/dim.rs | 5 +++ crates/doc/src/extents.rs | 4 ++ crates/doc/src/tests.rs | 39 +++++++++++++++++ crates/engine/src/cmd/annotate/common.rs | 1 + crates/engine/src/sample.rs | 3 ++ crates/engine/src/select.rs | 14 ++++--- crates/engine/tests/compare.rs | 1 + crates/engine/tests/it/compare_export.rs | 4 ++ crates/io/src/dxf_read/entities.rs | 1 + crates/io/src/dxf_write/entity.rs | 6 +++ crates/io/src/tests.rs | 2 + crates/io/tests/dimassoc_angular_radial.rs | 1 + crates/io/tests/it/acad_interop.rs | 1 + .../io/tests/it/dim_block_resave_roundtrip.rs | 42 +++++++++++++++++++ crates/io/tests/it/dim_block_text.rs | 2 + crates/io/tests/it/dim_marks_roundtrip.rs | 1 + crates/io/tests/it/dimstyle_vars_roundtrip.rs | 1 + crates/io/tests/it/dimtfill_roundtrip.rs | 1 + crates/io/tests/it/roundtrip/cases/complex.rs | 1 + crates/io/tests/it/roundtrip_audit.rs | 1 + crates/io/tests/it/text_carets_roundtrip.rs | 1 + crates/render/src/dim/tests.rs | 1 + crates/render/src/draw.rs | 9 +++- crates/render/src/tests.rs | 1 + crates/render/tests/it/dim_angular_centre.rs | 1 + crates/render/tests/it/dim_post_tolerance.rs | 1 + crates/render/tests/it/dim_text_fill.rs | 1 + crates/render/tests/it/dim_text_format.rs | 1 + crates/render/tests/it/render_props.rs | 1 + 29 files changed, 142 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/entity/dim.rs b/crates/doc/src/entity/dim.rs index d10237b26..dc4635c7a 100644 --- a/crates/doc/src/entity/dim.rs +++ b/crates/doc/src/entity/dim.rs @@ -52,6 +52,11 @@ pub struct Dimension { /// Anonymous block with the rendered geometry (from files); regenerated when edited. #[serde(default)] pub block: Option, + /// Insertion point (DXF group 12): a dimension moved by an older AutoCAD keeps its offset + /// here with the `*D` block's contents left where they were, and is drawn translated by it. + /// Zero once the geometry is regenerated from the definition points. + #[serde(default)] + pub insertion_point: Vec3, /// Per-dimension style overrides (DIMOVERRIDE): DimStyle field names (camelCase) → values, /// merged over the named style. #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 353a42b53..d87cdc9a2 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -212,6 +212,10 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< inner } }; + // The block draws translated by the insertion point (group 12), so its bounds + // move with it (#2634); the cache above keeps the block's own bounds. + let off = dm.insertion_point.xy(); + let inner = if off == Vec2::ZERO { inner } else { Bounds2 { min: inner.min + off, max: inner.max + off } }; b = b.union(&inner); } b diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index f0f979f12..29d55e30f 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -55,6 +55,44 @@ fn frozen_layers_are_left_out_of_extents_and_layers_turned_off_are_not() { assert_eq!(d.extents(&Space::Model).max, Vec2::new(1.0, 1.0)); } +/// DXF group 12: a dimension moved by an older AutoCAD keeps its `*D` block where it was and +/// the move in the insertion point, and the block draws translated by it. Extents follow the +/// drawing, not the stale block contents (#2634). +#[test] +fn dimension_insertion_point_moves_its_block_in_extents() { + let moved = |ins: Vec3| { + let mut d = Drawing::new_metric(); + let mut blk = Block::new("*D1"); + blk.entities.push(on_layer("0", line((850.0, 920.0), (860.0, 920.0)), 2)); + d.blocks.insert("*D1".into(), std::sync::Arc::new(blk)); + let dm = Dimension { + kind: DimKind::Aligned, + defpt: Vec3::new(5.0, 1.0, 0.0), + text_mid: Vec3::ZERO, + p13: Vec3::ZERO, + p14: Vec3::new(10.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: Some("*D1".into()), + insertion_point: ins, + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + }; + d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap(); + d + }; + // Without the offset the block's far-away contents reach the extents. + assert!(moved(Vec3::ZERO).extents(&Space::Model).max.x > 800.0); + // With it, the block draws at the definition points and the extents stay at the drawing. + assert!(moved(Vec3::new(-850.0, -920.0, 0.0)).extents(&Space::Model).max.x < 20.0); +} + /// ZOOM Extents in AutoCAD 2024 (accoreconsole, EXTMIN/EXTMAX read back; AutoCAD pads them by a /// few hundredths): a layer turned off counts and a frozen one does not, for an entity, for an /// entity inside a block, and for a block reference itself. @@ -637,6 +675,7 @@ fn invisible_dimblock_entity_is_ignored_in_dimension_extents() { overrides: Default::default(), assoc: vec![], marks: Default::default(), + insertion_point: Vec3::ZERO, }), ) .unwrap(); diff --git a/crates/engine/src/cmd/annotate/common.rs b/crates/engine/src/cmd/annotate/common.rs index 398102797..6854b4fb4 100644 --- a/crates/engine/src/cmd/annotate/common.rs +++ b/crates/engine/src/cmd/annotate/common.rs @@ -22,6 +22,7 @@ pub(super) fn dim(s: &Session, kind: DimKind, defpt: Vec2, p13: Vec2, p14: Vec2, overrides: s.doc().map(|d| d.dim_overrides()).unwrap_or_default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }) } diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 85a222f64..4e615a4f2 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -32,6 +32,7 @@ fn dim(kind: DimKind, p13: Vec2, p14: Vec2, defpt: Vec2) -> EntityKind { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }) } @@ -182,6 +183,7 @@ pub fn bracket() -> Drawing { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }), ); add( @@ -203,6 +205,7 @@ pub fn bracket() -> Drawing { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }), ); diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 8047412fd..6721cdad8 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -117,11 +117,15 @@ fn in_text(d: &Drawing, e: &Entity, p: Vec2) -> bool { // A dimension with a block (as AutoCAD saves them) is drawn from that block: its text is // the text there, not the text the dimension's own geometry would place. EntityKind::Dimension(dm) => match dm.block.as_ref().and_then(|n| d.block(n)) { - Some(blk) => blk.entities.iter().any(|be| match &be.kind { - EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p), - EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p), - _ => false, - }), + // The block draws translated by the insertion point (group 12): test there (#2634). + Some(blk) => { + let p = p - dm.insertion_point.xy(); + blk.entities.iter().any(|be| match &be.kind { + EntityKind::MText(t) => in_box(cadcraft_render::layout_mtext_entity(d, t).strokes.into_iter().flatten(), t.rotation, p), + EntityKind::Text(_) => entity_bounds(d, be, 0).contains(p), + _ => false, + }) + } None => { let g = cadcraft_render::dimension_in(d, dm); in_box(g.text.iter().flatten().chain(g.text_glyphs.iter().flatten().flatten()).copied(), g.text_angle, p) diff --git a/crates/engine/tests/compare.rs b/crates/engine/tests/compare.rs index 0e4486ccb..a346fbba2 100644 --- a/crates/engine/tests/compare.rs +++ b/crates/engine/tests/compare.rs @@ -208,6 +208,7 @@ fn derived_dimension_fields_are_not_differences() { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; let mut s = Session::new(); s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Dimension(dim(30.0, 7.0))).unwrap(); diff --git a/crates/engine/tests/it/compare_export.rs b/crates/engine/tests/it/compare_export.rs index 1aee1b9db..740133c2b 100644 --- a/crates/engine/tests/it/compare_export.rs +++ b/crates/engine/tests/it/compare_export.rs @@ -314,6 +314,7 @@ fn a_named_block_whose_dimension_draws_another_block_shows_the_other_definition( overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; let blocks = |dim_end: f64, first: u64| { let mut part = Block::new("PART"); @@ -400,6 +401,7 @@ fn a_named_block_whose_dimension_block_has_another_generated_name_keeps_this_dra overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; let mut part = Block::new("PART"); part.entities.push(Entity::new(Handle(first), EntityKind::Dimension(dim))); @@ -514,6 +516,7 @@ fn a_dimension_block_copy_keeps_its_geometry_when_the_snapshot_is_saved() { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; let mut s = Session::new(); let mut drawn = Block::new("*D1"); @@ -833,6 +836,7 @@ fn a_dimension_whose_block_is_past_the_nesting_limit_is_drawn_again() { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; for k in 1..=MAX_BLOCK_DEPTH { let mut b = Block::new(&format!("B{k}")); diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 2011c3d63..6ca0f30d1 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -197,6 +197,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef text_rotation: t.fd(53, 0.0).to_radians(), user_text_pos: t.i(70).unwrap_or(0) & 128 != 0, block: t.s(2).filter(|s| !s.is_empty()), + insertion_point: t.p(12), overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 51b6b4388..ee9c18d33 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -399,6 +399,12 @@ fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper let style = d.dim_style(&dm.style).cloned().unwrap_or_default(); let g = cadcraft_render::dimension_geometry(dm, &style, d.header.f64("DIMSCALE", 1.0)); w.p(11, if dm.user_text_pos { dm.text_mid } else { g.text_pos.to3(0.0) }); + // Group 12: a block read from a file keeps the dimension's moved-by offset (AutoCAD + // draws the block translated by it); regenerated geometry already sits where the + // definition points place it, so it writes no offset. + if dm.block.is_some() && dm.insertion_point != Vec3::ZERO { + w.p(12, dm.insertion_point); + } let ty: i64 = match dm.kind { DimKind::Linear { .. } => 0, DimKind::Aligned => 1, diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 4aa427bdd..5d08817c5 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -98,6 +98,7 @@ fn sample() -> Drawing { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }), ) .unwrap(); @@ -558,6 +559,7 @@ fn dim(kind: DimKind, p13: Vec3, p14: Vec3) -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/io/tests/dimassoc_angular_radial.rs b/crates/io/tests/dimassoc_angular_radial.rs index f955ad7b5..1df635320 100644 --- a/crates/io/tests/dimassoc_angular_radial.rs +++ b/crates/io/tests/dimassoc_angular_radial.rs @@ -27,6 +27,7 @@ fn dim(kind: DimKind, defpt: Vec3, p13: Vec3, p14: Vec3, p15: Vec3, p16: Vec3, a overrides: Default::default(), assoc, marks: Default::default(), + insertion_point: Vec3::ZERO, }) } diff --git a/crates/io/tests/it/acad_interop.rs b/crates/io/tests/it/acad_interop.rs index 387f23334..bc9cc90e1 100644 --- a/crates/io/tests/it/acad_interop.rs +++ b/crates/io/tests/it/acad_interop.rs @@ -98,6 +98,7 @@ fn s25(kind: DimKind, p13: Vec3, p14: Vec3, defpt: Vec3) -> Drawing { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap(); d diff --git a/crates/io/tests/it/dim_block_resave_roundtrip.rs b/crates/io/tests/it/dim_block_resave_roundtrip.rs index f0705d6fd..195706157 100644 --- a/crates/io/tests/it/dim_block_resave_roundtrip.rs +++ b/crates/io/tests/it/dim_block_resave_roundtrip.rs @@ -27,6 +27,7 @@ fn linear(a: [f64; 2], b: [f64; 2], at: [f64; 2]) -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } @@ -158,6 +159,47 @@ fn reopened_dimension_reuses_its_block_name_and_handles() { assert_eq!(again.handseed, back.handseed); } +#[test] +fn a_moved_dimension_keeps_its_group_12_offset() { + let mut d = Drawing::new_metric(); + // What an older AutoCAD left: the block contents where the dimension was measured, the + // move kept in group 12 (insertion point), as #2634's drawing has it. + let mut b = Block::new("*D3"); + let h = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::Line(Line { a: Vec3::new(150.0, 80.0, 0.0), b: Vec3::new(160.0, 80.0, 0.0) }))); + d.blocks.insert("*D3".into(), Arc::new(b)); + let mut dm = linear([0.0, 0.0], [10.0, 0.0], [5.0, 3.0]); + dm.block = Some("*D3".into()); + dm.insertion_point = Vec3::new(-150.0, -80.0, 0.0); + let h = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap(); + + // The block is written as read and the offset round-trips as group 12. + let back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + let Some(EntityKind::Dimension(dm)) = back.entity(h).map(|e| &e.kind) else { panic!("dimension lost") }; + assert_eq!(dm.insertion_point, Vec3::new(-150.0, -80.0, 0.0)); + assert_eq!(dm.block.as_deref(), Some("*D3")); + let p = pairs(&cadcraft_io::write_dxf(&d)); + let at = p.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap(); + let own = &p[at..p[at + 1..].iter().position(|(c, _)| *c == 0).map(|k| at + 1 + k).unwrap()]; + assert!(own.iter().any(|(c, v)| *c == 12 && v.parse::() == Ok(-150.0)), "no group 12 x"); + assert!(own.iter().any(|(c, v)| *c == 22 && v.parse::() == Ok(-80.0)), "no group 12 y"); + + // Edited (edits drop the block link): geometry regenerated from the definition points, + // so the save writes no offset. + let mut edited = back.clone(); + edited + .modify_entity(h, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + dm.block = None; + } + }) + .unwrap(); + let q = pairs(&cadcraft_io::write_dxf(&edited)); + let at = q.iter().position(|(c, v)| *c == 0 && v == "DIMENSION").unwrap(); + let own = &q[at..q[at + 1..].iter().position(|(c, _)| *c == 0).map(|k| at + 1 + k).unwrap()]; + assert!(!own.iter().any(|(c, _)| *c == 12), "regenerated geometry keeps a stale offset"); +} + #[test] fn hostile_handle_seed_does_not_panic() { let mut d = Drawing::new_metric(); diff --git a/crates/io/tests/it/dim_block_text.rs b/crates/io/tests/it/dim_block_text.rs index 0c5fa0cab..244e9401c 100644 --- a/crates/io/tests/it/dim_block_text.rs +++ b/crates/io/tests/it/dim_block_text.rs @@ -34,6 +34,7 @@ fn height_written(style_scale: f64, overrides: serde_json::Value) -> f64 { overrides: overrides.as_object().cloned().unwrap_or_default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).unwrap(); block_mtext_height(&cadcraft_io::write_dxf(&d)) @@ -73,6 +74,7 @@ fn angular_drawing(separator_override: Option<&str>) -> Drawing { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; if let Some(separator) = separator_override { dm.overrides.insert("DIMDSEP".into(), serde_json::json!(separator)); diff --git a/crates/io/tests/it/dim_marks_roundtrip.rs b/crates/io/tests/it/dim_marks_roundtrip.rs index 40a85d89a..c442376de 100644 --- a/crates/io/tests/it/dim_marks_roundtrip.rs +++ b/crates/io/tests/it/dim_marks_roundtrip.rs @@ -24,6 +24,7 @@ fn dim(kind: DimKind, marks: DimMarks) -> EntityKind { overrides: Default::default(), assoc: Vec::new(), marks, + insertion_point: Vec3::ZERO, }) } diff --git a/crates/io/tests/it/dimstyle_vars_roundtrip.rs b/crates/io/tests/it/dimstyle_vars_roundtrip.rs index 061054bbc..b2beac3e2 100644 --- a/crates/io/tests/it/dimstyle_vars_roundtrip.rs +++ b/crates/io/tests/it/dimstyle_vars_roundtrip.rs @@ -60,6 +60,7 @@ fn dimension(overrides: serde_json::Value) -> EntityKind { overrides: overrides.as_object().cloned().unwrap_or_default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }) } diff --git a/crates/io/tests/it/dimtfill_roundtrip.rs b/crates/io/tests/it/dimtfill_roundtrip.rs index 5e1b4f1bf..48f7d9e32 100644 --- a/crates/io/tests/it/dimtfill_roundtrip.rs +++ b/crates/io/tests/it/dimtfill_roundtrip.rs @@ -174,6 +174,7 @@ fn linear() -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/io/tests/it/roundtrip/cases/complex.rs b/crates/io/tests/it/roundtrip/cases/complex.rs index ab13f4800..163effa49 100644 --- a/crates/io/tests/it/roundtrip/cases/complex.rs +++ b/crates/io/tests/it/roundtrip/cases/complex.rs @@ -118,6 +118,7 @@ pub(crate) fn dimensions() -> Vec { overrides: Default::default(), assoc: Vec::new(), marks: DimMarks::default(), + insertion_point: Vec3::ZERO, }), ); let mut block = Block::new("*D42"); diff --git a/crates/io/tests/it/roundtrip_audit.rs b/crates/io/tests/it/roundtrip_audit.rs index c2a326935..57f99dbe2 100644 --- a/crates/io/tests/it/roundtrip_audit.rs +++ b/crates/io/tests/it/roundtrip_audit.rs @@ -1034,6 +1034,7 @@ fn add_associated_dimension(d: &mut Drawing, a: cadcraft_doc::Handle, b: cadcraf overrides: Default::default(), assoc: vec![at("p13", a), at("p14", b)], marks: Default::default(), + insertion_point: Vec3::ZERO, }; d.add(&Space::Model, Common::default(), EntityKind::Dimension(dm)).expect("add dimension"); } diff --git a/crates/io/tests/it/text_carets_roundtrip.rs b/crates/io/tests/it/text_carets_roundtrip.rs index 1c30dd1a3..d327c6694 100644 --- a/crates/io/tests/it/text_carets_roundtrip.rs +++ b/crates/io/tests/it/text_carets_roundtrip.rs @@ -38,6 +38,7 @@ fn dimension(label: &str) -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/render/src/dim/tests.rs b/crates/render/src/dim/tests.rs index fe3b3c74e..15001c6b7 100644 --- a/crates/render/src/dim/tests.rs +++ b/crates/render/src/dim/tests.rs @@ -19,6 +19,7 @@ fn lin(p1: (f64, f64), p2: (f64, f64), on: (f64, f64), rot: f64) -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 39b0ddfcc..e73659675 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -313,7 +313,10 @@ fn draw_dimension(b: &mut Builder, ctx: &Ctx, e: &Entity, dm: &cadcraft_doc::Dim if let Some(blk) = dm.block.as_ref().and_then(|n| ctx.d.block(n)) && ctx.depth < cadcraft_doc::MAX_BLOCK_DEPTH { - let sub = Ctx { block_pstyle: b.named, block_transparency: b.transparency, ..sub_ctx(ctx, e, Mat3::IDENTITY) }; + // DXF group 12: a moved dimension keeps its `*D` block where it was and the offset in + // the insertion point, so the block draws translated by it (#2634). + let off = dm.insertion_point.xy(); + let sub = Ctx { block_pstyle: b.named, block_transparency: b.transparency, ..sub_ctx(ctx, e, Mat3::translate(off)) }; // DIMTFILL: the block's MTEXT carries no background mask here, so a background // around each of the block's texts is drawn before the block's first text or first // line of the text's marks, except for a text that a SOLID of the block covers. @@ -333,6 +336,10 @@ fn draw_dimension(b: &mut Builder, ctx: &Ctx, e: &Entity, dm: &cadcraft_doc::Dim .take(MAX_FILL_TEXTS) .filter(|be| !covered(be)) .filter_map(|be| block_text_box(ctx.d, be, gap)) + .map(|mut corners| { + corners.iter_mut().for_each(|c| *c += off); + corners + }) .collect() }; let mut fill_pending = !boxes.is_empty(); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index fe2dc6470..e4b314ff5 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -370,6 +370,7 @@ fn lin_dim() -> cadcraft_doc::Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/render/tests/it/dim_angular_centre.rs b/crates/render/tests/it/dim_angular_centre.rs index 9e9c42bdc..149638e0c 100644 --- a/crates/render/tests/it/dim_angular_centre.rs +++ b/crates/render/tests/it/dim_angular_centre.rs @@ -23,6 +23,7 @@ fn dim(kind: DimKind) -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/render/tests/it/dim_post_tolerance.rs b/crates/render/tests/it/dim_post_tolerance.rs index 907271a7c..83177d6ec 100644 --- a/crates/render/tests/it/dim_post_tolerance.rs +++ b/crates/render/tests/it/dim_post_tolerance.rs @@ -22,6 +22,7 @@ fn text(vars: serde_json::Value) -> (String, String) { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; let mut st = DimStyle::default(); let rejected = st.apply_fields(vars.as_object().unwrap()); diff --git a/crates/render/tests/it/dim_text_fill.rs b/crates/render/tests/it/dim_text_fill.rs index b90e1595d..46028a576 100644 --- a/crates/render/tests/it/dim_text_fill.rs +++ b/crates/render/tests/it/dim_text_fill.rs @@ -26,6 +26,7 @@ fn dimension() -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/render/tests/it/dim_text_format.rs b/crates/render/tests/it/dim_text_format.rs index e70deea08..779667e5b 100644 --- a/crates/render/tests/it/dim_text_format.rs +++ b/crates/render/tests/it/dim_text_format.rs @@ -23,6 +23,7 @@ fn linear(len: f64) -> Dimension { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, } } diff --git a/crates/render/tests/it/render_props.rs b/crates/render/tests/it/render_props.rs index f210dc4e1..a40b1988d 100644 --- a/crates/render/tests/it/render_props.rs +++ b/crates/render/tests/it/render_props.rs @@ -47,6 +47,7 @@ fn dimensions_take_the_viewport_layer_colour() { overrides: Default::default(), assoc: Vec::new(), marks: Default::default(), + insertion_point: Vec3::ZERO, }; d.add(&Space::Model, on("A"), EntityKind::Dimension(dim)).unwrap(); d.add(&Space::Model, on("A"), EntityKind::Line(Line { a: Vec3::new(0.0, -1.0, 0.0), b: Vec3::new(10.0, -1.0, 0.0) })).unwrap(); From e4cc7ffc77d691589d134c3a3ad8481833af127a Mon Sep 17 00:00:00 2001 From: Coast Date: Mon, 2 Nov 2026 16:01:31 -0600 Subject: [PATCH 426/900] DWG: scale actions keep the byte AutoCAD reads after their connections (acadrust 0.6.6) (#1725) * DWG: scale actions keep the byte AutoCAD reads after their connections (acadrust 0.6.5) AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with one byte after its three connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD read past the object and refused every DWG CADCraft wrote with a dynamic block that scales ("Error Decrypting Data"), even an unchanged one. acadrust 0.6.5 keeps the byte (dwg_tail_byte). 0.6.5 also maps the dimension flags byte's bit 0 to text_user_positioned both ways, so the bridge no longer inverts it (it would now double-invert); it still sets bit 1, which acadrust keeps no DXF source for. Co-Authored-By: Claude Opus 5.5 * DWG: acadrust 0.6.6; multi-layout DWGs get unique paper space names 0.6.6 keeps the scale action byte and the dimension flag mapping this branch relies on, and writes only the active layout as *Paper_Space (others get unique *Paper_SpaceN names; hakanaktt/acadrust#143), so ACadSharp opens a DWG CADCraft saves with more than one layout. Co-Authored-By: Claude Opus 5.5 * io tests: a scale action survives CADCraft's own DWG save The cadcraft-dwg test builds its DXF with acadrust's writer; this one goes through cadcraft_io::write (the bridge DXF, then acadrust) with a scale action added to the synthetic Door fixture, and checks the DWG holds it with its connections and reads back as the same action. Co-Authored-By: Claude Opus 5.5 * ui: block description field ids from Ui::scope_id (egui 0.37 deprecates Ui::id) main's gate fails clippy -D warnings on the one Ui::id() call (#2113); Ui::scope_id is its new name. Co-Authored-By: Claude Opus 5.5 * DWG: the scale action byte doc names acadrust 0.6.6, the version in use Co-Authored-By: Claude Sonnet 5.5 * Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/dwg/Cargo.toml | 2 +- crates/dwg/src/lib.rs | 49 ++++++++++++++++++++++++++++- crates/io/Cargo.toml | 2 +- crates/io/tests/it/dynblock_read.rs | 42 +++++++++++++++++++++++++ 4 files changed, 92 insertions(+), 3 deletions(-) diff --git a/crates/dwg/Cargo.toml b/crates/dwg/Cargo.toml index 0be9fdf40..acb8d0aa7 100644 --- a/crates/dwg/Cargo.toml +++ b/crates/dwg/Cargo.toml @@ -13,4 +13,4 @@ workspace = true # 0.6.7 and 0.6.8 fix that but read some damaged DWGs as empty with no note (tests.rs, #800). [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.5" +acadrust = "0.6.6" diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index ffde17ee8..a5de9bffe 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -435,7 +435,7 @@ mod native { /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as /// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, - /// acadrust 0.6.5 reads and writes itself. + /// acadrust 0.6.6 reads and writes itself. fn dimension_flags(doc: &mut acadrust::CadDocument) { for e in doc.entities_mut() { let acadrust::entities::EntityType::Dimension(d) = e else { continue }; @@ -1167,4 +1167,51 @@ 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"]); } + + /// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three + /// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD + /// read past the object and refused every DWG CADCraft wrote with a dynamic block that scales + /// ("Error Decrypting Data"); 0.6.5 added it and 0.6.6, which this uses, still keeps it (0.6.6 also + /// fixes multi-layout DWGs, #1463). The byte reaches the DWG, and a scale action + /// from DXF is written whole, with the byte AutoCAD writes (0). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn scale_actions_keep_the_byte_autocad_reads_after_their_connections() { + use acadrust::objects::*; + let scale_action = |doc: &acadrust::CadDocument| { + doc.objects.values().find_map(|o| match o { + ObjectType::DynamicBlock(DynamicBlockObject { data: DynamicBlockData::ScaleAction(s), .. }) => Some(s.clone()), + _ => None, + }) + }; + let mut doc = acadrust::CadDocument::new(); + let h = doc.allocate_handle(); + let conn = |code, name: &str| BlockConnection { code, name: name.into() }; + let mut action = DynamicBlockObject::new("BLOCKSCALEACTION", "AcDbBlockScaleAction"); + action.handle = h; + action.owner = doc.header.named_objects_dict_handle; + let mut a = BlockBasePointAction::default(); + a.action.action.element.name = "Scale".into(); + a.action.connections = vec![conn(2, "UpdatedBaseX"), conn(2, "UpdatedBaseY")]; + a.action.dependent = true; + a.connections = vec![conn(2, "Scale"), conn(2, "XScale"), conn(2, "YScale")]; + a.dwg_tail_byte = 7; + action.data = DynamicBlockData::ScaleAction(a.clone()); + doc.objects.insert(h, ObjectType::DynamicBlock(action)); + + let dwg = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + assert_eq!(scale_action(&back).map(|s| s.dwg_tail_byte), Some(7), "the byte isn't written"); + + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); + for version in ["AC1018", "AC1032"] { + let dwg = dxf_to_dwg_as(&dxf, version).unwrap(); + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let read = scale_action(&back).unwrap_or_else(|| panic!("{version}: the scale action wasn't written")); + assert_eq!(read.connections, a.connections, "{version}"); + assert_eq!(read.action.connections, a.action.connections, "{version}"); + assert_eq!(read.dwg_tail_byte, 0, "{version}"); + } + } } diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 2e8b3cc80..49464e06c 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -25,7 +25,7 @@ quick-xml = { workspace = true } [dev-dependencies] # Reads CADCraft's DWG output as written (tests only; the same version as cadcraft-dwg's). -acadrust = "0.6.5" +acadrust = "0.6.6" tiny-skia = { workspace = true } # Reads plotted PDFs back. craft-pdf = { workspace = true, features = ["read"] } diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index 251029410..189a2305b 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -86,6 +86,48 @@ fn a_saved_drawing_keeps_the_dynamic_block_as_read() { assert_eq!(by_node(dynamic_block(&back, "Door").unwrap()), by_node(before)); } +/// The Door fixture with a scale action on the Width parameter: graph node 6, object 68. +fn with_scale_action() -> String { + let node = "91 6\n93 32\n95 7\n360 68\n92 -1\n92 -1\n92 -1\n92 -1\n"; + let action = "0 BLOCKSCALEACTION\n5 68\n330 61\n100 AcDbEvalExpr\n90 7\n98 33\n99 232\n\ + 100 AcDbBlockElement\n300 Scale\n98 33\n99 232\n1071 0\n\ + 100 AcDbBlockAction\n70 0\n71 1\n330 30\n1010 0\n1020 0\n1030 0\n\ + 100 AcDbBlockActionWithBasePt\n92 2\n93 2\n301 UpdatedBaseX\n302 UpdatedBaseY\n\ + 1011 0\n1021 0\n1031 0\n280 1\n1012 0\n1022 0\n1032 0\n\ + 100 AcDbBlockScaleAction\n94 2\n95 2\n96 2\n303 Scale\n304 XScale\n305 YScale\n"; + fixture() + .replacen("96 6\n97 6\n", "96 7\n97 7\n", 1) + .replacen("0 BLOCKVISIBILITYPARAMETER\n", &format!("{node}0 BLOCKVISIBILITYPARAMETER\n"), 1) + .replacen("0 BLOCKLOOKUPPARAMETER\n", &format!("{action}0 BLOCKLOOKUPPARAMETER\n"), 1) +} + +/// A scale action goes through CADCraft's own DWG save (the bridge DXF, then acadrust) whole: +/// the DWG holds it with its connections, and it reads back as the same action. AutoCAD refused +/// such DWGs while acadrust left out the byte after its connections (cadcraft-dwg's +/// `scale_actions_keep_the_byte_autocad_reads_after_their_connections` covers the byte). +#[test] +fn a_scale_action_survives_a_dwg_save() { + use acadrust::objects::{DynamicBlockData, DynamicBlockObject, ObjectType}; + let d = read_dxf(dxf(&with_scale_action()).as_bytes()).unwrap(); + let before = dynamic_block(&d, "Door").unwrap(); + assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale)), "{:?}", before.actions); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); + let scale = doc.objects.values().find_map(|o| match o { + ObjectType::DynamicBlock(DynamicBlockObject { data: DynamicBlockData::ScaleAction(s), .. }) => Some(s.clone()), + _ => None, + }); + let scale = scale.expect("the DWG has no scale action"); + let names = |c: &[acadrust::objects::BlockConnection]| c.iter().map(|c| (c.code, c.name.clone())).collect::>(); + assert_eq!(names(&scale.connections), [(2, "Scale".to_string()), (2, "XScale".into()), (2, "YScale".into())]); + assert_eq!(names(&scale.action.connections), [(2, "UpdatedBaseX".to_string()), (2, "UpdatedBaseY".into())]); + assert_eq!(scale.dwg_tail_byte, 0); + + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(by_node(dynamic_block(&back, "Door").unwrap()), by_node(before)); +} + /// The model with each parameter and action object named by its graph id instead of its handle. fn by_node(mut m: DynamicBlock) -> DynamicBlock { let ids: std::collections::HashMap = m From 3bb515485d0699a7c25ac34db0d77e26309c13d8 Mon Sep 17 00:00:00 2001 From: Newton Kilgore Sightsinger Date: Mon, 2 Nov 2026 14:01:36 -0800 Subject: [PATCH 427/900] Xrefs: a saved path is found regardless of letter case on case-sensitive file systems (#1982) --- crates/engine/src/cmd/blocks/xref/load.rs | 39 ++++++++++++++++++++++- crates/engine/tests/xref.rs | 17 ++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index fac289f23..b47aa00e0 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -208,7 +208,7 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result = { let _ = files; @@ -217,6 +217,43 @@ pub(crate) fn find(path: &str, host: Option<&Path>, chosen: bool) -> Result Option { + use std::path::Component; + let mut out = PathBuf::new(); + for c in p.components() { + let Component::Normal(name) = c else { + out.push(c.as_os_str()); + continue; + }; + let exact = out.join(name); + if exact.exists() { + out = exact; + continue; + } + let want = name.to_str()?.to_lowercase(); + let mut hits = std::fs::read_dir(if out.as_os_str().is_empty() { Path::new(".") } else { &out }) + .ok()? + .take(MAX_CASE_SCAN) + .flatten() + .filter(|e| e.file_name().to_str().is_some_and(|n| n.to_lowercase() == want)); + let hit = hits.next()?; + if hits.next().is_some() { + return None; + } + out.push(hit.file_name()); + } + out.is_file().then_some(out) +} + /// Read a drawing file through the host's io hooks, counting its bytes against the load's total. fn read(file: &Path, cx: &mut Ctx) -> Result { let hooks = super::super::super::file::io().ok_or("file formats are not available in this build")?; diff --git a/crates/engine/tests/xref.rs b/crates/engine/tests/xref.rs index c67c627b2..27fa505c4 100644 --- a/crates/engine/tests/xref.rs +++ b/crates/engine/tests/xref.rs @@ -506,3 +506,20 @@ fn saved_xref_paths_are_followed_beside_the_host_or_on_this_computer_only() { s.execute("-xref", &json!({ "option": "path", "names": "unc", "path": far.to_str().unwrap() })).unwrap(); assert_eq!(status(&s, "unc"), Some(XrefStatus::Loaded)); } + +/// A reference saved on Windows with different letter case (`..\XR\PLAN.DWG` for +/// `../xr/plan.dxf`) is still found on case-sensitive file systems. +#[test] +fn saved_xref_paths_ignore_letter_case() { + hooks(); + let base = folder("case"); + std::fs::create_dir_all(base.join("host")).unwrap(); + std::fs::create_dir_all(base.join("Xr")).unwrap(); + save(&site(), &base.join("Xr").join("Plan.dxf")); + let host = base.join("host").join("host.dxf"); + save(&host_with_paths(&[("plan", r"..\XR\PLAN.DXF")]), &host); + let mut s = Session::new(); + open(&mut s, &host); + assert_eq!(status(&s, "plan"), Some(XrefStatus::Loaded), "{:?}", s.log); + assert!(objects(&s, "plan") > 0); +} From 4e874d089a10562a454b38d8d3ee9c34dfa1662c Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:01:41 +0100 Subject: [PATCH 428/900] Persist current table style (CTABLESTYLE) in DXF header (#2117) Found while testing crates/io/src/dxf_write.rs:1964-1970 (xrecords written) and crates/io/src/dxf_read.rs:2049-2052 (apply) Co-authored-by: Claude Haiku 5.5 --- crates/io/src/dxf_write/header.rs | 1 + crates/io/tests/it/tables_objects_roundtrip.rs | 13 ++++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 354c293c8..9b8c1f800 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -19,6 +19,7 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("CMLJUST", 70), ("CMLSCALE", 40), ("TEXTSTYLE", 7), + ("CTABLESTYLE", 7), ("CLAYER", 8), ("CELTYPE", 6), ("CECOLOR", 62), diff --git a/crates/io/tests/it/tables_objects_roundtrip.rs b/crates/io/tests/it/tables_objects_roundtrip.rs index 0f75e4cd3..ec2fe7726 100644 --- a/crates/io/tests/it/tables_objects_roundtrip.rs +++ b/crates/io/tests/it/tables_objects_roundtrip.rs @@ -2,7 +2,9 @@ //! multileader styles, layout page setups, named views, UCSs and groups. use cadcraft_doc::geom::{Vec2, Vec3}; -use cadcraft_doc::{Common, DashElement, Drawing, EntityKind, Group, Line, Linetype, MLeaderStyle, NamedView, Space, TextStyle, Ucs, library}; +use cadcraft_doc::{ + Common, DashElement, Drawing, EntityKind, Group, Line, Linetype, MLeaderStyle, NamedView, Space, TableStyle, TextStyle, Ucs, library, +}; use cadcraft_io::{read_dxf, write_dxf}; fn round_trip(d: &Drawing) -> Drawing { @@ -82,6 +84,15 @@ fn multileader_styles_and_current_style_round_trip() { assert_eq!(r.header.str("CMLEADERSTYLE", ""), "Callout"); } +#[test] +fn current_table_style_round_trips() { + let mut d = Drawing::new_imperial(); + d.table_styles.push(TableStyle { name: "TS".into(), ..TableStyle::default() }); + d.header.set_str("CTABLESTYLE", "TS"); + let r = round_trip(&d); + assert_eq!(r.header.str("CTABLESTYLE", ""), "TS"); +} + #[test] fn layout_page_setup_and_paper_view_round_trip() { let mut d = Drawing::new_imperial(); From 3f57f8d3d49ca22e83bae85e4d1a8b445e385bc2 Mon Sep 17 00:00:00 2001 From: midasmatterhorn <248507632+midasmatterhorn@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:01:46 +0300 Subject: [PATCH 429/900] render: a display list past the block-expansion budget says what it left out (#1278) * render: a display list past the block-expansion budget says what it left out * Report viewport truncation only after the expansion budget is exceeded * fmt: keep ui-egui control.rs rustfmt-clean --- crates/io/tests/it/block_expansion.rs | 65 ++++++++++++++++++++++++++- crates/mcp/src/backend.rs | 2 +- crates/render/src/display.rs | 4 ++ crates/render/src/lib.rs | 6 ++- crates/render/src/viewports.rs | 1 + crates/ui-egui/src/control.rs | 20 +++++---- 6 files changed, 87 insertions(+), 11 deletions(-) diff --git a/crates/io/tests/it/block_expansion.rs b/crates/io/tests/it/block_expansion.rs index b190156f8..64fca189e 100644 --- a/crates/io/tests/it/block_expansion.rs +++ b/crates/io/tests/it/block_expansion.rs @@ -1,7 +1,10 @@ //! Nested, self-referencing and arrayed block references in a hostile DXF must not hang drawing //! or extents (issue #255): the expansion is bounded, not only its depth. -use cadcraft_doc::{Drawing, EntityKind, Space}; +use std::sync::Arc; + +use cadcraft_doc::{Block, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport}; +use cadcraft_geom::{Vec2, Vec3}; use cadcraft_render::{MAX_BLOCK_EXPANSION, Options, build}; fn read(text: &str) -> Drawing { @@ -63,3 +66,63 @@ fn ordinary_nested_and_arrayed_blocks_are_drawn_whole() { assert!(matches!(d.model.iter().next().map(|e| &e.kind), Some(EntityKind::Insert(_)))); assert_eq!(build(&d, &Space::Model, &Options::default()).prims.len(), cadcraft_doc::MAX_BLOCK_DEPTH); } + +#[test] +fn a_build_that_spends_the_expansion_budget_says_so() { + // 10,000 x 10,000 copies of a one-line block: far past the budget. The list stops at the + // budget and says so, so a screen, plot or export missing contents is not silent (#1070). + let d = read(&minsert(10_000, 10_000)); + let list = build(&d, &Space::Model, &Options::default()); + assert!(list.truncated, "block contents were left out without a word"); + assert!(list.prims.len() <= MAX_BLOCK_EXPANSION, "{}", list.prims.len()); + // A drawing within the budget is whole and says nothing. + let d = read(&minsert(3, 2)); + let list = build(&d, &Space::Model, &Options::default()); + assert!(!list.truncated); + assert_eq!(list.prims.len(), 6); +} + +#[test] +fn an_empty_followup_viewport_does_not_mark_an_exact_budget_truncated() { + let mut d = Drawing::new_imperial(); + d.ensure_layer("FROZEN"); + let mut block = Block::new("A"); + block.entities.push(Entity { + handle: Handle(0x200), + common: Common { layer: "FROZEN".into(), ..Common::default() }, + kind: EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) }), + }); + d.blocks.insert(block.name.clone(), Arc::new(block)); + let insert = Insert { + block: "A".into(), + insert: Vec3::ZERO, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1_000, + rows: 1_000, + col_spacing: 0.0, + row_spacing: 0.0, + }; + d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap(); + let viewport = |center: Vec3, view_center: Vec2, frozen_layers| Viewport { + center, + width: 100.0, + height: 100.0, + view_center, + view_height: 100.0, + id: 2, + locked: false, + frozen_layers, + layer_colors: Vec::new(), + clip: None, + on: true, + }; + let paper = Space::Paper("Layout1".into()); + d.add(&paper, Common::default(), EntityKind::Viewport(viewport(Vec3::new(50.0, 50.0, 0.0), Vec2::ZERO, vec!["FROZEN".into()]))).unwrap(); + d.add(&paper, Common::default(), EntityKind::Viewport(viewport(Vec3::new(200.0, 50.0, 0.0), Vec2::new(10_000.0, 10_000.0), Vec::new()))).unwrap(); + + let list = build(&d, &paper, &Options::default()); + assert_eq!(list.expanded, MAX_BLOCK_EXPANSION); + assert!(!list.truncated, "the first viewport consumed the budget exactly and the second saw no model content"); +} diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 20a86fce7..1a36144ca 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -418,7 +418,7 @@ impl Backend for Headless { if let Some(path) = str_p("path") { std::fs::write(&path, &png).map_err(|e| format!("{path}: {e}"))?; } - Ok(json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h})) + Ok(json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "truncated": list.truncated})) } "app.open" => { let path = str_p("path").ok_or("missing path")?; diff --git a/crates/render/src/display.rs b/crates/render/src/display.rs index e6ba6b7e9..9731ecbf7 100644 --- a/crates/render/src/display.rs +++ b/crates/render/src/display.rs @@ -59,6 +59,10 @@ pub struct DisplayList { pub sheet: Option, /// Block contents expanded while building (see [`MAX_BLOCK_EXPANSION`]). pub expanded: usize, + /// The expansion budget was spent: block contents past it are not in the list. The screen, + /// plots and exports draw what is here; the CLI and the control channel report this, so an + /// output that leaves contents out is never silent (#1070). + pub truncated: bool, /// Plot style end, join and fill style per primitive (parallel to `prims`; missing entries /// are "use object"), turned into geometry by [`pen::apply`]. pub pens: Vec, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6fa236e4c..e93c9fbff 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -291,10 +291,14 @@ impl Builder<'_> { /// 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); - match self.shared_budget { + let ok = match self.shared_budget { Some(spent) => spent.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < MAX_BLOCK_EXPANSION, None => self.list.expanded <= MAX_BLOCK_EXPANSION, + }; + if !ok { + self.list.truncated = true; } + ok } } diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 6f1e57517..67c31c694 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -174,6 +174,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou // The contents are in paper units now: draw their pens before clipping. pen::apply(&mut sub.list, unit_mm); b.list.expanded = b.list.expanded.saturating_add(sub.list.expanded); + b.list.truncated |= sub.list.truncated; append_clipped(&mut b.list, &sub.list, clip); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 8d0a39bf4..4abc6b1f4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -269,7 +269,7 @@ pub fn inspect(app: &CadApp, ctx: &egui::Context) -> Value { "snap": app.canvas.snap.map(|s| json!({"point": [s.point.x, s.point.y], "mode": s.name})), "session": app.session.summary(), "closePrompt": app.close_prompt(), - "perf": {"frameMs": app.frame_ms, "buildMs": app.canvas.build_ms, "drawMs": app.canvas.draw_ms, "meshMs": app.canvas.mesh_ms, "building": app.canvas.building(), "renderer": if app.canvas.gpu.is_some() { "gpu" } else { "cpu" }, "prims": app.canvas.list.as_ref().map(|l| l.prims.len()), "uiFrames": app.ui_frames, "passIndex": ctx.current_pass_index()}, + "perf": {"frameMs": app.frame_ms, "buildMs": app.canvas.build_ms, "drawMs": app.canvas.draw_ms, "meshMs": app.canvas.mesh_ms, "building": app.canvas.building(), "renderer": if app.canvas.gpu.is_some() { "gpu" } else { "cpu" }, "prims": app.canvas.list.as_ref().map(|l| l.prims.len()), "truncated": app.canvas.list.as_ref().map(|l| l.truncated), "uiFrames": app.ui_frames, "passIndex": ctx.current_pass_index()}, }) } @@ -492,9 +492,9 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou if let Err(e) = std::fs::write(path, &png) { return err(e); } - return ok(render_reply(&png, w, h, Some(path))); + return ok(render_reply(&png, w, h, Some(path), list.truncated)); } - ok(render_reply(&png, w, h, None)) + ok(render_reply(&png, w, h, None, list.truncated)) } "app.open" => { let Some(path) = s("path") else { return err("missing path") }; @@ -537,9 +537,11 @@ fn render_view(bounds: &cadcraft_geom::Bounds2, center: Vec2, height: f64, fit: } } -/// The `ui.render` reply, matching the headless backend (`pngBase64`, `width`, `height`), plus `bytes` and `path`. -fn render_reply(png: &[u8], w: u32, h: u32, path: Option<&str>) -> Value { - let mut v = json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(png), "width": w, "height": h, "bytes": png.len()}); +/// The `ui.render` reply, matching the headless backend (`pngBase64`, `width`, `height`), plus +/// `bytes`, `path` and `truncated` (the build left block contents out, see #1070). +fn render_reply(png: &[u8], w: u32, h: u32, path: Option<&str>, truncated: bool) -> Value { + let mut v = + json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(png), "width": w, "height": h, "bytes": png.len(), "truncated": truncated}); if let (Some(path), Some(o)) = (path, v.as_object_mut()) { o.insert("path".to_string(), json!(path)); } @@ -816,12 +818,14 @@ mod tests { #[test] fn render_reply_has_base64_width_height_and_keeps_old_keys() { - let r = render_reply(b"abc", 7, 5, Some("x.png")); + let r = render_reply(b"abc", 7, 5, Some("x.png"), false); assert_eq!(r["pngBase64"], "YWJj"); assert_eq!(r["width"], 7); assert_eq!(r["height"], 5); assert_eq!(r["bytes"], 3); assert_eq!(r["path"], "x.png"); - assert!(render_reply(b"abc", 7, 5, None).get("path").is_none()); + assert_eq!(r["truncated"], false); + assert!(render_reply(b"abc", 7, 5, None, true).get("path").is_none()); + assert_eq!(render_reply(b"abc", 7, 5, None, true)["truncated"], true); } } From 5ec0d215d826108c2bb3132e3edb71220f28fa84 Mon Sep 17 00:00:00 2001 From: STE1200 <319441566+STE1200@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:01:51 +0100 Subject: [PATCH 430/900] CLI: info and convert report what a damaged DWG left out (read notes, #859) (#2337) A damaged DWG opens partially since #859 and the drawing's read notes say how many object records were left out. OPEN echoes them and MCP `open` returns them as `warnings`, but `cadcraft-cli info` and `convert` stayed silent: a corpus round trip wrote thousands of skipped records away without a word. - convert: each read note goes to stderr as `IN: `, next to the skipped-records warning (#872). The exit code stays 0. - drawing.inspect (and so info, MCP inspect_drawing and the control channel): new field `readNotes`, next to `skipped`. Existing fields are unchanged. - run already prints OPEN's notes with the session log. - README and docs/control-protocol.md say where the notes appear. Part of #1039. Co-authored-by: Claude Opus 5.5 --- README.md | 5 ++ apps/cadcraft-cli/src/convert.rs | 5 +- apps/cadcraft-cli/src/output.rs | 23 +++++++++ apps/cadcraft-cli/tests/read_notes.rs | 69 +++++++++++++++++++++++++++ crates/engine/src/cmd/inquiry.rs | 2 + docs/control-protocol.md | 2 +- 6 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 apps/cadcraft-cli/tests/read_notes.rs diff --git a/README.md b/README.md index a24b33980..611110c3c 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,11 @@ How image exports (PNG 2400×1600, SVG, PDF) are framed: `convert` fits the mode rectangle, centred and scaled without distortion; `--view extents` or `--view current` forces either framing. To frame a selection set, `zoom {"mode":"object"}` after selecting. +When reading a file leaves something out (records a DXF reader can't place, object records of a +damaged DWG), `info` reports it (`skipped`, `readNotes`), `convert` warns on stderr and `run` +prints the DWG notes with its log; the exit code stays 0. MCP `open` replies with the notes as +`warnings`. + MCP tools include `command_line` (type at the prompt), `execute` (any command with JSON), `inspect_drawing`, `query_entities`, `render` (returns a PNG) and, when connected to the app, `screenshot` and `ui_click`. The desktop app's JSON control channel is documented in diff --git a/apps/cadcraft-cli/src/convert.rs b/apps/cadcraft-cli/src/convert.rs index 6a9c4edbf..35ffc6aed 100644 --- a/apps/cadcraft-cli/src/convert.rs +++ b/apps/cadcraft-cli/src/convert.rs @@ -1,6 +1,6 @@ use super::args::ConvertArgs; use super::error::Result; -use super::output::{Streams, export_framed, export_window, skipped_message, undrawn_message}; +use super::output::{Streams, export_framed, export_window, read_note_messages, skipped_message, undrawn_message}; use super::{open, unicode}; use cadcraft_engine::Session; @@ -9,7 +9,8 @@ pub(crate) fn convert(a: &ConvertArgs, io: &mut Streams) -> Result { let framing = a.framing.framing(); let mut s = Session::empty(); open(&mut s, &a.input)?; - if let Some(m) = skipped_message(s.doc()?, i) { + let d = s.doc()?; + for m in read_note_messages(d, i).into_iter().chain(skipped_message(d, i)) { io.errln(format_args!("{m}")); } if cadcraft_io::is_image(&a.output) diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index d783267dc..5716c486c 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -165,6 +165,12 @@ pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Some(format!("{path}: {n} {entities} not drawn ({})", list.join(", "))) } +/// The reader's notes on what it left out of `path` (a damaged DWG's unreadable object records, +/// #859), one warning line each; empty for a complete read. +pub(crate) fn read_note_messages(d: &cadcraft_engine::doc::Drawing, path: &str) -> Vec { + d.read_notes.iter().map(|note| format!("{path}: {note}")).collect() +} + /// The warning for the records of `path` the reader could not place, or `None` when there are none. pub(crate) fn skipped_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option { let n = d.skipped_records.values().fold(0usize, |a, n| a.saturating_add(*n)); @@ -175,3 +181,20 @@ pub(crate) fn skipped_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> let records = if n == 1 { "record" } else { "records" }; Some(format!("{path}: {n} {records} could not be read and are left out ({})", list.join(", "))) } + +#[cfg(test)] +mod tests { + use super::read_note_messages; + + #[test] + fn read_notes_become_one_warning_each() { + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + assert!(read_note_messages(&d, "a.dwg").is_empty()); + d.read_notes = + vec!["DWG: 3 of 10 object records couldn't be read and were left out (LINE × 3); saving over the original file would lose them".into()]; + assert_eq!( + read_note_messages(&d, "a.dwg"), + vec!["a.dwg: DWG: 3 of 10 object records couldn't be read and were left out (LINE × 3); saving over the original file would lose them"] + ); + } +} diff --git a/apps/cadcraft-cli/tests/read_notes.rs b/apps/cadcraft-cli/tests/read_notes.rs new file mode 100644 index 000000000..2f443f03a --- /dev/null +++ b/apps/cadcraft-cli/tests/read_notes.rs @@ -0,0 +1,69 @@ +//! A damaged DWG opens partially (#859); `info` lists the reader's notes on what it left out +//! (`readNotes`) and `convert` warns with them before writing the copy, so a script or agent sees +//! the loss. The exit code stays 0. + +use std::process::{Command, Output}; + +fn cli(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap() +} + +/// A DWG of 200 lines, and a copy damaged so that the reader skips some of its records (found the +/// way the reader's own test finds one: flipping a few bytes at a time across the objects area). +fn dwg_and_damaged_copy() -> (Vec, Vec) { + let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n"); + for i in 0..200 { + dxf += &format!("0\nLINE\n8\n0\n10\n{i}\n20\n0\n11\n{i}\n21\n10\n"); + } + dxf += "0\nENDSEC\n0\nEOF\n"; + let d = cadcraft_io::read(dxf.as_bytes(), "lines.dxf").unwrap(); + let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2000), binary: false }; + let dwg = cadcraft_io::write_with(&d, "lines.dwg", &opts).unwrap(); + let damaged = (dwg.len() / 4..dwg.len() * 3 / 5) + .step_by(97) + .map(|at| { + let mut b = dwg.clone(); + b[at..at + 6].iter_mut().for_each(|x| *x ^= 0xA5); + b + }) + .find(|b| cadcraft_io::read(b, "damaged.dwg").is_ok_and(|d| !d.read_notes.is_empty())) + .expect("no damaged copy read partially"); + (dwg, damaged) +} + +#[test] +fn info_lists_and_convert_warns_about_read_notes() { + let dir = std::env::temp_dir().join(format!("cc-cli-read-notes-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (whole, damaged) = dwg_and_damaged_copy(); + let path = dir.join("damaged.dwg"); + std::fs::write(&path, &damaged).unwrap(); + let path = path.to_str().unwrap(); + + let out = cli(&["info", path]); + assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr)); + let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + let notes = v["readNotes"].as_array().unwrap(); + assert_eq!(notes.len(), 1, "{v}"); + assert!(notes[0].as_str().unwrap().contains(" couldn't be read and "), "{v}"); + + let copy = dir.join("copy.dxf"); + let out = cli(&["convert", path, copy.to_str().unwrap()]); + assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr)); + let err = String::from_utf8_lossy(&out.stderr); + let warnings: Vec<&str> = err.lines().filter(|l| l.contains(" couldn't be read and ")).collect(); + assert_eq!(warnings.len(), 1, "{err}"); + assert!(warnings[0].starts_with(&format!("{path}: DWG: ")), "{err}"); + assert!(copy.exists()); + + // A complete read: no notes, and no warning. + let intact = dir.join("whole.dwg"); + std::fs::write(&intact, &whole).unwrap(); + let out = cli(&["info", intact.to_str().unwrap()]); + let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(v["readNotes"], serde_json::json!([])); + let out = cli(&["convert", intact.to_str().unwrap(), copy.to_str().unwrap()]); + assert!(out.status.success()); + assert!(!String::from_utf8_lossy(&out.stderr).contains("couldn't be read"), "{}", String::from_utf8_lossy(&out.stderr)); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index 364fa6796..283551dfd 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -596,6 +596,8 @@ fn run_inspect(s: &mut Session, p: &Value) -> Result { "view": { "center": [st.view().center.x, st.view().center.y], "height": st.view().height }, // Records of the file the drawing came from that the reader could not place. "skipped": { "count": d.skipped_records.values().fold(0usize, |a, n| a.saturating_add(*n)), "sections": d.skipped_records }, + // What reading the file left out, in words (a damaged DWG's unreadable object records). + "readNotes": d.read_notes, }); if bool_or(p, "entities", true) && let (Some(o), Some(store)) = (out.as_object_mut(), d.space(&space)) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 98db28330..d10d43abb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -49,7 +49,7 @@ field. `engine.commands` returns a separate command catalog, not a list of addit | `cmdline.state` | | Current prompt, keywords, accepted input kinds, history tail. | | `engine.execute` | `{command, params}` | Run any command with JSON parameters. Never opens a dialog. `command` is an alias of this method, with the same parameters and result. | | `engine.commands` | | Every command: id, label, menu path, shortcut, aliases, params doc, enabled. | -| `drawing.inspect` | `{entities?, limit?}` | Drawing summary (counts, extents, layers, styles, blocks, layouts, selection, undo) and entities with handles and geometry. | +| `drawing.inspect` | `{entities?, limit?}` | Drawing summary (counts, extents, layers, styles, blocks, layouts, selection, undo, and what reading the file left out: `skipped` records by section, `readNotes` in words) and entities with handles and geometry. | | `ui.inspect` | | UI state, canvas rect, view, cursor and snap, performance counters (`uiFrames`, `passIndex` included); `closePrompt`: the drawing a "Save changes?" prompt is asking about (null when none); and actual egui keyboard focus (`focus.id`, `focus.label`, `focus.role`). | | `ui.elements` | `{label?, role?, focused?}` | Observed toolbar, tab, drafting and layer-palette controls from the latest UI frame. Filters match exactly. Each entry has its real egui `id`, label, role, rectangle `[x,y,width,height]`, enabled/visible/selected state and current focus. | | `ui.menu.list` / `ui.menu.invoke` | `{command}` | The menu tree; invoke an item like a click (interactive). | From 2ac500925b6b53b6a3f00dc30e4428caf565ebbe Mon Sep 17 00:00:00 2001 From: Books Date: Tue, 3 Nov 2026 09:01:57 +1100 Subject: [PATCH 431/900] DWG: a table cell's text height is an override only when the file flags it (part of #2501) (#2588) * DWG: a table cell's text height is an override only when the file flags it (#2501) acadrust's DXF writer writes group 140 for any cell with a style record, even a default 0.18 with no override flag, and CADCraft read it as a per-cell height, so cells ignored the table style's height. The bridge now clears the height of a cell style that has neither the TEXT_HEIGHT property flag nor the content's height override bit (0 reads as no override). * Parity checklist: regenerated after merging main * Tests: inherited table cell heights must stay unset (review on #2588) A cell that inherits its height must read back as None, not an explicit 0.0625 override. * Parity checklist: regenerated after merging main * Test: a cell style with the TEXT_HEIGHT flag, content override bit 128 and a cell with no style record keep the right height (review on #2588) * DWG: a table cell's content height override (group 144) is kept (review on #2588) * Parity checklist: regenerated after merging main * DWG: table cell height takes the first content's override and the style's override flags (review on #2588) Only the first content's bit-128 height stands for the cell (one height for its text); an invalid content height no longer keeps the writer's default 0.18; a height marked only in the style's override flags (newer files) is kept. --- crates/dwg/src/lib.rs | 67 +++++++++ crates/io/tests/dwg_table_cell_height.rs | 173 +++++++++++++++++++++++ docs/parity-checklist.md | 4 +- 3 files changed, 242 insertions(+), 2 deletions(-) create mode 100644 crates/io/tests/dwg_table_cell_height.rs diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index a5de9bffe..e5463aaec 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -332,12 +332,51 @@ mod native { /// can cover rows × cols cells, so the total is bounded too. const MAX_MERGE_CELLS: usize = 1 << 24; + /// A table cell's own text height only when the file says it overrides the table style's. + /// acadrust's DXF writer writes a cell style's height (group 140) whenever the cell has a + /// style record, even a default 0.18 with no override flag, and CADCraft reads a 140 as an + /// override (#2501). The override is the cell style's TEXT_HEIGHT property flag or the + /// content's format override bit 128; without either the height is cleared (0 is no + /// override), so the table style's height applies. + fn table_cell_heights(doc: &mut acadrust::CadDocument) { + use acadrust::entities::table::CellStylePropertyFlags; + const CONTENT_TEXT_HEIGHT: i32 = 128; + for e in doc.entities_mut() { + let acadrust::entities::EntityType::Table(t) = e else { continue }; + for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { + // The first content's own height (group 144) when its format override sets bit 128. + // CADCraft keeps one height for the cell's text, so a later content's override + // must not stand in for the first content's. + let content_height = cell + .contents + .first() + .filter(|c| c.format_override_flags & CONTENT_TEXT_HEIGHT != 0) + .map(|c| c.text_height) + .filter(|h| h.is_finite() && *h > 0.0); + if let Some(h) = content_height { + // CADCraft reads only the style's height (group 140), so carry it there. + cell.style.get_or_insert_with(acadrust::entities::table::CellStyle::new).text_height = h; + continue; + } + // A style overrides through its property flags or, in newer files, its override + // flags; anything else is the writer's default and is cleared. + if let Some(style) = cell.style.as_mut() + && !style.property_flags.contains(CellStylePropertyFlags::TEXT_HEIGHT) + && style.override_flags & CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32 == 0 + { + style.text_height = 0.0; + } + } + } + } + /// The fix-ups made to a document after the DWG read, returning how many orphaned DGN /// components were dropped. The document comes from a third-party reader and is hostile. fn post_process(doc: &mut acadrust::CadDocument) -> usize { super::fail_in_test("post_process"); current_style_names(doc); table_merges(doc); + table_cell_heights(doc); table_style_rows(doc, false); keep_sort_handles(doc); drop_orphaned_dgn_components(doc) @@ -821,6 +860,34 @@ mod native { assert_eq!(table_merges_within(&mut doc, usize::MAX), 100); } + /// A height marked only in the style's override flags (as newer files store it) is kept, + /// and the same height with no flag at all is cleared (review on #2588). Tested on the + /// read document because acadrust's DWG writer doesn't write the override flags. + #[test] + fn a_style_override_flag_keeps_the_cell_height() { + use acadrust::entities::table::{CellStyle, CellStylePropertyFlags}; + let height = |override_flags: i32| { + let mut doc = doc_with_table(1, 1, 0); + for e in doc.entities_mut() { + if let EntityType::Table(t) = e { + for cell in t.rows.iter_mut().flat_map(|r| r.cells.iter_mut()) { + let mut s = CellStyle::new(); + s.text_height = 0.5; + s.override_flags = override_flags; + cell.style = Some(s); + } + } + } + table_cell_heights(&mut doc); + doc.entities().find_map(|e| match e { + EntityType::Table(t) => t.rows.first()?.cells.first()?.style.as_ref().map(|s| s.text_height), + _ => None, + }) + }; + assert_eq!(height(CellStylePropertyFlags::TEXT_HEIGHT.bits() as i32), Some(0.5)); + assert_eq!(height(0), Some(0.0)); + } + /// A panic in the post-read fix-ups is an error, not a crash (#1934). #[test] fn a_panic_in_post_processing_is_an_error() { diff --git a/crates/io/tests/dwg_table_cell_height.rs b/crates/io/tests/dwg_table_cell_height.rs new file mode 100644 index 000000000..11ee98c9d --- /dev/null +++ b/crates/io/tests/dwg_table_cell_height.rs @@ -0,0 +1,173 @@ +//! TABLE heights inherit from the table style unless the file records a cell override. +#![cfg(not(target_arch = "wasm32"))] + +use cadcraft_doc::{Common, Drawing, EntityKind, Space, Table, TableCell, TableStyle}; + +fn drawing() -> Drawing { + let mut d = Drawing::new_imperial(); + d.table_styles.push(TableStyle { name: "Small".into(), text_height: 0.0625, title: false, header: false, ..TableStyle::default() }); + let table = Table { + style: "Small".into(), + text_height: 0.0625, + title: false, + header: false, + row_heights: vec![0.2], + col_widths: vec![2.0; 3], + cells: vec![vec![ + TableCell { text: "plain".into(), ..TableCell::default() }, + TableCell { text: "{\\C256;formatted}".into(), ..TableCell::default() }, + TableCell { text: "explicit".into(), text_height: Some(0.125), ..TableCell::default() }, + ]], + ..Table::default() + }; + d.add(&Space::Model, Common::default(), EntityKind::Table(table)).unwrap(); + d +} + +fn check(d: &Drawing) { + let t = d + .model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(t.style, "Small"); + assert_eq!(t.text_height, 0.0625); + for cell in &t.cells[0][..2] { + assert!(cell.text_height.is_none(), "unexpected override: {:?}", cell.text_height); + } + assert_eq!(t.cells[0][2].text_height, Some(0.125)); +} + +#[test] +fn table_cell_heights_keep_inheritance_through_dwg() { + let bytes = cadcraft_io::write(&drawing(), "height.dwg").unwrap(); + // A style record can be present for metadata without overriding its text height. + // Write that synthetic representation directly so no earlier DXF conversion can + // turn the unused default into an explicit override before this import. + let mut doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(bytes)).read().unwrap(); + let table = doc + .entities_mut() + .find_map(|e| match e { + acadrust::entities::EntityType::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + table.rows[0].cells[0].style = Some(acadrust::entities::table::CellStyle::new()); + let bytes = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); + check(&cadcraft_io::read(&bytes, "height.dwg").unwrap()); +} + +#[test] +fn table_cell_heights_keep_inheritance_through_dxf() { + let bytes = cadcraft_io::write(&drawing(), "height.dxf").unwrap(); + check(&cadcraft_io::read(&bytes, "height.dxf").unwrap()); +} + +// ---- cells with their own style record (review on #2588) ---- + +use acadrust::entities::table::{CellContent, CellStyle, CellStylePropertyFlags}; + +/// Write the drawing as a DWG, edit its first cell through acadrust (`edit`), write it again as a +/// DWG (or, with `as_dxf`, as a DXF by acadrust's writer) and read it with CADCraft. Returns the first cell's +/// text height override. +fn first_cell_height(as_dxf: bool, edit: impl FnOnce(&mut acadrust::entities::table::TableCell)) -> Option { + let bytes = cadcraft_io::write(&drawing(), "height.dwg").unwrap(); + let mut doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(bytes)).read().unwrap(); + let table = doc + .entities_mut() + .find_map(|e| match e { + acadrust::entities::EntityType::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + edit(&mut table.rows[0].cells[0]); + let d = if as_dxf { + let bytes = acadrust::DxfWriter::new(&doc).write_to_vec().unwrap(); + cadcraft_io::read(&bytes, "height.dxf").unwrap() + } else { + let bytes = acadrust::DwgWriter::write_to_vec(&doc).unwrap(); + cadcraft_io::read(&bytes, "height.dwg").unwrap() + }; + d.model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Table(t) => Some(t.cells[0][0].text_height), + _ => None, + }) + .unwrap() +} + +fn styled(height: f64, flags: CellStylePropertyFlags) -> CellStyle { + let mut s = CellStyle::new(); + s.text_height = height; + s.property_flags = flags; + s +} + +#[test] +fn a_cell_style_with_the_text_height_flag_keeps_its_height() { + let h = first_cell_height(false, |c| c.style = Some(styled(0.5, CellStylePropertyFlags::TEXT_HEIGHT))); + assert_eq!(h, Some(0.5)); +} + +#[test] +fn content_with_format_override_bit_128_keeps_its_own_height() { + // acadrust writes the content's height as group 144 and the style's as 140; they differ here + // so the result shows which one CADCraft honoured. + let h = first_cell_height(false, |c| { + c.style = Some(styled(0.5, CellStylePropertyFlags::NONE)); + if c.contents.is_empty() { + c.contents.push(CellContent::new()); + } + c.contents[0].format_override_flags |= 128; + c.contents[0].text_height = 0.3125; + }); + assert_eq!(h, Some(0.3125)); +} + +/// Only the first content's override stands for the cell: a later content's height must not +/// replace the first content's inherited one (review on #2588). +#[test] +fn a_later_contents_height_does_not_replace_the_first_contents() { + let h = first_cell_height(false, |c| { + c.style = Some(styled(0.18, CellStylePropertyFlags::NONE)); + c.contents.clear(); + c.contents.push(CellContent::new()); + let mut later = CellContent::new(); + later.format_override_flags |= 128; + later.text_height = 0.3125; + c.contents.push(later); + }); + assert_eq!(h, None); +} + +/// Bit 128 with an unusable content height copies nothing, so the writer's default style height +/// is still cleared (review on #2588). +#[test] +fn bit_128_with_an_invalid_height_still_clears_the_default() { + for bad in [0.0, -1.0, f64::NAN] { + let h = first_cell_height(false, |c| { + c.style = Some(styled(0.18, CellStylePropertyFlags::NONE)); + if c.contents.is_empty() { + c.contents.push(CellContent::new()); + } + c.contents[0].format_override_flags |= 128; + c.contents[0].text_height = bad; + }); + assert_eq!(h, None, "content height {bad}"); + } +} + +#[test] +fn a_cell_with_no_style_record_inherits_the_table_style() { + assert_eq!(first_cell_height(false, |c| c.style = None), None); +} + +/// A style record with a height and neither override is not an override, through DWG. +#[test] +fn a_style_height_without_an_override_is_cleared() { + assert_eq!(first_cell_height(false, |c| c.style = Some(styled(0.18, CellStylePropertyFlags::NONE))), None); +} 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 eacdbe43eef1b58b7436317830751c8b6e93bf6e Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 17:10:53 -0700 Subject: [PATCH 432/900] Save: a folder that can't be made says so, not that the backup failed (#2669) The backup ran before the folders were made. On Linux, a path under a file gave 'the backup copy could not be written' instead of naming the folder. --- crates/engine/src/cmd/file.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 72d4ef692..76a53da46 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -440,7 +440,8 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result Result<()> { #[cfg(not(target_arch = "wasm32"))] { - if is_drawing_file(path) && crate::autosave::isavebak() { + // 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)) .map_err(|e| bad("save", format!("{path}: the backup copy could not be written ({e}); nothing was saved")))?; } From f389d6a72e3fc160ea125b4f264d68f64cbe2aba Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 2 Nov 2026 19:26:12 -0500 Subject: [PATCH 433/900] Release 0.17.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 32 ++++++++++++++++---------------- Cargo.toml | 2 +- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b5210faea..98d98880f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -614,7 +614,7 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cadcraft" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -644,7 +644,7 @@ dependencies = [ [[package]] name = "cadcraft-cli" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -660,14 +660,14 @@ dependencies = [ [[package]] name = "cadcraft-color" -version = "0.16.0" +version = "0.17.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-constraints" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-doc", "cadcraft-geom", @@ -677,7 +677,7 @@ dependencies = [ [[package]] name = "cadcraft-doc" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-color", "cadcraft-geom", @@ -688,14 +688,14 @@ dependencies = [ [[package]] name = "cadcraft-dwg" -version = "0.16.0" +version = "0.17.0" dependencies = [ "acadrust", ] [[package]] name = "cadcraft-dxf" -version = "0.16.0" +version = "0.17.0" dependencies = [ "encoding_rs", "log", @@ -704,7 +704,7 @@ dependencies = [ [[package]] name = "cadcraft-engine" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-color", "cadcraft-constraints", @@ -725,7 +725,7 @@ dependencies = [ [[package]] name = "cadcraft-fonts" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-geom", "harfrust 0.14.0", @@ -736,14 +736,14 @@ dependencies = [ [[package]] name = "cadcraft-geom" -version = "0.16.0" +version = "0.17.0" dependencies = [ "serde", ] [[package]] name = "cadcraft-io" -version = "0.16.0" +version = "0.17.0" dependencies = [ "acadrust", "cadcraft-color", @@ -764,7 +764,7 @@ dependencies = [ [[package]] name = "cadcraft-mcp" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -777,7 +777,7 @@ dependencies = [ [[package]] name = "cadcraft-render" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -791,7 +791,7 @@ dependencies = [ [[package]] name = "cadcraft-ui-egui" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-color", "cadcraft-doc", @@ -817,7 +817,7 @@ dependencies = [ [[package]] name = "cadcraft-web" -version = "0.16.0" +version = "0.17.0" dependencies = [ "cadcraft-engine", "cadcraft-io", @@ -5928,7 +5928,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.16.0" +version = "0.17.0" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index b84651eee..f51aa8909 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "0.16.0" +version = "0.17.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 0f94865fa9ef09fbd2d3d1ed6db4c0b0a506e338 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 19 Oct 2026 08:21:19 +0200 Subject: [PATCH 434/900] Write RevcloudProps xdata on revision clouds Fixes #1570 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/draw2/revcloud.rs | 49 ++++++++++++++++++------- crates/engine/src/cmd/draw2/tests.rs | 29 +++++++++++++++ 2 files changed, 65 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/draw2/revcloud.rs b/crates/engine/src/cmd/draw2/revcloud.rs index 634456b05..af9237bde 100644 --- a/crates/engine/src/cmd/draw2/revcloud.rs +++ b/crates/engine/src/cmd/draw2/revcloud.rs @@ -2,6 +2,7 @@ use super::{ Accept, Chain, Circle, Ellipse, EntityKind, Handle, Input, Interactive, Line, MAX_GEN, PolyVertex, Polyline, Prompt, Result, Session, Step, Value, Vec2, added, bad, bool_or, curves, lwpoly, number, other, point_param, points_param, rect_vertices, shoelace, str_param, }; +use cadcraft_doc::RawTag; // ===================================================================================== // REVCLOUD @@ -93,6 +94,38 @@ fn cloud_entity(vs: Vec, calligraphy: bool, arc_len: f64) -> EntityK lwpoly(vs, true) } +/// The application name of the xdata that marks a closed polyline as a revision cloud. +const REVCLOUD_APP: &str = "RevcloudProps"; + +/// Adds a revision cloud with its `RevcloudProps` xdata (how AutoCAD and other readers tell a +/// revision cloud from a polyline). Made from object `src`, the cloud takes the object's place +/// and properties. +fn add_cloud(s: &mut Session, vs: Vec, calligraphy: bool, arc_len: f64, src: Option) -> Result { + let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?; + let mut common = match src { + Some(src) => curves::entity(s, src)?.common, + None => curves::entity(s, h)?.common, + }; + let mut keep = true; + common.xdata.retain(|t| { + if t.code == 1001 { + keep = !t.value.trim().eq_ignore_ascii_case(REVCLOUD_APP); + } + keep + }); + common.xdata.extend([ + RawTag { code: 1001, value: REVCLOUD_APP.into() }, + RawTag { code: 1070, value: "0".into() }, + RawTag { code: 1040, value: arc_len.to_string() }, + ]); + let d = s.doc_mut()?; + d.modify_entity(h, |e| e.common = common)?; + if let Some(src) = src { + d.remove_entity(src); + } + Ok(h) +} + pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result { let arc_len = p.get("arcLength").and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).unwrap_or_else(|| default_arc_len(s)); let reverse = bool_or(p, "reverse", false); @@ -112,13 +145,7 @@ pub(super) fn run_revcloud(s: &mut Session, p: &Value) -> Result { return Err(bad("revcloud", "too many points")); } let vs = cloud_vertices(&pts, arc_len, per_edge, reverse).ok_or_else(|| bad("revcloud", "the boundary needs an area"))?; - let h = s.add_entity(cloud_entity(vs, calligraphy, arc_len))?; - if let Some(src) = src { - let common = curves::entity(s, src)?.common; - let d = s.doc_mut()?; - d.modify_entity(h, |e| e.common = common)?; - d.remove_entity(src); - } + let h = add_cloud(s, vs, calligraphy, arc_len, src)?; added(h) } @@ -150,7 +177,7 @@ impl RevcloudM { let b = self.boundary(None); match cloud_vertices(&b, self.arc_len, self.kind != CloudKind::Free, false) { Some(vs) => { - s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?; + add_cloud(s, vs, self.calligraphy, self.arc_len, None)?; s.echo("Revision cloud finished."); Ok(Step::Done) } @@ -217,11 +244,7 @@ impl Interactive for RevcloudM { let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; let pts = object_outline(s, h)?; let vs = cloud_vertices(&pts, self.arc_len, false, false).ok_or_else(|| other("The object has no area."))?; - let nh = s.add_entity(cloud_entity(vs, self.calligraphy, self.arc_len))?; - let common = curves::entity(s, h)?.common; - let d = s.doc_mut()?; - d.modify_entity(nh, |e| e.common = common)?; - d.remove_entity(h); + add_cloud(s, vs, self.calligraphy, self.arc_len, Some(h))?; s.echo("Revision cloud finished."); return Ok(Step::Done); } diff --git a/crates/engine/src/cmd/draw2/tests.rs b/crates/engine/src/cmd/draw2/tests.rs index efad025ca..4362a0f98 100644 --- a/crates/engine/src/cmd/draw2/tests.rs +++ b/crates/engine/src/cmd/draw2/tests.rs @@ -736,6 +736,35 @@ fn revcloud_json() { assert!(s.execute("revcloud", &json!({"p1": [0, 0], "p2": [1e300, 1e300], "arcLength": 1e-300})).is_ok()); } +#[test] +fn revcloud_saves_revcloudprops_xdata() { + let mut s = Session::new(); + let props = |s: &Session| { + let xd = s.doc().unwrap().model.last().unwrap().common.xdata.clone(); + xd.iter().map(|t| (t.code, t.value.clone())).collect::>() + }; + let want = vec![(1001, "RevcloudProps".to_string()), (1070, "0".to_string()), (1040, "2".to_string())]; + s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 2})).unwrap(); + assert_eq!(props(&s), want); + let dxf = cadcraft_io::write_dxf(s.doc().unwrap()); + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let groups: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect(); + assert!(groups.contains(&("1001", "RevcloudProps")), "no RevcloudProps xdata in the DXF"); + let appid = groups + .iter() + .enumerate() + .any(|(i, g)| *g == ("0", "APPID") && groups[i + 1..].iter().take_while(|g| g.0 != "0").any(|g| *g == ("2", "RevcloudProps"))); + assert!(appid, "no RevcloudProps APPID record"); + // Made from an object: the object's properties are kept, the cloud is still a revision cloud. + let c = h(&s.execute("circle", &json!({"center": [10, 10], "radius": 1})).unwrap()); + s.execute("revcloud", &json!({"handle": c, "arcLength": 2})).unwrap(); + assert_eq!(props(&s), want); + // Interactive. + s.cmdline("revcloud a 2").unwrap(); + s.cmdline("0,0 4,2").unwrap(); + assert_eq!(props(&s), want); +} + #[test] fn revcloud_command_line() { let mut s = Session::new(); From fdfe4d95a8e588dab40a174a45ec9e2586753f68 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 18:06:35 -0700 Subject: [PATCH 435/900] Autosave: failures are shown, and a crash is recovered at the first relaunch (#2670) * Autosave: a failed write is shown until one works (E6) A failure only reached the log, so someone could work for hours with no recovery copy. The autosaver keeps why each drawing's write failed; the app says it once at the command line and shows a notice that doesn't block saving. It ends when a write works or the drawing no longer needs a copy. * Crash recovery: offered at the first relaunch, not 5 minutes later (E5) A crashed app's lock file looked alive until it went stale, so a relaunch within 5 minutes skipped its autosaves, and a suspended app's looked dead. A running app now holds a system lock on the file, which the OS drops however the process ends. File age still decides where locks don't work and for lock files of older versions, which don't record holding one. --- crates/engine/src/autosave.rs | 112 +++++++++++++++++++---- crates/engine/tests/autosave.rs | 94 +++++++++++++++++++ crates/ui-egui/src/autosave.rs | 58 ++++++++++++ crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/tests/autosave_failure.rs | 82 +++++++++++++++++ 5 files changed, 331 insertions(+), 19 deletions(-) create mode 100644 crates/ui-egui/tests/autosave_failure.rs diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index 9ff7eab0b..92e97afeb 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -4,15 +4,18 @@ //! autosave is written as DXF to `/__.sv$`. The file goes //! away when the drawing is saved or closed and when the app exits normally, so a file left behind //! means the app (or the machine) went down; the next start offers it for recovery. A running app -//! keeps a lock file (`.lock`) fresh, so another copy running at the same time doesn't -//! offer its files. SAVEFILEPATH may be a folder other programs use too, so only names built from -//! an instance id ([`is_instance_id`]) are ever read as ours or deleted. +//! holds an operating-system lock on its lock file (`.lock`) and keeps the file fresh, so +//! another copy running at the same time doesn't offer its files. The system drops the lock the +//! moment a process ends, however it ended, so a relaunch after a crash can offer recovery at once. +//! Where locks aren't available, and for lock files of older versions, a file not refreshed for +//! [`STALE_LOCK_SECS`] counts as stopped. SAVEFILEPATH may be a folder other programs use too, so +//! only names built from an instance id ([`is_instance_id`]) are ever read as ours or deleted. //! //! [`Autosaver::plan`] decides what to write and delete (no I/O, so it is testable); on the desktop //! [`Autosaver::tick`] carries it out, writing on a background thread. SAVETIME and SAVEFILEPATH //! are profile settings: process-wide, not saved in the drawing. -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Mutex, Weak}; @@ -29,6 +32,10 @@ pub const DEFAULT_SAVETIME: u32 = 10; pub const MAX_SAVETIME: u32 = 600; /// A lock file not refreshed for this long belongs to an app that is no longer running. pub const STALE_LOCK_SECS: u64 = 5 * 60; +/// How a lock file ends when its app holds the system lock on it, so a free lock proves the app +/// stopped. Older versions write only the process id and never hold one. +#[cfg(not(target_arch = "wasm32"))] +const LOCK_HELD: &str = " held"; /// How often a running app refreshes its lock file. #[cfg(not(target_arch = "wasm32"))] const HEARTBEAT_SECS: f64 = 60.0; @@ -149,13 +156,19 @@ pub struct Autosaver { docs: HashMap, /// Drawings whose autosave is being written right now. busy: HashSet, - /// Writes in progress; each tells whether its file was written. + /// Why the last autosave of each drawing failed, until one succeeds or the drawing no longer + /// needs it. Ordered, so [`Autosaver::failure`] doesn't change between frames. + failed: BTreeMap, + /// Writes in progress; each ends with why its file wasn't written, if it wasn't. #[cfg(not(target_arch = "wasm32"))] - running: Vec<(u64, std::thread::JoinHandle)>, + running: Vec<(u64, std::thread::JoinHandle>)>, #[cfg(not(target_arch = "wasm32"))] start: std::time::Instant, #[cfg(not(target_arch = "wasm32"))] last_beat: Option, + /// The lock file this app holds the system lock on, open for as long as the lock is wanted. + #[cfg(not(target_arch = "wasm32"))] + lock: Option<(std::path::PathBuf, std::fs::File)>, } impl Autosaver { @@ -164,12 +177,15 @@ impl Autosaver { instance: instance.into(), docs: HashMap::new(), busy: HashSet::new(), + failed: BTreeMap::new(), #[cfg(not(target_arch = "wasm32"))] running: Vec::new(), #[cfg(not(target_arch = "wasm32"))] start: std::time::Instant::now(), #[cfg(not(target_arch = "wasm32"))] last_beat: None, + #[cfg(not(target_arch = "wasm32"))] + lock: None, } } @@ -187,6 +203,11 @@ impl Autosaver { self.docs.values().filter_map(|t| t.file.clone()).collect() } + /// Why a drawing currently has no up-to-date recovery copy, for the host to show the user. + pub fn failure(&self) -> Option<&str> { + self.failed.values().next().map(String::as_str) + } + /// What to do at `now` (seconds, any fixed origin) with SAVETIME `minutes` and autosave folder /// `dir`: write drawings changed `minutes` ago or earlier and not autosaved since, delete the /// files of drawings that were saved (no unsaved changes left) or closed. @@ -220,6 +241,7 @@ impl Autosaver { jobs.push(Job::Delete { path }); } *t = Tracked::default(); + self.failed.remove(&st.uid); continue; } let same = |w: &Option>, d: &Arc| w.as_ref().is_some_and(|w| std::ptr::eq(w.as_ptr(), Arc::as_ptr(d))); @@ -248,6 +270,8 @@ impl Autosaver { t.since = None; jobs.push(Job::Write { uid: st.uid, path, doc }); } + let docs = &self.docs; + self.failed.retain(|uid, _| docs.contains_key(uid)); jobs } @@ -277,12 +301,14 @@ pub use native::*; #[cfg(not(target_arch = "wasm32"))] mod native { + use std::fs::{File, OpenOptions, TryLockError}; + use std::io::{Read, Write}; use std::path::Path; use std::time::{Duration, SystemTime}; use super::{ - Autosaver, Drawing, HEARTBEAT_SECS, HashMap, Job, Recoverable, STALE_LOCK_SECS, Session, is_instance_id, parse_file_name, parse_lock_name, - savefilepath, savetime, + Autosaver, Drawing, HEARTBEAT_SECS, HashMap, Job, LOCK_HELD, Recoverable, STALE_LOCK_SECS, Session, is_instance_id, parse_file_name, + parse_lock_name, savefilepath, savetime, }; /// A new instance id: the process id and the start time. @@ -307,6 +333,28 @@ mod native { Some(SystemTime::now().duration_since(m).unwrap_or_default()) } + /// Whether the app instance named by a lock file in `dir` may still be running: its system + /// lock answers at once, and the file's age decides when it can't (no lock support, a lock + /// file from an older version). + fn owner_alive(dir: &Path, instance: &str) -> bool { + let by_age = || instance_alive(lock_age(dir, instance)); + let path = lock_path(dir, instance); + // Only a plain file is opened: opening a FIFO planted in a shared folder would block. + if !std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_file()) { + return by_age(); + } + let Ok(file) = File::open(&path) else { return by_age() }; + match file.try_lock() { + Err(TryLockError::WouldBlock) => true, + Err(TryLockError::Error(_)) => by_age(), + Ok(()) => { + let mut text = String::new(); + let held = file.take(64).read_to_string(&mut text).is_ok() && text.ends_with(LOCK_HELD); + !held && by_age() + } + } + } + /// The autosave files in `dir` left behind by apps that are no longer running (never those of /// `own`, this app's instance), oldest first. pub fn recoverable(dir: &Path, own: &str) -> Vec { @@ -316,7 +364,7 @@ mod native { for e in entries.flatten().take(10_000) { let name = e.file_name().to_string_lossy().to_string(); let Some((title, instance, _)) = parse_file_name(&name) else { continue }; - if instance == own || *alive.entry(instance.to_string()).or_insert_with(|| instance_alive(lock_age(dir, instance))) { + if instance == own || *alive.entry(instance.to_string()).or_insert_with(|| owner_alive(dir, instance)) { continue; } let Ok(meta) = e.metadata() else { continue }; @@ -358,7 +406,7 @@ mod native { for n in &names { let Some(instance) = parse_lock_name(n) else { continue }; let has_files = names.iter().any(|f| parse_file_name(f).is_some_and(|(_, i, _)| i == instance)); - if !has_files && !instance_alive(lock_age(dir, instance)) { + if !has_files && !owner_alive(dir, instance) { let _ = std::fs::remove_file(dir.join(n)); } } @@ -425,22 +473,27 @@ mod native { /// Take in the writes that have finished ([`Autosaver::tick`] does this first). A drawing /// whose write failed is no longer counted as autosaved: the next plan restarts its clock, - /// so it is tried again SAVETIME later even if it doesn't change. + /// so it is tried again SAVETIME later even if it doesn't change, and [`Autosaver::failure`] + /// says why until a write succeeds. pub fn reap(&mut self) { let (done, running) = std::mem::take(&mut self.running).into_iter().partition::, _>(|(_, h)| h.is_finished()); self.running = running; for (uid, h) in done { self.busy.remove(&uid); - if !h.join().unwrap_or(false) { - self.unwritten(uid); + match h.join().unwrap_or_else(|_| Err("the autosave writer stopped unexpectedly".to_string())) { + Ok(()) => { + self.failed.remove(&uid); + } + Err(e) => self.unwritten(uid, e), } } } - fn unwritten(&mut self, uid: u64) { + fn unwritten(&mut self, uid: u64, why: String) { if let Some(t) = self.docs.get_mut(&uid) { t.written = None; } + self.failed.insert(uid, why); } /// Carry out jobs from [`Autosaver::plan`]: writes on a background thread, deletes now. @@ -451,16 +504,17 @@ mod native { Job::Write { uid, path, doc } => { let Some(write) = crate::cmd::file::io().map(|h| h.write) else { log::warn!("autosave: file formats are not available in this build"); + self.unwritten(uid, "file formats are not available in this build".to_string()); continue; }; let spawned = std::thread::Builder::new().name("autosave".into()).spawn(move || match write_file(write, &doc, &path) { Ok(()) => { log::info!("autosaved {path}"); - true + Ok(()) } Err(e) => { log::warn!("autosave {path}: {e}"); - false + Err(format!("{path}: {e}")) } }); match spawned { @@ -470,7 +524,7 @@ mod native { } Err(e) => { log::warn!("autosave: {e}"); - self.unwritten(uid); + self.unwritten(uid, e.to_string()); } } } @@ -485,12 +539,31 @@ mod native { } self.last_beat = Some(now); let dir = Path::new(dir); - let r = create_folder(dir).and_then(|()| std::fs::write(lock_path(dir, &self.instance), std::process::id().to_string())); - if let Err(e) = r { + if let Err(e) = create_folder(dir).and_then(|()| self.refresh_lock(&lock_path(dir, &self.instance))) { log::warn!("autosave: lock file in {}: {e}", dir.display()); } } + /// Refresh the lock file at `path`, taking the system lock on it first if this app doesn't + /// hold it there yet. Without one the file still works by its age. + fn refresh_lock(&mut self, path: &Path) -> std::io::Result<()> { + if let Some((held, file)) = &self.lock + && held == path + { + return file.set_modified(SystemTime::now()); + } + self.lock = None; + let id = std::process::id(); + let mut file = OpenOptions::new().write(true).create(true).truncate(false).open(path)?; + if file.try_lock().is_err() { + return std::fs::write(path, id.to_string()); + } + file.set_len(0)?; + file.write_all(format!("{id}{LOCK_HELD}").as_bytes())?; + self.lock = Some((path.to_path_buf(), file)); + Ok(()) + } + /// The app is closing normally: finish writes in progress, then delete this app's autosave /// files and its lock file. pub fn shutdown(&mut self) { @@ -502,6 +575,7 @@ mod native { discard(&path); } self.docs.clear(); + self.lock = None; let dir = savefilepath(); if !dir.is_empty() && is_instance_id(&self.instance) { let _ = std::fs::remove_file(lock_path(Path::new(&dir), &self.instance)); diff --git a/crates/engine/tests/autosave.rs b/crates/engine/tests/autosave.rs index f44be5231..32d21fd05 100644 --- a/crates/engine/tests/autosave.rs +++ b/crates/engine/tests/autosave.rs @@ -169,6 +169,7 @@ fn recovery_offers_files_of_apps_that_stopped() { #[test] fn autosave_files_are_written_in_the_background_and_removed_on_exit() { + let _turn = folder_turn(); hooks(); let dir = temp_dir("write"); let mut s = Session::new(); @@ -255,6 +256,68 @@ fn a_new_autosave_folder_is_owner_only() { let _ = std::fs::remove_dir_all(&base); } +/// SAVEFILEPATH is process-wide: the tests that set it take turns. +static FOLDER: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn folder_turn() -> std::sync::MutexGuard<'static, ()> { + FOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Run autosave once in `dir`, so `a` writes a file and takes its lock, and wait for the file. +fn autosave_once(a: &mut Autosaver, s: &Session, dir: &std::path::Path) -> String { + autosave::set_savefilepath(&dir.to_string_lossy()); + assert_eq!(a.save_now(s), 1); + for _ in 0..500 { + a.reap(); + if !a.writing() && !a.files().is_empty() { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + a.files().pop().unwrap() +} + +#[test] +fn a_crashed_app_is_offered_at_once_and_a_running_one_never() { + hooks(); + let _turn = folder_turn(); + let dir = temp_dir("instant"); + let mut s = Session::new(); + draw(&mut s); + let mut a = Autosaver::new("41-e"); + let file = autosave_once(&mut a, &s, &dir); + let lock = dir.join("41-e.lock"); + assert!(std::fs::metadata(&lock).is_ok()); + + // Running: not offered, even once its lock file looks old (a suspended laptop). + std::fs::File::options().write(true).open(&lock).unwrap().set_modified(SystemTime::now() - Duration::from_secs(3600)).ok(); + assert!(autosave::recoverable(&dir, "9-f").is_empty()); + autosave::prune_locks(&dir); + assert!(lock.exists(), "a running app's lock stays"); + + // Gone without closing, as in a crash: the file is fresh, and it is offered right away. + std::fs::File::options().write(true).open(&lock).unwrap().set_modified(SystemTime::now()).ok(); + drop(a); + let found = autosave::recoverable(&dir, "9-f"); + assert_eq!(found.iter().map(|r| r.path.as_str()).collect::>(), vec![file.as_str()]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_normal_exit_removes_the_lock_file() { + hooks(); + let _turn = folder_turn(); + let dir = temp_dir("exit"); + let mut s = Session::new(); + draw(&mut s); + let mut a = Autosaver::new("42-e"); + autosave_once(&mut a, &s, &dir); + assert!(dir.join("42-e.lock").exists()); + a.shutdown(); + assert!(!dir.join("42-e.lock").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_failed_autosave_is_tried_again_without_another_change() { hooks(); @@ -283,6 +346,7 @@ fn a_failed_autosave_is_tried_again_without_another_change() { std::thread::sleep(Duration::from_millis(10)); } assert!(rearmed, "a failed autosave must be tried again"); + assert!(a.failure().is_some_and(|m| m.contains("out")), "{:?}", a.failure()); std::fs::remove_file(&out).unwrap(); let jobs = a.plan(&s, 180.0, 1, &dir); @@ -303,6 +367,36 @@ fn a_failed_autosave_is_tried_again_without_another_change() { std::thread::sleep(Duration::from_millis(10)); } assert_eq!(a.next_due(1e4, 1), None); + assert_eq!(a.failure(), None, "a write that worked clears the failure"); + a.shutdown(); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_failure_ends_when_the_drawing_no_longer_needs_a_copy() { + hooks(); + let root = temp_dir("failed-close"); + let out = root.join("out"); + std::fs::write(&out, b"not a folder").unwrap(); + let dir = out.to_string_lossy().to_string(); + let mut s = Session::new(); + draw(&mut s); + let mut a = Autosaver::new("32-e"); + a.plan(&s, 0.0, 1, &dir); + let jobs = a.plan(&s, 60.0, 1, &dir); + a.perform(jobs); + for _ in 0..500 { + a.reap(); + if a.failure().is_some() { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + assert!(a.failure().is_some()); + let i = s.active; + s.execute("close", &json!({ "index": i })).unwrap(); + a.plan(&s, 120.0, 1, &dir); + assert_eq!(a.failure(), None); a.shutdown(); let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/ui-egui/src/autosave.rs b/crates/ui-egui/src/autosave.rs index 012231683..d09d95770 100644 --- a/crates/ui-egui/src/autosave.rs +++ b/crates/ui-egui/src/autosave.rs @@ -32,6 +32,15 @@ pub fn load_prefs(json: &str) { } } +/// What the autosave failure notice says (see [`failure_notice`]). +#[derive(Clone, Debug, PartialEq)] +pub struct AutosaveNotice { + pub message: String, + /// The user closed it. The failure stays recorded so the notice doesn't come back on every + /// retry; it does for the next failure after a write has worked. + pub dismissed: bool, +} + /// What the GPU error notice says (see [`gpu_notice`]). #[derive(Clone, Debug, PartialEq)] pub struct GpuNotice { @@ -90,6 +99,24 @@ impl CadApp { if let Some(wait) = self.autosave.as_mut().and_then(|s| s.tick(&self.session)) { _ctx.request_repaint_after(wait); } + #[cfg(not(target_arch = "wasm32"))] + self.note_autosave_failure(_ctx); + } + + /// Keep [`Self::autosave_notice`] in step with autosave: a new failure is said once at the + /// command line and shown until it is dismissed or a write works. + #[cfg(not(target_arch = "wasm32"))] + fn note_autosave_failure(&mut self, ctx: &egui::Context) { + let failure = self.autosave.as_ref().and_then(|s| s.failure()).map(str::to_string); + match (failure, &mut self.autosave_notice) { + (None, notice) => *notice = None, + (Some(message), Some(n)) => n.message = message, + (Some(message), notice) => { + self.session.echo(format!("Autosave failed: {message}")); + *notice = Some(AutosaveNotice { message, dismissed: false }); + ctx.request_repaint(); + } + } } /// Every frame: after a GPU error or device loss, autosave unsaved drawings at once (the @@ -242,6 +269,37 @@ pub fn gpu_notice(app: &mut CadApp, ctx: &egui::Context) { } } +/// The notice that autosave isn't working, so unsaved changes have no recovery copy. It doesn't +/// block the drawing: the user needs to be able to save. +pub fn failure_notice(app: &mut CadApp, ctx: &egui::Context) { + let Some(n) = app.autosave_notice.as_ref().filter(|n| !n.dismissed) else { return }; + let t = Tokens::get(); + let mut dismiss = false; + egui::Window::new("Autosave failed") + .id(egui::Id::unique("cc_autosave_notice")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_TOP, vec2(0.0, 48.0)) + .show(ctx, |ui| { + ui.set_width(440.0); + ui.label("CADCraft could not write a recovery copy, so recent changes would be lost if the app stopped now."); + ui.label(RichText::new("Save your work. Autosave tries again after the SAVETIME interval; its folder is in Options.").strong()); + ui.add_space(4.0); + ui.collapsing("Details", |ui| { + ui.label(RichText::new(&n.message).color(t.text_dim).monospace()); + }); + // A row just as tall as the button (a plain right-to-left layout takes the rest). + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Dismiss").clicked() { + dismiss = true; + } + }); + }); + if dismiss && let Some(n) = &mut app.autosave_notice { + n.dismissed = true; + } +} + #[cfg(test)] mod tests { #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 142a589a3..03fa5285b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -305,6 +305,8 @@ pub struct CadApp { pub gpu_faults: std::sync::Arc, /// The notice shown after one (see [`autosave::gpu_notice`]). pub gpu_notice: Option, + /// The notice shown while autosave fails (see [`autosave::failure_notice`]). + pub autosave_notice: Option, /// The Command Aliases dialog while open ([`aliasdlg`]). pub alias_dlg: Option, /// The Hatch and Gradient dialog while open or picking ([`hatchdlg`]). @@ -364,6 +366,7 @@ impl CadApp { recovery: autosave::Recovery::default(), gpu_faults: std::sync::Arc::default(), gpu_notice: None, + autosave_notice: None, alias_dlg: None, hatch_dlg: None, bedit: bedit::State::default(), @@ -903,6 +906,7 @@ impl CadApp { save_loss::prompt(self, ui.ctx()); autosave::show(self, ui.ctx()); autosave::gpu_notice(self, ui.ctx()); + autosave::failure_notice(self, ui.ctx()); self.frame_ms = now_ms() - t0; } diff --git a/crates/ui-egui/tests/autosave_failure.rs b/crates/ui-egui/tests/autosave_failure.rs new file mode 100644 index 000000000..28b6a66d0 --- /dev/null +++ b/crates/ui-egui/tests/autosave_failure.rs @@ -0,0 +1,82 @@ +//! A failed autosave reaches the user: a notice and one command-line message, gone once a write +//! works. SAVEFILEPATH is process-wide, so everything runs in one test. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::Drawing; +use cadcraft_ui_egui::{CadApp, Services}; + +fn wait_for(app: &mut CadApp, ctx: &egui::Context, done: impl Fn(&CadApp) -> bool) { + for _ in 0..500 { + app.autosave_tick(ctx); + if done(app) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } +} + +/// The text the notice paints (the second frame: a new window sizes itself in the first). +fn painted_text(app: &mut CadApp, ctx: &egui::Context) -> String { + fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(t) => text.push_str(t.galley.text()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, text)), + _ => {} + } + } + let mut text = String::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| cadcraft_ui_egui::autosave::failure_notice(app, ui.ctx())); + out.textures_delta.clear(); // no renderer here + text.clear(); + out.shapes.iter().for_each(|s| collect(&s.shape, &mut text)); + } + text +} + +#[test] +fn a_failed_autosave_is_shown_until_a_write_works() { + set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + let root = std::env::temp_dir().join(format!("cadcraft-autosave-failure-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + // The folder can't be created while a file holds its name. + let dir = root.join("out"); + std::fs::write(&dir, b"not a folder").unwrap(); + cadcraft_engine::autosave::set_savefilepath(&dir.to_string_lossy()); + + let mut app = CadApp::new(Session::new(), Services::default()); + app.enable_autosave(&dir); + let ctx = egui::Context::default(); + app.autosave_tick(&ctx); + assert!(app.autosave_notice.is_none(), "nothing failed yet"); + + app.run("circle", serde_json::json!({"center": [0, 0], "radius": 1})).unwrap(); + app.gpu_faults.error("forces an autosave now".into()); + app.gpu_fault_tick(&ctx); + wait_for(&mut app, &ctx, |a| a.autosave_notice.is_some()); + let n = app.autosave_notice.clone().expect("the failure reaches the notice"); + assert!(!n.dismissed && n.message.contains("out"), "{n:?}"); + let said = |app: &CadApp| app.session.log.iter().filter(|l| l.starts_with("Autosave failed:")).count(); + assert_eq!(said(&app), 1); + assert!(painted_text(&mut app, &ctx).contains("could not write a recovery copy")); + + // Dismissed, it stays away through retries and isn't repeated at the command line. + app.autosave_notice.as_mut().unwrap().dismissed = true; + app.autosave_tick(&ctx); + assert!(app.autosave_notice.as_ref().is_some_and(|n| n.dismissed)); + assert!(painted_text(&mut app, &ctx).is_empty()); + assert_eq!(said(&app), 1); + + // The folder comes back: the next write clears it. + std::fs::remove_file(&dir).unwrap(); + app.run("circle", serde_json::json!({"center": [5, 0], "radius": 1})).unwrap(); + app.gpu_faults.error("forces an autosave now".into()); + app.gpu_fault_tick(&ctx); + wait_for(&mut app, &ctx, |a| a.autosave_notice.is_none()); + assert!(app.autosave_notice.is_none(), "a write that worked ends the notice"); + + app.shutdown_autosave(); + let _ = std::fs::remove_dir_all(&root); +} From 6c4984f5ad05ef0cbd9b42028ce06521c7f29341 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 18:14:29 -0700 Subject: [PATCH 436/900] A panic in the interface saves the work and reports it (E4) (#2671) The frame now runs under a guard. A panic autosaves unsaved drawings at once, even with SAVETIME 0, and shows a notice that doesn't block saving. A panic hook writes a local report for every panic. Panics that keep coming stop the interface and leave a window that closes, with the recovery copies kept. --- apps/cadcraft/src/main.rs | 7 +- crates/engine/src/autosave.rs | 39 ++++- crates/engine/tests/autosave.rs | 20 +++ crates/ui-egui/src/autosave.rs | 5 +- crates/ui-egui/src/fault.rs | 235 ++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/tests/ui_faults.rs | 97 ++++++++++++ 7 files changed, 396 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/fault.rs create mode 100644 crates/ui-egui/tests/ui_faults.rs diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 3454dc35f..4b124ad1d 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -86,7 +86,7 @@ impl eframe::App for App { fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { self.cad.system_animations = self.system_animations.current(); // Consume control/open/screenshot queues and time-based autosave, including hidden ticks. - self.cad.logic(ctx); + self.cad.guarded_logic(ctx); // Host frame work runs here, once per frame, and so also on a hidden logic-only tick (which // never reaches `App::ui`): native menus stay current, the spacemouse still navigates and a // workspace changed while hidden is persisted. `current_pass_index()` is zero on the first @@ -116,7 +116,7 @@ impl eframe::App for App { cadcraft_ui_egui::cmdline::capture_tab(ctx, raw); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { - self.cad.ui(ui); + self.cad.guarded_ui(ui); #[cfg(target_os = "macos")] craft_window::title_bar::sync_movable(ui.ctx(), &mut self.movable); } @@ -289,6 +289,9 @@ fn main() -> eframe::Result { } install_io(); cadcraft_engine::settings_dir::set(vars.config_dir.clone()); + if let Some(dir) = &vars.config_dir { + cadcraft_ui_egui::fault::install_report_hook(dir.join(cadcraft_ui_egui::fault::REPORT_DIR)); + } if let Some(name) = &vars.font_alt { cadcraft_engine::fonts::ttf::set_font_alt(name); } diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index 92e97afeb..ca6d6ede4 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -479,16 +479,41 @@ mod native { let (done, running) = std::mem::take(&mut self.running).into_iter().partition::, _>(|(_, h)| h.is_finished()); self.running = running; for (uid, h) in done { - self.busy.remove(&uid); - match h.join().unwrap_or_else(|_| Err("the autosave writer stopped unexpectedly".to_string())) { - Ok(()) => { - self.failed.remove(&uid); - } - Err(e) => self.unwritten(uid, e), - } + self.settle(uid, h); } } + fn settle(&mut self, uid: u64, h: std::thread::JoinHandle>) { + self.busy.remove(&uid); + match h.join().unwrap_or_else(|_| Err("the autosave writer stopped unexpectedly".to_string())) { + Ok(()) => { + self.failed.remove(&uid); + } + Err(e) => self.unwritten(uid, e), + } + } + + /// Write every drawing with changes not yet autosaved and wait until it is done, because + /// the app has gone wrong and may not get another frame. Unlike [`Autosaver::save_now`] + /// this also runs when SAVETIME is 0: unsaved work comes before that preference. Returns + /// how many drawings were written. + pub fn emergency_save(&mut self, s: &Session) -> usize { + for (uid, h) in std::mem::take(&mut self.running) { + self.settle(uid, h); + } + let now = self.start.elapsed().as_secs_f64(); + let dir = savefilepath(); + let jobs = self.plan_with(s, now, savetime().max(1), &dir, true); + let uids: Vec = jobs.iter().filter_map(|j| if let Job::Write { uid, .. } = j { Some(*uid) } else { None }).collect(); + self.perform(jobs); + self.last_beat = None; + self.heartbeat(&dir, now); + for (uid, h) in std::mem::take(&mut self.running) { + self.settle(uid, h); + } + uids.iter().filter(|uid| !self.failed.contains_key(uid)).count() + } + fn unwritten(&mut self, uid: u64, why: String) { if let Some(t) = self.docs.get_mut(&uid) { t.written = None; diff --git a/crates/engine/tests/autosave.rs b/crates/engine/tests/autosave.rs index 32d21fd05..a878faae7 100644 --- a/crates/engine/tests/autosave.rs +++ b/crates/engine/tests/autosave.rs @@ -303,6 +303,26 @@ fn a_crashed_app_is_offered_at_once_and_a_running_one_never() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn an_emergency_save_finishes_before_it_returns_even_with_savetime_off() { + hooks(); + let _turn = folder_turn(); + let dir = temp_dir("emergency"); + autosave::set_savefilepath(&dir.to_string_lossy()); + let before = autosave::savetime(); + autosave::set_savetime(0); + let mut s = Session::new(); + draw(&mut s); + let mut a = Autosaver::new("43-e"); + assert_eq!(a.save_now(&s), 0, "an ordinary save honours SAVETIME 0"); + assert_eq!(a.emergency_save(&s), 1); + autosave::set_savetime(before); + let file = a.files().pop().unwrap(); + assert!(std::fs::read(&file).unwrap().ends_with(b"EOF\n"), "the file is whole on return"); + assert_eq!(a.emergency_save(&s), 0, "nothing changed since"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_normal_exit_removes_the_lock_file() { hooks(); diff --git a/crates/ui-egui/src/autosave.rs b/crates/ui-egui/src/autosave.rs index d09d95770..0d50e2dcc 100644 --- a/crates/ui-egui/src/autosave.rs +++ b/crates/ui-egui/src/autosave.rs @@ -134,8 +134,9 @@ impl CadApp { /// The app closes normally: this app's autosave files are not needed any more. pub fn shutdown_autosave(&mut self) { + // After the interface gave up, the recovery copies are all that's left of the work. #[cfg(not(target_arch = "wasm32"))] - if let Some(s) = &mut self.autosave { + if let Some(s) = self.autosave.as_mut().filter(|_| !self.fault.broken) { s.shutdown(); } } @@ -143,7 +144,7 @@ impl CadApp { /// `secs` since 1970 as `YYYY-MM-DD HH:MM` (UTC). Past chrono's year 262143 range the proleptic /// Gregorian date is kept via the 400-year cycle rather than falling back to the epoch. -fn utc(secs: u64) -> String { +pub(crate) fn utc(secs: u64) -> String { let (h, m) = ((secs % 86_400) / 3600, (secs % 3600) / 60); let (y, mo, d) = civil_from_days(secs / 86_400); // `{y:04}` rather than `%Y`, which writes a `+` before years past 9999. diff --git a/crates/ui-egui/src/fault.rs b/crates/ui-egui/src/fault.rs new file mode 100644 index 000000000..7d087ed23 --- /dev/null +++ b/crates/ui-egui/src/fault.rs @@ -0,0 +1,235 @@ +//! What happens when the interface panics. Commands already run under their own guard +//! (`cadcraft_engine::guard`); this one covers the rest of the frame, so a panic in a panel keeps +//! the user's work: every drawing with unsaved changes is autosaved at once and the app says so. +//! A panic that keeps coming back leaves a plain window that only closes, with the recovery copies +//! kept for the next start. A panic hook writes a report for each, which stays on this machine. +//! None of this helps on the web, where a panic aborts. + +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use egui::{RichText, vec2}; + +use crate::theme::Tokens; +use crate::{CadApp, now_ms}; + +/// Where crash reports go, under the settings folder. +pub const REPORT_DIR: &str = "crash-reports"; +/// This many panics, each within [`QUIET_MS`] of the last, and the interface is given up on. +const MAX_STRIKES: u32 = 3; +/// A stretch this long without a panic means the app has recovered. +const QUIET_MS: f64 = 5_000.0; + +/// Panics caught around the frame. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct UiFault { + /// The last panic's message, until the user dismisses the notice. + pub message: Option, + /// Drawings autosaved because of panics so far. + pub autosaved: usize, + /// Panics in the current run of them. + pub strikes: u32, + /// When the last one happened. + pub last_ms: f64, + /// The interface keeps panicking: it no longer runs, and recovery copies are kept on exit. + pub broken: bool, +} + +impl CadApp { + /// [`CadApp::logic`] under the panic guard. + pub fn guarded_logic(&mut self, ctx: &egui::Context) { + self.guarded(ctx, |app| app.logic(ctx)); + } + + /// [`CadApp::ui`] under the panic guard, then the notice about any panic. Once the interface + /// has been given up on, only the window that closes the app is drawn. + pub fn guarded_ui(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + self.guarded(&ctx, |app| app.ui(ui)); + self.show_fault(&ctx); + } + + /// The notice about a caught panic, or the window that closes the app. + pub fn show_fault(&mut self, ctx: &egui::Context) { + if self.fault.broken { + broken_window(self, ctx); + } else { + notice(self, ctx); + } + } + + /// Run `frame`; a panic in it autosaves unsaved drawings instead of ending the app. + pub fn guarded(&mut self, ctx: &egui::Context, frame: impl FnOnce(&mut CadApp)) { + if self.fault.broken { + return; + } + if let Err(p) = catch_unwind(AssertUnwindSafe(|| frame(self))) { + let message = p.downcast_ref::<&str>().map(ToString::to_string).or_else(|| p.downcast_ref::().cloned()); + self.on_panic(ctx, message.unwrap_or_else(|| "panic".into())); + } + } + + fn on_panic(&mut self, ctx: &egui::Context, message: String) { + let now = now_ms(); + let fault = &mut self.fault; + fault.strikes = if now - fault.last_ms < QUIET_MS { fault.strikes + 1 } else { 1 }; + fault.last_ms = now; + fault.broken = fault.strikes >= MAX_STRIKES; + log::error!("the interface panicked: {message}"); + #[cfg(not(target_arch = "wasm32"))] + if let Some(saver) = &mut self.autosave { + let session = &self.session; + // The save is the point of being here: a panic inside it must not end the app either. + self.fault.autosaved += catch_unwind(AssertUnwindSafe(|| saver.emergency_save(session))).unwrap_or(0); + } + self.fault.message = Some(message); + ctx.request_repaint(); + } +} + +/// The notice after a panic. It doesn't block the drawing: the user needs to be able to save. +fn notice(app: &mut CadApp, ctx: &egui::Context) { + let Some(message) = app.fault.message.clone() else { return }; + let t = Tokens::get(); + let mut dismiss = false; + egui::Window::new("Internal error") + .id(egui::Id::unique("cc_fault_notice")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_TOP, vec2(0.0, 48.0)) + .show(ctx, |ui| { + ui.set_width(440.0); + ui.label("Part of CADCraft failed, and the app kept running."); + ui.label(saved_text(app.fault.autosaved)); + ui.label(RichText::new("Save your work and restart CADCraft.").strong()); + ui.add_space(4.0); + details(ui, t, &message); + // A row just as tall as the button (a plain right-to-left layout takes the rest). + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Dismiss").clicked() { + dismiss = true; + } + }); + }); + if dismiss { + app.fault.message = None; + } +} + +/// All that's left once the interface keeps panicking. +fn broken_window(app: &CadApp, ctx: &egui::Context) { + let t = Tokens::get(); + egui::Window::new("CADCraft has to close") + .id(egui::Id::unique("cc_fault_broken")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .show(ctx, |ui| { + ui.set_width(440.0); + ui.label("Part of CADCraft keeps failing, so it can't continue."); + ui.label(saved_text(app.fault.autosaved)); + ui.label(RichText::new("Drawing Recovery offers them at the next start.").strong()); + ui.add_space(4.0); + if let Some(message) = &app.fault.message { + details(ui, t, message); + } + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Close CADCraft").clicked() { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + }); + }); +} + +fn saved_text(autosaved: usize) -> String { + match autosaved { + 0 => "No drawing needed a new recovery copy.".to_string(), + 1 => "A recovery copy of the drawing with unsaved changes was autosaved.".to_string(), + k => format!("Recovery copies of {k} drawings with unsaved changes were autosaved."), + } +} + +fn details(ui: &mut egui::Ui, t: Tokens, message: &str) { + ui.collapsing("Details", |ui| { + ui.label(RichText::new(message).color(t.text_dim).monospace()); + #[cfg(not(target_arch = "wasm32"))] + if let Some(path) = report::last() { + ui.label(RichText::new(format!("Report: {}", path.display())).color(t.text_dim).monospace()); + } + }); +} + +#[cfg(not(target_arch = "wasm32"))] +pub use report::install_report_hook; + +#[cfg(not(target_arch = "wasm32"))] +mod report { + use std::fmt::Write as _; + use std::panic::PanicHookInfo; + use std::path::{Path, PathBuf}; + use std::sync::Mutex; + use std::sync::atomic::{AtomicU32, Ordering}; + use std::time::{SystemTime, UNIX_EPOCH}; + + /// Reports one run may write: a panic every frame must not fill the disk. + const MAX_PER_RUN: u32 = 5; + /// Reports kept in the folder. + const KEEP: usize = 20; + + static WRITTEN: AtomicU32 = AtomicU32::new(0); + static LAST: Mutex> = Mutex::new(None); + + /// The report of the latest panic, once one was written. + pub(super) fn last() -> Option { + LAST.lock().ok().and_then(|g| g.clone()) + } + + /// Write a report into `dir` for every panic, on any thread, before the hook already in + /// place runs. Panics that a guard then catches get one too: they are still bugs. A panic that + /// can't be reported goes on as it would have: a report never makes things worse. + pub fn install_report_hook(dir: PathBuf) { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + if WRITTEN.fetch_add(1, Ordering::Relaxed) < MAX_PER_RUN + && let Ok(path) = write_report(&dir, info) + && let Ok(mut last) = LAST.lock() + { + *last = Some(path); + } + previous(info); + })); + } + + fn write_report(dir: &Path, info: &PanicHookInfo<'_>) -> std::io::Result { + std::fs::create_dir_all(dir)?; + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default(); + let mut text = String::new(); + let _ = writeln!(text, "CADCraft {} on {} {}", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH); + let _ = writeln!(text, "Time: {} UTC", crate::autosave::utc(now.as_secs())); + let _ = writeln!(text, "Thread: {}", std::thread::current().name().unwrap_or("unnamed")); + if let Some(l) = info.location() { + let _ = writeln!(text, "Location: {}:{}:{}", l.file(), l.line(), l.column()); + } + let _ = writeln!(text, "Message: {}", info.payload_as_str().unwrap_or("(not text)")); + let _ = writeln!(text, "\n{}", std::backtrace::Backtrace::force_capture()); + let path = dir.join(format!("crash-{:012x}-{}.txt", now.as_millis(), std::process::id())); + cadcraft_engine::atomic_write::write_atomic(&path, text.as_bytes())?; + prune(dir); + Ok(path) + } + + /// Keep the newest [`KEEP`] reports. Names start with the time, so they sort by age. + fn prune(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + let mut reports: Vec = entries + .flatten() + .take(10_000) + .map(|e| e.path()) + .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("crash-") && n.ends_with(".txt"))) + .collect(); + reports.sort(); + let extra = reports.len().saturating_sub(KEEP); + for old in reports.drain(..extra) { + let _ = std::fs::remove_file(old); + } + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 03fa5285b..3319e639c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -32,6 +32,7 @@ pub mod control; pub mod credits; pub mod dialogs; pub mod docking; +pub mod fault; pub mod hatchdlg; mod mtext_editor; mod panel_state; @@ -305,6 +306,8 @@ pub struct CadApp { pub gpu_faults: std::sync::Arc, /// The notice shown after one (see [`autosave::gpu_notice`]). pub gpu_notice: Option, + /// Panics caught around the frame ([`fault`]). + pub fault: fault::UiFault, /// The notice shown while autosave fails (see [`autosave::failure_notice`]). pub autosave_notice: Option, /// The Command Aliases dialog while open ([`aliasdlg`]). @@ -366,6 +369,7 @@ impl CadApp { recovery: autosave::Recovery::default(), gpu_faults: std::sync::Arc::default(), gpu_notice: None, + fault: fault::UiFault::default(), autosave_notice: None, alias_dlg: None, hatch_dlg: None, diff --git a/crates/ui-egui/tests/ui_faults.rs b/crates/ui-egui/tests/ui_faults.rs new file mode 100644 index 000000000..3c382e38f --- /dev/null +++ b/crates/ui-egui/tests/ui_faults.rs @@ -0,0 +1,97 @@ +//! A panic in the interface keeps the user's work: unsaved drawings are autosaved at once, the +//! app says so and writes a report, and a panic that keeps coming back leaves only a way to close +//! with the recovery copies kept. The panic hook is process-wide, so everything runs in one test. + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::Drawing; +use cadcraft_ui_egui::{CadApp, Services}; + +fn panic_in_a_nested_ui(app: &mut CadApp, ctx: &egui::Context, text: &'static str) -> String { + let mut painted = String::new(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let ctx = ui.ctx().clone(); + app.guarded(&ctx, |_| { + egui::CentralPanel::default().show(ui, |ui| { + ui.vertical(|ui| { + ui.label("before"); + std::panic::panic_any(text); + }); + }); + }); + app.show_fault(ui.ctx()); + }); + out.textures_delta.clear(); // no renderer here + out.shapes.iter().for_each(|s| collect(&s.shape, &mut painted)); + painted +} + +fn painted_text(app: &mut CadApp, ctx: &egui::Context) -> String { + let mut painted = String::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.show_fault(ui.ctx())); + out.textures_delta.clear(); // no renderer here + painted.clear(); + out.shapes.iter().for_each(|s| collect(&s.shape, &mut painted)); + } + painted +} + +fn collect(shape: &egui::Shape, text: &mut String) { + match shape { + egui::Shape::Text(t) => { + text.push_str(t.galley.text()); + text.push('\n'); + } + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, text)), + _ => {} + } +} + +fn recovery_copies(dir: &std::path::Path) -> usize { + std::fs::read_dir(dir).map(|d| d.flatten().filter(|e| e.path().extension().is_some_and(|x| x == "sv$")).count()).unwrap_or(0) +} + +#[test] +fn a_panic_saves_the_work_and_reports_and_repeated_ones_close_safely() { + set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); + let root = std::env::temp_dir().join(format!("cadcraft-ui-faults-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (auto, reports) = (root.join("autosave"), root.join("crash-reports")); + cadcraft_ui_egui::fault::install_report_hook(reports.clone()); + + let mut app = CadApp::new(Session::new(), Services::default()); + app.enable_autosave(&auto); + app.run("circle", serde_json::json!({"center": [0, 0], "radius": 1})).unwrap(); + let ctx = egui::Context::default(); + + // One panic: the drawing has a whole recovery copy by the time the frame goes on. + panic_in_a_nested_ui(&mut app, &ctx, "a bug in a panel"); + assert_eq!(app.fault.message.as_deref(), Some("a bug in a panel")); + assert_eq!((app.fault.autosaved, app.fault.broken), (1, false)); + assert_eq!(recovery_copies(&auto), 1); + let text = painted_text(&mut app, &ctx); + assert!(text.contains("kept running") && text.contains("recovery copy"), "{text}"); + + let report = std::fs::read_dir(&reports).unwrap().flatten().next().expect("a report").path(); + let report = std::fs::read_to_string(report).unwrap(); + assert!(report.contains("Message: a bug in a panel") && report.contains("ui_faults.rs"), "{report}"); + assert!(report.starts_with("CADCraft "), "{report}"); + + // The app still works after it. + app.run("circle", serde_json::json!({"center": [5, 0], "radius": 1})).unwrap(); + + // Panics that keep coming: the interface stops running and only offers to close. + panic_in_a_nested_ui(&mut app, &ctx, "again"); + panic_in_a_nested_ui(&mut app, &ctx, "and again"); + assert!(app.fault.broken); + let mut ran = false; + app.guarded(&ctx, |_| ran = true); + assert!(!ran, "a broken interface isn't run again"); + assert!(painted_text(&mut app, &ctx).contains("Drawing Recovery offers them")); + + // Closing now keeps the copies for the next start. + app.shutdown_autosave(); + assert_eq!(recovery_copies(&auto), 1); + let _ = std::fs::remove_dir_all(&root); +} From 806654aedfea7bd9a7dcc2e978b7a2d46ccacc0d Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 18:24:51 -0700 Subject: [PATCH 437/900] Add a security policy (E33) (#2672) --- SECURITY.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..635ab902e --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,34 @@ +# Security policy + +## Reporting a vulnerability + +Please report it privately through [GitHub's private reporting](https://github.com/storytold/cadcraft/security/advisories/new), not in a public issue or pull request. Say which version you ran, on which platform, and how to reproduce it. A small sample file helps, as long as it holds nothing private. + +Maintainers read reports as they arrive, but there is no fixed response time yet. + +## Supported versions + +Only the latest release gets security fixes. CADCraft is pre-alpha and moves quickly, so please check that a problem still exists there before reporting it. + +## What counts + +CADCraft treats these as untrusted, and a way past these defences is a vulnerability: + +- **Drawing files.** Opening a DXF, DWG or other file must not run code, write outside the paths the user chose, or crash the app. Panics are bugs too, but memory exhaustion or a decoder abort on a crafted file is the more serious case. +- **AutoLISP in a drawing's folder.** A drawing must not run code that the user didn't choose to load. +- **The control channel.** It listens on loopback only and needs the session token from an owner-only file on every request. Another local account reaching it without that token is a vulnerability. +- **Temporary and autosave files.** Autosave files are unsaved drawings: another account must not be able to read them or redirect a write through them. +- **Updates.** A release must not be replaceable by someone other than the project. + +## Known limits + +These are known and being worked on, so they don't need a report: + +- Agents connected through MCP or the control channel can read and write any path the user can. There are no workspace roots yet. +- A local process can make the control channel buffer up to 512 MiB before its token is checked. The total is capped, so this can slow the app but not exhaust memory without limit. +- The DWG decoder runs inside the app, so a decoder abort ends every open drawing. Autosave limits what's lost. +- The web build has no autosave yet. + +## What stays on your machine + +Crash reports are written to the `crash-reports` folder in the settings folder and are never uploaded. They hold the version, the platform, the panic message and a stack trace, and a message can include a file path, so read a report before you attach it anywhere. From f6d84e28f31ff98224a2b63b04e5153f4899ae2b Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 18:47:29 -0700 Subject: [PATCH 438/900] DWG reader and writer run in a child process (E7) (#2673) * DWG reader and writer run in a child process (E7) An allocation failure or stack overflow in the third-party code ends its process, which catch_unwind can't stop, so one bad file took every open drawing with it. The app and CLI now run them in a copy of themselves over pipes. A worker that dies or runs past 30 minutes costs that one open or save. If no worker can be started, the work stays in the process, as before. * DWG worker: keep the reply's bytes instead of copying them; skip the test without a bridge --- Cargo.lock | 1 + SECURITY.md | 2 +- apps/cadcraft-cli/src/main.rs | 5 + apps/cadcraft-cli/tests/dwg_worker.rs | 33 +++ apps/cadcraft/src/main.rs | 5 + crates/dwg/Cargo.toml | 3 + crates/dwg/src/lib.rs | 29 ++- crates/dwg/src/worker.rs | 311 ++++++++++++++++++++++++++ crates/io/src/lib.rs | 11 +- 9 files changed, 393 insertions(+), 7 deletions(-) create mode 100644 apps/cadcraft-cli/tests/dwg_worker.rs create mode 100644 crates/dwg/src/worker.rs diff --git a/Cargo.lock b/Cargo.lock index 98d98880f..c2f4ce914 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -691,6 +691,7 @@ name = "cadcraft-dwg" version = "0.17.0" dependencies = [ "acadrust", + "log", ] [[package]] diff --git a/SECURITY.md b/SECURITY.md index 635ab902e..fbad5435b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -26,7 +26,7 @@ These are known and being worked on, so they don't need a report: - Agents connected through MCP or the control channel can read and write any path the user can. There are no workspace roots yet. - A local process can make the control channel buffer up to 512 MiB before its token is checked. The total is capped, so this can slow the app but not exhaust memory without limit. -- The DWG decoder runs inside the app, so a decoder abort ends every open drawing. Autosave limits what's lost. +- The DWG worker process has no memory limit of its own yet, so a crafted file can use a lot of memory before it stops. It ends that one open or save, not the app. - The web build has no autosave yet. ## What stays on your machine diff --git a/apps/cadcraft-cli/src/main.rs b/apps/cadcraft-cli/src/main.rs index 7561b96b5..866923c9a 100644 --- a/apps/cadcraft-cli/src/main.rs +++ b/apps/cadcraft-cli/src/main.rs @@ -1,6 +1,11 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] fn main() { + // A copy of this program started to read or write a DWG file does only that. + if let Some(code) = cadcraft_io::dwg_worker::serve_if_asked() { + std::process::exit(code); + } + cadcraft_io::dwg_worker::use_own_worker(); // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must be // reported as an error, not panic before anything is printed. let code = cadcraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); diff --git a/apps/cadcraft-cli/tests/dwg_worker.rs b/apps/cadcraft-cli/tests/dwg_worker.rs new file mode 100644 index 000000000..8656b84ff --- /dev/null +++ b/apps/cadcraft-cli/tests/dwg_worker.rs @@ -0,0 +1,33 @@ +//! The DWG reader and writer run in a child process, so a decoder that dies ends one open or save, +//! not the app. The worker setting is process-wide, so everything runs in one test. + +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + +use cadcraft_io::dwg_worker; + +#[test] +fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() { + let drawing = cadcraft_engine::sample::bracket(); + let in_process = cadcraft_io::write(&drawing, "a.dwg").unwrap(); + + dwg_worker::use_worker(env!("CARGO_BIN_EXE_cadcraft-cli").into(), vec![dwg_worker::WORKER_ARG.into()]); + let written = cadcraft_io::write(&drawing, "a.dwg").unwrap(); + assert_eq!(written.get(..6), in_process.get(..6), "the same version of file"); + let read = cadcraft_io::read(&written, "a.dwg").unwrap(); + assert_eq!(read.model.len(), drawing.model.len()); + + // A decode error comes back as that error, not as the worker stopping. + let mut bad = in_process.clone(); + bad.truncate(64); + let e = cadcraft_io::read(&bad, "a.dwg").unwrap_err().to_string(); + assert!(!e.contains("worker"), "{e}"); + + // The worker aborts as the third-party code can. This process goes on. + let e = dwg_worker::crash_worker_for_test().unwrap_err(); + assert!(e.contains("worker stopped"), "{e}"); + assert!(cadcraft_io::read(&written, "a.dwg").is_ok(), "the next file gets a new worker"); + + // No worker to start: the work happens here, as without one. + dwg_worker::use_worker("no-such-program-here".into(), Vec::new()); + assert!(cadcraft_io::read(&written, "a.dwg").is_ok()); +} diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 4b124ad1d..71700095d 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -258,6 +258,11 @@ fn version_string() -> String { /// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe. fn main() -> eframe::Result { + // A copy of this program started to read or write a DWG file does only that. + if let Some(code) = cadcraft_io::dwg_worker::serve_if_asked() { + std::process::exit(code); + } + cadcraft_io::dwg_worker::use_own_worker(); // First, so every start-up record is captured; see `logging`. let logger = logging::install(); // The update helper relaunches this binary after a self-update; it runs and exits here. diff --git a/crates/dwg/Cargo.toml b/crates/dwg/Cargo.toml index acb8d0aa7..23d1c82d2 100644 --- a/crates/dwg/Cargo.toml +++ b/crates/dwg/Cargo.toml @@ -8,6 +8,9 @@ license.workspace = true [lints] workspace = true +[dependencies] +log = { workspace = true } + # The same targets as build.rs's `no_dwg_bridge` leave acadrust out: wasm32, and FreeBSD aarch64, # where acadrust 0.6.6 passes a `*const c_char` (u8 there) to its own `*const i8` sysctlbyname. # 0.6.7 and 0.6.8 fix that but read some damaged DWGs as empty with no note (tests.rs, #800). diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index e5463aaec..70646a19a 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -19,10 +19,8 @@ //! crashing. //! //! These bound the input- and output-size variants. A small file that declares a huge internal -//! table or section can still make the dependency allocate before any size is known; fully fixing -//! that requires an upstream fix in `acadrust` (validate declared sizes against a decoded-memory -//! budget) or running the decode in a separate worker with an OS memory limit. The limits here -//! keep the blast radius bounded in the meantime. +//! table or section can still make the dependency allocate before any size is known, so the app +//! runs both directions in a child process ([`worker`]): what that kills is the child. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -64,6 +62,11 @@ fn mb(n: u64) -> String { if m >= 100.0 { format!("{m:.0} MB") } else { format!("{m:.1} MB") } } +#[cfg(not(no_dwg_bridge))] +pub mod worker; +#[cfg(not(no_dwg_bridge))] +pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, serve_if_asked, use_own_worker, use_worker}; + #[cfg(not(no_dwg_bridge))] mod native { use std::io::{Cursor, Write}; @@ -930,6 +933,24 @@ fn unsupported(version: &str) -> String { #[cfg(no_dwg_bridge)] const NO_BRIDGE_BUILD: &str = if cfg!(target_arch = "wasm32") { "web" } else { "FreeBSD aarch64" }; +/// There's no worker without a bridge. +#[cfg(no_dwg_bridge)] +pub const WORKER_ARG: &str = "--dwg-worker"; +#[cfg(no_dwg_bridge)] +pub fn serve_if_asked() -> Option { + None +} +#[cfg(no_dwg_bridge)] +pub fn use_own_worker() {} +#[cfg(no_dwg_bridge)] +pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { + dwg_to_dxf_noted(bytes, limits) +} +#[cfg(no_dwg_bridge)] +pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { + dxf_to_dwg_as(dxf, version) +} + #[cfg(no_dwg_bridge)] pub fn dwg_to_dxf(_bytes: &[u8]) -> Result, String> { Err(format!("DWG files can't be opened in the {NO_BRIDGE_BUILD} build yet; save as DXF")) diff --git a/crates/dwg/src/worker.rs b/crates/dwg/src/worker.rs new file mode 100644 index 000000000..5ccf5cf6a --- /dev/null +++ b/crates/dwg/src/worker.rs @@ -0,0 +1,311 @@ +//! The DWG reader and writer in a child process. +//! +//! An allocation failure or stack overflow in the third-party code ends the process it runs in, and +//! `catch_unwind` can't stop that. So the app runs them in a copy of itself: [`use_own_worker`] says +//! how to start one, and [`serve_if_asked`], first thing in `main`, turns the copy into a worker +//! that reads one request from standard input and writes one reply to standard output. A file that +//! kills the worker then costs that one open or save, and every other open drawing stays safe. +//! +//! Without a worker (libraries, tests, a build that can't start one) [`decode`] and [`encode_as`] +//! run in the calling process, as they always did. There's no memory limit on the worker yet: that +//! takes per-platform system calls, which `unsafe_code = "forbid"` keeps out of this crate. +//! +//! A reply comes from a process that just handled a possibly hostile file, so it is parsed as +//! untrusted input. + +use std::ffi::OsString; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::Mutex; +use std::sync::mpsc::{RecvTimeoutError, channel}; +use std::time::Duration; + +use super::Limits; + +/// The argument that makes the app a worker. +pub const WORKER_ARG: &str = "--dwg-worker"; +/// Bumped when the messages change: an app updated while running may start a newer copy. +const PROTOCOL: u8 = 1; +const DECODE: u8 = 1; +const ENCODE: u8 = 2; +const CRASH: u8 = 0xff; +/// How long one file may take before the worker is stopped. It can't be interrupted otherwise. +const TIMEOUT: Duration = Duration::from_secs(30 * 60); +/// Most bytes accepted for what a reply carries besides the drawing. +const MAX_NOTES_BYTES: u64 = 64 << 20; +/// Most bytes accepted as a written DWG. +const MAX_DWG_REPLY: u64 = 2 << 30; +/// Most bytes one request holds: the largest input, whichever the direction, and its header. +const MAX_REQUEST: u64 = (2 << 30) + 256; + +struct Worker { + program: PathBuf, + args: Vec, +} + +static WORKER: Mutex> = Mutex::new(None); + +/// Start `program args` as the worker from now on. `program` must call [`serve_if_asked`]. +pub fn use_worker(program: PathBuf, args: Vec) { + if let Ok(mut w) = WORKER.lock() { + *w = Some(Worker { program, args }); + } +} + +/// Use a copy of this program as the worker, started with [`WORKER_ARG`]. If its path can't be +/// found, the reader and writer stay in this process. +pub fn use_own_worker() { + match std::env::current_exe() { + Ok(program) => use_worker(program, vec![WORKER_ARG.into()]), + Err(e) => log::warn!("DWG worker: can't find this program: {e}"), + } +} + +/// Serve one request and return the exit code if this process was started as a worker. +pub fn serve_if_asked() -> Option { + (std::env::args_os().nth(1)? == WORKER_ARG).then(|| serve(std::io::stdin().lock(), std::io::stdout().lock())) +} + +/// [`super::dwg_to_dxf_noted`] in the worker, when there is one. +pub fn decode(bytes: &[u8], limits: Limits) -> Result<(Vec, Vec), String> { + // Before starting a process, and so the same limit holds with or without one. + if bytes.len() > limits.max_dwg_bytes { + return super::dwg_to_dxf_noted(bytes, limits); + } + let reply_limit = (limits.max_dxf_bytes as u64).saturating_add(MAX_NOTES_BYTES); + match call(&request(DECODE, limits, ""), bytes, reply_limit, "reading this file") { + Some(reply) => reply?, + None => super::dwg_to_dxf_noted(bytes, limits), + } +} + +/// [`super::dxf_to_dwg_as`] in the worker, when there is one. +pub fn encode_as(dxf: &[u8], version: &str) -> Result, String> { + if u8::try_from(version.len()).is_err() { + return Err(super::unsupported(version)); + } + match call(&request(ENCODE, Limits::DEFAULT, version), dxf, MAX_DWG_REPLY, "writing this file") { + Some(reply) => reply?.map(|(dwg, _)| dwg), + None => super::dxf_to_dwg_as(dxf, version), + } +} + +/// Make the worker abort, as the third-party code can: what the tests prove isolation with. +#[doc(hidden)] +pub fn crash_worker_for_test() -> Result<(), String> { + call(&request(CRASH, Limits::DEFAULT, ""), &[], 1024, "testing").ok_or("no worker")??.map(|_| ()) +} + +fn request(op: u8, limits: Limits, version: &str) -> Vec { + let mut r = vec![PROTOCOL, op]; + r.extend((limits.max_dwg_bytes as u64).to_le_bytes()); + r.extend((limits.max_dxf_bytes as u64).to_le_bytes()); + r.push(u8::try_from(version.len()).unwrap_or(0)); + r.extend(version.as_bytes()); + r +} + +type Reply = Result<(Vec, Vec), String>; + +/// Run one request in a worker. `None`: none could be started, so the caller does the work. +/// `Err`: the worker went wrong, and `doing` says at what, for the user. +fn call(header: &[u8], payload: &[u8], reply_limit: u64, doing: &str) -> Option> { + let mut command = { + let worker = WORKER.lock().ok()?; + let worker = worker.as_ref()?; + let mut c = Command::new(&worker.program); + c.args(&worker.args); + c + }; + command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + let mut child = match command.spawn() { + Ok(c) => c, + Err(e) => { + log::warn!("DWG worker: can't start it: {e}"); + return None; + } + }; + let (Some(mut to_child), Some(from_child)) = (child.stdin.take(), child.stdout.take()) else { + let _ = child.kill(); + let _ = child.wait(); + return None; + }; + let received = std::thread::scope(|scope| { + // Written beside the read: a worker that replies before it has read everything, or dies, + // must block neither side. A failed write shows up as the reply going wrong. + scope.spawn(move || { + let _ = to_child.write_all(header).and_then(|()| to_child.write_all(payload)); + }); + let (tx, rx) = channel(); + scope.spawn(move || { + let mut reply = Vec::new(); + let read = from_child.take(reply_limit).read_to_end(&mut reply); + let _ = tx.send(read.map(|_| reply)); + }); + let received = rx.recv_timeout(TIMEOUT); + if matches!(received, Err(RecvTimeoutError::Timeout)) { + let _ = child.kill(); + } + received + }); + let status = child.wait(); + let stopped = || format!("the DWG worker stopped while {doing}; nothing else is affected"); + Some(match (received, status) { + (Err(RecvTimeoutError::Timeout), _) => Err(format!("{doing} took too long, so the DWG worker was stopped; nothing else is affected")), + (Ok(Ok(reply)), Ok(status)) if status.success() => parse_reply(reply).ok_or_else(stopped), + _ => Err(stopped()), + }) +} + +/// Take `n` bytes off the front of `b`. +fn take<'a>(b: &mut &'a [u8], n: usize) -> Option<&'a [u8]> { + let (head, tail) = b.split_at_checked(n)?; + *b = tail; + Some(head) +} + +fn take_u32(b: &mut &[u8]) -> Option { + let bytes: [u8; 4] = take(b, 4)?.try_into().ok()?; + usize::try_from(u32::from_le_bytes(bytes)).ok() +} + +fn take_u64(b: &mut &[u8]) -> Option { + Some(u64::from_le_bytes(take(b, 8)?.try_into().ok()?)) +} + +/// A reply: 0, the note count, each note with its length, then the bytes with their length; or 1 +/// and a message. `None` when it isn't one, whole. Takes the reply, because the bytes can be most +/// of the memory the app may use: they are kept, not copied. +fn parse_reply(mut reply: Vec) -> Option { + let total = reply.len(); + let mut b = &reply[..]; + match *take(&mut b, 1)?.first()? { + 0 => { + let count = take_u32(&mut b)?; + let mut notes = Vec::new(); + for _ in 0..count { + let n = take_u32(&mut b)?; + notes.push(String::from_utf8_lossy(take(&mut b, n)?).into_owned()); + } + let n = usize::try_from(take_u64(&mut b)?).ok()?; + if b.len() != n { + return None; + } + reply.drain(..total - n); + Some(Ok((reply, notes))) + } + 1 => Some(Err(String::from_utf8_lossy(b).into_owned())), + _ => None, + } +} + +fn write_reply(out: &mut impl Write, reply: Reply) -> std::io::Result<()> { + match reply { + Ok((bytes, notes)) => { + out.write_all(&[0])?; + out.write_all(&u32::try_from(notes.len()).unwrap_or(0).to_le_bytes())?; + for note in ¬es { + out.write_all(&u32::try_from(note.len()).unwrap_or(0).to_le_bytes())?; + if u32::try_from(note.len()).is_ok() { + out.write_all(note.as_bytes())?; + } + } + out.write_all(&(bytes.len() as u64).to_le_bytes())?; + out.write_all(&bytes)?; + } + Err(e) => { + out.write_all(&[1])?; + out.write_all(e.as_bytes())?; + } + } + out.flush() +} + +/// What a request asks for, or why it can't be served. +fn handle(mut b: &[u8]) -> Reply { + let bad = || "the DWG worker got a request it can't read (a different CADCraft version?)".to_string(); + if take(&mut b, 1).and_then(<[u8]>::first) != Some(&PROTOCOL) { + return Err(bad()); + } + let op = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?; + let max_dwg_bytes = take_u64(&mut b).and_then(|n| usize::try_from(n).ok()).ok_or_else(bad)?; + let max_dxf_bytes = take_u64(&mut b).and_then(|n| usize::try_from(n).ok()).ok_or_else(bad)?; + let version_len = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?; + let version = take(&mut b, usize::from(version_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?; + match op { + DECODE => super::dwg_to_dxf_noted(b, Limits { max_dwg_bytes, max_dxf_bytes }), + ENCODE => super::dxf_to_dwg_as(b, version).map(|dwg| (dwg, Vec::new())), + CRASH => std::process::abort(), + _ => Err(bad()), + } +} + +/// Serve the one request on `input`. The exit code is 0 unless the reply couldn't be sent. +fn serve(input: impl Read, mut output: impl Write) -> i32 { + let mut request = Vec::new(); + let reply = match input.take(MAX_REQUEST).read_to_end(&mut request) { + Ok(_) => handle(&request), + Err(e) => Err(format!("the DWG worker could not read its request: {e}")), + }; + i32::from(write_reply(&mut output, reply).is_err()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn wire(reply: Reply) -> Vec { + let mut out = Vec::new(); + write_reply(&mut out, reply).unwrap(); + out + } + + #[test] + fn replies_round_trip() { + let ok: Reply = Ok((b"bytes".to_vec(), vec!["one".into(), "two é".into()])); + assert_eq!(parse_reply(wire(ok.clone())), Some(ok)); + let failed: Reply = Err("DWG: no".into()); + assert_eq!(parse_reply(wire(failed.clone())), Some(failed)); + } + + #[test] + fn a_reply_cut_short_or_made_up_is_refused() { + let whole = wire(Ok((b"bytes".to_vec(), vec!["note".into()]))); + for n in 0..whole.len() { + assert_eq!(parse_reply(whole[..n].to_vec()), None, "cut at {n}"); + } + assert_eq!(parse_reply(vec![7, 0, 0]), None); + // A note count far beyond what follows ends at the first missing note. + assert_eq!(parse_reply(vec![0, 0xff, 0xff, 0xff, 0xff]), None); + assert_eq!(parse_reply(vec![0, 1, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]), None); + } + + #[test] + fn a_request_it_cannot_read_is_an_error_not_a_crash() { + for request in [ + &[][..], + &[PROTOCOL + 1, DECODE], + &[PROTOCOL], + &[PROTOCOL, DECODE, 1, 2, 3], + &[PROTOCOL, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] { + assert!(handle(request).is_err(), "{request:?}"); + } + } + + #[test] + fn serving_reports_a_decode_failure_as_a_reply() { + let mut request = self::request(DECODE, Limits::DEFAULT, ""); + request.extend(b"AC1032 not really a drawing"); + let mut out = Vec::new(); + assert_eq!(serve(&request[..], &mut out), 0); + assert!(matches!(parse_reply(out.clone()), Some(Err(_))), "{out:?}"); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ccfba201e..4863ddb34 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -55,6 +55,13 @@ pub enum IoError { pub type Result = std::result::Result; +/// How a program runs the DWG reader and writer in a child process (`cadcraft_dwg::worker`). +pub mod dwg_worker { + pub use cadcraft_dwg::{WORKER_ARG, serve_if_asked, use_own_worker}; + #[cfg(all(not(target_arch = "wasm32"), not(all(target_os = "freebsd", target_arch = "aarch64"))))] + pub use cadcraft_dwg::{crash_worker_for_test, use_worker}; +} + fn ext(name: impl AsRef) -> String { name.as_ref().extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default() } @@ -64,7 +71,7 @@ fn ext(name: impl AsRef) -> String { pub fn read(bytes: &[u8], name: impl AsRef) -> Result { let name = name.as_ref(); if cadcraft_dwg::is_dwg(bytes) { - let (dxf, notes) = cadcraft_dwg::dwg_to_dxf_noted(bytes, cadcraft_dwg::Limits::DEFAULT).map_err(IoError::Format)?; + let (dxf, notes) = cadcraft_dwg::decode(bytes, cadcraft_dwg::Limits::DEFAULT).map_err(IoError::Format)?; let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?; d.read_notes = notes; return Ok(d); @@ -106,7 +113,7 @@ pub fn write_with(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Re // gradients, so a drawing from an R2000 DXF doesn't lose them by default. 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) + cadcraft_dwg::encode_as(dxf_write::dwg_bridge(d, version).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), From 44823163063ad33dc9593dfe381f87cdf0b1c629 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:16:44 -0500 Subject: [PATCH 439/900] constraints: find the next default parameter name in one pass (#2674) next_name tested up to 100,000 candidate names, each against every parameter and constraint name, so a drawing with many occupied names made adding one dimensional constraint quadratic. Collect the numeric suffixes in use once and take the first free one. --- crates/constraints/src/lib.rs | 20 ++++++++++++++++++-- crates/constraints/src/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/constraints/src/lib.rs b/crates/constraints/src/lib.rs index 89c6276cd..0bf230323 100644 --- a/crates/constraints/src/lib.rs +++ b/crates/constraints/src/lib.rs @@ -30,7 +30,7 @@ mod lm; mod model; mod residual; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use cadcraft_doc::{Constraint, ConstraintKind, Drawing, GeomRef, Handle}; use cadcraft_geom::Vec2; @@ -169,10 +169,26 @@ pub fn name_in_use(d: &Drawing, name: &str) -> bool { d.parametric.parameters.iter().any(|p| p.name == name) || d.constraints.iter().any(|c| c.name == name) } +/// Highest numbered default name [`next_name`] tries. +const MAX_NAME_SUFFIX: u32 = 100_000; + /// Next free parameter name for a dimensional constraint kind (`d1`, `rad2`, `ang1`, …). pub fn next_name(d: &Drawing, kind: ConstraintKind) -> String { let prefix = kind.name_prefix(); - (1..=100_000).map(|i| format!("{prefix}{i}")).find(|n| !name_in_use(d, n)).unwrap_or_else(|| format!("{prefix}_x")) + // Collect the suffixes in use in one pass, then take the first free one: checking every + // candidate against every name is quadratic in the number of names (CWE-407). Only a + // suffix spelled as `format!("{prefix}{i}")` spells it counts (`d07` does not take `d7`). + let taken: HashSet = d + .parametric + .parameters + .iter() + .map(|p| p.name.as_str()) + .chain(d.constraints.iter().map(|c| c.name.as_str())) + .filter_map(|n| n.strip_prefix(prefix)) + .filter(|s| !s.starts_with('0') && s.bytes().all(|b| b.is_ascii_digit())) + .filter_map(|s| s.parse::().ok()) + .collect(); + (1..=MAX_NAME_SUFFIX).find(|i| !taken.contains(i)).map_or_else(|| format!("{prefix}_x"), |i| format!("{prefix}{i}")) } /// Next free constraint id. diff --git a/crates/constraints/src/tests.rs b/crates/constraints/src/tests.rs index 35b73fea2..eadc7a3c2 100644 --- a/crates/constraints/src/tests.rs +++ b/crates/constraints/src/tests.rs @@ -489,3 +489,30 @@ fn arc_solved_with_a_negative_radius_keeps_its_points() { } } } + +/// The default name is the first free numbered one, found in one pass over many names in use. +#[test] +fn next_name_skips_names_in_use() { + let mut d = Drawing::default(); + assert_eq!(next_name(&d, ConstraintKind::Radius), "rad1"); + for i in (1..=20_000).filter(|i| *i != 15_000) { + d.parametric.parameters.push(cadcraft_doc::Parameter { name: format!("d{i}"), expr: "1".into(), description: String::new() }); + } + assert_eq!(next_name(&d, ConstraintKind::Distance(DistAxis::Aligned)), "d15000"); + d.parametric.parameters.push(cadcraft_doc::Parameter { name: "d15000".into(), expr: "1".into(), description: String::new() }); + assert_eq!(next_name(&d, ConstraintKind::Distance(DistAxis::Aligned)), "d20001"); + // A differently spelled suffix does not occupy the plain name. + let mut d = Drawing::default(); + for name in ["d01", "d+1", "d1x", "D1"] { + d.parametric.parameters.push(cadcraft_doc::Parameter { name: name.into(), expr: "1".into(), description: String::new() }); + } + assert_eq!(next_name(&d, ConstraintKind::Distance(DistAxis::Aligned)), "d1"); + d.constraints.push(Constraint { + id: 1, + kind: ConstraintKind::Distance(DistAxis::Aligned), + refs: Vec::new(), + name: "d1".into(), + expr: "1".into(), + }); + assert_eq!(next_name(&d, ConstraintKind::Distance(DistAxis::Aligned)), "d2"); +} From 0d3b3d21c0d872b1ae6720d75ef4909f3be2e51d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:16:51 -0500 Subject: [PATCH 440/900] Regions: test a loop's probe only against loops whose box holds it, within a budget (#2680) Region::renest tested every loop's probe point against every other tessellated loop, scanning all of its edges each time, so the work was the loop count times the total vertex count. It now skips loops whose bounding box does not hold the probe, and stops once MAX_RENEST_EDGE_VISITS edge tests have been spent, leaving the flags unchanged and returning false; UNION, SUBTRACT and INTERSECT then report the regions as too complex to combine, as they already do for too many boundary pairs (CWE-407). --- crates/doc/src/entity/region.rs | 80 +++++++++++++++++++++--- crates/engine/src/cmd/inquiry/regions.rs | 4 +- 2 files changed, 76 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/entity/region.rs b/crates/doc/src/entity/region.rs index 0d2594ea8..8c63b43bf 100644 --- a/crates/doc/src/entity/region.rs +++ b/crates/doc/src/entity/region.rs @@ -9,6 +9,9 @@ use super::HatchLoop; /// Most loops one region has (hostile files and edits). pub const MAX_REGION_LOOPS: usize = 10_000; +/// Most polygon edges [`Region::renest`] tests, over all its point-in-loop tests. +pub const MAX_RENEST_EDGE_VISITS: usize = 50_000_000; + #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Region { /// Closed loops with bulges; `outer` false for islands. @@ -76,20 +79,49 @@ impl Region { } /// Set each loop's `outer` flag from how deeply other loops enclose it: an even depth is - /// an outer loop, odd an island. - pub fn renest(&mut self) { + /// an outer loop, odd an island. `false`, with the flags left as they were, when that takes + /// more than [`MAX_RENEST_EDGE_VISITS`] polygon edge tests. + #[must_use] + pub fn renest(&mut self) -> bool { let polys = self.tessellate(self.fine_tol()); - let depth: Vec = polys + // A loop's probe can only be inside loops whose box holds it: test only those. A box with + // a non-finite corner says nothing (an edge through a non-finite point never counts, so + // such a polygon need not be closed), so its loop is always tested. + let boxes: Vec> = polys .iter() - .enumerate() - .map(|(i, l)| { - let Some(p) = probe(l) else { return 0 }; - polys.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count() + .map(|l| { + let b = Bounds2::from_points(l.iter().copied()); + (l.iter().all(|p| p.is_finite()) && b.min.is_finite() && b.max.is_finite()).then_some(b) }) .collect(); + let mut visits = 0usize; + let mut depth = Vec::with_capacity(polys.len()); + for (i, l) in polys.iter().enumerate() { + let Some(p) = probe(l) else { + depth.push(0); + continue; + }; + let mut d = 0; + for (j, (o, b)) in polys.iter().zip(&boxes).enumerate() { + if j == i || b.is_some_and(|b| !b.contains(p)) { + continue; + } + // Each loop against every other is loops x vertices: bounded so a region of many + // large nested loops cannot hold the thread (CWE-407). + visits = visits.saturating_add(o.len()); + if visits > MAX_RENEST_EDGE_VISITS { + return false; + } + if point_in_polygon(o, p) { + d += 1; + } + } + depth.push(d); + } for (l, d) in self.loops.iter_mut().zip(depth) { l.outer = d % 2 == 0; } + true } /// Area, perimeter, bounding box, centroid and second moments (outer loops counted @@ -128,3 +160,37 @@ fn probe(l: &[Vec2]) -> Option { (a.dist(b) > 1e-12).then(|| (a + b) * 0.5).filter(|m| m.is_finite()) }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn square(c: f64, half: f64, n: usize, outer: bool) -> HatchLoop { + // `n` vertices along the bottom edge, then the other three corners. + let mut vertices: Vec = + (0..n).map(|k| PolyVertex::new(Vec2::new(c - half + 2.0 * half * k as f64 / n as f64, c - half))).collect(); + vertices.extend([Vec2::new(c + half, c - half), Vec2::new(c + half, c + half), Vec2::new(c - half, c + half)].map(PolyVertex::new)); + HatchLoop { vertices, outer, sources: Vec::new() } + } + + #[test] + fn renest_sets_depth_parity_and_skips_loops_far_away() { + // Three nested squares, and one beside them. + let mut r = + Region { loops: vec![square(0.0, 3.0, 1, false), square(0.0, 2.0, 1, false), square(0.0, 1.0, 1, false), square(10.0, 1.0, 1, false)] }; + assert!(r.renest()); + assert_eq!(r.loops.iter().map(|l| l.outer).collect::>(), [true, false, true, true]); + } + + #[test] + fn renest_of_many_large_nested_loops_stops_at_its_budget() { + // Concentric loops of many vertices each: each probe is inside the box of every larger + // loop (about loops² / 2 pairs), so each of those tests is a full polygon scan. + let loops = 300; + let n = 3 * MAX_RENEST_EDGE_VISITS / (loops * loops); + let mut r = Region { loops: (0..loops).map(|i| square(0.0, 1.0 + i as f64, n, false)).collect() }; + let before = r.clone(); + assert!(!r.renest()); + assert_eq!(r, before, "flags left as they were"); + } +} diff --git a/crates/engine/src/cmd/inquiry/regions.rs b/crates/engine/src/cmd/inquiry/regions.rs index 9e6b11a49..033d6e0c2 100644 --- a/crates/engine/src/cmd/inquiry/regions.rs +++ b/crates/engine/src/cmd/inquiry/regions.rs @@ -128,7 +128,9 @@ fn combine(a: &Region, b: &Region, op: Op) -> Result> { } loops.retain(|l| l.vertices.len() >= 2); let mut r = Region { loops }; - r.renest(); + if !r.renest() { + return Err(other("These regions are too complex to combine.")); + } Ok(Some(r)) } From 997f152cea9e3ece7f62f0cf19a866f8e03d706f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:16:56 -0500 Subject: [PATCH 441/900] Extents: share block-bounds memoization across all the entities measured (#2681) Each top-level bounds call started with an empty block cache, so measuring a space's extents or building a spatial-index chunk measured a block definition again for every reference to it: R references to a block of B entities cost R x B. BlockBoundsCache keeps the per-depth block bounds (separately for drawn bounds and extents, which differ on layers turned off) across one bulk operation; Drawing::extents and the spatial index use it (CWE-407). --- crates/doc/src/extents.rs | 82 +++++++++++++++++++++++++++++++++--- crates/doc/src/lib.rs | 7 ++- crates/engine/src/spatial.rs | 8 ++-- 3 files changed, 87 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index d87cdc9a2..e44809df4 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -94,25 +94,48 @@ fn mtext_box(t: &crate::MText) -> Bounds2 { /// The box of what `e` draws (block contents on layers turned off left out). pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 { - bounds_of(d, e, depth, false) + bounds_of(d, e, depth, false, &mut HashMap::new()) } /// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer /// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not). pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 { - bounds_of(d, e, 0, true) + bounds_of(d, e, 0, true, &mut HashMap::new()) } -fn bounds_of(d: &Drawing, e: &Entity, depth: usize, off_counts: bool) -> Bounds2 { +/// The bounds of block contents measured so far, kept across the entities of one unchanged +/// drawing. Measuring many entities with [`entity_bounds_cached`] or [`extent_bounds_cached`] +/// and one cache measures each block definition once per depth for all of them; a fresh cache per +/// entity would measure a block again for every reference to it, R references to a block of B +/// entities costing R x B (CWE-407). Use a cache only while the drawing it measured is unchanged. +#[derive(Default)] +pub struct BlockBoundsCache<'a> { + /// By block name and depth, block contents on layers turned off left out ([`entity_bounds`]). + drawn: HashMap<(&'a str, usize), Bounds2>, + /// The same with those contents counted ([`extent_bounds`]). + extents: HashMap<(&'a str, usize), Bounds2>, +} + +/// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. +pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { + bounds_of(d, e, depth, false, &mut cache.drawn) +} + +/// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`. +pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 { + bounds_of(d, e, 0, true, &mut cache.extents) +} + +fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 { // A top-level annotative object measures as it draws at the current annotation scale. if depth == 0 { match d.anno_draw(e) { crate::AnnoDraw::Plain => {} crate::AnnoDraw::Hidden => return Bounds2::EMPTY, - crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, &mut HashMap::new(), off_counts), + crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts), } } - bounds_in(d, e, depth, &mut HashMap::new(), off_counts) + bounds_in(d, e, depth, blocks, off_counts) } /// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed, @@ -442,4 +465,53 @@ mod tests { empty.text = Some(crate::MText { contents: " ".into(), ..mtext }); assert!(bounds(EntityKind::MLeader(empty)).max.x < 26.0); } + + #[test] + fn a_shared_block_cache_measures_as_a_fresh_one_for_each_entity() { + let line = |a: (f64, f64), b: (f64, f64), layer: &str| { + let mut e = Entity::new(crate::Handle(1), EntityKind::Line(crate::Line { a: Vec3::new(a.0, a.1, 0.0), b: Vec3::new(b.0, b.1, 0.0) })); + e.common.layer = layer.into(); + e + }; + let ins = |block: &str, at: f64| { + Entity::new( + crate::Handle(2), + EntityKind::Insert(crate::Insert { + block: block.into(), + insert: Vec3::new(at, at, 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 mut d = Drawing::new_imperial(); + d.ensure_layer("OFF"); + if let Some(l) = d.layer_mut("OFF") { + l.on = false; + } + // A block with a part on a layer turned off (left out when drawn, counted in extents), + // and a block that nests it. + let mut b = crate::Block::new("B"); + b.entities.push(line((0.0, 0.0), (1.0, 1.0), "0")); + b.entities.push(line((0.0, 0.0), (5.0, 5.0), "OFF")); + d.blocks.insert("B".into(), std::sync::Arc::new(b)); + let mut n = crate::Block::new("N"); + n.entities.push(ins("B", 10.0)); + d.blocks.insert("N".into(), std::sync::Arc::new(n)); + let ents: Vec = (0..50).map(|i| ins(if i % 2 == 0 { "B" } else { "N" }, f64::from(i))).collect(); + // One cache for both kinds of measure, interleaved: neither may answer for the other. + let mut cache = BlockBoundsCache::default(); + for e in &ents { + let (drawn, extents) = (entity_bounds_cached(&d, e, 0, &mut cache), extent_bounds_cached(&d, e, &mut cache)); + let (want_drawn, want_extents) = (entity_bounds(&d, e, 0), extent_bounds(&d, e)); + assert_eq!((drawn.min, drawn.max), (want_drawn.min, want_drawn.max)); + assert_eq!((extents.min, extents.max), (want_extents.min, want_extents.max)); + assert!(extents.width() > drawn.width()); + } + } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8f2a1e2e4..19f486240 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::{BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached}; pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; @@ -383,10 +383,13 @@ impl Drawing { /// Bounds of the entities in a space that count in its extents ([`Drawing::in_extents`]). pub fn extents(&self, space: &Space) -> cadcraft_geom::Bounds2 { let mut b = cadcraft_geom::Bounds2::EMPTY; + // One block-bounds cache for the whole space: every reference to a block reuses its + // measured contents instead of measuring the definition again. + let mut cache = BlockBoundsCache::default(); if let Some(store) = self.space(space) { for e in store.iter() { if self.in_extents(e) { - b = b.union(&extent_bounds(self, e)); + b = b.union(&extent_bounds_cached(self, e, &mut cache)); } } } diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index dd2e0d593..a62537262 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; -use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Space, entity_bounds}; +use cadcraft_doc::{Block, BlockBoundsCache, DimStyle, Drawing, Entity, EntityKind, EntityStore, Space, entity_bounds_cached}; use cadcraft_geom::Bounds2; use rstar::primitives::{GeomWithData, Rectangle}; use rstar::{AABB, RTree}; @@ -44,6 +44,8 @@ struct ChunkIx { impl ChunkIx { fn build(d: &Drawing, key: usize, items: &[Arc]) -> ChunkIx { let mut infinite = Vec::new(); + // One block-bounds cache for the chunk: references to the same block measure it once. + let mut cache = BlockBoundsCache::default(); let bounds = items .iter() .enumerate() @@ -51,7 +53,7 @@ impl ChunkIx { if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) { infinite.push(u32::try_from(i).unwrap_or(u32::MAX)); } - entity_bounds(d, e, 0) + entity_bounds_cached(d, e, 0, &mut cache) }) .collect(); let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -200,7 +202,7 @@ impl SpatialIndex { let (c, l) = self.locate(i)?; c.ents.get(l) } - /// The bounds of the entity at draw index `i` (as [`entity_bounds`] computes them). + /// The bounds of the entity at draw index `i` (as [`cadcraft_doc::entity_bounds`] computes them). pub fn bounds(&self, i: u32) -> Bounds2 { self.locate(i).and_then(|(c, l)| c.bounds.get(l).copied()).unwrap_or(Bounds2::EMPTY) } From c956baa3493743b83c2a389869e0308cd7130f87 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:17:23 -0500 Subject: [PATCH 442/900] constraints: share geometry preparation across an operation and budget spline rebuilds (#2677) Endpoint residuals rebuilt a fit spline through a dense interpolation solve on every evaluation, so many Tangent/Smooth constraints on one spline, or numerical differentiation along other objects' parameters, repeated identical O(n^3) rebuilds; solving had no budget for them. purge_invalid built a fresh model per constraint, re-sampling the same block for every reference, and an Insert naming no block scanned every block definition case-insensitively. - Models built for one operation share a Prep: block samples are taken once per block (in block coordinates, transformed per Insert), block names resolve through a lazily built case-insensitive index, and the last rebuild of each spline is reused at the same defining points. - Comp::run and the Fix redundancy check refuse a system whose per-iteration residual work, including spline rebuilds, exceeds the limit DOF analysis already applied (MAX_EVAL_WORK). - Spline templates keep only what a rebuild reads: no fit points for a control spline, no control net for a fit spline. - purge_invalid validates every constraint with one Prep. --- crates/constraints/src/dof.rs | 44 +++++- crates/constraints/src/lib.rs | 65 ++++++-- crates/constraints/src/model.rs | 255 ++++++++++++++++++++++++-------- 3 files changed, 285 insertions(+), 79 deletions(-) diff --git a/crates/constraints/src/dof.rs b/crates/constraints/src/dof.rs index 559452223..e6128665c 100644 --- a/crates/constraints/src/dof.rs +++ b/crates/constraints/src/dof.rs @@ -11,16 +11,13 @@ use std::collections::HashSet; use cadcraft_doc::{Constraint, Drawing, Handle}; use serde::Serialize; -use crate::model::Model; -use crate::{Comp, MAX_CONSTRAINTS, SolveError, SolveOptions, build_budgeted, lm}; +use crate::model::{Model, Prep}; +use crate::{Comp, MAX_CONSTRAINTS, MAX_EVAL_WORK, SolveError, SolveOptions, build_with, lm}; /// Most free parameters for which per-object freedom is analysed (null-space basis size). const MAX_NULL_COLS: usize = 600; /// Largest Jacobian (rows × columns × min) whose rank is computed. const MAX_RANK_WORK: f64 = 4e8; -/// Largest residual-evaluation work (rows × free × per-residual cost, including spline -/// reconstruction) allowed before building the Jacobian during numerical differentiation. -const MAX_EVAL_WORK: f64 = 2e9; /// Most objects listed in one report. const MAX_OBJECTS: usize = 10_000; @@ -139,8 +136,8 @@ fn plural(n: usize, one: &str, many: &str) -> String { /// (constrained or not) and the constraint components they belong to. pub fn dof(d: &Drawing, handles: &[Handle]) -> Result { let cons: Vec<&Constraint> = d.constraints.iter().take(MAX_CONSTRAINTS).collect(); - let mut members_left = crate::model::MAX_RIGID_WORK; - let (comps, _) = build_budgeted(d, &cons, &SolveOptions::default(), &mut members_left)?; + let mut prep = Prep::new(crate::model::MAX_RIGID_WORK); + let (comps, _) = build_with(d, &cons, &SolveOptions::default(), &mut prep)?; let want = |h: Handle| handles.is_empty() || handles.contains(&h); let mut objects = Vec::new(); let mut seen = HashSet::new(); @@ -179,7 +176,7 @@ pub fn dof(d: &Drawing, handles: &[Handle]) -> Result { if seen.contains(&h) { continue; } - let m = Model::build_budgeted(d, &[h], &mut members_left); + let m = Model::build_with(d, &[h], &mut prep); let Some(s) = m.slots.first() else { continue }; seen.insert(h); free_objects = true; @@ -237,5 +234,36 @@ mod budget_tests { }; let comp = Comp { model, built: vec![endpoint], weights: vec![1.0; 2], held: Vec::new(), tol: 1e-9 }; assert!(analyse(&comp).dof.is_none()); + // Solving it is refused for the same reason, before any Jacobian is built. + assert!(matches!(comp.run(None), Err(SolveError::TooLarge))); + } + + /// Many Tangent constraints on one large fit spline rebuild it once while being interpreted, + /// and the solve is refused by its rebuild budget instead of running. + #[test] + fn repeated_spline_tangents_rebuild_once_and_solve_is_bounded() { + use cadcraft_doc::{Constraint, Line}; + use cadcraft_geom::Vec3; + let mut d = Drawing::default(); + let pts: Vec<_> = (0..400).map(|i| Vec2::new(i as f64, (i % 3) as f64)).collect(); + let h = d.add(&Space::Model, Common::default(), EntityKind::Spline(Spline::fit_with(&pts, false, Default::default()))).unwrap(); + let l = + d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(-1.0, 0.0, 0.0), b: Vec3::new(-1.0, 5.0, 0.0) })).unwrap(); + for id in 1..=200 { + d.constraints.push(Constraint { + id, + kind: ConstraintKind::Tangent, + refs: vec![GeomRef::whole(h), GeomRef::whole(l)], + name: String::new(), + expr: String::new(), + }); + } + let cons: Vec<&Constraint> = d.constraints.iter().collect(); + let (comps, skipped) = crate::build(&d, &cons, &SolveOptions::default()).unwrap(); + assert!(skipped.is_empty()); + let comp = comps.first().unwrap(); + assert_eq!(comp.built.len(), 200); + assert!(matches!(comp.run(None), Err(SolveError::TooLarge))); + assert!(crate::purge_invalid(&mut d).is_empty()); } } diff --git a/crates/constraints/src/lib.rs b/crates/constraints/src/lib.rs index 0bf230323..5b01fc022 100644 --- a/crates/constraints/src/lib.rs +++ b/crates/constraints/src/lib.rs @@ -41,7 +41,7 @@ pub use dof::{DofReport, DofStatus, ObjectDof, dof}; pub use expr::{Env, ExprError}; pub use model::{ref_points, rigid_points, supported}; -use model::Model; +use model::{Model, Prep}; use residual::{Built, Form}; /// Most constraints one drawing may hold. @@ -50,6 +50,11 @@ pub const MAX_CONSTRAINTS: usize = 5000; const MAX_CONFLICT_PROBES: usize = 48; /// Solver iterations. const MAX_ITER: usize = 200; +/// Largest residual-evaluation work (including spline rebuilds) one numerical Jacobian may take, +/// shared by solving, redundancy checks and DOF analysis. +pub(crate) const MAX_EVAL_WORK: f64 = 2e9; +/// Residual evaluations a solver iteration makes besides its Jacobian (damped trial steps). +const TRIAL_EVALS: f64 = 14.0; #[derive(Clone, Debug, PartialEq, thiserror::Error)] pub enum SolveError { @@ -267,12 +272,41 @@ impl Comp { pub(crate) fn rows(&self, skip: Option) -> usize { self.built.iter().enumerate().filter(|(i, _)| Some(*i) != skip).map(|(_, b)| b.rows).sum() } + /// Work of one solver iteration's residual evaluations over `free`: every residual twice per + /// free parameter, plus a spline rebuild each time a spline's own defining points move (rebuilds + /// are shared by residuals at the same points, see [`Model`]). + pub(crate) fn eval_work(&self, free: &[usize], skip: Option) -> f64 { + let rows = self.rows(skip) as f64; + let evals = 2.0 * free.len() as f64 + TRIAL_EVALS; + let mut splines: Vec = Vec::new(); + for (i, b) in self.built.iter().enumerate() { + if Some(i) != skip && b.spline_reconstruct_cost(&self.model) > 0.0 { + splines.extend(b.refs.iter().map(|r| r.handle).filter(|h| self.model.spline_reconstruct_cost(*h) > 0.0)); + } + } + splines.sort_unstable(); + splines.dedup(); + let rebuilds: f64 = splines + .iter() + .filter_map(|h| self.model.slot(*h)) + .map(|s| { + let own = free.iter().filter(|j| (s.off..s.off + s.len).contains(*j)).count() as f64; + (2.0 * own + TRIAL_EVALS + 1.0) * self.model.spline_reconstruct_cost(s.handle) + }) + .sum(); + evals * rows + rebuilds + } fn run(&self, skip: Option) -> Result { let free = self.free(skip); let rows = self.rows(skip); if rows > lm::MAX_ROWS || (rows as f64) * (rows as f64) * (free.len() as f64) > 4e8 { return Err(SolveError::TooLarge); } + // Numerical differentiation rebuilds a fit spline through a dense solve for every move of + // its own fit points: refuse before iterating when that alone is too much (CWE-407). + if self.eval_work(&free, skip) > MAX_EVAL_WORK { + return Err(SolveError::TooLarge); + } let f = |x: &[f64], out: &mut Vec| self.eval(x, out, skip); let mut o = lm::solve(&f, &self.model.x0, &free, &self.weights, self.tol, MAX_ITER); // A solution the ellipses would be stored differently from (axes swapped, minor axis @@ -426,24 +460,24 @@ fn slot_scales(model: &Model, s: &model::Slot) -> Vec<(usize, f64)> { /// Build the component systems. Constraints that cannot be interpreted are returned as skipped. pub(crate) fn build(d: &Drawing, cons: &[&Constraint], opts: &SolveOptions) -> Result<(Vec, Vec<(u32, String)>), SolveError> { - let mut members_left = model::MAX_RIGID_WORK; - build_budgeted(d, cons, opts, &mut members_left) + build_with(d, cons, opts, &mut Prep::new(model::MAX_RIGID_WORK)) } -/// Build constraint components with one caller-owned rigid-member sampling budget shared by every model. +/// Build constraint components sharing one caller-owned geometry preparation (block sampling and +/// its member budget, spline rebuilds) between every model. /// Return constraints that cannot be interpreted as skipped entries. -pub(crate) fn build_budgeted( +pub(crate) fn build_with( d: &Drawing, cons: &[&Constraint], opts: &SolveOptions, - members_left: &mut usize, + prep: &mut Prep, ) -> Result<(Vec, Vec<(u32, String)>), SolveError> { let mut e = env(d); let mut skipped = Vec::new(); let mut comps = Vec::new(); for group in components(cons) { let handles: Vec = group.iter().flat_map(|c| c.refs.iter().map(|r| r.handle)).collect(); - let mut model = Model::build_budgeted(d, &handles, members_left); + let mut model = Model::build_with(d, &handles, prep); let mut built = Vec::new(); for c in group { let target = if c.kind.is_dimensional() { constraint_value(&mut e, c)? } else { 0.0 }; @@ -656,6 +690,11 @@ pub fn all_satisfied(d: &Drawing) -> bool { /// Check that a constraint's references make sense for its type. pub fn validate(d: &Drawing, c: &Constraint) -> Result<(), String> { + validate_with(d, c, &mut Prep::new(model::MAX_RIGID_WORK)) +} + +/// [`validate`] sharing block samples and spline rebuilds with other checks of the same drawing. +fn validate_with(d: &Drawing, c: &Constraint, prep: &mut Prep) -> Result<(), String> { let handles: Vec = c.refs.iter().map(|r| r.handle).collect(); for h in &handles { match d.entity(*h) { @@ -664,7 +703,7 @@ pub fn validate(d: &Drawing, c: &Constraint) -> Result<(), String> { _ => {} } } - let mut model = Model::build(d, &handles); + let mut model = Model::build_with(d, &handles, prep); interpret(c, &mut model, 1.0).map(|_| ()) } @@ -681,7 +720,12 @@ pub fn measure(d: &Drawing, kind: ConstraintKind, refs: &[GeomRef]) -> Result Vec { let mut gone = Vec::new(); - let keep: Vec = d.constraints.iter().map(|c| validate(d, c).is_ok()).collect(); + // One preparation for every check: each block is sampled and each spline rebuilt once, + // however many constraints refer to them (CWE-407). Its member budget is not shared, so + // a constraint is never dropped because earlier ones spent it: every block is still + // examined at most once, up to its own member limit. + let mut prep = Prep::new(usize::MAX); + let keep: Vec = d.constraints.iter().map(|c| validate_with(d, c, &mut prep).is_ok()).collect(); let mut i = 0; d.constraints.retain(|c| { let k = keep.get(i).copied().unwrap_or(true); @@ -768,6 +812,9 @@ pub fn add(d: &mut Drawing, mut c: Constraint, opts: &SolveOptions) -> Result MAX_EVAL_WORK { + return Err(SolveError::TooLarge); + } let after = comp.free(None); let locked: Vec = before.iter().enumerate().filter(|(_, j)| !after.contains(j)).map(|(k, _)| k).collect(); let rows_old = comp.rows(Some(pos)); diff --git a/crates/constraints/src/model.rs b/crates/constraints/src/model.rs index d18646c32..f9ff51fe5 100644 --- a/crates/constraints/src/model.rs +++ b/crates/constraints/src/model.rs @@ -14,9 +14,11 @@ //! Constraints may append auxiliary unknowns after the entity parameters (contact parameters of //! a tangency between curves); they are never written back. +use std::cell::RefCell; use std::collections::HashMap; +use std::rc::Rc; -use cadcraft_doc::{Drawing, EntityKind, GeomRef, Handle, Insert, Sub}; +use cadcraft_doc::{Block, Drawing, EntityKind, GeomRef, Handle, Insert, Sub}; use cadcraft_geom::{Spline as GSpline, Vec2, ccw_sweep}; use crate::curves::{Ell, Frame, clamped, spline_end}; @@ -70,6 +72,9 @@ pub(crate) struct Slot { pub len: usize, } +/// The spline last rebuilt for each handle, with the defining points it was rebuilt from. +type SplineCache = HashMap, Rc)>; + #[derive(Clone, Debug, Default)] pub(crate) struct Model { pub slots: Vec, @@ -79,20 +84,75 @@ pub(crate) struct Model { splines: HashMap, /// Block reference rigid points relative to the insertion point at rotation 0. rigid: HashMap>, + /// Rebuilt splines, shared with every model of the same [`Prep`]: residuals that ask for the + /// same spline at the same defining points (several constraints on one spline, or derivatives + /// taken along other objects' parameters) reuse one rebuild instead of a dense solve each. + rebuilt: Rc>, +} + +/// Geometry preparation shared by every model built for one operation (a solve, a DOF report, a +/// purge): rigid samples per block, a case-insensitive block-name index and rebuilt splines. A +/// block referenced by many Inserts is sampled once, an unknown block name costs one hashed +/// lookup, and a spline referenced by many constraints is rebuilt once (CWE-407). +#[derive(Debug)] +pub(crate) struct Prep { + /// Block members that may still be examined across the operation. + members_left: usize, + /// Block-local rigid samples by the name an Insert gives (`None`: no such block). + blocks: HashMap>>, + /// Lower-cased block name to the stored name it resolves to, built on the first exact miss. + folded: Option>, + rebuilt: Rc>, +} + +impl Prep { + /// Preparation that may examine at most `members` block members in all. + pub(crate) fn new(members: usize) -> Prep { + Prep { members_left: members, blocks: HashMap::new(), folded: None, rebuilt: Rc::default() } + } + + /// The block an Insert names, as [`Drawing::block`] resolves it (exact name, else the first + /// stored name equal ignoring ASCII case), without scanning every block on each miss. + fn resolve<'d>(&mut self, d: &'d Drawing, name: &str) -> Option<&'d Block> { + if let Some(b) = d.blocks.get(name) { + return Some(b); + } + let folded = self.folded.get_or_insert_with(|| { + let mut m = HashMap::with_capacity(d.blocks.len()); + for k in d.blocks.keys() { + m.entry(k.to_ascii_lowercase()).or_insert_with(|| k.clone()); + } + m + }); + d.blocks.get(folded.get(&name.to_ascii_lowercase())?).map(|b| &**b) + } + + /// Finite characteristic points of a block in its own coordinates, sampled once per name. + fn block_points(&mut self, d: &Drawing, name: &str) -> Option> { + if let Some(s) = self.blocks.get(name) { + return s.clone(); + } + let sampled = self.resolve(d, name).map(|b| sample_block(b, &mut self.members_left)); + self.blocks.insert(name.to_string(), sampled.clone()); + sampled + } + + /// World positions of an Insert's rigid points, at most [`MAX_RIGID_POINTS`]. + fn rigid_points(&mut self, d: &Drawing, ins: &Insert) -> Vec { + let Some(local) = self.block_points(d, &ins.block) else { return Vec::new() }; + let Some(block) = self.resolve(d, &ins.block) else { return Vec::new() }; + let m = ins.transform(block.base.xy()); + local.iter().map(|p| m.apply(*p)).filter(|p| p.is_finite()).take(MAX_RIGID_POINTS).collect() + } } impl Model { /// Work for a spline that an endpoint residual actually reconstructs. Fit interpolation /// uses dense Gaussian elimination (cubic); control splines clone and evaluate their template. pub(crate) fn spline_reconstruct_cost(&self, handle: Handle) -> f64 { - let Some(s) = self.splines.get(&handle) else { return 0.0 }; - let n = s.fit.len() as f64; - if fit_mode(s) { - n * n * n - } else { - let n = s.control.len() as f64; - n * n - } + let Some(Shape::Spline { n, fit, .. }) = self.slot(handle).map(|s| s.shape) else { return 0.0 }; + let n = n as f64; + if fit { n * n * n } else { n * n } } } @@ -115,23 +175,18 @@ pub fn supported(kind: &EntityKind) -> bool { /// centres, vertices, nested insertion points) of the block's own objects, at most /// [`MAX_RIGID_POINTS`]. Nested blocks are not entered. pub fn rigid_points(d: &Drawing, ins: &Insert) -> Vec { - let mut members_left = MAX_RIGID_MEMBERS; - rigid_points_budgeted(d, ins, &mut members_left) + Prep::new(MAX_RIGID_MEMBERS).rigid_points(d, ins) } -/// Sample finite block points within per-insert and caller-shared member limits. -/// Members that contribute no points still consume traversal work; nested blocks are not entered. -fn rigid_points_budgeted(d: &Drawing, ins: &Insert, members_left: &mut usize) -> Vec { - let Some(block) = d.block(&ins.block) else { return Vec::new() }; - let m = ins.transform(block.base.xy()); +/// Sample a block's finite characteristic points in block coordinates, within the per-block +/// member limit and the caller-shared `members_left`. Members that contribute no points still +/// consume traversal work; nested blocks are not entered. +fn sample_block(block: &Block, members_left: &mut usize) -> Rc<[Vec2]> { let mut out = Vec::new(); // Bound the members examined, not only the points collected: entities that contribute no - // points (Text, Ray, …) still cost traversal, so a block full of them — scanned again for - // every Insert — would otherwise be unbounded (CWE-407). - let mut examined = 0usize; - for e in block.entities.iter() { - examined += 1; - if out.len() >= MAX_RIGID_POINTS || examined > MAX_RIGID_MEMBERS || *members_left == 0 { + // points (Text, Ray, …) still cost traversal (CWE-407). + for (examined, e) in block.entities.iter().enumerate() { + if out.len() >= MAX_RIGID_POINTS || examined >= MAX_RIGID_MEMBERS || *members_left == 0 { break; } *members_left -= 1; @@ -148,10 +203,10 @@ fn rigid_points_budgeted(d: &Drawing, ins: &Insert, members_left: &mut usize) -> EntityKind::LwPolyline(p) => p.vertices.iter().take(MAX_RIGID_POINTS).map(|v| v.p).collect(), _ => Vec::new(), }; - out.extend(pts.into_iter().map(|p| m.apply(p)).filter(|p| p.is_finite())); + out.extend(pts.into_iter().filter(|p| p.is_finite())); } out.truncate(MAX_RIGID_POINTS); - out + out.into() } /// Constraint points of an object as the solver sees them (`Sub`, position): end points, @@ -187,13 +242,12 @@ fn fit_mode(s: &GSpline) -> bool { impl Model { /// Build a model for the given entities. Unsupported or missing entities are skipped. pub fn build(d: &Drawing, handles: &[Handle]) -> Model { - let mut members_left = MAX_RIGID_WORK; - Self::build_budgeted(d, handles, &mut members_left) + Self::build_with(d, handles, &mut Prep::new(MAX_RIGID_WORK)) } /// Add the parameters of one supported entity to `m`, and return its shape; `None` when it is /// left out (too large, degenerate or unsupported). - fn add_params(m: &mut Model, d: &Drawing, h: Handle, kind: &EntityKind, off: usize, members_left: &mut usize) -> Option { + fn add_params(m: &mut Model, d: &Drawing, h: Handle, kind: &EntityKind, off: usize, prep: &mut Prep) -> Option { let shape = match kind { EntityKind::Line(l) => { m.x0.extend([l.a.x, l.a.y, l.b.x, l.b.y]); @@ -243,15 +297,22 @@ impl Model { // fit point; a control polygon's ends are its first and last points when the // knots are clamped. let ends = !sp.closed && (fit || (clamped(sp, false) && clamped(sp, true))); - // Missing weights default to 1 in eval; only excess weights are unused. - let mut kept = sp.clone(); + // Keep only what rebuilding reads, so each rebuild copies no unused data: missing + // weights default to 1 in eval and only excess weights are unused; a control + // spline's fit points are dropped when its control points move (write_back), and + // a fit spline is rebuilt from its parameters, not from its old control net. + let mut kept = if fit { + GSpline { fit_opts: sp.fit_opts, closed: sp.closed, ..GSpline::default() } + } else { + GSpline { fit: Vec::new(), ..sp.clone() } + }; kept.weights.truncate(kept.control.len()); m.splines.insert(h, kept); Shape::Spline { n, fit, ends } } EntityKind::Insert(ins) => { let base = Vec2::new(ins.insert.x, ins.insert.y); - let pts: Vec = rigid_points_budgeted(d, ins, members_left).into_iter().map(|p| (p - base).rotate(-ins.rotation)).collect(); + let pts: Vec = prep.rigid_points(d, ins).into_iter().map(|p| (p - base).rotate(-ins.rotation)).collect(); m.x0.extend([ins.insert.x, ins.insert.y, ins.rotation]); let n = pts.len(); m.rigid.insert(h, pts); @@ -262,16 +323,17 @@ impl Model { Some(shape) } - /// Build solver parameters for supported entities while sharing rigid-member sampling work with other models. - pub(crate) fn build_budgeted(d: &Drawing, handles: &[Handle], members_left: &mut usize) -> Model { - let mut m = Model::default(); + /// Build solver parameters for supported entities, sharing block sampling, its member budget + /// and spline rebuilds with every other model built from `prep`. + pub(crate) fn build_with(d: &Drawing, handles: &[Handle], prep: &mut Prep) -> Model { + let mut m = Model { rebuilt: Rc::clone(&prep.rebuilt), ..Model::default() }; for &h in handles { if m.index.contains_key(&h) { continue; } let Some(e) = d.entity(h) else { continue }; let off = m.x0.len(); - let Some(shape) = Self::add_params(&mut m, d, h, &e.kind, off, members_left) else { continue }; + let Some(shape) = Self::add_params(&mut m, d, h, &e.kind, off, prep) else { continue }; if m.x0.len() > MAX_PARAMS || m.x0.get(off..).unwrap_or(&[]).iter().any(|v| !v.is_finite()) { m.x0.truncate(off); continue; @@ -373,18 +435,20 @@ impl Model { self.slot(r.handle).is_some_and(|s| matches!(s.shape, Shape::Spline { .. })) } - /// The spline of a reference with the defining points taken from `x`. - fn spline(&self, x: &[f64], s: &Slot) -> Option { + /// The spline of a reference with the defining points taken from `x`. The last rebuild of + /// each spline is kept, so asking again at the same points costs a comparison, not a rebuild. + fn spline(&self, x: &[f64], s: &Slot) -> Option> { let Shape::Spline { n, fit, .. } = s.shape else { return None }; let t = self.splines.get(&s.handle)?; let pts = (0..n).map(|i| p2(x, s.off + 2 * i)).collect::>>()?; - Some(if fit { - t.refit(&pts, t.closed) - } else { - let mut sp = t.clone(); - sp.control = pts; - sp - }) + if let Some((at, sp)) = self.rebuilt.borrow().get(&s.handle) + && *at == pts + { + return Some(Rc::clone(sp)); + } + let sp = Rc::new(if fit { t.refit(&pts, t.closed) } else { GSpline { control: pts.clone(), ..t.clone() } }); + self.rebuilt.borrow_mut().insert(s.handle, (pts, Rc::clone(&sp))); + Some(sp) } /// The start (`at_end` false) or end of a curve reference, in the curve's own direction: @@ -421,7 +485,7 @@ impl Model { let e = self.ell_at(x, o, true)?; e.frame(if at_end { e.t1 } else { e.t0 }) } - (Shape::Spline { ends: true, .. }, Sub::Whole | Sub::Start | Sub::End) => spline_end(&self.spline(x, s)?, at_end), + (Shape::Spline { ends: true, .. }, Sub::Whole | Sub::Start | Sub::End) => spline_end(&*self.spline(x, s)?, at_end), _ => None, } } @@ -590,7 +654,8 @@ impl Model { } let shape = s.shape; // A control-point spline loses its fit data once its control points move. - let spline = self.spline(x, s).map(|mut sp| { + let spline = self.spline(x, s).map(|sp| { + let mut sp = GSpline::clone(&sp); if matches!(shape, Shape::Spline { fit: false, .. }) { sp.fit.clear(); } @@ -712,21 +777,21 @@ mod budget_tests { } } - /// A second model receives no sampled block points after the first model spends the shared member budget. - #[test] - fn rigid_sampling_budget_is_shared_between_models() { - let mut d = Drawing::default(); - let mut block = Block::new("BAR"); - for _ in 0..3 { + fn add_block(d: &mut Drawing, name: &str, lines: usize) { + let mut block = Block::new(name); + for _ in 0..lines { block.entities.push(Entity { handle: d.new_handle(), common: Common::default(), kind: EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }), }); } - d.blocks.insert("BAR".into(), Arc::new(block)); - let ins = Insert { - block: "BAR".into(), + d.blocks.insert(name.into(), Arc::new(block)); + } + + fn insert(block: &str) -> Insert { + Insert { + block: block.into(), insert: Vec3::ZERO, scale: Vec3::new(1.0, 1.0, 1.0), rotation: 0.0, @@ -735,13 +800,79 @@ mod budget_tests { rows: 1, col_spacing: 0.0, row_spacing: 0.0, - }; - let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); - let mut budget = 2; - let first = Model::build_budgeted(&d, &[h], &mut budget); - assert_eq!(first.rigid[&h].len(), 4); - assert_eq!(budget, 0); - let next = Model::build_budgeted(&d, &[h], &mut budget); - assert!(next.rigid[&h].is_empty()); + } + } + + fn add_insert(d: &mut Drawing, block: &str) -> Handle { + d.add(&Space::Model, Common::default(), EntityKind::Insert(insert(block))).unwrap() + } + + /// The member budget is shared by every model of one preparation, and a block it already + /// sampled is reused by later Inserts without examining its members again. + #[test] + fn rigid_sampling_budget_is_shared_and_blocks_sampled_once() { + let mut d = Drawing::default(); + add_block(&mut d, "BAR", 3); + add_block(&mut d, "BAZ", 3); + let (bar, baz, bar2) = (add_insert(&mut d, "BAR"), add_insert(&mut d, "BAZ"), add_insert(&mut d, "BAR")); + let mut prep = Prep::new(2); + let first = Model::build_with(&d, &[bar], &mut prep); + assert_eq!(first.rigid[&bar].len(), 4); + assert_eq!(prep.members_left, 0); + let other = Model::build_with(&d, &[baz], &mut prep); + assert!(other.rigid[&baz].is_empty()); + let again = Model::build_with(&d, &[bar2], &mut prep); + assert_eq!(again.rigid[&bar2].len(), 4); + } + + /// Block names resolve ignoring ASCII case, as `Drawing::block` does, through one index. + #[test] + fn block_names_resolve_ignoring_case() { + let mut d = Drawing::default(); + add_block(&mut d, "Bar", 2); + let (lower, missing) = (add_insert(&mut d, "bAR"), add_insert(&mut d, "nope")); + let mut prep = Prep::new(MAX_RIGID_WORK); + let m = Model::build_with(&d, &[lower, missing], &mut prep); + assert_eq!(m.rigid[&lower].len(), 4); + assert!(m.rigid[&missing].is_empty()); + assert!(prep.folded.as_ref().is_some_and(|f| f.len() == 1)); + assert_eq!(rigid_points(&d, &insert("BAR")).len(), 4); + } + + /// A spline asked for again at the same defining points is not rebuilt, also from another + /// model of the same preparation; moved points rebuild it. + #[test] + fn spline_rebuilds_are_reused_at_the_same_points() { + let mut d = Drawing::default(); + let pts: Vec = (0..6).map(|i| Vec2::new(i as f64, (i % 2) as f64)).collect(); + let h = d.add(&Space::Model, Common::default(), EntityKind::Spline(GSpline::fit_with(&pts, false, Default::default()))).unwrap(); + let mut prep = Prep::new(MAX_RIGID_WORK); + let a = Model::build_with(&d, &[h], &mut prep); + let b = Model::build_with(&d, &[h], &mut prep); + let (sa, sb) = (a.slot(h).unwrap(), b.slot(h).unwrap()); + assert!(matches!(sa.shape, Shape::Spline { fit: true, .. })); + let first = a.spline(&a.x0, sa).unwrap(); + assert!(Rc::ptr_eq(&first, &a.spline(&a.x0, sa).unwrap())); + assert!(Rc::ptr_eq(&first, &b.spline(&b.x0, sb).unwrap())); + let mut moved = a.x0.clone(); + moved[1] += 0.5; + let other = a.spline(&moved, sa).unwrap(); + assert!(!Rc::ptr_eq(&first, &other)); + assert_eq!(other.fit[0], Vec2::new(0.0, 0.5)); + } + + /// A control spline's template keeps no fit points and no excess weights. + #[test] + fn control_template_drops_unused_data() { + let mut d = Drawing::default(); + let mut sp = GSpline::from_control(vec![Vec2::ZERO, Vec2::new(1.0, 2.0), Vec2::new(3.0, 0.0), Vec2::new(4.0, 1.0)], 3); + sp.fit = vec![Vec2::ZERO; 10_000]; + sp.fit_opts.tolerance = 0.5; + sp.weights = vec![1.0; 10_000]; + let h = d.add(&Space::Model, Common::default(), EntityKind::Spline(sp)).unwrap(); + let m = Model::build(&d, &[h]); + let t = &m.splines[&h]; + assert!(t.fit.is_empty()); + assert_eq!(t.weights.len(), 4); } } From 2e9761249a023d45b97436ffe8a31f74595c17d7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 19:22:30 -0700 Subject: [PATCH 443/900] Autosave: keep every folder's lock, and don't let a failure hide or wait (#2676) From review of #2670. Changing SAVEFILEPATH released the old folder's lock while files remained there, so another app could offer a running app's drawings. A write failing while the app was idle waited for the next input to be shown. A second drawing's failure stayed hidden behind a dismissed notice. --- crates/engine/src/autosave.rs | 52 ++++++++++++++++-------- crates/engine/tests/autosave.rs | 30 +++++++++++--- crates/ui-egui/src/autosave.rs | 33 +++++++++++---- crates/ui-egui/tests/autosave_failure.rs | 7 +++- 4 files changed, 93 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index ca6d6ede4..0caac6143 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -166,9 +166,11 @@ pub struct Autosaver { start: std::time::Instant, #[cfg(not(target_arch = "wasm32"))] last_beat: Option, - /// The lock file this app holds the system lock on, open for as long as the lock is wanted. + /// This app's lock files: one per folder, because SAVEFILEPATH can change while files remain + /// in the old folder. Each with the file it holds open for the system lock, or `None` where + /// locks don't work and only the file's age counts. #[cfg(not(target_arch = "wasm32"))] - lock: Option<(std::path::PathBuf, std::fs::File)>, + locks: Vec<(std::path::PathBuf, Option)>, } impl Autosaver { @@ -185,7 +187,7 @@ impl Autosaver { #[cfg(not(target_arch = "wasm32"))] last_beat: None, #[cfg(not(target_arch = "wasm32"))] - lock: None, + locks: Vec::new(), } } @@ -203,9 +205,9 @@ impl Autosaver { self.docs.values().filter_map(|t| t.file.clone()).collect() } - /// Why a drawing currently has no up-to-date recovery copy, for the host to show the user. - pub fn failure(&self) -> Option<&str> { - self.failed.values().next().map(String::as_str) + /// The drawings with no up-to-date recovery copy and why, for the host to show the user. + pub fn failures(&self) -> impl Iterator { + self.failed.iter().map(|(uid, why)| (*uid, why.as_str())) } /// What to do at `now` (seconds, any fixed origin) with SAVETIME `minutes` and autosave folder @@ -471,6 +473,12 @@ mod native { self.running.iter().any(|(_, h)| !h.is_finished()) } + /// Whether a write's result hasn't been taken in yet, finished or not: the host needs + /// another [`Autosaver::tick`] to learn whether it failed. + pub fn results_pending(&self) -> bool { + !self.running.is_empty() + } + /// Take in the writes that have finished ([`Autosaver::tick`] does this first). A drawing /// whose write failed is no longer counted as autosaved: the next plan restarts its clock, /// so it is tried again SAVETIME later even if it doesn't change, and [`Autosaver::failure`] @@ -569,23 +577,32 @@ mod native { } } - /// Refresh the lock file at `path`, taking the system lock on it first if this app doesn't - /// hold it there yet. Without one the file still works by its age. + /// Refresh this app's lock files, and start one at `path` if there isn't one yet, taking + /// the system lock on it if it can. Without that lock the file still works by its age. + /// Only trouble at `path` is an error: an older folder may be gone by now. fn refresh_lock(&mut self, path: &Path) -> std::io::Result<()> { - if let Some((held, file)) = &self.lock - && held == path - { - return file.set_modified(SystemTime::now()); - } - self.lock = None; let id = std::process::id(); + let mut current = None; + for (held, file) in &self.locks { + let refreshed = match file { + Some(file) => file.set_modified(SystemTime::now()), + None => std::fs::write(held, id.to_string()), + }; + if held == path { + current = Some(refreshed); + } + } + if let Some(refreshed) = current { + return refreshed; + } let mut file = OpenOptions::new().write(true).create(true).truncate(false).open(path)?; if file.try_lock().is_err() { + self.locks.push((path.to_path_buf(), None)); return std::fs::write(path, id.to_string()); } file.set_len(0)?; file.write_all(format!("{id}{LOCK_HELD}").as_bytes())?; - self.lock = Some((path.to_path_buf(), file)); + self.locks.push((path.to_path_buf(), Some(file))); Ok(()) } @@ -600,7 +617,10 @@ mod native { discard(&path); } self.docs.clear(); - self.lock = None; + for (path, file) in self.locks.drain(..) { + drop(file); + let _ = std::fs::remove_file(path); + } let dir = savefilepath(); if !dir.is_empty() && is_instance_id(&self.instance) { let _ = std::fs::remove_file(lock_path(Path::new(&dir), &self.instance)); diff --git a/crates/engine/tests/autosave.rs b/crates/engine/tests/autosave.rs index a878faae7..8fd70b6ae 100644 --- a/crates/engine/tests/autosave.rs +++ b/crates/engine/tests/autosave.rs @@ -323,6 +323,26 @@ fn an_emergency_save_finishes_before_it_returns_even_with_savetime_off() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_new_autosave_folder_keeps_the_old_folder_locked() { + hooks(); + let _turn = folder_turn(); + let (old, new) = (temp_dir("moved-old"), temp_dir("moved-new")); + let mut s = Session::new(); + draw(&mut s); + let mut a = Autosaver::new("44-e"); + autosave_once(&mut a, &s, &old); + autosave::set_savefilepath(&new.to_string_lossy()); + draw(&mut s); + assert_eq!(a.emergency_save(&s), 1); + assert!(new.join("44-e.lock").exists()); + assert!(autosave::recoverable(&old, "9-f").is_empty(), "this app is still running"); + a.shutdown(); + assert!(!old.join("44-e.lock").exists() && !new.join("44-e.lock").exists()); + let _ = std::fs::remove_dir_all(&old); + let _ = std::fs::remove_dir_all(&new); +} + #[test] fn a_normal_exit_removes_the_lock_file() { hooks(); @@ -366,7 +386,7 @@ fn a_failed_autosave_is_tried_again_without_another_change() { std::thread::sleep(Duration::from_millis(10)); } assert!(rearmed, "a failed autosave must be tried again"); - assert!(a.failure().is_some_and(|m| m.contains("out")), "{:?}", a.failure()); + assert!(a.failures().next().is_some_and(|(_, why)| why.contains("out"))); std::fs::remove_file(&out).unwrap(); let jobs = a.plan(&s, 180.0, 1, &dir); @@ -387,7 +407,7 @@ fn a_failed_autosave_is_tried_again_without_another_change() { std::thread::sleep(Duration::from_millis(10)); } assert_eq!(a.next_due(1e4, 1), None); - assert_eq!(a.failure(), None, "a write that worked clears the failure"); + assert_eq!(a.failures().next(), None, "a write that worked clears the failure"); a.shutdown(); let _ = std::fs::remove_dir_all(&root); } @@ -407,16 +427,16 @@ fn a_failure_ends_when_the_drawing_no_longer_needs_a_copy() { a.perform(jobs); for _ in 0..500 { a.reap(); - if a.failure().is_some() { + if a.failures().next().is_some() { break; } std::thread::sleep(Duration::from_millis(10)); } - assert!(a.failure().is_some()); + assert!(a.failures().next().is_some()); let i = s.active; s.execute("close", &json!({ "index": i })).unwrap(); a.plan(&s, 120.0, 1, &dir); - assert_eq!(a.failure(), None); + assert_eq!(a.failures().next(), None); a.shutdown(); let _ = std::fs::remove_dir_all(&root); } diff --git a/crates/ui-egui/src/autosave.rs b/crates/ui-egui/src/autosave.rs index 0d50e2dcc..716c27371 100644 --- a/crates/ui-egui/src/autosave.rs +++ b/crates/ui-egui/src/autosave.rs @@ -35,6 +35,9 @@ pub fn load_prefs(json: &str) { /// What the autosave failure notice says (see [`failure_notice`]). #[derive(Clone, Debug, PartialEq)] pub struct AutosaveNotice { + /// The drawings it has told the user about. Another drawing's failure is news, even after + /// the notice was dismissed. + pub reported: std::collections::BTreeSet, pub message: String, /// The user closed it. The failure stays recorded so the notice doesn't come back on every /// retry; it does for the next failure after a write has worked. @@ -100,23 +103,39 @@ impl CadApp { _ctx.request_repaint_after(wait); } #[cfg(not(target_arch = "wasm32"))] - self.note_autosave_failure(_ctx); + { + // A write that fails while the app is idle must still reach the notice. + if self.autosave.as_ref().is_some_and(cadcraft_engine::autosave::Autosaver::results_pending) { + _ctx.request_repaint_after(std::time::Duration::from_secs(1)); + } + self.note_autosave_failure(_ctx); + } } /// Keep [`Self::autosave_notice`] in step with autosave: a new failure is said once at the /// command line and shown until it is dismissed or a write works. #[cfg(not(target_arch = "wasm32"))] fn note_autosave_failure(&mut self, ctx: &egui::Context) { - let failure = self.autosave.as_ref().and_then(|s| s.failure()).map(str::to_string); - match (failure, &mut self.autosave_notice) { - (None, notice) => *notice = None, - (Some(message), Some(n)) => n.message = message, - (Some(message), notice) => { + let failures: Vec<(u64, String)> = self.autosave.iter().flat_map(|s| s.failures()).map(|(uid, why)| (uid, why.to_string())).collect(); + if failures.is_empty() { + self.autosave_notice = None; + return; + } + let notice = + self.autosave_notice.get_or_insert_with(|| AutosaveNotice { reported: Default::default(), message: String::new(), dismissed: false }); + notice.reported.retain(|uid| failures.iter().any(|(failed, _)| failed == uid)); + for (uid, message) in &failures { + if notice.reported.insert(*uid) { self.session.echo(format!("Autosave failed: {message}")); - *notice = Some(AutosaveNotice { message, dismissed: false }); + notice.message.clone_from(message); + notice.dismissed = false; ctx.request_repaint(); } } + // The drawing it names recovered while another still fails. + if let Some((_, message)) = failures.first().filter(|_| !failures.iter().any(|(_, m)| *m == notice.message)) { + notice.message.clone_from(message); + } } /// Every frame: after a GPU error or device loss, autosave unsaved drawings at once (the diff --git a/crates/ui-egui/tests/autosave_failure.rs b/crates/ui-egui/tests/autosave_failure.rs index 28b6a66d0..6e266fedd 100644 --- a/crates/ui-egui/tests/autosave_failure.rs +++ b/crates/ui-egui/tests/autosave_failure.rs @@ -67,7 +67,12 @@ fn a_failed_autosave_is_shown_until_a_write_works() { app.autosave_tick(&ctx); assert!(app.autosave_notice.as_ref().is_some_and(|n| n.dismissed)); assert!(painted_text(&mut app, &ctx).is_empty()); - assert_eq!(said(&app), 1); + + // Another drawing's failure is news, even after the first was dismissed. + app.autosave_notice.as_mut().unwrap().reported.clear(); + app.autosave_tick(&ctx); + assert!(app.autosave_notice.as_ref().is_some_and(|n| !n.dismissed)); + assert_eq!(said(&app), 2); // The folder comes back: the next write clears it. std::fs::remove_file(&dir).unwrap(); From d180b28ef61ca3a5a7dd796611b0b218249ea77a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 21:33:55 -0500 Subject: [PATCH 444/900] Multilines: find each segment's usable neighbour direction in linear time (#2679) * Multilines: find each segment's usable neighbour direction in two linear passes MLine::miters searched the direction array forwards and backwards from every vertex for the nearest non-degenerate segment, so a long run of coincident vertices made it quadratic. The nearest usable directions ahead and behind are now computed once, in one backward and one forward pass (CWE-407). * Multilines: test that a run of coincident vertices at a corner takes the corner's miter --- crates/doc/src/entity/mline.rs | 108 ++++++++++++++++++++++++++++++--- 1 file changed, 98 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/entity/mline.rs b/crates/doc/src/entity/mline.rs index 62ab1d8f3..f6ceef519 100644 --- a/crates/doc/src/entity/mline.rs +++ b/crates/doc/src/entity/mline.rs @@ -207,6 +207,41 @@ pub struct MLineGeometry { pub fill: Vec>, } +/// For each segment direction in `dirs`, the first non-zero direction at or after it and the +/// first at or before it, both wrapping around (`Vec2::X` when every direction is zero). +/// +/// Two linear passes: searching from every segment separately is quadratic in a run of +/// coincident vertices, which a hostile file can make as long as it likes (CWE-407). +fn usable_directions(dirs: &[Vec2]) -> (Vec, Vec) { + let n = dirs.len(); + let (Some(first), Some(last)) = (dirs.iter().position(|d| *d != Vec2::ZERO), dirs.iter().rposition(|d| *d != Vec2::ZERO)) else { + return (vec![Vec2::X; n], vec![Vec2::X; n]); + }; + let (mut ahead, mut behind) = (vec![Vec2::X; n], vec![Vec2::X; n]); + // Walking backwards from the last usable direction, the latest one seen is the next ahead. + let mut cur = Vec2::X; + for k in 0..n { + let i = (last + n - k) % n; + if let Some(d) = dirs.get(i).filter(|d| **d != Vec2::ZERO) { + cur = *d; + } + if let Some(a) = ahead.get_mut(i) { + *a = cur; + } + } + // Walking forwards from the first usable direction, the latest one seen is the nearest behind. + for k in 0..n { + let i = (first + k) % n; + if let Some(d) = dirs.get(i).filter(|d| **d != Vec2::ZERO) { + cur = *d; + } + if let Some(b) = behind.get_mut(i) { + *b = cur; + } + } + (ahead, behind) +} + impl MLine { /// A multiline through `pts` in style `def`. pub fn new(def: &MLineStyle, pts: &[Vec2], closed: bool, just: MLineJust, scale: f64) -> MLine { @@ -268,16 +303,11 @@ impl MLine { let dirs = self.directions(); let n = self.vertices.len(); let nseg = dirs.len(); - // A degenerate segment takes its neighbour's direction. - let dir = |i: usize| -> Vec2 { - (0..nseg).map(|k| dirs.get((i + k) % nseg.max(1)).copied().unwrap_or_default()).find(|d| *d != Vec2::ZERO).unwrap_or(Vec2::X) - }; - let dir_back = |i: usize| -> Vec2 { - (0..nseg) - .map(|k| dirs.get((i + nseg - k % nseg) % nseg.max(1)).copied().unwrap_or_default()) - .find(|d| *d != Vec2::ZERO) - .unwrap_or(Vec2::X) - }; + // A degenerate segment takes its neighbour's direction: the first usable one at or after + // it (`ahead`), or at or before it (`behind`), wrapping around. + let (ahead, behind) = usable_directions(&dirs); + let dir = |i: usize| -> Vec2 { ahead.get(i).copied().unwrap_or(Vec2::X) }; + let dir_back = |i: usize| -> Vec2 { behind.get(i).copied().unwrap_or(Vec2::X) }; let end = |d: Vec2, angle: f64| { let u = d.rotate(angle); let s = angle.sin(); @@ -426,3 +456,61 @@ impl crate::Drawing { self.mline_style(&name).or_else(|| self.mline_style(STANDARD_MLINE_STYLE)).cloned().unwrap_or_default() } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The nearest usable directions found by searching from each segment, as miters did before. + fn searched(dirs: &[Vec2]) -> (Vec, Vec) { + let n = dirs.len(); + let ahead = (0..n).map(|i| (0..n).filter_map(|k| dirs.get((i + k) % n).copied()).find(|d| *d != Vec2::ZERO).unwrap_or(Vec2::X)); + let behind = (0..n).map(|i| (0..n).filter_map(|k| dirs.get((i + n - k) % n).copied()).find(|d| *d != Vec2::ZERO).unwrap_or(Vec2::X)); + (ahead.collect(), behind.collect()) + } + + #[test] + fn usable_directions_match_a_search_from_each_segment() { + let (z, a, b, c) = (Vec2::ZERO, Vec2::Y, -Vec2::X, Vec2::new(0.6, 0.8)); + for dirs in [ + vec![], + vec![z], + vec![a], + vec![z, z, z], + vec![a, z, z, b], + vec![z, a, z, b, z], + vec![z, z, c], + vec![c, z, z], + vec![a, b, c], + vec![z, a, z, z, b, c, z], + ] { + assert_eq!(usable_directions(&dirs), searched(&dirs), "{dirs:?}"); + } + } + + #[test] + fn coincident_vertices_at_a_corner_take_the_corner_miter() { + // Every vertex of a run on one point mitres between the segment before the run and the one after. + let style = MLineStyle::default(); + let corner = MLine::new(&style, &[Vec2::ZERO, Vec2::Y, Vec2::new(-1.0, 1.0)], false, MLineJust::Zero, 1.0); + let pts = [Vec2::ZERO, Vec2::Y, Vec2::Y, Vec2::Y, Vec2::new(-1.0, 1.0)]; + let run = MLine::new(&style, &pts, false, MLineJust::Zero, 1.0); + let (expected, got) = (corner.miters(), run.miters()); + assert_eq!(got.get(1..4), Some(&[expected[1]; 3][..])); + assert_eq!((got.first(), got.last()), (expected.first(), expected.last())); + } + + #[test] + fn a_long_run_of_coincident_vertices_takes_linear_time() { + // 200 000 vertices on one point but the last: the miters must not search the run once per + // vertex (quadratic, minutes) to find the one usable direction. + let mut pts = vec![Vec2::ZERO; 200_000]; + pts.push(Vec2::new(1.0, 0.0)); + let m = MLine::new(&MLineStyle::default(), &pts, false, MLineJust::Zero, 1.0); + let t = std::time::Instant::now(); + let miters = m.miters(); + assert_eq!(miters.len(), pts.len()); + assert!(miters.iter().all(|v| v.is_finite())); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + } +} From e24c4553d2ca715073383720c9e2d7aa0e98f8dd Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 19:47:36 -0700 Subject: [PATCH 445/900] DXF: 100 million group codes by default, and memory for them that can be refused The tag list for a counted ASCII file is reserved once with a fallible allocation, so where the system refuses the memory, opening fails with an error instead of ending the app. Growing it would also take half as much again for a moment. 100 million rather than 150 bounds a crafted 512 MB file to about 4 GB of tags; CADCRAFT_MAX_DXF_TAGS raises it, and the error says so. --- crates/dxf/src/lib.rs | 33 +++++++++++++++++++++++++-------- crates/io/src/tests.rs | 2 +- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index ab2597a21..c31defc21 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -23,8 +23,11 @@ pub enum DxfError { Eof, /// More group codes than [`MAX_TAGS`]: `tags` is the count found (or the count read when the /// limit was reached), `limit` the maximum. - #[error("drawing too large: {tags} DXF group codes, more than the {limit} CADCraft reads")] + #[error("drawing too large: {tags} DXF group codes, more than the {limit} CADCraft reads (set CADCRAFT_MAX_DXF_TAGS to read more)")] TooLarge { tags: usize, limit: usize }, + /// The memory for `tags` group codes couldn't be had: an error, not the process ending. + #[error("not enough memory to read this drawing's {tags} DXF group codes")] + OutOfMemory { tags: usize }, } pub type Result = std::result::Result; @@ -164,10 +167,11 @@ fn typed(code: i32, text: &str) -> Value { const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0"; /// Most group codes read from one file by default. A `Tag` takes 40 bytes plus its text, so this -/// bounds the tag list to roughly 6 GB plus text. It matches the 1 GB DXF rendition a DWG may -/// convert to (a 1 GB DXF holds well over 50 million group codes, so a lower cap rejected large -/// DWGs that converted fine, issue #1948). Set `CADCRAFT_MAX_DXF_TAGS` to raise or lower it. -pub const MAX_TAGS: usize = 150_000_000; +/// bounds the tag list to about 4 GB plus text. 50 million rejected large DWGs that converted fine +/// (a 172 MB drawing has 56 million, issue #1948). The file-size limits bound memory too: 512 MB +/// for a DXF opened directly, 1 GB for a DWG's DXF rendition. Set `CADCRAFT_MAX_DXF_TAGS` to +/// raise or lower it. +pub const MAX_TAGS: usize = 100_000_000; /// Environment variable overriding [`MAX_TAGS`] (a positive integer). pub const MAX_TAGS_ENV: &str = "CADCRAFT_MAX_DXF_TAGS"; @@ -214,7 +218,7 @@ pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result> { if tags > max_tags { return Err(DxfError::TooLarge { tags, limit: max_tags }); } - parse_ascii_with_limit(&codepage::decode_ascii_file(bytes), max_tags) + parse_ascii_counted(&codepage::decode_ascii_file(bytes), max_tags, tags) } /// The four hex digits of a `\U+XXXX` escape starting at `chars[i]`, if there is one. @@ -286,12 +290,17 @@ fn unescape_unicode(s: &str) -> String { } pub fn parse_ascii(text: &str) -> Result> { - parse_ascii_with_limit(text, max_tags()) + parse_ascii_counted(text, max_tags(), 0) } +/// [`parse_ascii`] of a file known to hold `expected` group codes. Their list is reserved first, +/// with an allocation that can fail: where the system refuses that much memory, opening the file +/// is an error instead of the end of the app. Growing the list instead could also briefly take +/// half as much again. #[allow(clippy::while_let_loop)] -fn parse_ascii_with_limit(text: &str, max_tags: usize) -> Result> { +fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result> { let mut tags = Vec::new(); + tags.try_reserve_exact(expected.min(max_tags)).map_err(|_| DxfError::OutOfMemory { tags: expected })?; let mut lines = text.strip_prefix('\u{feff}').unwrap_or(text).lines().enumerate(); loop { let Some((ln, code_line)) = lines.next() else { break }; @@ -807,4 +816,12 @@ mod limit_tests { // Issue #1948: the default must admit a DXF rendition well above 50 million group codes. const { assert!(MAX_TAGS >= 100_000_000) }; } + + #[test] + fn the_tag_list_is_reserved_once_and_a_refusal_is_an_error() { + let tags = parse_ascii_counted("0\nSECTION\n0\nENDSEC\n0\nEOF\n", MAX_TAGS, 3).unwrap(); + assert_eq!((tags.len(), tags.capacity()), (3, 3)); + let e = parse_ascii_counted("0\nEOF\n", usize::MAX, usize::MAX).unwrap_err(); + assert!(matches!(e, DxfError::OutOfMemory { .. }), "{e}"); + } } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 5d08817c5..fca680385 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -1039,7 +1039,7 @@ fn oversized_dwg_and_dxf_are_rejected_early() { // Lines that aren't even group codes: the size is reported before anything is parsed. let text = "not a group code\nx\n".repeat(60); let e = cadcraft_dxf::parse_with_limit(text.as_bytes(), 50).unwrap_err(); - assert_eq!(e.to_string(), "drawing too large: 60 DXF group codes, more than the 50 CADCraft reads"); + assert_eq!(e.to_string(), "drawing too large: 60 DXF group codes, more than the 50 CADCraft reads (set CADCRAFT_MAX_DXF_TAGS to read more)"); } /// Issue #800: one unreadable object record doesn't fail the whole DWG. The reader skips it, the From deca6b1062fc7d723f667853d85fc0ce819c65b3 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 14:25:33 +1100 Subject: [PATCH 446/900] 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 9d83f219102b89cbb10df56146ae6395827b6726 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 20:36:01 -0700 Subject: [PATCH 447/900] Round-trip harness: typed tolerance error, report folders it couldn't read, --out=DIR From review of #2685. The ast-grep string-error rule refused the tolerance parser's String error. A folder the walk couldn't read was skipped silently, so a strict run could pass on part of the corpus; it is now said on stderr and fails a strict run. xtask corpus resolves --out=DIR against the caller's folder, as --out DIR. --- apps/cadcraft-cli/src/args.rs | 6 ++- apps/cadcraft-cli/src/roundtrip.rs | 25 ++++++++++-- crates/io/src/roundtrip/corpus.rs | 62 +++++++++++++++++++++++++----- crates/io/src/roundtrip/tests.rs | 7 ++++ xtask/src/main.rs | 4 ++ 5 files changed, 89 insertions(+), 15 deletions(-) diff --git a/apps/cadcraft-cli/src/args.rs b/apps/cadcraft-cli/src/args.rs index 1df9bacbe..f3b70fdc8 100644 --- a/apps/cadcraft-cli/src/args.rs +++ b/apps/cadcraft-cli/src/args.rs @@ -336,10 +336,10 @@ pub(crate) struct RoundtripArgs { } /// `--tolerance`: a finite number, 0 or more. -fn tolerance(v: &str) -> Result { +fn tolerance(v: &str) -> Result { match v.parse::() { Ok(t) if t.is_finite() && t >= 0.0 => Ok(t), - _ => Err(format!("must be a number >= 0, got `{v}`")), + _ => Err(ValueError::Tolerance(v.to_string())), } } @@ -395,6 +395,8 @@ pub(crate) enum ValueError { CmdId, #[error(transparent)] CmdJson(#[from] serde_json::Error), + #[error("expected a number of 0 or more, got `{0}`")] + Tolerance(String), } /// Why `parse` refuses flags clap accepted: clap prints it as a usage error (exit 2). diff --git a/apps/cadcraft-cli/src/roundtrip.rs b/apps/cadcraft-cli/src/roundtrip.rs index 00f7595ea..8cc4bb11e 100644 --- a/apps/cadcraft-cli/src/roundtrip.rs +++ b/apps/cadcraft-cli/src/roundtrip.rs @@ -19,13 +19,28 @@ pub(crate) enum RoundtripError { Strict(Vec), } +/// What the walk couldn't look at, so the report isn't taken for the whole corpus: said on +/// stderr, and failures of a strict run. +fn left_out(w: &cadcraft_io::roundtrip::corpus::Walk) -> Vec { + let mut out: Vec = w.unreadable.iter().map(|u| format!("not read: {u}")).collect(); + if w.truncated { + out.push("left out: files or folders past the harness limits".to_string()); + } + out +} + pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result { use cadcraft_io::roundtrip::corpus; let path = a.path.clone().or_else(|| std::env::var_os("CADCRAFT_CORPUS_DIR").map(Into::into)).ok_or(RoundtripError::NoPath)?; + let mut missed = Vec::new(); let (root, files, out) = if path.is_dir() { let out = a.out.clone().unwrap_or_else(|| path.join("report")); - let files = corpus::corpus_files(&path, std::slice::from_ref(&out)); - (path, files, out) + let walk = corpus::walk(&path, std::slice::from_ref(&out)); + missed = left_out(&walk); + for m in &missed { + io.errln(format_args!("roundtrip: {m}")); + } + (path, walk.files, out) } else if path.is_file() { let root = path.parent().map(std::path::Path::to_path_buf).unwrap_or_default(); let out = a.out.clone().unwrap_or_else(|| root.join("report")); @@ -34,7 +49,8 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result { return Err(RoundtripError::Missing(path).into()); }; if files.is_empty() { - return Err(RoundtripError::Empty(root).into()); + // A folder it couldn't read isn't an empty one. + return Err(if missed.is_empty() { RoundtripError::Empty(root) } else { RoundtripError::Strict(missed) }.into()); } let mut opts = corpus::CorpusOptions { cross_format: !a.same_format, census: !a.no_census, ..Default::default() }; opts.compare.abs_tol = a.tolerance; @@ -66,7 +82,8 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result { // CADCRAFT_CORPUS_STRICT=1: a file that doesn't open, save or reopen, or records a writer // leaves out, fail the run (the report is written first). if std::env::var("CADCRAFT_CORPUS_STRICT").is_ok_and(|v| v == "1") { - let failed = report.strict_failures(); + let mut failed = report.strict_failures(); + failed.extend(missed); if !failed.is_empty() { return Err(CliError::from(RoundtripError::Strict(failed))); } diff --git a/crates/io/src/roundtrip/corpus.rs b/crates/io/src/roundtrip/corpus.rs index 36895527e..fe5f2abdf 100644 --- a/crates/io/src/roundtrip/corpus.rs +++ b/crates/io/src/roundtrip/corpus.rs @@ -347,27 +347,71 @@ pub fn is_drawing_file(path: &Path) -> bool { /// Every DXF and DWG file under `dir`, sorted, leaving out hidden folders and the folders in /// `skip` (the report folder). Symbolic links are not followed. pub fn corpus_files(dir: &Path, skip: &[PathBuf]) -> Vec { + walk(dir, skip).files +} + +/// What [`walk`] found, and what it couldn't look at, so a report never passes for a whole one. +#[derive(Debug, Default)] +pub struct Walk { + pub files: Vec, + /// Folders and entries that couldn't be read, with why. + pub unreadable: Vec, + /// Files past [`MAX_FILES`] or folders past the depth limit were left out. + pub truncated: bool, +} + +/// [`corpus_files`], also saying what it had to leave out. +pub fn walk(dir: &Path, skip: &[PathBuf]) -> Walk { let skip: Vec = skip.iter().map(|p| p.canonicalize().unwrap_or_else(|_| p.clone())).collect(); - let mut out = Vec::new(); + let mut w = Walk::default(); let mut stack = vec![(dir.to_path_buf(), 0usize)]; while let Some((d, depth)) = stack.pop() { - let Ok(entries) = std::fs::read_dir(&d) else { continue }; - for entry in entries.flatten() { + let entries = match std::fs::read_dir(&d) { + Ok(entries) => entries, + Err(e) => { + w.unreadable.push(format!("{}: {e}", d.display())); + continue; + } + }; + for entry in entries { + let entry = match entry { + Ok(entry) => entry, + Err(e) => { + w.unreadable.push(format!("{}: {e}", d.display())); + continue; + } + }; let path = entry.path(); - let Ok(ft) = entry.file_type() else { continue }; + let ft = match entry.file_type() { + Ok(ft) => ft, + Err(e) => { + w.unreadable.push(format!("{}: {e}", path.display())); + continue; + } + }; if ft.is_dir() { let hidden = entry.file_name().to_string_lossy().starts_with('.'); let canon = path.canonicalize().unwrap_or_else(|_| path.clone()); - if !hidden && depth < MAX_DEPTH && !skip.contains(&canon) { + if hidden || skip.contains(&canon) { + continue; + } + if depth < MAX_DEPTH { stack.push((path, depth + 1)); + } else { + w.truncated = true; + } + } else if ft.is_file() && is_drawing_file(&path) { + if w.files.len() < MAX_FILES { + w.files.push(path); + } else { + w.truncated = true; } - } else if ft.is_file() && is_drawing_file(&path) && out.len() < MAX_FILES { - out.push(path); } } } - out.sort(); - out + w.files.sort(); + w.unreadable.sort(); + w } /// `path` relative to `root`, with forward slashes. diff --git a/crates/io/src/roundtrip/tests.rs b/crates/io/src/roundtrip/tests.rs index 57b77a74a..2107fb48f 100644 --- a/crates/io/src/roundtrip/tests.rs +++ b/crates/io/src/roundtrip/tests.rs @@ -462,6 +462,13 @@ fn report_renders_as_markdown_and_json() { } #[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_folder_it_cannot_read_is_reported_not_skipped() { + let w = corpus::walk(std::path::Path::new("no/such/corpus/folder"), &[]); + assert!(w.files.is_empty()); + assert_eq!(w.unreadable.len(), 1, "{:?}", w.unreadable); +} + #[test] fn corpus_files_walks_folders_and_skips_the_report() { use corpus::corpus_files; diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 8d8d78631..5d8bd5111 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -247,6 +247,10 @@ fn cmd_corpus(args: &[&str]) -> Result<(), String> { let v = it.next().ok_or_else(|| format!("{a} needs a value"))?; pass.extend([a.to_string(), v.to_string()]); } + s if s.starts_with("--out=") => { + let v = s.trim_start_matches("--out="); + pass.extend(["--out".to_string(), here.join(v).display().to_string()]); + } s if s.starts_with("--") => pass.push(s.to_string()), s if dir.is_none() => dir = Some(s.to_string()), _ => return Err("corpus takes one DIR".into()), From a4ff30d11eb97c9a34556f37a8b68e7d2399864a Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 2 Nov 2026 20:49:27 -0700 Subject: [PATCH 448/900] Round-trip harness: never read the kept copies back as corpus files --- apps/cadcraft-cli/src/roundtrip.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/cadcraft-cli/src/roundtrip.rs b/apps/cadcraft-cli/src/roundtrip.rs index 8cc4bb11e..dba9c8d04 100644 --- a/apps/cadcraft-cli/src/roundtrip.rs +++ b/apps/cadcraft-cli/src/roundtrip.rs @@ -35,7 +35,8 @@ pub(crate) fn roundtrip(a: &RoundtripArgs, io: &mut Streams) -> Result { let mut missed = Vec::new(); let (root, files, out) = if path.is_dir() { let out = a.out.clone().unwrap_or_else(|| path.join("report")); - let walk = corpus::walk(&path, std::slice::from_ref(&out)); + // The report folder, and the saved copies in it, are never read back as corpus files. + let walk = corpus::walk(&path, &[out.clone(), out.join("saved")]); missed = left_out(&walk); for m in &missed { io.errln(format_args!("roundtrip: {m}")); From f1790d2be7ed80154c7f614227b367415798aef0 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 14:49:47 +1100 Subject: [PATCH 449/900] 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 31e6e16bc0bc9dc5eed9f87ee6dd7f6a3fb4526d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 22:51:07 -0500 Subject: [PATCH 450/900] constraints: evaluate a named expression without copying its text (#2675) * constraints: evaluate a named expression without copying its text Env::value cloned the stored expression before parse rejected it as too long, and failures are not cached, so an oversized imported expression referenced from many dimensional constraints was copied on every reference. Parse the stored text in place, and keep only a bounded prefix of an over-long expression when it is inserted (it still fails as too long). * constraints: test repeated evaluation of an oversized named expression --- crates/constraints/src/expr.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/constraints/src/expr.rs b/crates/constraints/src/expr.rs index c71ed3486..057ef3e1c 100644 --- a/crates/constraints/src/expr.rs +++ b/crates/constraints/src/expr.rs @@ -284,7 +284,14 @@ impl Env { pub fn new() -> Self { Env::default() } + /// Add or replace a named expression. Text longer than [`MAX_LEN`] could never parse, so + /// only a bounded prefix of it is kept: it still fails (as too long), without the environment + /// holding or copying the whole text. pub fn insert(&mut self, name: &str, expr: &str) { + let expr = match expr.char_indices().map(|(i, _)| i).find(|i| *i > MAX_LEN) { + Some(end) => expr.get(..end).unwrap_or(expr), + None => expr, + }; self.exprs.insert(name.to_string(), expr.to_string()); self.cache.clear(); } @@ -309,8 +316,9 @@ impl Env { if stack.len() >= MAX_DEPTH { return Err(ExprError::TooDeep); } - let text = self.exprs.get(name).cloned().ok_or_else(|| ExprError::Unknown(name.to_string()))?; - let e = parse(&text)?; + // Parse the stored text in place: `parse` refuses an oversized expression before reading + // it, so a long imported expression referenced many times is never copied (CWE-400). + let e = parse(self.exprs.get(name).ok_or_else(|| ExprError::Unknown(name.to_string()))?)?; stack.push(name.to_string()); let r = eval_at_depth(&e, &mut |n, depth| self.value_inner(n, stack, depth), depth); stack.pop(); @@ -400,6 +408,22 @@ mod tests { .unwrap(); } + /// An oversized named expression is kept only as a bounded prefix and still fails, however + /// often it is referenced. + #[test] + fn oversized_named_expression_is_bounded_and_fails() { + let mut env = Env::new(); + let long = format!("1+{}", "é".repeat(500_000)); + env.insert("big", &long); + assert!(env.exprs.get("big").is_some_and(|t| t.len() > MAX_LEN && t.len() <= MAX_LEN + 4)); + assert_eq!(env.value("big"), Err(ExprError::TooDeep)); + for _ in 0..200 { + assert_eq!(env.eval("big"), Err(ExprError::TooDeep)); + } + env.insert("ok", "1+1+1"); + assert_eq!(env.value("ok"), Ok(3.0)); + } + #[test] fn rename_replaces_whole_names_only() { assert_eq!(rename("d1+d10*d1 / (d1_x+2e1)", "d1", "w"), "w+d10*w / (d1_x+2e1)"); From 77142aa79ecaa9c6b9c49120658b4dea93e09dda Mon Sep 17 00:00:00 2001 From: qshh <101165772+qinshah@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:52:31 +0800 Subject: [PATCH 451/900] fonts: scan the Android and HarmonyOS system font directories (#2650) * fonts: scan the Android system font directories System fonts are the only fallback for text whose own font lacks a glyph (CJK in an SHX big font, for example), and Android was falling through to the XDG directories it does not have: a drawing came out in the stroke font with missing-glyph boxes for Chinese. Search /system/fonts and the product and vendor partitions too. The directory list moves out of scan() so the platform's main location is tested directly. * fonts: scan the HarmonyOS system font directories HarmonyOS targets are target_os = "linux" with target_env = "ohos", so they fell into the XDG branch and found no fonts at all: Chinese text in a drawing came out as missing-glyph boxes while the stroke font drew the ASCII around it. Search /system/fonts there too, as on Android. * contributors: add qinshah Credits them by the name on their public GitHub profile. * fonts: document the platform font directories --- contributors/people.toml | 3 +++ crates/fonts/src/ttf.rs | 46 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 994c68bb1..de6d22923 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -102,3 +102,6 @@ sync_github_name = true [people.starise] real_name = "Andrea Brandi" + +[people.qinshah] +sync_github_name = true diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index fff4ecde7..bcf610e0a 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -5,6 +5,11 @@ //! (`Noto Sans CJK TC`) among installed files with a similar name. TrueType collections //! (`.ttc` / `.otc`) are scanned too; a stem lookup takes their first face. //! +//! System fonts are searched in the platform's own directories: `/System/Library/Fonts` and +//! friends on macOS, `C:\Windows\Fonts` on Windows, `/system/fonts` and the product/vendor +//! partitions on Android and HarmonyOS, and the XDG directories elsewhere. Web builds have no +//! system fonts. +//! //! 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. @@ -270,15 +275,20 @@ fn lock() -> MutexGuard<'static, Db> { g } +/// The platform's system font directories, in search order. #[cfg(not(target_arch = "wasm32"))] -fn scan() -> HashMap { - let mut out = HashMap::new(); +fn 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)); if let Some(h) = std::env::var_os("HOME") { dirs.push(PathBuf::from(h).join("Library/Fonts")); } + } else if cfg!(any(target_os = "android", target_env = "ohos")) { + // Android and HarmonyOS keep system fonts under /system/fonts; Android devices also use + // the product and vendor partitions for faces of their own. An app may read all of them, + // and directories a device lacks are skipped. + dirs.extend(["/system/fonts", "/product/fonts", "/system_ext/fonts", "/vendor/fonts"].map(Into::into)); } else if cfg!(windows) { dirs.push("C:\\Windows\\Fonts".into()); if let Some(l) = std::env::var_os("LOCALAPPDATA") { @@ -291,7 +301,14 @@ fn scan() -> HashMap { dirs.push(PathBuf::from(h).join(".local/share/fonts")); } } - let mut stack = dirs; + dirs +} + +/// Every font file under [`font_dirs`], by lower-case file stem. +#[cfg(not(target_arch = "wasm32"))] +fn scan() -> HashMap { + let mut out = HashMap::new(); + let mut stack = font_dirs(); let mut seen = 0usize; while let Some(d) = stack.pop() { let Ok(rd) = std::fs::read_dir(&d) else { continue }; @@ -1080,3 +1097,26 @@ mod geometry_budget_tests { assert!(shaped.text.is_empty()); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod scan_tests { + use super::*; + + /// Each platform searches its own system font directories. A branch that is missing or + /// misnamed leaves a device with no fonts at all, so the platform's main location is checked + /// 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(); + #[cfg(target_os = "macos")] + assert!(dirs.iter().any(|d| d == std::path::Path::new("/System/Library/Fonts")), "{dirs:?}"); + #[cfg(target_os = "android")] + assert!(dirs.iter().any(|d| d == std::path::Path::new("/system/fonts")), "{dirs:?}"); + #[cfg(target_env = "ohos")] + assert!(dirs.iter().any(|d| d == std::path::Path::new("/system/fonts")), "{dirs:?}"); + #[cfg(windows)] + assert!(dirs.iter().any(|d| d == std::path::Path::new("C:\\Windows\\Fonts")), "{dirs:?}"); + #[cfg(all(unix, not(any(target_os = "macos", target_os = "android", target_env = "ohos"))))] + assert!(dirs.iter().any(|d| d == std::path::Path::new("/usr/share/fonts")), "{dirs:?}"); + } +} From 1b7c705face307317158f8afe5600de97647ef4b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 2 Nov 2026 22:52:35 -0500 Subject: [PATCH 452/900] Dynamic blocks: index kept objects once per listing; copy each value record once (#2678) * Dynamic blocks: index kept objects once per listing and copy each value record once Listing blocks rebuilt a handle index of every kept foreign object for each block with an extension dictionary, multiplying the block count by the object count. The listing now builds one ObjectIndex and asks is_dynamic_block_in per block; dynamic_block answers None before indexing when the block has no extension dictionary. templates() copied a value record's tags once per dictionary key, so a record listed under many keys was copied many times, and it looked up each dictionary entry by scanning every object. It now resolves entries through its handle index and copies each record at most once (CWE-400, CWE-407). * Dynamic blocks: list a block as dynamic from its graph object without walking the graph's members --- crates/doc/src/dynblock.rs | 47 ++++++++++++++--- crates/doc/src/dynblock/apply.rs | 53 +++++++++++++++++--- crates/engine/src/cmd/blocks.rs | 5 +- crates/engine/tests/it/dynamic_block_data.rs | 4 ++ 4 files changed, 96 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 392861388..409d403dd 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -323,8 +323,9 @@ impl<'a> Cursor<'a> { } } -/// The objects `xdict`'s `ACAD_ENHANCEDBLOCK` evaluation graph lists, when the dictionary has one. -fn graph_members<'a>(objects: &HashMap, xdict: Handle) -> Option> { +/// `xdict`'s `ACAD_ENHANCEDBLOCK` evaluation graph object, when the dictionary has one. Only the +/// dictionary's own tags are read, so asking whether a block is dynamic never walks the graph. +fn evaluation_graph<'a>(objects: &HashMap, xdict: Handle) -> Option<&'a ForeignObject> { let dict = objects.get(&xdict)?; let mut graph = None; let mut tags = dict.tags.iter(); @@ -334,7 +335,12 @@ fn graph_members<'a>(objects: &HashMap, xdict: Handle break; } } - let graph = objects.get(&graph?).filter(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH"))?; + objects.get(&graph?).copied().filter(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH")) +} + +/// The objects `xdict`'s `ACAD_ENHANCEDBLOCK` evaluation graph lists, when the dictionary has one. +fn graph_members<'a>(objects: &HashMap, xdict: Handle) -> Option> { + let graph = evaluation_graph(objects, xdict)?; let members = section(§ions(&graph.tags), "AcDbEvalGraph").iter().filter(|t| t.code == 360).filter_map(|t| Handle::parse_hex(&t.value)); // Deduplicate member handles before resolving them: a graph can list the same member many // times, and parsing each occurrence into its own owned parameter multiplies a single large @@ -343,13 +349,42 @@ fn graph_members<'a>(objects: &HashMap, xdict: Handle Some(members.take(MAX_NODES).filter(|h| seen.insert(*h)).filter_map(|h| objects.get(&h).copied()).collect()) } +/// The kept foreign objects of a drawing by handle. Building it walks every object, so a caller +/// that asks about many blocks (listing them) builds it once and passes it to +/// [`dynamic_block_in`] and [`is_dynamic_block_in`] instead of rebuilding it per block, which +/// multiplies the block count by the object count (CWE-407). +pub struct ObjectIndex<'a>(HashMap); + +impl<'a> ObjectIndex<'a> { + pub fn new(d: &'a Drawing) -> Self { + ObjectIndex(d.foreign.objects.iter().map(|o| (o.handle, o)).collect()) + } +} + +/// The extension dictionary of block `name`'s record, if it has one. +fn block_xdict(d: &Drawing, name: &str) -> Option { + d.foreign.records.get(&("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()))?.xdict +} + /// The dynamic block data of block `name` (any case; `*Model_Space` for a drawing that is a /// block's own drawing), or `None` when it has none. pub fn dynamic_block(d: &Drawing, name: &str) -> Option { - let xdict = d.foreign.records.get(&("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()))?.xdict?; - let objects: HashMap = d.foreign.objects.iter().map(|o| (o.handle, o)).collect(); + // A block without an extension dictionary is never dynamic: answer before indexing objects. + block_xdict(d, name)?; + dynamic_block_in(d, &ObjectIndex::new(d), name) +} + +/// Whether block `name` is a dynamic block (has an evaluation graph), without reading its +/// parameters and actions; `objects` is the drawing's [`ObjectIndex`]. +pub fn is_dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> bool { + block_xdict(d, name).and_then(|x| evaluation_graph(&objects.0, x)).is_some() +} + +/// [`dynamic_block`] with the drawing's [`ObjectIndex`] already built. +pub fn dynamic_block_in(d: &Drawing, objects: &ObjectIndex<'_>, name: &str) -> Option { + let xdict = block_xdict(d, name)?; let mut out = DynamicBlock::default(); - for o in graph_members(&objects, xdict)? { + for o in graph_members(&objects.0, xdict)? { let secs = sections(&o.tags); let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90); let element = Cursor::new(section(&secs, "AcDbBlockElement")).string(300); diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index ecca36257..c22a6df86 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -54,7 +54,11 @@ fn record_handle(d: &Drawing, name: &str) -> Option { /// The object entry `key` of dictionary `dict` refers to. fn entry(d: &Drawing, dict: Handle, key: &str) -> Option { - let o = d.foreign.objects.iter().find(|o| o.handle == dict)?; + dictionary_entry(d.foreign.objects.iter().find(|o| o.handle == dict)?, key) +} + +/// The object entry `key` (any case) of dictionary object `o` names. +fn dictionary_entry(o: &ForeignObject, key: &str) -> Option { let mut tags = o.tags.iter(); while let Some(t) = tags.next() { if t.code == 3 && t.value.eq_ignore_ascii_case(key) { @@ -66,7 +70,11 @@ fn entry(d: &Drawing, dict: Handle, key: &str) -> Option { /// Every entry of dictionary `dict`: (key, object). fn entries(d: &Drawing, dict: Handle) -> Vec<(String, Handle)> { - let Some(o) = d.foreign.objects.iter().find(|o| o.handle == dict) else { return Vec::new() }; + d.foreign.objects.iter().find(|o| o.handle == dict).map(dictionary_entries).unwrap_or_default() +} + +/// Every entry of dictionary object `o`: (key, object). +fn dictionary_entries(o: &ForeignObject) -> Vec<(String, Handle)> { let mut out = Vec::new(); let mut key: Option<&str> = None; for t in &o.tags { @@ -692,19 +700,33 @@ fn refill_hatches(b: &mut Block) { /// The value records of the references to the dynamic block whose record is `def_record` (from /// any one of them, by graph id): AutoCAD's layout of each record, class ids included. +/// +/// Each record is copied once at most: a key naming a record an earlier key already took is +/// skipped. Records are copied per key (and copied again per key when a new reference's data is +/// made), so a file listing one large record under many keys would otherwise multiply its size by +/// the key count (CWE-400); AutoCAD gives every key its own record. fn templates(d: &Drawing, def_record: Handle) -> HashMap> { let objects: HashMap = d.foreign.objects.iter().map(|o| (o.handle, o)).collect(); + // Dictionary entries looked up through the index, not by scanning every object per + // dictionary (which is quadratic in the object count). + let entry = |dict: Handle, key: &str| objects.get(&dict).and_then(|o| dictionary_entry(o, key)); let mut out: HashMap> = HashMap::new(); + let mut taken: HashSet = HashSet::new(); for rep in d.foreign.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("DICTIONARY")) { // A representation dictionary whose data names this dynamic block. - let Some(rd) = entry(d, rep.handle, "AcDbRepData").and_then(|h| objects.get(&h)) else { continue }; + let Some(rd) = dictionary_entry(rep, "AcDbRepData").and_then(|h| objects.get(&h)) else { continue }; if !rd.tags.iter().any(|t| t.code == 340 && Handle::parse_hex(&t.value) == Some(def_record)) { continue; } - let Some(values) = entry(d, rep.handle, "AppDataCache").and_then(|c| entry(d, c, "ACAD_ENHANCEDBLOCKDATA")) else { continue }; - for (k, h) in entries(d, values) { + let Some(values) = dictionary_entry(rep, "AppDataCache").and_then(|c| entry(c, "ACAD_ENHANCEDBLOCKDATA")) else { continue }; + let Some(values) = objects.get(&values) else { continue }; + for (k, h) in dictionary_entries(values) { + if out.contains_key(&k) || taken.contains(&h) { + continue; + } if let Some(x) = objects.get(&h).filter(|x| x.kind.eq_ignore_ascii_case("XRECORD")) { - out.entry(k).or_insert_with(|| x.tags.clone()); + taken.insert(h); + out.insert(k, x.tags.clone()); } } } @@ -1044,4 +1066,23 @@ mod tests { assert_eq!(by_tag(&d, &def), vec![(10, Handle(1)), (20, Handle(2))]); assert_eq!(by_tag(&d, &anon), vec![(20, Handle(5)), (1_000_001, Handle(6))]); } + + #[test] + fn a_value_record_listed_under_many_keys_is_copied_once() { + // One large XRECORD named by many keys of a reference's value dictionary: the templates + // keep one copy, not one per key. + let mut d = Drawing::new_imperial(); + let (def_record, rep, rd, cache, values, record) = (Handle(0x10), Handle(0x20), Handle(0x21), Handle(0x22), Handle(0x23), Handle(0x24)); + let keys: Vec = (0..1000).map(|i| i.to_string()).collect(); + let entries: Vec<(&str, Handle)> = keys.iter().map(|k| (k.as_str(), record)).collect(); + let f = std::sync::Arc::make_mut(&mut d.foreign); + f.objects.push(dictionary(rep, Handle(1), &[("AcDbRepData", rd), ("AppDataCache", cache)])); + f.objects.push(ForeignObject { handle: rd, kind: "ACDB_BLOCKREPRESENTATION_DATA".into(), tags: vec![tag(340, def_record.hex())] }); + f.objects.push(dictionary(cache, rep, &[("ACAD_ENHANCEDBLOCKDATA", values)])); + f.objects.push(dictionary(values, cache, &entries)); + f.objects.push(ForeignObject { handle: record, kind: "XRECORD".into(), tags: (0..1000).map(|_| tag(1, "x")).collect() }); + let t = templates(&d, def_record); + assert_eq!(t.len(), 1, "one record, one template"); + assert_eq!(t.get("0").map(Vec::len), Some(1000)); + } } diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 258594ff0..45ab8ae15 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -379,8 +379,11 @@ fn run_base(s: &mut Session, p: &Value) -> Result { fn run_list(s: &mut Session, _p: &Value) -> Result { let d = s.doc()?; + // One object index for the whole listing: rebuilding it per block multiplies the block count + // by the drawing's kept object count (CWE-407). + let objects = cadcraft_doc::dynblock::ObjectIndex::new(d); let block = |b: &Block| { - let dynamic = cadcraft_doc::dynblock::dynamic_block(d, &b.name).is_some(); + let dynamic = cadcraft_doc::dynblock::is_dynamic_block_in(d, &objects, &b.name); json!({"name": b.name, "entities": b.entities.len(), "base": [b.base.x, b.base.y], "description": b.description, "dynamic": dynamic}) }; Ok(json!({ "blocks": d.blocks.values().filter(|b| !b.anonymous).map(|b| block(b)).collect::>() })) diff --git a/crates/engine/tests/it/dynamic_block_data.rs b/crates/engine/tests/it/dynamic_block_data.rs index 5b4cb11e3..2e3f0baaa 100644 --- a/crates/engine/tests/it/dynamic_block_data.rs +++ b/crates/engine/tests/it/dynamic_block_data.rs @@ -83,6 +83,10 @@ fn blocks_without_dynamic_data_and_bad_names() { s.execute("block", &json!({ "name": "Window", "base": [0, 0], "handles": [l] })).unwrap(); assert_eq!(s.execute("blocks.dynamic", &json!({ "name": "Window" })).unwrap(), json!(null)); assert_eq!(s.execute("blocks.dynamic", &json!({ "name": "*Model_Space" })).unwrap(), json!(null)); + let list = s.execute("blocks.list", &json!({})).unwrap(); + let flags: Vec<_> = list["blocks"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap().to_string(), b["dynamic"].clone())).collect(); + assert!(flags.contains(&("Window".into(), json!(false))), "{flags:?}"); + assert!(flags.contains(&("Door".into(), json!(true))), "{flags:?}"); for p in [json!({}), json!({ "name": 3 }), json!({ "name": "Nope" }), json!(null)] { assert!(s.execute("blocks.dynamic", &p).is_err(), "{p}"); } From 455b2a87cb2df9cbc67b7edec09c2c94e9c8358f Mon Sep 17 00:00:00 2001 From: Tyler Chiriboga Date: Mon, 2 Nov 2026 21:52:39 -0600 Subject: [PATCH 453/900] EXTEND: a polyline's arc end segment runs on round its circle (#2656) EXTEND on an open polyline ran a ray along the chord of an arc end segment and kept the old bulge, so the arc changed radius and centre, or the boundary was reported missed when only the circle reached it. The arc end segment now runs on round its own circle to the nearest crossing ahead, turning the same way, and its bulge becomes that of the total turn, as EXTEND does with an ARC. The polyline also keeps its constant width, elevation and linetype generation, which the rebuilt polyline dropped. Co-authored-by: Tyler Chiriboga <18270301+Tyler-Chiriboga@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/modify/trim.rs | 60 ++++++-- .../tests/it/extend_polyline_arc_end.rs | 137 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + 3 files changed, 187 insertions(+), 11 deletions(-) create mode 100644 crates/engine/tests/it/extend_polyline_arc_end.rs diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 66eab0be8..9f8e856dd 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -283,6 +283,28 @@ pub(super) fn param_on(s: &Segment, p: Vec2) -> f64 { } } +/// 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 +/// new end point and the segment's new bulge. `None` when no edge crosses the rest of the circle. +fn extend_arc_segment(ga: &Arc, end: Vec2, sweep: f64, cut: &[Segment]) -> Option<(Vec2, f64)> { + let full = Segment::Arc { arc: Arc { start: 0.0, end: TAU - 1e-12, ..*ga }, ccw: true }; + let a_end = ga.center.angle_to(end); + let ccw = sweep > 0.0; + // How far past `end` each crossing is, turning the way the segment turns; crossings on the + // segment itself (the last |sweep| of a turn) are not ahead of it. + let (x, more) = cut + .iter() + .flat_map(|c| intersect_ext(&full, c, false)) + .map(|x| { + let a = ga.center.angle_to(x); + (x, norm_angle(if ccw { a - a_end } else { a_end - a })) + }) + .filter(|(_, more)| *more > 1e-9 && *more + sweep.abs() < TAU - 1e-9) + .min_by(|a, b| a.1.total_cmp(&b.1))?; + let total = sweep.abs() + more; + Some((x, cadcraft_geom::arc_to_bulge(if ccw { total } else { -total }))) +} + /// Extend the end of `h` nearest `pick` to the nearest boundary edge. pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<()> { if crate::cmd::curves::is_locked(s, h) { @@ -326,18 +348,34 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re 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(); - let dir = (end - prev).normalized(); - let ray = Segment::Line(Line::new(end, end + dir * 1e8)); - let np = cut - .iter() - .flat_map(|c| intersect_ext(&ray, c, false)) - .filter(|x| (*x - end).dot(dir) > 1e-9) - .min_by(|x, y| x.dist(end).total_cmp(&y.dist(end))) - .ok_or_else(|| EngineError::Other("Object does not intersect an edge.".into()))?; - if let Some(v) = vs.get_mut(i_end) { - v.p = np; + // The end segment's bulge, signed for travel from `prev` out to `end`. + let i_seg = if from_end { i_prev } else { i_end }; + let bulge = vs.get(i_seg).map_or(0.0, |v| if from_end { v.bulge } else { -v.bulge }); + let none = || EngineError::Other("Object does not intersect an edge.".into()); + if let Some((ga, _)) = cadcraft_geom::bulge_to_arc(prev, end, bulge) { + // An arc end segment runs on round its circle, as an arc does. + let (np, b) = extend_arc_segment(&ga, end, 4.0 * bulge.atan(), &cut).ok_or_else(none)?; + if let Some(v) = vs.get_mut(i_end) { + v.p = np; + } + if let Some(v) = vs.get_mut(i_seg) { + v.bulge = if from_end { b } else { -b }; + } + } else { + let dir = (end - prev).normalized(); + let ray = Segment::Line(Line::new(end, end + dir * 1e8)); + let np = cut + .iter() + .flat_map(|c| intersect_ext(&ray, c, false)) + .filter(|x| (*x - end).dot(dir) > 1e-9) + .min_by(|x, y| x.dist(end).total_cmp(&y.dist(end))) + .ok_or_else(none)?; + if let Some(v) = vs.get_mut(i_end) { + v.p = np; + } } - lwpoly(vs, false) + // Width, elevation and linetype generation stay as they were. + EntityKind::LwPolyline(cadcraft_doc::LwPolyline { vertices: vs, ..p.clone() }) } k => crate::cmd::modify2::extend_other(k, &cut, pick)?, }; diff --git a/crates/engine/tests/it/extend_polyline_arc_end.rs b/crates/engine/tests/it/extend_polyline_arc_end.rs new file mode 100644 index 000000000..496187767 --- /dev/null +++ b/crates/engine/tests/it/extend_polyline_arc_end.rs @@ -0,0 +1,137 @@ +//! EXTEND on an open polyline whose end segment is an arc: the arc runs on round its own circle +//! to the boundary, as EXTEND does with an ARC, instead of the end vertex sliding along the chord +//! with the old bulge (which changed the arc's radius and centre, or missed the boundary). The +//! polyline keeps its width, elevation and linetype generation. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Common, Entity, EntityKind, Handle, LwPolyline}; +use cadcraft_engine::geom::{PolyVertex, Vec2}; +use serde_json::json; + +const TOL: f64 = 1e-9; + +fn add(s: &mut Session, kind: EntityKind) -> String { + 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::default(), kind }); + handle.hex() +} + +fn v(x: f64, y: f64, bulge: f64) -> PolyVertex { + PolyVertex { p: Vec2::new(x, y), bulge, ..Default::default() } +} + +fn pline(vertices: Vec) -> LwPolyline { + LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false } +} + +fn edge(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String { + let r = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + r["handles"][0].as_str().unwrap().to_string() +} + +fn polyline(s: &Session, h: &str) -> LwPolyline { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::LwPolyline(p) => p.clone(), + k => panic!("not a polyline: {k:?}"), + } +} + +fn near(a: Vec2, x: f64, y: f64) -> bool { + (a.x - x).abs() < 1e-6 && (a.y - y).abs() < 1e-6 +} + +/// tan(22.5°): the bulge of a quarter circle. +fn quarter() -> f64 { + (std::f64::consts::PI / 8.0).tan() +} + +/// The bulge of an arc turning through `deg` degrees (positive counterclockwise). +fn bulge(deg: f64) -> f64 { + (deg.to_radians() / 4.0).tan() +} + +#[test] +fn a_counterclockwise_arc_at_the_end_runs_on_round_its_circle() { + let mut s = Session::new(); + let e = edge(&mut s, [-50.0, -5.0], [50.0, -5.0]); + // A line in from (20,0), then a quarter circle about the origin from (10,0) to (0,10). + let mut pl = pline(vec![v(20.0, 0.0, 0.0), v(10.0, 0.0, quarter()), v(0.0, 10.0, 0.0)]); + pl.const_width = 0.5; + pl.elevation = 3.0; + pl.plinegen = true; + let h = add(&mut s, EntityKind::LwPolyline(pl)); + s.execute("extend", &json!({ "handle": h, "pick": [0.5, 9.9], "edges": [e] })).unwrap(); + let p = polyline(&s, &h); + assert_eq!(p.vertices.len(), 3); + // Round the circle (radius 10) through (-10,0) to y = -5: a 210° turn in all. + let end = p.vertices[2].p; + assert!(near(end, -(75.0f64.sqrt()), -5.0), "end {end:?}"); + assert!((p.vertices[1].bulge - bulge(210.0)).abs() < TOL, "bulge {}", p.vertices[1].bulge); + assert!(near(p.vertices[0].p, 20.0, 0.0) && near(p.vertices[1].p, 10.0, 0.0)); + assert_eq!((p.const_width, p.elevation, p.plinegen), (0.5, 3.0, true)); +} + +#[test] +fn an_arc_at_the_start_runs_on_backwards_round_its_circle() { + let mut s = Session::new(); + let e = edge(&mut s, [-50.0, -5.0], [50.0, -5.0]); + // The same path drawn the other way: clockwise from (0,10) to (10,0), then out to (20,0). + let h = add(&mut s, EntityKind::LwPolyline(pline(vec![v(0.0, 10.0, -quarter()), v(10.0, 0.0, 0.0), v(20.0, 0.0, 0.0)]))); + s.execute("extend", &json!({ "handle": h, "pick": [0.5, 9.9], "edges": [e] })).unwrap(); + let p = polyline(&s, &h); + assert!(near(p.vertices[0].p, -(75.0f64.sqrt()), -5.0), "start {:?}", p.vertices[0].p); + assert!((p.vertices[0].bulge + bulge(210.0)).abs() < TOL, "bulge {}", p.vertices[0].bulge); + assert!(near(p.vertices[1].p, 10.0, 0.0) && near(p.vertices[2].p, 20.0, 0.0)); +} + +#[test] +fn a_clockwise_arc_at_the_end_runs_on_clockwise() { + let mut s = Session::new(); + let e = edge(&mut s, [-50.0, 5.0], [50.0, 5.0]); + // Clockwise about the origin from (10,0) to (0,-10); on round through (-10,0) to y = 5. + let h = add(&mut s, EntityKind::LwPolyline(pline(vec![v(20.0, 0.0, 0.0), v(10.0, 0.0, -quarter()), v(0.0, -10.0, 0.0)]))); + s.execute("extend", &json!({ "handle": h, "pick": [0.5, -9.9], "edges": [e] })).unwrap(); + let p = polyline(&s, &h); + assert!(near(p.vertices[2].p, -(75.0f64.sqrt()), 5.0), "end {:?}", p.vertices[2].p); + assert!((p.vertices[1].bulge + bulge(210.0)).abs() < TOL, "bulge {}", p.vertices[1].bulge); +} + +#[test] +fn the_nearest_crossing_ahead_on_the_circle_wins() { + let mut s = Session::new(); + // A boundary crossing the circle twice ahead of the end: x = -6 at about 127° and 233°. + let e = edge(&mut s, [-6.0, -50.0], [-6.0, 50.0]); + let h = add(&mut s, EntityKind::LwPolyline(pline(vec![v(20.0, 0.0, 0.0), v(10.0, 0.0, quarter()), v(0.0, 10.0, 0.0)]))); + s.execute("extend", &json!({ "handle": h, "pick": [0.5, 9.9], "edges": [e] })).unwrap(); + let p = polyline(&s, &h); + assert!(near(p.vertices[2].p, -6.0, 8.0), "end {:?}", p.vertices[2].p); + let turn = 8.0f64.atan2(-6.0).to_degrees(); + assert!((p.vertices[1].bulge - bulge(turn)).abs() < TOL, "bulge {}", p.vertices[1].bulge); +} + +#[test] +fn an_arc_end_whose_circle_misses_every_edge_is_left_alone() { + let mut s = Session::new(); + // The chord (10,0)→(0,10) runs on to this edge, but the circle never reaches it. + let e = edge(&mut s, [-50.0, 30.0], [50.0, 30.0]); + let before = pline(vec![v(20.0, 0.0, 0.0), v(10.0, 0.0, quarter()), v(0.0, 10.0, 0.0)]); + let h = add(&mut s, EntityKind::LwPolyline(before.clone())); + assert!(s.execute("extend", &json!({ "handle": h, "pick": [0.5, 9.9], "edges": [e] })).is_err()); + assert_eq!(polyline(&s, &h), before); +} + +#[test] +fn a_straight_end_keeps_the_polyline_width_and_elevation() { + let mut s = Session::new(); + let e = edge(&mut s, [50.0, -50.0], [50.0, 50.0]); + let mut pl = pline(vec![v(0.0, 0.0, 0.0), v(10.0, 0.0, 0.0)]); + pl.const_width = 0.5; + pl.elevation = 3.0; + let h = add(&mut s, EntityKind::LwPolyline(pl)); + s.execute("extend", &json!({ "handle": h, "pick": [9.0, 0.0], "edges": [e] })).unwrap(); + let p = polyline(&s, &h); + assert!(near(p.vertices[1].p, 50.0, 0.0), "end {:?}", p.vertices[1].p); + assert_eq!((p.const_width, p.elevation), (0.5, 3.0)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 38fb4d005..b6ec02d60 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -46,6 +46,7 @@ mod draworder; mod dyn_input; mod dynamic_block_data; mod dynamic_grips; +mod extend_polyline_arc_end; mod fillet_chamfer; mod fix_holds_grips; mod followups_626; From 7b6be7835f29e427aa2c785e8afcbe01c9082996 Mon Sep 17 00:00:00 2001 From: Thiago Matheus Campelo Ferreira <133534183+euthiferreira@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:53:20 -0300 Subject: [PATCH 454/900] fix(io): a solid HATCH keeps its angle, scale and double flag (#2665) * fix(io): a solid HATCH keeps its angle, scale and double flag The writer wrote groups 52 (angle), 41 (scale) and 77 (double) for pattern fills only, so a SOLID hatch read with them lost them on save. Write them for solid fills too, as read. Co-Authored-By: Claude Opus 5.5 * test(io): fixture for a solid HATCH keeps angle, scale and double flag Add a synthetic DXF with a SOLID and an ANSI31 hatch and a test that saves it and compares groups 52, 41 and 77 of each hatch by handle. Co-Authored-By: Claude Haiku 5.5 * docs(io): document the functions this change touches Add doc comments to the functions the diff changes whose complexity is above one, so the docstring coverage check passes. Co-Authored-By: Claude Haiku 5.5 * Drop the DXF fixture: the inline test covers the fix; test data belongs in a corpus repo Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/io/src/dxf_write/entity.rs | 11 ++++++++--- crates/io/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index ee9c18d33..6e1d84270 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -600,6 +600,9 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap } } +/// Writes a HATCH: its pattern name, solid and associative flags, its boundary loops, and the +/// pattern angle, scale and double flag (written for solid hatches too). Pattern lines are written +/// only for non-solid hatches. fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, _cx: &Ctx) { if let EntityKind::Hatch(h) = &e.kind { w.s(0, "HATCH"); @@ -634,10 +637,12 @@ fn write_hatch_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo } w.i(75, i64::from(h.style)); w.i(76, 1); + // Angle, scale and double flag are written for solid fills too, as read (AutoCAD and + // other writers keep them on SOLID hatches; readers ignore them there). + w.f(52, h.angle.to_degrees()); + w.f(41, h.scale); + w.i(77, 0); if !h.solid { - w.f(52, h.angle.to_degrees()); - w.f(41, h.scale); - w.i(77, 0); // The lines read from the file, else the library's pattern of that name. let lines = if h.pattern_lines.is_empty() { cadcraft_doc::library::pattern_for(d, &h.pattern).map(|p| p.lines).unwrap_or_default() diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index fca680385..46536f24e 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2896,3 +2896,19 @@ fn non_unicode_names_pick_the_format_by_extension() { assert!(write(&d, name("png")).unwrap().starts_with(b"\x89PNG")); assert!(write(&d, name("dwt")).is_ok(), "a template is written as DWG"); } + +/// A SOLID hatch keeps its angle (52), scale (41) and double flag (77) through a save: the writer +/// wrote them for pattern fills only. +#[test] +fn solid_hatch_keeps_angle_scale_and_double_flag() { + let src = "0\nSECTION\n2\nENTITIES\n0\nHATCH\n5\n40\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n2\nSOLID\n70\n1\n71\n0\n\ +91\n1\n92\n2\n72\n0\n73\n1\n93\n4\n10\n0\n20\n0\n10\n40\n20\n0\n10\n40\n20\n40\n10\n0\n20\n40\n97\n0\n\ +75\n0\n76\n1\n52\n30\n41\n2\n77\n0\n98\n0\n0\nENDSEC\n0\nEOF\n"; + let out = write_dxf(&read_dxf(src.as_bytes()).unwrap()); + let pairs = dxf_pairs(&out); + let h = dxf_records(&pairs, "HATCH")[0]; + let f = |code: &str| group(h, code).and_then(|v| v.parse::().ok()); + assert!(f("52").is_some_and(|a| (a - 30.0).abs() < 1e-9), "{h:?}"); + assert!(f("41").is_some_and(|s| (s - 2.0).abs() < 1e-12), "{h:?}"); + assert_eq!(group(h, "77"), Some("0"), "{h:?}"); +} From 4c00f8b9e3fa2515986f62809a5cf80f038a46d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=81=E4=BC=AA?= <56018602+r4x2t7@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:53:24 +0800 Subject: [PATCH 455/900] FIND: a Find and Replace window, not only the command line (#2607) * FIND: report the text around each match The result list needs to show what matched, not just its handle, so each entry now carries a snippet of the text around the first hit, the hit's offset in it and its length. Offsets count characters, not bytes, so a Chinese or Vietnamese drawing never splits a glyph. Two optional parameters let a window search part of the space: `types` narrows the search by object type name and `handles` limits it to the objects a caller has already listed, which is what makes replacing a single row possible. Both default to the old behaviour, so scripts, LISP and the MCP server get the answer they always got. * FIND: a Find and Replace window FIND only had a command line: it asked for the text, ran, and printed a count, and the palette's Find and Replace tile opened the same prompt. The answer lived in the drawing and the place to read it was the command line. This adds a window behind the same command. The result list shows each object with the hit lit up, a click selects that object and zooms to it, Replace edits the row under the cursor and Replace All the rows on the list. The window stays open while the drawing is edited, because finding and replacing is a loop: look, locate, edit, look again. A JSON call carries its parameters, so scripts, LISP and the MCP server still get the engine's answer; only the bare command opens the window. Cmd+F reaches it from anywhere, and the twenty labels it adds are in every interface language. * FIND: clear the window's state when it closes or the drawing changes The result rows hold handles, and a handle only means something in the drawing it was found in. The state now lives exactly as long as the window does, and an epoch change while the window sits open clears the rows instead of letting Replace All edit an object the search never matched. A successful replacement keeps the engine's replacement report rather than letting the re-search overwrite it with a match count. * FIND: an empty replacement is a deletion, and stale rows die on any change Replacing with nothing deletes the matched text, which is a legitimate replacement, so the buttons no longer require text in the Replace field. The result rows answer one question - this text, with these switches, in this drawing and space. Editing the search term or either switch now clears the rows and owes a fresh search, and so does switching between model space and a layout: a handle means nothing outside the space it was found in. * rustfmt: sort the module list after the merge Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/utility.rs | 107 ++++++++++- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/finddlg.rs | 294 ++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.tsv | 12 ++ crates/ui-egui/src/i18n/bs.tsv | 12 ++ crates/ui-egui/src/i18n/cs.tsv | 12 ++ crates/ui-egui/src/i18n/de.tsv | 12 ++ crates/ui-egui/src/i18n/el.tsv | 12 ++ crates/ui-egui/src/i18n/es.tsv | 12 ++ crates/ui-egui/src/i18n/fr.tsv | 12 ++ crates/ui-egui/src/i18n/hu.tsv | 12 ++ crates/ui-egui/src/i18n/it.tsv | 12 ++ crates/ui-egui/src/i18n/ko.tsv | 12 ++ crates/ui-egui/src/i18n/pt_br.tsv | 12 ++ crates/ui-egui/src/i18n/ru.tsv | 12 ++ crates/ui-egui/src/i18n/sv.tsv | 12 ++ crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/tr.tsv | 12 ++ crates/ui-egui/src/i18n/uk.tsv | 12 ++ crates/ui-egui/src/i18n/vi.tsv | 12 ++ crates/ui-egui/src/i18n/zh.tsv | 12 ++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus.rs | 11 +- 23 files changed, 616 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/finddlg.rs diff --git a/crates/engine/src/cmd/utility.rs b/crates/engine/src/cmd/utility.rs index 97678ae24..8faab4f9c 100644 --- a/crates/engine/src/cmd/utility.rs +++ b/crates/engine/src/cmd/utility.rs @@ -26,7 +26,10 @@ pub fn specs() -> Vec { .params("{mode: point|distance|angle|intersection, points: [[x,y],...]} → {value} | {point}") .noundo() .interactive(|_| Ok(Box::::default())), - CommandSpec::new("find", "Find...", run_find).menu(&["Edit", "Find..."]).params("{find, replace?, matchCase?: bool, wholeWord?: bool}"), + CommandSpec::new("find", "Find...", run_find).menu(&["Edit", "Find..."]).params( + "{find, replace?, matchCase?: bool, wholeWord?: bool, types?: [\"Text\", \"MText\", ...], handles?: [...]} → \ + {matches: [{handle, type, count, snippet, hit, hitLen}], total, message}", + ), CommandSpec::new("measuregeom", "Measure Geometry", run_measuregeom) .params("{mode: distance|radius|angle|area|volume, ...}") .noundo() @@ -194,6 +197,46 @@ fn run_quickcalc_pick(s: &mut Session, p: &Value) -> Result { // ---------------- FIND ---------------- +/// Characters of context kept on each side of a hit in the Find dialog's result list. +const SNIPPET_CONTEXT: usize = 18; + +/// The text around the first hit of `find` in `text`, for the result list: at most +/// [`SNIPPET_CONTEXT`] characters before the hit and as many after it, the hit's offset in the +/// snippet (in characters) and its length (in characters). +/// +/// The offset and length are character counts, not bytes: the dialog slices the snippet by +/// character so a Chinese or Vietnamese drawing never splits a glyph. Lower-casing can change a +/// string's character count in rare scripts, so every slice goes through `get` and a snippet that +/// cannot be cut is reported as absent rather than guessed at. +fn snippet_at(text: &str, find: &str, case: bool, whole: bool) -> Option<(String, usize, usize)> { + if find.is_empty() { + return None; + } + let (hay, needle) = if case { (text.to_string(), find.to_string()) } else { (text.to_lowercase(), find.to_lowercase()) }; + let mut at = 0; + let pos = loop { + let rest = hay.get(at..)?; + let p = rest.find(&needle)? + at; + let end = p + needle.len(); + let boundary = |i: usize| hay.get(..i).and_then(|s| s.chars().last()).is_none_or(|c| !c.is_alphanumeric()); + let after = hay.get(end..).and_then(|s| s.chars().next()).is_none_or(|c| !c.is_alphanumeric()); + if !whole || (boundary(p) && after) { + break p; + } + at = end.max(p + 1); + if at >= hay.len() { + return None; + } + }; + let start = hay.get(..pos)?.chars().count(); + let hit_len = needle.chars().count(); + let chars: Vec = text.chars().collect(); + let from = start.saturating_sub(SNIPPET_CONTEXT); + let to = start.saturating_add(hit_len).saturating_add(SNIPPET_CONTEXT).min(chars.len()); + let snippet: String = chars.get(from..to)?.iter().collect(); + Some((snippet, start.saturating_sub(from), hit_len)) +} + fn replace_in(text: &str, find: &str, rep: &str, case: bool, whole: bool) -> (String, usize) { if find.is_empty() { return (text.to_string(), 0); @@ -228,21 +271,40 @@ fn run_find(s: &mut Session, p: &Value) -> Result { let rep = str_param(p, "replace").map(str::to_string); let case = bool_or(p, "matchCase", false); let whole = bool_or(p, "wholeWord", false); + // Only the named object types, when the dialog narrows the search; `type_name()` is the same + // name the result list shows, so a caller never has to guess the spelling. + let types: Option> = + p.get("types").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_ascii_lowercase).collect()); let space = s.space(); let d = s.doc()?; - let hs: Vec = d.space(&space).map(|st| st.handles()).unwrap_or_default(); + // The whole current space by default; the Find window narrows it to the objects its result + // list already holds, so Replace All touches exactly what the user can see. + let hs: Vec = match p.get("handles").and_then(Value::as_array) { + Some(a) => a.iter().filter_map(|v| v.as_str().and_then(Handle::parse_hex)).collect(), + None => d.space(&space).map(|st| st.handles()).unwrap_or_default(), + }; let mut found: Vec = Vec::new(); let mut total = 0; let mut edits: Vec<(Handle, EntityKind)> = Vec::new(); for h in hs { let Some(e) = d.entity(h) else { continue }; + if let Some(names) = &types + && !names.iter().any(|n| n == &e.kind.type_name().to_ascii_lowercase()) + { + continue; + } let mut k = e.kind.clone(); let mut hits = 0; + // The first hit's surroundings, taken before a replacement rewrites the text. + let mut snippet: Option<(String, usize, usize)> = None; let r = rep.as_deref().unwrap_or(&find); let mut apply = |t: &mut String| { let (nt, n) = replace_in(t, &find, r, case, whole); if n > 0 { hits += n; + if snippet.is_none() { + snippet = snippet_at(t, &find, case, whole); + } if rep.is_some() { *t = nt; } @@ -263,7 +325,15 @@ fn run_find(s: &mut Session, p: &Value) -> Result { } if hits > 0 { total += hits; - found.push(json!({ "handle": h.hex(), "type": e.kind.type_name(), "count": hits })); + let (text, at, len) = snippet.unwrap_or_default(); + found.push(json!({ + "handle": h.hex(), + "type": e.kind.type_name(), + "count": hits, + "snippet": text, + "hit": at, + "hitLen": len, + })); if rep.is_some() { edits.push((h, k)); } @@ -577,4 +647,35 @@ mod tests { assert_eq!(replace_in("aaa", "a", "b", true, false), ("bbb".to_string(), 3)); assert_eq!(replace_in("x", "", "y", true, false).1, 0); } + + /// `snippet_at` returns the whole text when the hit fills it, with the hit at offset 0. + #[test] + fn snippet_reports_the_hit_offset() { + assert_eq!(snippet_at("BOLT-01", "BOLT-01", true, false), Some(("BOLT-01".to_string(), 0, 7))); + } + + /// Matching ignores case but the snippet keeps the text as it is written, so the result list + /// shows the drawing's own spelling. + #[test] + fn snippet_keeps_the_original_case() { + assert_eq!(snippet_at("法兰 bolt-01 安装孔", "BOLT-01", false, false), Some(("法兰 bolt-01 安装孔".to_string(), 3, 7))); + } + + /// A long text keeps [`SNIPPET_CONTEXT`] characters on each side of the hit, counted in + /// characters so a CJK hit is never split. + #[test] + fn snippet_is_windowed_in_characters() { + let text = format!("{}命中{}", "前".repeat(30), "后".repeat(30)); + let (snippet, hit, len) = snippet_at(&text, "命中", true, false).expect("a hit"); + assert_eq!((hit, len), (SNIPPET_CONTEXT, 2)); + assert_eq!(snippet.chars().count(), SNIPPET_CONTEXT * 2 + 2); + } + + /// A whole-word search skips an embedded hit, and text without a hit has no snippet. + #[test] + fn snippet_respects_whole_word() { + assert_eq!(snippet_at("BOLTS", "BOLT", true, true), None); + assert_eq!(snippet_at("a BOLT b", "BOLT", true, true).map(|s| s.1), Some(2)); + assert_eq!(snippet_at("nothing", "BOLT", true, false), None); + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index acdddb552..1f8035434 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -23,6 +23,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "units" => units(app, ctx, &mut open), "hatch" => crate::hatchdlg::dialog(app, ctx, &mut open), "aliasedit" => crate::aliasdlg::dialog(app, ctx, &mut open), + "find" => crate::finddlg::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/finddlg.rs b/crates/ui-egui/src/finddlg.rs new file mode 100644 index 000000000..7341f3cfa --- /dev/null +++ b/crates/ui-egui/src/finddlg.rs @@ -0,0 +1,294 @@ +//! Find and Replace: the window behind the FIND command. +//! +//! FIND used to be a command line that asked for its parameters and then printed a count. The +//! parameters are still what the engine takes; this window is the surface where a user can see +//! *what* matched, jump to it and replace one object at a time. It stays open while the drawing +//! is edited — find-and-replace in a drawing is a loop (look, locate, edit, look again), so a +//! window that closed on the first result would be closed and reopened all afternoon. +//! +//! Everything the engine cannot answer is left out rather than faked: the search covers the +//! current space, and the note under the switches says so in as many words. + +use egui::{Color32, RichText, Sense, TextFormat}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::{self, Tokens}; + +/// One object the search hit, as the engine reports it. +#[derive(Clone, Default)] +struct Row { + handle: String, + kind: String, + count: u64, + /// The text around the first hit, and where the hit sits inside it (characters, not bytes). + snippet: String, + hit: usize, + hit_len: usize, +} + +/// A `u64` from the reply as a `usize`, or 0 when it does not fit: an offset past the end of a +/// snippet is a bad reply, not a reason to fail the search that produced it. +fn as_index(v: Option<&Value>) -> usize { + v.and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).unwrap_or(0) +} + +impl Row { + /// Read one `matches` entry; anything missing keeps its default so a partially understood + /// reply still lists something. + fn from_json(v: &Value) -> Self { + Self { + handle: v.get("handle").and_then(Value::as_str).unwrap_or_default().to_string(), + kind: v.get("type").and_then(Value::as_str).unwrap_or_default().to_string(), + count: v.get("count").and_then(Value::as_u64).unwrap_or(0), + snippet: v.get("snippet").and_then(Value::as_str).unwrap_or_default().to_string(), + hit: as_index(v.get("hit")), + hit_len: as_index(v.get("hitLen")), + } + } + + /// The snippet in three pieces: before the hit, the hit, after it. Every slice is by + /// character and every range is clamped, so a reply with a nonsensical offset still draws. + fn pieces(&self) -> (String, String, String) { + let n = self.snippet.chars().count(); + let at = self.hit.min(n); + let end = at.saturating_add(self.hit_len).min(n); + let before: String = self.snippet.chars().take(at).collect(); + let hit: String = self.snippet.chars().skip(at).take(end.saturating_sub(at)).collect(); + let after: String = self.snippet.chars().skip(end).collect(); + (before, hit, after) + } +} + +/// The window's state between frames: kept in egui's temporary store, like the other dialogs, +/// so it lives exactly as long as the window does and never reaches the preferences file. +#[derive(Default, Clone)] +struct State { + find: String, + replace: String, + match_case: bool, + whole_word: bool, + /// The `doc_epoch` and space the rows were found in. A row's handle is only meaningful in + /// the drawing and the space it was found in, so when either moves the rows must go. + epoch: u64, + space: cadcraft_doc::Space, + rows: Vec, + /// The row Enter and Replace act on. + current: Option, + message: String, +} + +/// Run FIND and keep the parsed matches, or the engine's complaint in `message`. +fn search(app: &mut CadApp, st: &mut State) { + if st.find.trim().is_empty() { + st.rows.clear(); + st.current = None; + st.message = crate::i18n::t("Type something to find").to_string(); + return; + } + let params = json!({ "find": st.find, "matchCase": st.match_case, "wholeWord": st.whole_word }); + match app.run("find", params) { + Ok(v) => { + st.rows = v.get("matches").and_then(Value::as_array).map(|a| a.iter().map(Row::from_json).collect()).unwrap_or_default(); + st.current = if st.rows.is_empty() { None } else { Some(0) }; + let total = v.get("total").and_then(Value::as_u64).unwrap_or(0); + let objects = v.get("matches").and_then(Value::as_array).map_or(0, Vec::len); + st.message = format!("{total} match(es) in {objects} object(s)"); + } + Err(e) => { + st.rows.clear(); + st.current = None; + st.message = e; + } + } +} + +/// Select `row` in the drawing and zoom to it: the result list's rows navigate, they do not just +/// report. +fn reveal(app: &mut CadApp, st: &State, index: usize) { + let Some(row) = st.rows.get(index) else { return }; + let Some(h) = cadcraft_doc::Handle::parse_hex(&row.handle) else { return }; + app.session.set_selection(vec![h]); + let _ = app.run("zoom", json!({ "mode": "object" })); +} + +/// Replace inside the objects the result list already holds. `only` limits it to one row, so +/// Replace touches the object the user is looking at and Replace All touches the whole list. +fn replace(app: &mut CadApp, st: &mut State, only: Option) { + if st.find.trim().is_empty() { + return; + } + let handles: Vec = match only { + Some(i) => st.rows.get(i).map(|r| r.handle.clone()).into_iter().collect(), + None => st.rows.iter().map(|r| r.handle.clone()).collect(), + }; + if handles.is_empty() { + return; + } + let params = json!({ + "find": st.find, + "replace": st.replace, + "matchCase": st.match_case, + "wholeWord": st.whole_word, + "handles": handles, + }); + match app.run("find", params) { + Ok(v) => { + // The engine's reply reports what the replacement did; the re-search below would + // overwrite that message with a match count, so the replacement report is what + // the user ends up reading. + let replaced = v.get("message").and_then(Value::as_str).unwrap_or_default().to_string(); + search(app, st); + if !replaced.is_empty() { + st.message = replaced; + } + } + Err(e) => st.message = e, + } +} + +/// The Find and Replace window. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let sid = egui::Id::unique("find_state"); + let mut st: State = ctx.data_mut(|d| d.get_temp(sid)).unwrap_or_default(); + // A handle from an earlier drawing or space now names whatever object took its place; if + // Replace All ran on such a row it would edit an object the search never matched. Clearing + // the rows on an epoch or space change costs a re-click on Find All, which is the cheap + // side of that trade. + if *open && (st.epoch != app.session.doc_epoch || st.space != app.session.space()) { + st.epoch = app.session.doc_epoch; + st.space = app.session.space(); + st.rows.clear(); + st.current = None; + st.message.clear(); + } + // The rows answer one question — this text, with these switches, in this drawing. Editing + // any of them makes the rows stale: Replace All would rewrite with the old switches while + // the user is looking at the new ones, so the rows go and a fresh search is owed. + let criteria = (st.find.clone(), st.match_case, st.whole_word); + let mut do_search = false; + let mut do_replace: Option> = None; + let mut do_select_all = false; + let mut pick: Option = None; + egui::Window::new(crate::tl!("Find and Replace")) + .id(egui::Id::unique("Find and Replace")) + .open(open) + .collapsible(false) + .resizable(true) + .default_width(480.0) + .default_height(400.0) + .show(ctx, |ui| { + egui::Grid::new("find_fields").num_columns(2).spacing(egui::vec2(10.0, 6.0)).show(ui, |ui| { + ui.label(crate::tl!("Find what:")); + let r = ui.add(egui::TextEdit::singleline(&mut st.find).desired_width(f32::INFINITY).hint_text(crate::tl!("Text to find"))); + if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + do_search = true; + } + ui.end_row(); + ui.label(crate::tl!("Replace with:")); + ui.add(egui::TextEdit::singleline(&mut st.replace).desired_width(f32::INFINITY).hint_text(crate::tl!("Replacement text"))); + ui.end_row(); + }); + ui.horizontal(|ui| { + ui.checkbox(&mut st.match_case, crate::tl!("Match case")); + ui.checkbox(&mut st.whole_word, crate::tl!("Whole words")); + }); + ui.label(RichText::new(crate::tl!("Searches the current space.")).color(t.text_faint).small()); + ui.add_space(2.0); + ui.separator(); + let found = if st.rows.is_empty() { crate::tl!("Nothing found").to_string() } else { st.rows.len().to_string() }; + ui.label(RichText::new(format!("{} · {found}", crate::tl!("Results"))).color(t.text_dim).small()); + let body_h = (ui.available_height() - 76.0).clamp(80.0, 280.0); + egui::Frame::NONE.fill(t.field).corner_radius(3).inner_margin(egui::Margin::same(2)).show(ui, |ui| { + egui::ScrollArea::vertical().max_height(body_h).auto_shrink([false, false]).show(ui, |ui| { + ui.set_width(ui.available_width()); + for (i, row) in st.rows.iter().enumerate() { + let bg = if st.current == Some(i) { t.select_bg } else { Color32::TRANSPARENT }; + let inner = egui::Frame::NONE.fill(bg).corner_radius(2).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.label(RichText::new(crate::i18n::t(&row.kind)).color(t.text_dim).small()); + ui.label(RichText::new(row.handle.as_str()).color(t.text_faint).small().monospace()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(format!("×{}", row.count)).color(t.text_faint).small()); + }); + }); + let (before, hit, after) = row.pieces(); + let mut job = egui::text::LayoutJob::default(); + let plain = TextFormat { font_id: theme::small(), color: t.text, ..Default::default() }; + let marked = TextFormat { font_id: theme::mono(), color: accent(), ..Default::default() }; + job.append(&before, 0.0, plain.clone()); + job.append(&hit, 0.0, marked); + job.append(&after, 0.0, plain); + ui.add(egui::Label::new(job).wrap()); + }); + let click = ui.interact(inner.response.rect, ui.scope_id().with(("find_row", i)), Sense::click()); + if click.clicked() { + st.current = Some(i); + pick = Some(i); + } + } + }); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + if ui.button(crate::tl!("Find All")).clicked() { + do_search = true; + } + let has = !st.rows.is_empty(); + if ui.add_enabled(has, egui::Button::new(crate::tl!("Select All"))).clicked() { + do_select_all = true; + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // An empty replacement is deleting the matched text, which is a legitimate + // replacement, so the buttons care only about having something to act on. + if ui.add_enabled(has, egui::Button::new(crate::tl!("Replace All"))).clicked() { + do_replace = Some(None); + } + if ui.add_enabled(st.current.is_some(), egui::Button::new(crate::tl!("Replace"))).clicked() { + do_replace = Some(st.current); + } + }); + }); + if !st.message.is_empty() { + ui.label(RichText::new(st.message.as_str()).color(t.text_faint).small()); + } + }); + if let Some(i) = pick { + reveal(app, &st, i); + } + if criteria != (st.find.clone(), st.match_case, st.whole_word) { + st.rows.clear(); + st.current = None; + if !do_search { + st.message.clear(); + } + } + if do_search { + search(app, &mut st); + } + if do_select_all { + let hs: Vec = st.rows.iter().filter_map(|r| cadcraft_doc::Handle::parse_hex(&r.handle)).collect(); + if !hs.is_empty() { + app.session.set_selection(hs); + st.message = format!("{} object(s) selected", st.rows.len()); + } + } + if let Some(only) = do_replace { + replace(app, &mut st, only); + } + // The state lives exactly as long as the window does: a closed window leaves nothing behind, + // so reopening it reads the drawing instead of a stale result list. + if *open { + ctx.data_mut(|d| d.insert_temp(sid, st)); + } else { + ctx.data_mut(|d| d.remove_temp::(sid)); + } +} + +/// The colour a hit is drawn in: the theme's point colour, the same orange the drawing uses for +/// points and grips, so the highlight belongs to the drawing rather than to the interface. +fn accent() -> Color32 { + Tokens::get().icon_point +} diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 7713378d9..cf5741cdd 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -1368,3 +1368,15 @@ menu View عرض overrides built-in يتجاوز المدمج {alias} is already defined; select it and use Edit. {alias} معرَّف مسبقاً؛ حدده واستخدم «تحرير». {command} is an unknown command. {command} أمر غير معروف. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index b349db278..957c48993 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1444,3 +1444,15 @@ menu Modify Izmijeni Save changes to block "{name}"? Sačuvati promjene u bloku „{name}”? Layouts Rasporedi Associate Poveži + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 61dc1b2b6..67a6e90f6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1224,3 +1224,15 @@ 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. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f36e9ed02..0925cb6af 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1041,3 +1041,15 @@ 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. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 528dacf55..3bcf59c0c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1335,3 +1335,15 @@ menu View Προβολή Check for Updates… Έλεγχος για ενημερώσεις… CADCraft is up to date. Το CADCraft είναι ενημερωμένο. Could not check for updates. Δεν ήταν δυνατός ο έλεγχος για ενημερώσεις. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 457341c36..f0e6471ee 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1255,3 +1255,15 @@ Check for Updates… Buscar actualizaciones… CADCraft is up to date. CADCraft está actualizado. Could not check for updates. No se pudo buscar actualizaciones. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 62c77c3f9..2f391809e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1014,3 +1014,15 @@ 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. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e486f6337..b87edd3c3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1346,3 +1346,15 @@ 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. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b437397b6..d69b4fa6c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1364,3 +1364,15 @@ menu Modify Edita Check for Updates… Verifica aggiornamenti… CADCraft is up to date. CADCraft è aggiornato. Could not check for updates. Impossibile verificare gli aggiornamenti. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2f269b051..3f01bb695 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1244,3 +1244,15 @@ menu Modify 수정 Check for Updates… 업데이트 확인… CADCraft is up to date. CADCraft가 최신 버전입니다. Could not check for updates. 업데이트를 확인하지 못했습니다. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 3d8f03449..3d1791c1b 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -1253,6 +1253,18 @@ 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. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found # Strings the sibling catalogs translate that pt-BR did not yet cover (translated 2026-10-31). Add: Pick points Adicionar: indicar pontos Add: Select objects Adicionar: selecionar objetos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 619988f45..f1a5124f0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1015,3 +1015,15 @@ Check for Updates… Проверить обновления… CADCraft is up to date. У вас последняя версия CADCraft. Could not check for updates. Не удалось проверить обновления. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ecfe35b40..4d86a21be 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1448,3 +1448,15 @@ 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. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 24fac6a79..f9f41c798 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -113,6 +113,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "quick", "vpscale", "options/dialog", + "finddlg", ]; 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 cc8576aa7..26308975f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1349,3 +1349,15 @@ 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. + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8d8c6b875..5d0660112 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1373,3 +1373,15 @@ CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f1b8dca7b..34eb084eb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1448,3 +1448,15 @@ 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 + Find All Find All + Find what: Find what: + Match case Match case + Replace Replace + Replace All Replace All + Replace with: Replace with: + Replacement text Replacement text + Results Results + Searches the current space. Searches the current space. + Text to find Text to find + Whole words Whole words + Nothing found Nothing found diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index de4e6a633..a8d979efa 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1377,6 +1377,18 @@ Save Layout as Template 将布局另存为样板 Set Dynamic Property 设置动态特性 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 未找到 # The strings the report listed as missing for zh. Add… 添加… diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3319e639c..3e635ea2f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -33,6 +33,8 @@ pub mod credits; pub mod dialogs; pub mod docking; pub mod fault; +// The Find and Replace window behind the FIND command. +pub mod finddlg; pub mod hatchdlg; mod mtext_editor; mod panel_state; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 55d058811..438c06d97 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -73,6 +73,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.cmdline.lines", "Command Line History Lines", &[], None), ("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.language", "Language", &[], None), ("ui.noop", "", &[], None), ("ui.quit", "Quit CADCraft", &[], Some("Cmd+Q")), @@ -332,6 +333,12 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { let picked = app.services.pick_open.as_ref().and_then(|f| f()); @@ -456,7 +463,8 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { + | "ui.dialog.parameters" + | "ui.dialog.find" => { app.ui.dialog = Some(id.trim_start_matches("ui.dialog.").to_string()); Ok(Value::Null) } @@ -816,6 +824,7 @@ pub(crate) fn builtin_shortcuts() -> Vec<(egui::KeyboardShortcut, &'static str)> (sc(cmd, Key::S), "qsave"), (sc(cmd, Key::P), "plot"), (sc(cmd, Key::A), "selectall"), + (sc(cmd, Key::F), "ui.dialog.find"), (sc(cmd_shift, Key::C), "copybase"), (sc(cmd, Key::C), "copyclip"), (sc(cmd, Key::X), "cutclip"), From 5ed192555ca8c3e0fd5c7092163ed3cf0c59ce9a Mon Sep 17 00:00:00 2001 From: Tyler Chiriboga Date: Mon, 2 Nov 2026 21:54:03 -0600 Subject: [PATCH 456/900] EXPLODE: a block reference with different X and Y scales gives ellipses, not circles (#2649) * EXPLODE: a block reference with different X and Y scales gives ellipses, not circles EXPLODE of a block reference whose X and Y scales differ kept its circles as circles with the mean scale, its arcs as circular arcs, its ellipses with their old ratio and its polyline arcs as circular bulges: not the shape the reference draws. BURST and INSERT with explode go the same way. When the reference's transform isn't a similarity, a circle now becomes a full ELLIPSE, an arc an elliptical arc, an ellipse gets its true axes, and a polyline with arc segments (and no widths) its lines and elliptical arcs. Everything else, and every evenly scaled or mirrored reference, transforms as before. The exact ellipse transform and the similarity test move unchanged from snap.rs to cadcraft-geom (Ellipse::transformed, Mat3::similarity_scale) and are shared by object snaps and EXPLODE. Co-Authored-By: Claude Opus 5.5 * contributors: add Tyler-Chiriboga Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Tyler Chiriboga <18270301+Tyler-Chiriboga@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- contributors/people.toml | 4 + crates/engine/src/cmd/modify/explode.rs | 61 ++++++++- crates/engine/src/snap.rs | 37 +----- crates/engine/tests/it/explode_stretched.rs | 140 ++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/geom/src/curve.rs | 19 ++- crates/geom/src/mat.rs | 8 ++ 7 files changed, 234 insertions(+), 36 deletions(-) create mode 100644 crates/engine/tests/it/explode_stretched.rs diff --git a/contributors/people.toml b/contributors/people.toml index de6d22923..8bb73b9ea 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -100,6 +100,10 @@ sync_github_name = true [people.GULERTOLGA] sync_github_name = true +[people.Tyler-Chiriboga] +real_name = "Tyler Chiriboga" +sync_github_name = true + [people.starise] real_name = "Andrea Brandi" diff --git a/crates/engine/src/cmd/modify/explode.rs b/crates/engine/src/cmd/modify/explode.rs index d7db29d35..b4edc2e80 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -1,19 +1,74 @@ +use cadcraft_geom::{Ellipse as GEllipse, Mat3}; + use super::{Entity, EntityKind, Handle, PolyVertex, Polyline, Result, Segment, Session, Value, Vec2, arc, json, line, lwpoly, targets, v3}; // ---------------- explode / array / order / break / join ---------------- +/// `ell` placed by `m` as an ELLIPSE at elevation `z`; `None` when `m` flattens it. +fn placed_ellipse(ell: GEllipse, m: &Mat3, z: f64) -> Option { + let g = ell.transformed(m); + let len = g.major.len(); + (len.is_finite() && len > 0.0 && g.ratio.is_finite() && g.ratio > 0.0).then(|| { + EntityKind::Ellipse(cadcraft_doc::Ellipse { center: g.center.to3(z), major: g.major.to3(0.0), ratio: g.ratio, start: g.start, end: g.end }) + }) +} + +/// The pieces of block object `be` placed by `m`, a transform that stretches unevenly (a block +/// reference whose X and Y scales differ), where its own kind can't hold the result: a circle +/// or an arc becomes an ellipse or an elliptical arc, a polyline with arc segments (and no +/// widths) its lines and elliptical arcs. `None`: the object transforms as itself. +fn stretched_pieces(be: &Entity, m: &Mat3) -> Option> { + let circular = |center: Vec2, radius: f64, start: f64, end: f64| GEllipse { center, major: Vec2::X * radius, ratio: 1.0, start, end }; + let kinds = match &be.kind { + EntityKind::Circle(c) => vec![placed_ellipse(GEllipse::full(c.center.xy(), Vec2::X * c.radius, 1.0), m, c.center.z)?], + EntityKind::Arc(a) => vec![placed_ellipse(circular(a.center.xy(), a.radius, a.start, a.end), m, a.center.z)?], + EntityKind::Ellipse(el) => { + let g = GEllipse { center: el.center.xy(), major: el.major.xy(), ratio: el.ratio, start: el.start, end: el.end }; + vec![placed_ellipse(g, m, el.center.z)?] + } + EntityKind::LwPolyline(p) + if p.vertices.iter().any(|v| v.bulge != 0.0) + && p.const_width == 0.0 + && p.vertices.iter().all(|v| v.start_width == 0.0 && v.end_width == 0.0) => + { + let z = p.elevation; + let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; + pl.segments() + .into_iter() + .map(|s| match s { + Segment::Line(l) => Some(EntityKind::Line(cadcraft_doc::Line { a: m.apply(l.a).to3(z), b: m.apply(l.b).to3(z) })), + Segment::Arc { arc: a, .. } => placed_ellipse(circular(a.center, a.radius, a.start, a.end), m, z), + }) + .collect::>>()? + } + _ => return None, + }; + // The pieces of a polyline are new objects, as when it explodes itself: its xdata goes. + let mut common = be.common.clone(); + if matches!(be.kind, EntityKind::LwPolyline(_)) { + common.xdata.clear(); + } + Some(kinds.into_iter().map(|kind| Entity { handle: Handle(0), common: common.clone(), kind }).collect()) +} + fn explode_block_ref(d: &cadcraft_doc::Drawing, e: &Entity, ins: &cadcraft_doc::Insert) -> Option> { if let Some(items) = crate::cmd::array::explode_array(d, e) { return Some(items); } let blk = d.block(&ins.block)?; let m = ins.transform(blk.base.xy()); + let stretched = m.similarity_scale().is_none(); Some( blk.entities .iter() - .map(|be| { - let mut ne = (**be).clone(); - ne.kind.transform(&m); + .flat_map(|be| { + stretched.then(|| stretched_pieces(be, &m)).flatten().unwrap_or_else(|| { + let mut ne = (**be).clone(); + ne.kind.transform(&m); + vec![ne] + }) + }) + .map(|mut ne| { if ne.common.layer == "0" { ne.common.layer = e.common.layer.clone(); } diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 8def404d2..e2e24d9bc 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -813,22 +813,13 @@ fn prim_near(p: &Prim, probe: &Bounds2, aperture: f64) -> bool { b.expand(aperture).intersects(probe) } -/// The rotation-and-uniform-scale factor of `m`'s linear part (mirroring allowed), or `None` -/// when it distorts shapes (non-uniform scale or shear). -fn similarity_scale(m: &Mat3) -> Option { - let (u, v) = (Vec2::new(m.a, m.b), Vec2::new(m.c, m.d)); - let (lu, lv) = (u.len(), v.len()); - let tol = 1e-9 * lu.max(lv); - ((lu - lv).abs() <= tol && u.dot(v).abs() <= tol * lu.max(lv) && lu > 0.0).then_some(lu) -} - /// `p` placed by the affine transform `m`, exactly: circles and arcs under a non-uniform scale /// become ellipses and elliptical arcs. fn xform_prim(p: &Prim, m: &Mat3) -> Prim { let mirror = m.is_mirroring(); match p { Prim::Seg(Segment::Line(l)) => Prim::Seg(Segment::Line(cadcraft_geom::Line::new(m.apply(l.a), m.apply(l.b)))), - Prim::Seg(Segment::Arc { arc, ccw }) => match similarity_scale(m) { + Prim::Seg(Segment::Arc { arc, ccw }) => match m.similarity_scale() { Some(s) => { let c = m.apply(arc.center); let (a0, a1) = (c.angle_to(m.apply(arc.start_point())), c.angle_to(m.apply(arc.end_point()))); @@ -837,14 +828,14 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim { } None => { let e = Ellipse { center: arc.center, major: Vec2::X * arc.radius, ratio: 1.0, start: arc.start, end: arc.end }; - Prim::Ellipse(xform_ellipse(&e, m)) + Prim::Ellipse(e.transformed(m)) } }, - Prim::Circle(c) => match similarity_scale(m) { + Prim::Circle(c) => match m.similarity_scale() { Some(s) => Prim::Circle(Circle::new(m.apply(c.center), c.radius * s)), - None => Prim::Ellipse(xform_ellipse(&Ellipse::full(c.center, Vec2::X * c.radius, 1.0), m)), + None => Prim::Ellipse(Ellipse::full(c.center, Vec2::X * c.radius, 1.0).transformed(m)), }, - Prim::Ellipse(e) => Prim::Ellipse(xform_ellipse(e, m)), + Prim::Ellipse(e) => Prim::Ellipse(e.transformed(m)), Prim::Spline(s) => { let mut s = s.clone(); s.control.iter_mut().chain(s.fit.iter_mut()).for_each(|q| *q = m.apply(*q)); @@ -856,24 +847,6 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim { } } -/// The image of an ellipse (or elliptical arc) under an affine transform: the conjugate -/// semi-diameters `A·major`, `A·minor` give the new principal axes; parameters shift with them -/// (and reverse under a mirroring transform). -fn xform_ellipse(e: &Ellipse, m: &Mat3) -> Ellipse { - let center = m.apply(e.center); - let (am, an) = (m.apply_vec(e.major), m.apply_vec(e.minor())); - // |am·cos t + an·sin t| is largest at t0: the new major axis. - let t0 = 0.5 * (2.0 * am.dot(an)).atan2(am.dot(am) - an.dot(an)); - let (s0, c0) = t0.sin_cos(); - let (u, v) = (am * c0 + an * s0, an * c0 - am * s0); - let ratio = if u.len() > 0.0 { (v.len() / u.len()).min(1.0) } else { 1.0 }; - if e.is_full() { - return Ellipse::full(center, u, ratio); - } - let (start, end) = if u.cross(v) >= 0.0 { (e.start - t0, e.end - t0) } else { (t0 - e.end, t0 - e.start) }; - Ellipse { center, major: u, ratio, start: cadcraft_geom::norm_angle(start), end: cadcraft_geom::norm_angle(end) } -} - /// The nearest deferred tangent/perpendicular within `aperture` of `cursor`. fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option) -> Option { let mut best: Option<(f64, SnapHit)> = None; diff --git a/crates/engine/tests/it/explode_stretched.rs b/crates/engine/tests/it/explode_stretched.rs new file mode 100644 index 000000000..d7a7ac843 --- /dev/null +++ b/crates/engine/tests/it/explode_stretched.rs @@ -0,0 +1,140 @@ +//! EXPLODE of a block reference whose X and Y scales differ: its circles, arcs, ellipses and +//! polyline arcs come out as the ellipses and elliptical arcs the reference draws, not as circles +//! scaled by the mean of the two scales. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Entity, EntityKind}; +use serde_json::json; + +const AT: [f64; 2] = [100.0, 50.0]; +const ROTATION: f64 = 30.0; + +/// Block S (base 0,0): a circle (r 5 at 0,0), an arc (r 4 at 20,0, 0°..90°), an elliptical arc +/// (centre 40,0, major 6 along X, ratio 0.5, 0°..180°), a slot polyline (two lines, two +/// semicircles of r 2 at 60,0 and 70,0) and a line. One reference to it at `AT`, rotated by +/// `ROTATION`, scaled by `scale`, exploded. +fn exploded(scale: [f64; 2]) -> Vec { + let mut s = Session::new(); + let mut hs = Vec::new(); + for (id, p) in [ + ("circle", json!({"center": [0, 0], "radius": 5})), + ("arc", json!({"center": [20, 0], "radius": 4, "start": 0, "end": 90})), + ("ellipse", json!({"center": [40, 0], "major": [6, 0], "ratio": 0.5, "start": 0, "end": 180})), + ("pline", json!({"vertices": [[60, -2], {"p": [70, -2], "bulge": 1}, [70, 2], {"p": [60, 2], "bulge": 1}], "closed": true})), + ("line", json!({"points": [[0, 10], [10, 10]]})), + ] { + s.execute(id, &p).unwrap(); + hs.push(s.doc().unwrap().model.iter().last().unwrap().handle.hex()); + } + s.execute("block", &json!({"name": "S", "base": [0, 0], "keep": "delete", "handles": hs})).unwrap(); + let r = s.execute("insert", &json!({"name": "S", "at": AT, "scale": scale, "rotation": ROTATION})).unwrap(); + s.execute("explode", &json!({"handles": [r["handle"]]})).unwrap(); + s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect() +} + +/// A drawing point back in block coordinates. +fn to_block(p: [f64; 2], scale: [f64; 2]) -> [f64; 2] { + let (s, c) = (-ROTATION.to_radians()).sin_cos(); + let (dx, dy) = (p[0] - AT[0], p[1] - AT[1]); + [(dx * c - dy * s) / scale[0], (dx * s + dy * c) / scale[1]] +} + +/// Points along an ELLIPSE from its start to its end parameter. +fn samples(e: &cadcraft_engine::doc::Ellipse) -> Vec<[f64; 2]> { + let mut sweep = e.end - e.start; + if sweep <= 0.0 { + sweep += std::f64::consts::TAU; + } + let (mx, my) = (e.major.x, e.major.y); + let (nx, ny) = (-my * e.ratio, mx * e.ratio); + (0..=16) + .map(|i| { + let t = e.start + sweep * f64::from(i) / 16.0; + [e.center.x + mx * t.cos() + nx * t.sin(), e.center.y + my * t.cos() + ny * t.sin()] + }) + .collect() +} + +fn ellipses(v: &[Entity]) -> Vec { + v.iter() + .filter_map(|e| match &e.kind { + EntityKind::Ellipse(el) => Some(el.clone()), + _ => None, + }) + .collect() +} + +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).hypot(a[1] - b[1]) < 1e-9 +} + +/// Every point of `el`, taken back into the block, lies on the circle of radius `r` about `c` +/// in block coordinates, and its ends are `ends` (the whole circle when `None`). +fn on_circle(el: &cadcraft_engine::doc::Ellipse, scale: [f64; 2], c: [f64; 2], r: f64, ends: Option<([f64; 2], [f64; 2])>) { + let pts: Vec<[f64; 2]> = samples(el).into_iter().map(|p| to_block(p, scale)).collect(); + for q in &pts { + let d = (q[0] - c[0]).hypot(q[1] - c[1]); + assert!((d - r).abs() < 1e-9, "{q:?} is {d} from {c:?}, not {r}: {el:?}"); + } + if let Some((a, b)) = ends { + let (first, last) = (pts[0], pts[pts.len() - 1]); + assert!(near(first, a) && near(last, b) || near(first, b) && near(last, a), "ends {first:?} {last:?}, expected {a:?} {b:?}"); + } +} + +#[test] +fn explode_of_a_stretched_reference_draws_circles_and_arcs_as_ellipses() { + for scale in [[2.0, 0.5], [-2.0, 0.5], [1.0, 3.0]] { + let v = exploded(scale); + assert!(!v.iter().any(|e| matches!(e.kind, EntityKind::Circle(_) | EntityKind::Arc(_) | EntityKind::LwPolyline(_))), "{scale:?}: {v:?}"); + let els = ellipses(&v); + // Circle, arc, elliptical arc and the slot's two semicircles. + assert_eq!(els.len(), 5, "{scale:?}: {els:?}"); + let at = |c: [f64; 2]| els.iter().filter(move |e| near(to_block([e.center.x, e.center.y], scale), c)); + let circle = at([0.0, 0.0]).next().unwrap(); + on_circle(circle, scale, [0.0, 0.0], 5.0, None); + // Its axes are the scaled radii: 10 and 2.5 for 2 x 0.5. + let major = circle.major.x.hypot(circle.major.y); + let (big, small) = (5.0 * scale[0].abs().max(scale[1].abs()), 5.0 * scale[0].abs().min(scale[1].abs())); + assert!((major - big).abs() < 1e-9 && (major * circle.ratio - small).abs() < 1e-9, "{circle:?}"); + on_circle(at([20.0, 0.0]).next().unwrap(), scale, [20.0, 0.0], 4.0, Some(([24.0, 0.0], [20.0, 4.0]))); + on_circle(at([60.0, 0.0]).next().unwrap(), scale, [60.0, 0.0], 2.0, Some(([60.0, 2.0], [60.0, -2.0]))); + on_circle(at([70.0, 0.0]).next().unwrap(), scale, [70.0, 0.0], 2.0, Some(([70.0, -2.0], [70.0, 2.0]))); + // The elliptical arc: its points, back in the block, are on the block's ellipse + // ((x-40)/6)^2 + (y/3)^2 = 1, from (46,0) over the top to (34,0). + let ell = at([40.0, 0.0]).next().unwrap(); + let pts: Vec<[f64; 2]> = samples(ell).into_iter().map(|p| to_block(p, scale)).collect(); + for q in &pts { + let f = ((q[0] - 40.0) / 6.0).powi(2) + (q[1] / 3.0).powi(2); + assert!((f - 1.0).abs() < 1e-9 && q[1] > -1e-9, "{q:?}: {ell:?}"); + } + let (first, last) = (pts[0], pts[pts.len() - 1]); + assert!(near(first, [46.0, 0.0]) && near(last, [34.0, 0.0]) || near(first, [34.0, 0.0]) && near(last, [46.0, 0.0]), "{pts:?}"); + // The slot's straight sides and the line are lines, where the reference draws them. + let lines: Vec<[[f64; 2]; 2]> = v + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) => Some([to_block([l.a.x, l.a.y], scale), to_block([l.b.x, l.b.y], scale)]), + _ => None, + }) + .collect(); + assert_eq!(lines.len(), 3); + for [a, b] in [[[60.0, -2.0], [70.0, -2.0]], [[70.0, 2.0], [60.0, 2.0]], [[0.0, 10.0], [10.0, 10.0]]] { + assert!(lines.iter().any(|l| near(l[0], a) && near(l[1], b)), "{a:?}-{b:?} not in {lines:?}"); + } + } +} + +#[test] +fn explode_of_an_evenly_scaled_or_mirrored_reference_keeps_circles_arcs_and_polylines() { + for scale in [[2.0, 2.0], [-1.0, 1.0]] { + let v = exploded(scale); + let count = |f: fn(&EntityKind) -> bool| v.iter().filter(|e| f(&e.kind)).count(); + assert_eq!(count(|k| matches!(k, EntityKind::Circle(_))), 1, "{scale:?}"); + assert_eq!(count(|k| matches!(k, EntityKind::Arc(_))), 1, "{scale:?}"); + assert_eq!(count(|k| matches!(k, EntityKind::LwPolyline(_))), 1, "{scale:?}"); + assert_eq!(count(|k| matches!(k, EntityKind::Ellipse(_))), 1, "{scale:?}"); + let r = v.iter().find_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }).unwrap(); + assert!((r - 5.0 * scale[0].abs()).abs() < 1e-9); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b6ec02d60..9e014d4b1 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -46,6 +46,7 @@ mod draworder; mod dyn_input; mod dynamic_block_data; mod dynamic_grips; +mod explode_stretched; mod extend_polyline_arc_end; mod fillet_chamfer; mod fix_holds_grips; diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index 2b799e433..04f665f88 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::{Bounds2, EPS, PI, TAU, Vec2, angle_in_sweep, arc_segments, ccw_sweep, norm_angle}; +use crate::{Bounds2, EPS, Mat3, PI, TAU, Vec2, angle_in_sweep, arc_segments, ccw_sweep, norm_angle}; /// A straight segment. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] @@ -247,6 +247,23 @@ impl Ellipse { pub fn sweep(&self) -> f64 { ccw_sweep(self.start, self.end) } + /// The image under the affine transform `m`, exactly: the conjugate semi-diameters + /// `A·major`, `A·minor` give the new principal axes; parameters shift with them (and + /// reverse under a mirroring transform). + pub fn transformed(&self, m: &Mat3) -> Ellipse { + let center = m.apply(self.center); + let (am, an) = (m.apply_vec(self.major), m.apply_vec(self.minor())); + // |am·cos t + an·sin t| is largest at t0: the new major axis. + let t0 = 0.5 * (2.0 * am.dot(an)).atan2(am.dot(am) - an.dot(an)); + let (s0, c0) = t0.sin_cos(); + let (u, v) = (am * c0 + an * s0, an * c0 - am * s0); + let ratio = if u.len() > 0.0 { (v.len() / u.len()).min(1.0) } else { 1.0 }; + if self.is_full() { + return Ellipse::full(center, u, ratio); + } + let (start, end) = if u.cross(v) >= 0.0 { (self.start - t0, self.end - t0) } else { (t0 - self.end, t0 - self.start) }; + Ellipse { center, major: u, ratio, start: norm_angle(start), end: norm_angle(end) } + } pub fn tessellate(&self, tol: f64, out: &mut Vec) { let r = self.major.len(); let sweep = self.sweep(); diff --git a/crates/geom/src/mat.rs b/crates/geom/src/mat.rs index 5f2613540..5f28b068d 100644 --- a/crates/geom/src/mat.rs +++ b/crates/geom/src/mat.rs @@ -98,6 +98,14 @@ impl Mat3 { pub fn is_mirroring(&self) -> bool { self.det() < 0.0 } + /// The rotation-and-uniform-scale factor of the linear part (mirroring allowed), or `None` + /// when it distorts shapes (non-uniform scale or shear). + pub fn similarity_scale(&self) -> Option { + let (u, v) = (Vec2::new(self.a, self.b), Vec2::new(self.c, self.d)); + let (lu, lv) = (u.len(), v.len()); + let tol = 1e-9 * lu.max(lv); + ((lu - lv).abs() <= tol && u.dot(v).abs() <= tol * lu.max(lv) && lu > 0.0).then_some(lu) + } } /// A 4x4 transform, row-major, for 3D views and block transforms with elevation. From 51b3e8b112029fe4903422844b5f9569ec55b7ba Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 14:59:25 +1100 Subject: [PATCH 457/900] 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 458/900] 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 459/900] 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 460/900] 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 461/900] 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 462/900] 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 463/900] 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 464/900] 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 465/900] 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 466/900] 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 467/900] 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 b3a1e1af40955846835b6407d2c1658e6b129bb1 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:59:50 +0200 Subject: [PATCH 468/900] Object snaps: Tab cycles every candidate snap under the cursor, not one per mode Tab cycling offered the closest snap of each running mode: two endpoints within the aperture, or a circle's tangent and perpendicular at the same spot, could not both be reached. `snap::osnap_all` now returns every object snap within the aperture, ranked as `osnap` picks: specific snaps nearest first (Endpoint and Intersection favoured a little), then deferred tangents and perpendiculars, then Nearest, without repeats; `osnap` is its first entry, so the pick order is unchanged. `pointmod::snap_candidates` cycles that list. Snaps seen through layout viewports are included. Split from #1582 as asked in review; the display settings (magnet, aperture box, marker and tooltip switches) stay there. Co-Authored-By: Claude Fable 5.1 --- crates/engine/src/pointmod.rs | 17 +--- crates/engine/src/snap.rs | 185 +++++++++++++++++++++++----------- 2 files changed, 129 insertions(+), 73 deletions(-) diff --git a/crates/engine/src/pointmod.rs b/crates/engine/src/pointmod.rs index 74c1ab083..2d8c3fd03 100644 --- a/crates/engine/src/pointmod.rs +++ b/crates/engine/src/pointmod.rs @@ -119,23 +119,14 @@ pub fn snap_name(m: u32) -> &'static str { mode::ALL.iter().find(|(b, _)| *b == m).map_or("None", |(_, n)| *n) } -/// The candidate snaps near `cursor` for Tab cycling: the snap [`crate::snap::osnap`] picks -/// first, then the closest snap of each other mode in `osmode`, nearest first, without repeats. +/// The candidate snaps near `cursor` for Tab cycling: every object snap within the aperture, the +/// one [`crate::snap::osnap`] picks first and the rest in its order (specific snaps nearest +/// first, then deferred snaps, then Nearest), without repeats. pub fn snap_candidates(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option, deferred: bool) -> Vec { if osmode & !mode::HATCH == 0 || osmode & mode::OFF != 0 { return Vec::new(); } - let osnap = |m: u32| crate::snap::osnap(d, space, cursor, aperture, m, base, deferred); - let extra = osmode & mode::HATCH; - let mut per_mode: Vec = mode::ALL.iter().filter(|(b, _)| osmode & b != 0).filter_map(|(b, _)| osnap(*b | extra)).collect(); - per_mode.sort_by(|a, b| a.point.dist(cursor).total_cmp(&b.point.dist(cursor))); - let mut out: Vec = osnap(osmode).into_iter().collect(); - for h in per_mode { - if !out.iter().any(|o| o.mode == h.mode && o.point.near(h.point, aperture * 1e-6)) { - out.push(h); - } - } - out + crate::snap::osnap_all(d, space, cursor, aperture, osmode, base, deferred) } /// Strip the international (`_`) and transparent (`'`) prefixes a modifier may be typed with. diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index e2e24d9bc..b7ac6aded 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -72,6 +72,28 @@ impl SnapHit { None => crate::Input::Point(self.point), } } + + fn plain(mode: u32, point: Vec2) -> SnapHit { + SnapHit { point, mode, name: name_of(mode), viewport: None, deferred: None } + } + + /// Where this hit sorts among the candidates near a cursor: specific snaps by distance + /// (Endpoint and Intersection favoured a little), then deferred snaps, then Nearest. + fn rank(&self, cursor: Vec2, aperture: f64) -> (u8, f64) { + let class = if self.deferred.is_some() { + 1 + } else if self.mode == mode::NEA { + 2 + } else { + 0 + }; + (class, snap_score(self.mode, self.point, cursor, aperture)) + } + + /// The same snap (mode and point) as `o`. + fn same(&self, o: &SnapHit) -> bool { + self.mode == o.mode && self.deferred.is_some() == o.deferred.is_some() && self.point.near(o.point, 1e-9 * (1.0 + self.point.len())) + } } /// The curve a deferred snap refers to. @@ -211,6 +233,14 @@ pub fn osnap(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u3 osnap_with(d, space, &ix, cursor, aperture, osmode, base, deferred) } +/// Every object snap within `aperture` of `cursor`, the one [`osnap`] picks first and the rest +/// in the order Tab cycles them: specific snaps nearest first, then deferred snaps, then Nearest. +/// Snaps seen through layout viewports are included. +pub fn osnap_all(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, osmode: u32, base: Option, deferred: bool) -> Vec { + let ix = crate::spatial::index(d, space); + osnap_all_with_neighborhood(d, space, &ix, cursor, aperture, osmode, base, deferred).0 +} + #[allow(clippy::too_many_arguments)] pub(crate) fn osnap_with( d: &Drawing, @@ -237,16 +267,32 @@ pub(crate) fn osnap_with_neighborhood( base: Option, deferred: bool, ) -> (Option, Option>) { + let (all, prims) = osnap_all_with_neighborhood(d, space, ix, cursor, aperture, osmode, base, deferred); + (all.into_iter().next(), prims) +} + +/// Every object snap near the cursor ([`osnap_all`]) and the local-space primitives gathered. +#[allow(clippy::too_many_arguments)] +fn osnap_all_with_neighborhood( + d: &Drawing, + space: &Space, + ix: &Option>, + cursor: Vec2, + aperture: f64, + osmode: u32, + base: Option, + deferred: bool, +) -> (Vec, Option>) { if osmode == 0 || osmode & mode::OFF != 0 || !cursor.is_finite() || !(aperture.is_finite() && aperture > 0.0) { - return (None, None); + return (Vec::new(), None); } - let (mut best, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) { - Some((hit, prims)) => (hit, Some(prims)), - None => (None, None), + let (mut all, near_prims) = match osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, &[], None) { + Some((hits, prims)) => (hits, Some(prims)), + None => (Vec::new(), None), }; let views = viewport::near(d, space, cursor, aperture); if views.is_empty() { - return (best, near_prims); + return (all, near_prims); } let model = Space::Model; let model_ix = crate::spatial::index(d, &model); @@ -257,7 +303,7 @@ pub(crate) fn osnap_with_neighborhood( if !model_cursor.is_finite() || !(model_aperture.is_finite() && model_aperture > 0.0) || model_base.is_some_and(|p| !p.is_finite()) { continue; } - let hit = osnap_in( + let hits = osnap_in( d, &model, &model_ix, @@ -268,15 +314,26 @@ pub(crate) fn osnap_with_neighborhood( deferred, &view.viewport.frozen_layers, Some(view.model_clip), - ) - .and_then(|h| view.hit(h)); - if let Some(hit) = hit - && best.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture)) - { - best = Some(hit); + ); + all.extend(hits.into_iter().filter_map(|h| view.hit(h))); + } + (ranked(all, cursor, aperture), near_prims) +} + +/// `hits` best first ([`SnapHit::rank`]), without repeats. +fn ranked(mut hits: Vec, cursor: Vec2, aperture: f64) -> Vec { + hits.sort_by(|a, b| { + let (ca, sa) = a.rank(cursor, aperture); + let (cb, sb) = b.rank(cursor, aperture); + ca.cmp(&cb).then(sa.total_cmp(&sb)) + }); + let mut out: Vec = Vec::with_capacity(hits.len()); + for h in hits { + if !out.iter().any(|o| o.same(&h)) { + out.push(h); } } - (best, near_prims) + out } #[allow(clippy::too_many_arguments)] @@ -291,10 +348,11 @@ fn osnap_in( deferred: bool, frozen: &[String], clip: Option, -) -> Option { - osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).and_then(|(hit, _)| hit) +) -> Vec { + osnap_in_with_prims(d, space, ix, cursor, aperture, osmode, base, deferred, frozen, clip).map(|(hits, _)| hits).unwrap_or_default() } +/// The snaps near the cursor in one space, best first, and the primitives gathered there. #[allow(clippy::too_many_arguments)] fn osnap_in_with_prims( d: &Drawing, @@ -307,7 +365,7 @@ fn osnap_in_with_prims( deferred: bool, frozen: &[String], clip: Option, -) -> Option<(Option, Vec)> { +) -> Option<(Vec, Vec)> { let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?; // Intersections between nearby primitives; Apparent Intersection also where their extensions // meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects @@ -345,8 +403,8 @@ fn osnap_in_with_prims( } } } - let hit = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip); - Some((hit, near_prims)) + let hits = finish(cands, &near_prims, cursor, aperture, osmode, base, deferred, clip); + Some((hits, near_prims)) } fn finite_intersection_probe(cursor: Vec2, aperture: f64) -> Option { @@ -458,7 +516,8 @@ fn gather_in( Some((cands, near_prims)) } -/// Picks the best of the gathered candidates, adding the base-dependent and deferred snaps. +/// Ranks the gathered candidates within the aperture ([`ranked`]), adding the base-dependent +/// snaps, the deferred snaps and Nearest. #[allow(clippy::too_many_arguments)] fn finish( mut cands: Vec<(u32, Vec2)>, @@ -469,7 +528,7 @@ fn finish( base: Option, deferred: bool, clip: Option, -) -> Option { +) -> Vec { // Perpendicular / tangent from the base point. if let Some(bp) = base { for p in near_prims { @@ -507,20 +566,10 @@ fn finish( } } let visible = |p: Vec2| p.is_finite() && clip.is_none_or(|c| c.contains(p)); - let best = cands.iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).min_by(|a, b| { - // Prefer more specific modes when nearly equidistant. - let da = snap_score(a.0, a.1, cursor, aperture); - let db = snap_score(b.0, b.1, cursor, aperture); - da.total_cmp(&db) - }); - if let Some((m, p)) = best { - return Some(SnapHit { point: *p, mode: *m, name: name_of(*m), viewport: None, deferred: None }); - } - if base.is_none() - && deferred - && let Some(h) = deferred_hit(near_prims, cursor, aperture, osmode, clip) - { - return Some(h); + let mut hits: Vec = + cands.into_iter().filter(|(_, p)| visible(*p) && p.dist(cursor) <= aperture).map(|(m, p)| SnapHit::plain(m, p)).collect(); + if base.is_none() && deferred { + hits.extend(deferred_hits(near_prims, cursor, aperture, osmode, clip)); } if osmode & mode::NEA != 0 { // The closest point of all nearby objects, whatever their drawing order. @@ -540,12 +589,13 @@ fn finish( } } if let Some((_, p)) = nb { - return Some(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None }); + hits.push(SnapHit { point: p, mode: mode::NEA, name: "Nearest", viewport: None, deferred: None }); } } - None + ranked(hits, cursor, aperture) } +/// Prefer more specific modes when nearly equidistant. fn snap_score(mode: u32, point: Vec2, cursor: Vec2, aperture: f64) -> f64 { point.dist(cursor) - if mode == mode::INT || mode == mode::END { aperture * 0.15 } else { 0.0 } } @@ -847,9 +897,11 @@ fn xform_prim(p: &Prim, m: &Mat3) -> Prim { } } -/// The nearest deferred tangent/perpendicular within `aperture` of `cursor`. -fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option) -> Option { - let mut best: Option<(f64, SnapHit)> = None; +/// Every deferred tangent and perpendicular within `aperture` of `cursor`: one per curve and +/// mode, in drawing order (the caller ranks them), so Tab can cycle from the tangent to the +/// perpendicular on the same circle. +fn deferred_hits(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Option) -> Vec { + let mut hits = Vec::new(); for p in prims { let curve = match p { Prim::Circle(c) => SnapCurve::Circle { center: c.center, radius: c.radius }, @@ -858,32 +910,28 @@ fn deferred_hit(prims: &[Prim], cursor: Vec2, aperture: f64, osmode: u32, clip: Prim::Infinite { base, dir, .. } => SnapCurve::Line { a: *base, b: *base + *dir }, _ => continue, }; - let (m, name, at) = match curve { - SnapCurve::Circle { center, radius } if osmode & mode::TAN != 0 => { - (mode::TAN, "Deferred Tangent", Circle::new(center, radius).closest(cursor)) - } - SnapCurve::Circle { center, radius } if osmode & mode::PER != 0 => { - (mode::PER, "Deferred Perpendicular", Circle::new(center, radius).closest(cursor)) - } - SnapCurve::Arc { center, radius, start, end } if osmode & mode::TAN != 0 => { - (mode::TAN, "Deferred Tangent", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor)) - } - SnapCurve::Arc { center, radius, start, end } if osmode & mode::PER != 0 => { - (mode::PER, "Deferred Perpendicular", cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor)) - } - SnapCurve::Line { a, b } if osmode & mode::PER != 0 => { - // Pick on the drawn extent: a segment's own span, an xline/ray anywhere. + // Where the curve was picked: a circle's, an arc's or a segment's own span, an xline/ray + // anywhere. + let at = match curve { + SnapCurve::Circle { center, radius } => Circle::new(center, radius).closest(cursor), + SnapCurve::Arc { center, radius, start, end } => cadcraft_geom::Arc::new(center, radius, start, end).closest(cursor), + SnapCurve::Line { a, b } => { let l = cadcraft_geom::Line::new(a, b); - (mode::PER, "Deferred Perpendicular", if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) }) + if matches!(p, Prim::Seg(_)) { l.closest(cursor) } else { l.project(cursor) } } - _ => continue, }; - let dd = at.dist(cursor); - if at.is_finite() && clip.is_none_or(|c| c.contains(at)) && dd <= aperture && best.is_none_or(|(bd, _)| dd < bd) { - best = Some((dd, SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) })); + if !(at.is_finite() && clip.is_none_or(|c| c.contains(at)) && at.dist(cursor) <= aperture) { + continue; + } + let modes: &[(u32, &'static str)] = match curve { + SnapCurve::Circle { .. } | SnapCurve::Arc { .. } => &[(mode::TAN, "Deferred Tangent"), (mode::PER, "Deferred Perpendicular")], + SnapCurve::Line { .. } => &[(mode::PER, "Deferred Perpendicular")], + }; + for &(m, name) in modes.iter().filter(|(m, _)| osmode & m != 0) { + hits.push(SnapHit { point: at, mode: m, name, viewport: None, deferred: Some(Deferred { mode: m, curve, at }) }); } } - best.map(|(_, h)| h) + hits } /// Solve a line whose ends may be deferred tangent/perpendicular snaps: returns its two @@ -1095,6 +1143,23 @@ mod tests { assert_eq!(h.name, "Intersection"); } + /// Tab cycling sees every snap within the aperture: specific snaps nearest first (Intersection + /// favoured), then deferred snaps, then Nearest, and no snap twice; the first is what `osnap` + /// picks. + #[test] + fn osnap_all_ranks_every_candidate() { + let d = drawing(); + let modes = mode::END | mode::MID | mode::INT | mode::NEA; + let all = osnap_all(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false); + assert_eq!(all.iter().map(|h| h.mode).collect::>(), [mode::INT, mode::MID, mode::NEA], "{all:?}"); + assert_eq!(all[0].point, osnap(&d, &Space::Model, Vec2::new(5.2, 0.2), 0.5, modes, None, false).unwrap().point); + // On the circle: its quadrant, then the deferred tangent and perpendicular at the same spot. + let all = osnap_all(&d, &Space::Model, Vec2::new(22.1, 0.1), 0.5, mode::QUA | mode::TAN | mode::PER, None, true); + let kinds: Vec<(u32, bool)> = all.iter().map(|h| (h.mode, h.deferred.is_some())).collect(); + assert_eq!(kinds, [(mode::QUA, false), (mode::TAN, true), (mode::PER, true)], "{all:?}"); + assert!(osnap_all(&d, &Space::Model, Vec2::new(50.0, 50.0), 0.5, modes, None, false).is_empty()); + } + #[test] fn center_quadrant_tangent() { let d = drawing(); From 2bd916661d7af0236818353ddf6cca05990e3d2a Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:12:16 +0100 Subject: [PATCH 469/900] Object snaps: a click across spaces picks as before; viewports stay apart in Tab's list osnap_all ranked paper-space snaps and snaps seen through viewports in one list, so a farther Endpoint through a viewport could come before a closer paper-space Nearest and take the click. The click's snap now comes first as main picks it (a viewport's best replaces paper space's only when it scores closer); the rest follow in Tab order. Two snaps at one paper point from different viewports (overlapping viewports showing different model points) are no longer merged: each keeps its model point for DIST. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/snap.rs | 25 +++++++++-- .../tests/it/measure_distance_snapping.rs | 42 ++++++++++++++++++- 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index b7ac6aded..a1409d7a9 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -90,9 +90,14 @@ impl SnapHit { (class, snap_score(self.mode, self.point, cursor, aperture)) } - /// The same snap (mode and point) as `o`. + /// The same snap as `o`: mode and point, from the same source (paper space, or one + /// viewport). Overlapping viewports can show different model points at one paper point; + /// each stays a candidate, since DIST measures in the model units of the viewport picked. fn same(&self, o: &SnapHit) -> bool { - self.mode == o.mode && self.deferred.is_some() == o.deferred.is_some() && self.point.near(o.point, 1e-9 * (1.0 + self.point.len())) + self.mode == o.mode + && self.deferred.is_some() == o.deferred.is_some() + && self.viewport.map(|v| v.viewport) == o.viewport.map(|v| v.viewport) + && self.point.near(o.point, 1e-9 * (1.0 + self.point.len())) } } @@ -296,6 +301,10 @@ fn osnap_all_with_neighborhood( } let model = Space::Model; let model_ix = crate::spatial::index(d, &model); + // What a click picks across spaces stays as it was: each space's best snap, and a viewport's + // replaces the best so far only when it scores closer. A paper-space Nearest can therefore + // beat an Endpoint seen through a viewport, which `ranked` alone would put first. + let mut pick = all.first().copied(); for view in views { let model_cursor = view.to_model(cursor); let model_aperture = aperture / view.scale; @@ -315,9 +324,19 @@ fn osnap_all_with_neighborhood( &view.viewport.frozen_layers, Some(view.model_clip), ); + if let Some(hit) = hits.first().and_then(|h| view.hit(*h)) + && pick.as_ref().is_none_or(|b| snap_score(hit.mode, hit.point, cursor, aperture) < snap_score(b.mode, b.point, cursor, aperture)) + { + pick = Some(hit); + } all.extend(hits.into_iter().filter_map(|h| view.hit(h))); } - (ranked(all, cursor, aperture), near_prims) + let mut out = ranked(all, cursor, aperture); + if let Some(pick) = pick { + out.retain(|h| !h.same(&pick)); + out.insert(0, pick); + } + (out, near_prims) } /// `hits` best first ([`SnapHit::rank`]), without repeats. diff --git a/crates/engine/tests/it/measure_distance_snapping.rs b/crates/engine/tests/it/measure_distance_snapping.rs index 9842b65e0..8749f8492 100644 --- a/crates/engine/tests/it/measure_distance_snapping.rs +++ b/crates/engine/tests/it/measure_distance_snapping.rs @@ -2,7 +2,7 @@ use cadcraft_engine::doc::{Block, Circle, Common, Drawing, Entity, EntityKind, Handle, Insert, Line, Space, Viewport}; use cadcraft_engine::geom::{Vec2, Vec3}; -use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap}; +use cadcraft_engine::snap::{SnapCurve, SnapHit, mode, osnap, osnap_all}; use cadcraft_engine::{Input, Session}; use serde_json::json; @@ -277,6 +277,46 @@ fn clipped_endpoints_do_not_hide_a_visible_candidate() { assert!(osnap(&d, &paper, Vec2::new(110.11, 51.0), 0.2, mode::END, None, false).is_none()); } +/// Across spaces a click keeps the snap it had before Tab cycling: a viewport's best snap +/// replaces paper space's only when it scores closer. Tab still reaches the other one. +#[test] +fn a_closer_paper_space_nearest_keeps_the_click_over_a_viewport_endpoint() { + let (mut d, paper) = drawing(); + // A paper-space line 0.3 left of the model endpoint (0, 0), which the viewport shows at (95, 50). + d.add(&paper, Common::default(), EntityKind::Line(Line { a: Vec3::new(94.7, 48.0, 0.0), b: Vec3::new(94.7, 52.0, 0.0) })).unwrap(); + let (cursor, modes) = (Vec2::new(94.8, 50.0), mode::END | mode::NEA); + let hit = osnap(&d, &paper, cursor, 0.5, modes, None, false).unwrap(); + assert_eq!((hit.mode, hit.viewport), (mode::NEA, None), "{hit:?}"); + assert!(hit.point.near(Vec2::new(94.7, 50.0), 1e-9), "{hit:?}"); + let all = osnap_all(&d, &paper, cursor, 0.5, modes, None, false); + assert_eq!(all.first(), Some(&hit), "Tab starts at the click's snap"); + assert!( + all.iter().any(|h| h.mode == mode::END && h.viewport.is_some() && h.point.near(Vec2::new(95.0, 50.0), 1e-9)), + "Tab reaches the viewport's endpoint: {all:?}" + ); +} + +/// Overlapping viewports can show different model points at one paper point; Tab offers each, +/// since DIST measures in the model units of the viewport picked. +#[test] +fn overlapping_viewports_each_offer_their_model_point() { + let (mut d, paper) = drawing(); + // This viewport shows the model endpoint (20, 0) at paper (100, 50), a second one over it (0, 0). + edit_viewport(&mut d, &paper, |vp| vp.view_center = Vec2::new(20.0, 0.0)); + let mut vp = match &d.entity(viewport(&d, &paper)).unwrap().kind { + EntityKind::Viewport(vp) => vp.clone(), + _ => panic!("viewport fixture"), + }; + vp.view_center = Vec2::new(0.0, 0.0); + vp.id = 3; + d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); + let all = osnap_all(&d, &paper, Vec2::new(100.05, 50.04), 0.5, mode::END, None, false); + let mut models: Vec = + all.iter().filter(|h| h.point.near(Vec2::new(100.0, 50.0), 1e-9)).filter_map(|h| h.viewport).map(|v| v.point).collect(); + models.sort_by(|a, b| a.x.total_cmp(&b.x)); + assert_eq!(models, [Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0)], "{all:?}"); +} + #[test] fn viewport_frozen_layers_do_not_hide_paper_space_geometry() { let (mut d, paper) = drawing(); 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 470/900] 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 471/900] 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 472/900] 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 473/900] 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 474/900] 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 475/900] 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 476/900] 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 9a112830c5994ef2434699557dbe2f76a4c95a21 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 09:06:49 -0500 Subject: [PATCH 477/900] fix(engine): merge another drawing's tables and blocks in linear time (#2689) INSERT of a file, IMPORT, paste and COMPARE export each checked every incoming layer, linetype, style and block name by scanning the growing destination vector, and restarted the anonymous block name search from 1 at every collision, so a compact drawing with many distinct names made the command quadratic. The four copies of that code become one helper (cmd/merge.rs) that looks names up in a set built once per table and continues each generated prefix from the last number it allocated. Xref loading does the same for its dependent symbols, and no longer rescans the block table after a fetch that imported nothing. --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/blocks/insert_file.rs | 41 +------- crates/engine/src/cmd/blocks/xref/load.rs | 35 ++++--- crates/engine/src/cmd/clipboard.rs | 40 +------- crates/engine/src/cmd/exchange.rs | 44 +-------- crates/engine/src/cmd/file/compare/export.rs | 18 ++-- crates/engine/src/cmd/merge.rs | 99 ++++++++++++++++++++ 7 files changed, 140 insertions(+), 138 deletions(-) create mode 100644 crates/engine/src/cmd/merge.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index bc93b9f55..f54573595 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -22,6 +22,7 @@ mod inquiry; mod layer; mod layout; mod lisp; +mod merge; mod mleader_content; mod mleader_edit; mod modify; diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index a00dbc64c..7a0492fad 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -6,7 +6,7 @@ //! (names this drawing already has keep this drawing's definitions). The file is read through the //! host's io hooks like OPEN, so the engine stays I/O-agnostic. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::sync::Arc; use cadcraft_doc::{Block, Drawing, Entity, EntityKind, Handle}; @@ -102,7 +102,7 @@ fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { // Redefining keeps the existing definition's name (block names are case-insensitive). let name = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned().unwrap_or_else(|| name.to_string()); merge_tables(&mut d, src); - let renames = block_names(&d, src, &name); + let renames = crate::cmd::merge::block_renames(&d, src, Some(&name)); for (from, to) in &renames { let Some(b) = src.blocks.get(from) else { continue }; let mut nb = (**b).clone(); @@ -136,13 +136,7 @@ fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { /// Add the source's layers, linetypes and styles that this drawing doesn't have (a name that /// exists keeps this drawing's definition). fn merge_tables(d: &mut Drawing, src: &Drawing) { - fn merge(ours: &mut Vec, theirs: &[T], name: fn(&T) -> &str) { - for t in theirs { - if !ours.iter().any(|o| name(o).eq_ignore_ascii_case(name(t))) { - ours.push(t.clone()); - } - } - } + use crate::cmd::merge::merge_named as merge; merge(&mut d.layers, &src.layers, |l| &l.name); merge(&mut d.linetypes, &src.linetypes, |l| &l.name); merge(&mut d.text_styles, &src.text_styles, |t| &t.name); @@ -152,35 +146,6 @@ fn merge_tables(d: &mut Drawing, src: &Drawing) { merge(&mut d.mline_styles, &src.mline_styles, |t| &t.name); } -/// Which source blocks to copy, and under which name: new names keep theirs, generated -/// (anonymous `*…`) blocks that collide get a fresh generated name, and a named block this drawing -/// already has (or the block being defined) keeps this drawing's definition (not copied). -fn block_names(d: &Drawing, src: &Drawing, defining: &str) -> BTreeMap { - let mut out = BTreeMap::new(); - let mut taken: BTreeSet = d.blocks.keys().map(|k| k.to_ascii_uppercase()).collect(); - taken.insert(defining.to_ascii_uppercase()); - for (name, b) in &src.blocks { - let upper = name.to_ascii_uppercase(); - if upper.starts_with("*MODEL_SPACE") || upper.starts_with("*PAPER_SPACE") { - continue; - } - let to = if !taken.contains(&upper) { - name.clone() - } else if b.anonymous || name.starts_with('*') { - let prefix: String = name.chars().take_while(|c| !c.is_ascii_digit()).collect(); - match (1..=1_000_000).map(|i| format!("{prefix}{i}")).find(|n| !taken.contains(&n.to_ascii_uppercase())) { - Some(n) => n, - None => continue, - } - } else { - continue; - }; - taken.insert(to.to_ascii_uppercase()); - out.insert(name.clone(), to); - } - out -} - /// A copy of a source entity for this drawing: a fresh handle, block references renamed, and /// links to other source objects (associative dimension points) dropped. fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &BTreeMap) -> Entity { diff --git a/crates/engine/src/cmd/blocks/xref/load.rs b/crates/engine/src/cmd/blocks/xref/load.rs index b47aa00e0..981df918d 100644 --- a/crates/engine/src/cmd/blocks/xref/load.rs +++ b/crates/engine/src/cmd/blocks/xref/load.rs @@ -10,6 +10,7 @@ //! loaded further up (a circular reference) is not loaded again. Every failure leaves the xref's //! block empty with a status saying why; nothing here stops the host drawing from opening. +use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -339,14 +340,15 @@ fn load_in(d: &mut Drawing, name: &str, host: Option<&Path>, chosen: bool, cx: & let (status, detail) = match fetch(&path, host, chosen, cx, depth) { Ok((x, file)) => match import(d, &key, &x, cx) { Ok(()) => (XrefStatus::Loaded, file.to_string_lossy().into_owned()), - Err(e) => (XrefStatus::Unresolved, e), + Err(e) => { + // Whatever made it in before the failure goes again. A fetch that failed imported + // nothing, so it doesn't pay for a second scan of the block table. + clear(d, &key); + (XrefStatus::Unresolved, e) + } }, Err(e) => e, }; - if status != XrefStatus::Loaded { - // Whatever made it in before the failure goes again. - clear(d, &key); - } set_status(d, &key, status); (status, detail) } @@ -390,9 +392,15 @@ fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), S return Err(format!("more than {MAX_XREF_OBJECTS} objects")); } let dep = |sym: Sym, n: &str| (!shared(sym, n)).then(|| format!("{key}|{n}")); + // The host's names per table, looked up in a set built once: both drawings are hostile input, + // so a scan per imported record would be quadratic. + fn names(all: &[T], name: fn(&T) -> &str) -> HashSet { + all.iter().map(|t| name(t).to_ascii_uppercase()).collect() + } + let mut have = names(&d.layers, |l| &l.name); for l in &x.layers { if let Some(n) = dep(Sym::Layer, &l.name) - && d.layer(&n).is_none() + && have.insert(n.to_ascii_uppercase()) { let mut l = l.clone(); l.name = n; @@ -400,39 +408,44 @@ fn import(d: &mut Drawing, key: &str, x: &Drawing, cx: &mut Ctx) -> Result<(), S d.layers.push(l); } } + let mut have = names(&d.linetypes, |t| &t.name); for t in &x.linetypes { if let Some(n) = dep(Sym::Linetype, &t.name) - && d.linetype(&n).is_none() + && have.insert(n.to_ascii_uppercase()) { d.linetypes.push(cadcraft_doc::Linetype { name: n, ..t.clone() }); } } + let mut have = names(&d.text_styles, |t| &t.name); for t in &x.text_styles { if let Some(n) = dep(Sym::Style, &t.name) - && d.text_style(&n).is_none() + && have.insert(n.to_ascii_uppercase()) { d.text_styles.push(cadcraft_doc::TextStyle { name: n, ..t.clone() }); } } + let mut have = names(&d.dim_styles, |t| &t.name); for t in &x.dim_styles { if let Some(n) = dep(Sym::DimStyle, &t.name) - && d.dim_style(&n).is_none() + && have.insert(n.to_ascii_uppercase()) { let text_style = dep(Sym::Style, &t.text_style).unwrap_or_else(|| t.text_style.clone()); d.dim_styles.push(cadcraft_doc::DimStyle { name: n, text_style, ..t.clone() }); } } + let mut have = names(&d.mleader_styles, |t| &t.name); for t in &x.mleader_styles { if let Some(n) = dep(Sym::MLeaderStyle, &t.name) - && !d.mleader_styles.iter().any(|o| o.name.eq_ignore_ascii_case(&n)) + && have.insert(n.to_ascii_uppercase()) { let text_style = dep(Sym::Style, &t.text_style).unwrap_or_else(|| t.text_style.clone()); d.mleader_styles.push(cadcraft_doc::MLeaderStyle { name: n, text_style, ..t.clone() }); } } + let mut have = names(&d.table_styles, |t| &t.name); for t in &x.table_styles { if let Some(n) = dep(Sym::TableStyle, &t.name) - && !d.table_styles.iter().any(|o| o.name.eq_ignore_ascii_case(&n)) + && have.insert(n.to_ascii_uppercase()) { d.table_styles.push(cadcraft_doc::TableStyle { name: n, ..t.clone() }); } diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 49a7e7f33..3ddf8cf5b 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -10,7 +10,7 @@ //! The clipboard can also travel as DXF text ([`system_text`], [`load_system_text`]), so a front //! end can put it on the system clipboard and paste it into another CADCraft window. -use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::collections::{BTreeMap, HashSet}; use std::sync::Arc; use cadcraft_doc::{Block, Drawing, Entity, EntityKind, HVal, Handle}; @@ -279,20 +279,14 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing { /// Add `defs`' table records and blocks that `d` doesn't have. Returns the blocks copied, from /// their name in `defs` to their name in `d`. fn merge(d: &mut Drawing, defs: &Drawing) -> BTreeMap { - fn add(ours: &mut Vec, theirs: &[T], name: fn(&T) -> &str) { - for t in theirs { - if !ours.iter().any(|o| name(o).eq_ignore_ascii_case(name(t))) { - ours.push(t.clone()); - } - } - } + use crate::cmd::merge::merge_named as add; add(&mut d.layers, &defs.layers, |l| &l.name); add(&mut d.linetypes, &defs.linetypes, |l| &l.name); add(&mut d.text_styles, &defs.text_styles, |t| &t.name); add(&mut d.dim_styles, &defs.dim_styles, |t| &t.name); add(&mut d.mleader_styles, &defs.mleader_styles, |t| &t.name); add(&mut d.table_styles, &defs.table_styles, |t| &t.name); - let renames = block_names(d, defs); + let renames = crate::cmd::merge::block_renames(d, defs, None); for (from, to) in &renames { let Some(b) = defs.blocks.get(from) else { continue }; let mut nb = (**b).clone(); @@ -308,34 +302,6 @@ fn merge(d: &mut Drawing, defs: &Drawing) -> BTreeMap { renames } -/// Which blocks of `defs` to copy, and under which name: a new name keeps its own, a generated -/// (anonymous `*…`) block whose name is taken gets a fresh generated name, and a named block `d` -/// already has keeps `d`'s definition (not copied). -fn block_names(d: &Drawing, defs: &Drawing) -> BTreeMap { - let mut out = BTreeMap::new(); - let mut taken: BTreeSet = d.blocks.keys().map(|k| up(k)).collect(); - for (name, b) in &defs.blocks { - let upper = up(name); - if upper.starts_with("*MODEL_SPACE") || upper.starts_with("*PAPER_SPACE") { - continue; - } - let to = if !taken.contains(&upper) { - name.clone() - } else if b.anonymous || name.starts_with('*') { - let prefix: String = name.chars().take_while(|c| !c.is_ascii_digit()).collect(); - match (1..=1_000_000).map(|i| format!("{prefix}{i}")).find(|n| !taken.contains(&up(n))) { - Some(n) => n, - None => continue, - } - } else { - continue; - }; - taken.insert(up(&to)); - out.insert(name.clone(), to); - } - out -} - /// A copy of a clipboard object for `d`: a fresh handle, block references renamed, and links to /// objects of the source drawing (associative dimension points) dropped. fn adopt(d: &mut Drawing, e: &Entity, renames: &BTreeMap) -> Entity { diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 2a6a01f67..f0fbb9cef 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -7,7 +7,7 @@ //! stays I/O-agnostic; the JSON forms never open dialogs (the UI asks for files when these //! commands come from a menu, the tool bar or the command line). -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::sync::Arc; use cadcraft_color::Rgb; @@ -166,7 +166,7 @@ fn import_drawing(s: &mut Session, src: &Drawing, at: Vec2, scale: f64, file: &s let space = s.space(); let d = s.doc_mut()?; let (layers, styles) = merge_tables(d, src); - let renames = block_names(d, src); + let renames = crate::cmd::merge::block_renames(d, src, None); for (from, to) in &renames { let Some(b) = src.blocks.get(from) else { continue }; let mut nb = (**b).clone(); @@ -213,16 +213,7 @@ fn read_file(_path: &str) -> Result> { /// Add the source's layers, linetypes and styles that this drawing doesn't have (a name that /// exists keeps this drawing's definition). Returns how many layers and how many other records were added. fn merge_tables(d: &mut Drawing, src: &Drawing) -> (usize, usize) { - fn merge(ours: &mut Vec, theirs: &[T], name: fn(&T) -> &str) -> usize { - let mut n = 0; - for t in theirs { - if !ours.iter().any(|o| name(o).eq_ignore_ascii_case(name(t))) { - ours.push(t.clone()); - n += 1; - } - } - n - } + use crate::cmd::merge::merge_named as merge; let layers = merge(&mut d.layers, &src.layers, |l| &l.name); let others = merge(&mut d.linetypes, &src.linetypes, |l| &l.name) + merge(&mut d.text_styles, &src.text_styles, |t| &t.name) @@ -232,35 +223,6 @@ fn merge_tables(d: &mut Drawing, src: &Drawing) -> (usize, usize) { (layers, others) } -/// Which source blocks to copy, and under which name: new names keep theirs, generated -/// (anonymous `*…`) blocks that collide get a fresh generated name, and a named block this drawing -/// already has keeps this drawing's definition (not copied). -fn block_names(d: &Drawing, src: &Drawing) -> BTreeMap { - let mut out = BTreeMap::new(); - let mut taken: BTreeSet = d.blocks.keys().map(|k| k.to_ascii_uppercase()).collect(); - for (name, b) in &src.blocks { - let upper = name.to_ascii_uppercase(); - if upper.starts_with("*MODEL_SPACE") || upper.starts_with("*PAPER_SPACE") { - continue; - } - let anonymous = b.anonymous || name.starts_with('*'); - let to = if !taken.contains(&upper) { - name.clone() - } else if anonymous { - let prefix: String = name.chars().take_while(|c| !c.is_ascii_digit()).collect(); - match (1..=1_000_000).map(|i| format!("{prefix}{i}")).find(|n| !taken.contains(&n.to_ascii_uppercase())) { - Some(n) => n, - None => continue, - } - } else { - continue; - }; - taken.insert(to.to_ascii_uppercase()); - out.insert(name.clone(), to); - } - out -} - /// A copy of a source entity for this drawing: a fresh handle, block references renamed, and /// links to other source objects (associative dimension points) dropped. fn adopt(d: &mut Drawing, e: &Entity, renames: &BTreeMap) -> Entity { diff --git a/crates/engine/src/cmd/file/compare/export.rs b/crates/engine/src/cmd/file/compare/export.rs index f3801049d..667a19a36 100644 --- a/crates/engine/src/cmd/file/compare/export.rs +++ b/crates/engine/src/cmd/file/compare/export.rs @@ -20,7 +20,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use cadcraft_doc::color::{Color, Rgb}; -use cadcraft_doc::{Block, CellStyle, DimStyle, Drawing, Entity, EntityKind, EntityStore, Group, Handle, MAX_BLOCK_DEPTH, TableStyle}; +use cadcraft_doc::{Block, CellStyle, DimStyle, Drawing, Entity, EntityKind, EntityStore, Group, Handle, Layer, MAX_BLOCK_DEPTH, TableStyle}; use serde_json::{Value, json}; use super::super::super::{CommandSpec, bad}; @@ -197,6 +197,7 @@ fn snapshot(cur: &Drawing, c: &Comparison, folders: &Folders) -> Snapshot { d.skipped_records.clear(); d.handseed = d.handseed.max(other.handseed); + use crate::cmd::merge::merge_named as merge; merge(&mut d.layers, &other.layers, |t| &t.name); merge(&mut d.linetypes, &other.linetypes, |t| &t.name); merge(&mut d.text_styles, &other.text_styles, |t| &t.name); @@ -235,22 +236,17 @@ fn snapshot(cur: &Drawing, c: &Comparison, folders: &Folders) -> Snapshot { Snapshot { drawing: d, current, compared, counts: (here.len(), there.len()), truncated: diff.truncated, blocks_left_out, uncolored } } -/// Add the entries of `from` whose names `to` lacks (compared without letter case). -fn merge(to: &mut Vec, from: &[T], name: impl Fn(&T) -> &String) { - for t in from { - if !to.iter().any(|x| name(x).eq_ignore_ascii_case(name(t))) { - to.push(t.clone()); - } - } -} - /// Add copies of `objs` to model space with new handles, their block references renamed by /// `renames` and their files rebased on `folder`, each painted in its comparison color, and /// group them as `name` (or `name_2`… when that group name is taken). Returns the group's name. fn add_group(d: &mut Drawing, name: &str, objs: &[(&Entity, Color)], renames: &Renames, folder: Option<&Path>, tinted: &mut Tinted) -> String { let mut members = Vec::new(); + // The layers this drawing has, looked up once per object rather than scanned. + let mut layers: HashSet = d.layers.iter().map(|l| l.name.to_ascii_uppercase()).collect(); for (e, color) in objs { - d.ensure_layer(&e.common.layer); + if layers.insert(e.common.layer.to_ascii_uppercase()) { + d.layers.push(Layer::new(&e.common.layer)); + } let h = d.new_handle(); let mut copy = Entity { handle: h, ..(*e).clone() }; detach(&mut copy.kind); diff --git a/crates/engine/src/cmd/merge.rs b/crates/engine/src/cmd/merge.rs new file mode 100644 index 000000000..119f678b7 --- /dev/null +++ b/crates/engine/src/cmd/merge.rs @@ -0,0 +1,99 @@ +//! Bringing another drawing's symbol tables and blocks into this one (INSERT of a file, IMPORT, +//! paste, COMPARE export). +//! +//! Both drawings are hostile input, so the work is linear in their sizes: names are looked up in a +//! set built once per table, and a generated block name continues from the last one allocated for +//! its prefix instead of probing every taken number again (CWE-407). + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; + +use cadcraft_doc::Drawing; + +/// Add the entries of `theirs` whose names `ours` lacks (compared without letter case; a name that +/// exists keeps `ours`' definition). Returns how many were added. +pub(crate) fn merge_named(ours: &mut Vec, theirs: &[T], name: fn(&T) -> &str) -> usize { + let mut have: HashSet = ours.iter().map(|o| name(o).to_ascii_uppercase()).collect(); + let mut added = 0; + for t in theirs { + if have.insert(name(t).to_ascii_uppercase()) { + ours.push(t.clone()); + added += 1; + } + } + added +} + +/// Which blocks of `src` to copy into `d`, and under which name: a new name keeps its own, a +/// generated (anonymous `*…`) block whose name is taken gets a fresh generated name, and a named +/// block `d` already has (or `defining`, the block being defined from `src`) keeps `d`'s +/// definition (not copied). +pub(crate) fn block_renames(d: &Drawing, src: &Drawing, defining: Option<&str>) -> BTreeMap { + let mut out = BTreeMap::new(); + let mut taken: BTreeSet = d.blocks.keys().map(|k| k.to_ascii_uppercase()).collect(); + taken.extend(defining.map(str::to_ascii_uppercase)); + // The next number to try per generated prefix: numbers below it are taken. + let mut next: HashMap = HashMap::new(); + for (name, b) in &src.blocks { + let upper = name.to_ascii_uppercase(); + if upper.starts_with("*MODEL_SPACE") || upper.starts_with("*PAPER_SPACE") { + continue; + } + let to = if !taken.contains(&upper) { + name.clone() + } else if b.anonymous || name.starts_with('*') { + let prefix: String = name.chars().take_while(|c| !c.is_ascii_digit()).collect(); + let cursor = next.entry(prefix.to_ascii_uppercase()).or_insert(1); + match (*cursor..=1_000_000).map(|i| (i, format!("{prefix}{i}"))).find(|(_, n)| !taken.contains(&n.to_ascii_uppercase())) { + Some((i, n)) => { + *cursor = i + 1; + n + } + None => continue, + } + } else { + continue; + }; + taken.insert(to.to_ascii_uppercase()); + out.insert(name.clone(), to); + } + out +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use cadcraft_doc::{Block, Layer}; + + use super::*; + + #[test] + fn merge_keeps_ours_and_adds_the_rest_without_regard_to_case() { + let mut ours = vec![Layer::new("Walls")]; + let theirs = vec![Layer::new("WALLS"), Layer::new("Doors"), Layer::new("doors")]; + assert_eq!(merge_named(&mut ours, &theirs, |l| &l.name), 1); + assert_eq!(ours.iter().map(|l| l.name.as_str()).collect::>(), ["Walls", "Doors"]); + } + + /// Many colliding anonymous blocks get consecutive names in one pass, not a rescan each. + #[test] + fn anonymous_collisions_take_consecutive_numbers() { + let mut d = Drawing::new_imperial(); + let mut src = Drawing::new_imperial(); + for i in 1..=5000 { + let mut b = Block::new(&format!("*U{i}")); + b.anonymous = true; + d.blocks.insert(b.name.clone(), Arc::new(b.clone())); + src.blocks.insert(b.name.clone(), Arc::new(b)); + } + let started = std::time::Instant::now(); + let renames = block_renames(&d, &src, None); + assert!(started.elapsed() < std::time::Duration::from_secs(2)); + assert_eq!(renames.len(), 5000); + assert_eq!(renames.get("*U1").map(String::as_str), Some("*U5001")); + let distinct: HashSet<&String> = renames.values().collect(); + assert_eq!(distinct.len(), 5000); + // Every new name is the next free number: nothing below 5001 is free, nothing above 10000 is needed. + assert!(renames.values().all(|n| n.strip_prefix("*U").and_then(|i| i.parse::().ok()).is_some_and(|i| (5001..=10000).contains(&i)))); + } +} From e10f394b2880ad539819647cd4b8d4e70c4ef585 Mon Sep 17 00:00:00 2001 From: kler Date: Tue, 3 Nov 2026 15:06:54 +0100 Subject: [PATCH 478/900] i18n(sv): translate 20 new strings (#2695) Brings the Swedish catalog up to date with upstream main (b04273e). Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/i18n/sv.tsv | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4d86a21be..d67d39c03 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1460,3 +1460,23 @@ menu Modify Ändra Text to find Text to find Whole words Whole words Nothing found Nothing found + Layouts Layouter + Associate Associera + Change Ändra + Change Properties Ändra egenskaper + Save Layout as Template Spara layout som mall + Units Enheter + Backup copy Säkerhetskopia + Create backup copy with each save Skapa en säkerhetskopia vid varje sparande + Font Typsnitt + Save changes to block "{name}"? Spara ändringar i blocket "{name}"? + Backup copies are off, so the current file will be replaced. Säkerhetskopior är avstängda, så den aktuella filen kommer att ersättas. + DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. DXF 2010 och tidigare behåller dem. Använd Spara som för att behålla dem i ritningen. + DXF keeps them. Use Save As to keep them in the drawing. DXF behåller dem. Använd Spara som för att behålla dem i ritningen. + Save Anyway Spara ändå + Save cancelled: {path} was not changed. Sparandet avbröts: {path} ändrades inte. + Saving {name} will remove content Om du sparar {name} tas innehåll bort + The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. Den aktuella filen verkar inte vara hel, så {name} lämnas som den är och den aktuella filen kommer att ersättas. + The current file is kept as {name} until the next save. Den aktuella filen sparas som {name} till nästa sparande. + This format can't keep these objects yet: {objects}. Det här formatet kan ännu inte behålla följande objekt: {objects}. + {count} more types {count} typer till From 7bb6c2f06f5d47cb1cacf37ec1a196882c86c860 Mon Sep 17 00:00:00 2001 From: Khuong Doan <108074836+2ez4gcx@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:06:58 +0700 Subject: [PATCH 479/900] MINSERT: a block reference repeated in rows and columns, as AutoCAD does (#2698) * MINSERT: a block reference repeated in rows and columns MINSERT asks INSERT's questions, then the grid's as AutoCAD 2024 does (measured with accoreconsole): the numbers of rows and columns (1 to 32767), the distance between rows or a unit cell when there is more than one row, the distance between columns when there is more than one column, then the attribute values once. A distance along an axis with one copy is 0, and one row by one column is a plain reference. EXPLODE leaves a grid whole ("The object is minserted.") instead of exploding its first copy and dropping the rest. MIRROR mirrors a block reference as AutoCAD does, negating the X scale factor and a grid's column distance, so a mirrored grid's rows stay on the right side. An attribute with no default is asked without "<>". Co-Authored-By: Claude Opus 5.5 * MINSERT JSON: refuse a distance that is not a number `rowSpacing` and `columnSpacing` went through `f64_or`, which takes any value that is not a number as the default, so `"rowSpacing": "15"` stored 0 and put every copy on top of the others without an error. They are now checked as `rows` and `columns` are: absent or null is 0, a finite number is kept, anything else is refused. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/entity.rs | 8 +- crates/engine/src/cmd/blocks.rs | 186 ++++++++++++++++++-- crates/engine/src/cmd/modify/explode.rs | 19 +++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/minsert.rs | 218 ++++++++++++++++++++++++ crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh.tsv | 1 + 7 files changed, 417 insertions(+), 17 deletions(-) create mode 100644 crates/engine/tests/it/minsert.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index a516137fa..535506806 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -362,9 +362,13 @@ impl EntityKind { i.scale.y *= s; i.scale.z *= s; i.rotation = cadcraft_geom::norm_angle(i.rotation + rot); + // Mirrored as AutoCAD 2024 mirrors a block reference: the X scale factor + // negated, the rotation 180 degrees plus twice the mirror line's angle less the + // old one, and a MINSERT grid's columns running the other way. if mirror { - i.scale.y = -i.scale.y; - i.rotation = cadcraft_geom::norm_angle(rot - (i.rotation - rot)); + i.scale.x = -i.scale.x; + i.rotation = cadcraft_geom::norm_angle(std::f64::consts::PI + rot - (i.rotation - rot)); + i.col_spacing = -i.col_spacing; } for a in &mut i.attribs { transform_text(&mut a.text, m, s, rot, false); diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 45ab8ae15..8189e37c1 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -43,6 +43,9 @@ pub fn specs() -> Vec { .alias(&["i", "-insert", "ddinsert"]) .params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}") .interactive(|_| Ok(Box::new(InsertM::default()))), + CommandSpec::new("minsert", "Multiple Insert", run_minsert) + .params("{name, file?: DXF/DWG path (as INSERT), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y], attribs?: {TAG: value}, rows?: 1..32767 (default 1), columns?: 1..32767 (default 1), rowSpacing?, columnSpacing? (along the reference's own axes, not scaled with it)}") + .interactive(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))), CommandSpec::new("attdef", "Define Attributes...", run_attdef) .menu(&["Draw", "Block", "Define Attributes..."]) .alias(&["att", "-attdef"]) @@ -233,6 +236,33 @@ fn insert_entity(blk: &Block, at: Vec2, scale: Vec3, rotation: f64, base: Option ins } +/// MINSERT's rectangular array of a block reference: rows and columns, and the distances between +/// them along the reference's rotated axes (not scaled with it). One row and one column is a plain +/// reference. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Grid { + rows: u32, + cols: u32, + row_spacing: f64, + col_spacing: f64, +} + +impl Grid { + const ONE: Grid = Grid { rows: 1, cols: 1, row_spacing: 0.0, col_spacing: 0.0 }; + /// The most rows or columns MINSERT takes, as AutoCAD 2024 asks for them. + const MAX: u32 = 32767; + + /// A distance is kept only along an axis with more than one copy: AutoCAD 2024 asks for no + /// other and stores 0 for it (one row of three columns: 44 = 20, 45 = 0). + fn new(rows: u32, cols: u32, row_spacing: f64, col_spacing: f64) -> Grid { + Grid { rows, cols, row_spacing: if rows > 1 { row_spacing } else { 0.0 }, col_spacing: if cols > 1 { col_spacing } else { 0.0 } } + } + + fn apply(self, ins: &mut Insert) { + (ins.rows, ins.cols, ins.row_spacing, ins.col_spacing) = (self.rows, self.cols, self.row_spacing, self.col_spacing); + } +} + /// [`insert`] with separate X/Y scale factors (Z as X) and an optional base point (see /// [`insert_entity`]). pub(crate) fn insert_with( @@ -244,10 +274,12 @@ pub(crate) fn insert_with( base: Option, values: &serde_json::Map, ) -> Result { - insert_scaled(s, name, at, Vec3::new(scale.x, scale.y, scale.x), rotation, base, values) + insert_scaled(s, name, at, Vec3::new(scale.x, scale.y, scale.x), rotation, base, values, Grid::ONE) } -/// [`insert_with`] with a Z scale factor of its own. +/// [`insert_with`] with a Z scale factor of its own, and MINSERT's grid. A grid has the one set +/// of attributes (AutoCAD 2024 asks for their values once). +#[allow(clippy::too_many_arguments)] fn insert_scaled( s: &mut Session, name: &str, @@ -256,9 +288,11 @@ fn insert_scaled( rotation: f64, base: Option, values: &serde_json::Map, + grid: Grid, ) -> Result { let blk = s.doc()?.block(name).cloned().ok_or_else(|| EngineError::Other(format!("Block \"{name}\" not found.")))?; let mut ins = insert_entity(&blk, at, scale, rotation, base); + grid.apply(&mut ins); let m = ins.transform(blk.base.xy()); for e in blk.entities.iter() { if let EntityKind::AttDef(ad) = &e.kind { @@ -310,24 +344,52 @@ fn run_block(s: &mut Session, p: &Value) -> Result { } fn run_insert(s: &mut Session, p: &Value) -> Result { + insert_json(s, p, "insert", Grid::ONE) +} + +/// MINSERT's JSON form: INSERT's parameters and the grid. +fn run_minsert(s: &mut Session, p: &Value) -> Result { + let count = |key: &str| -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(1), + Some(v) => v + .as_f64() + .filter(|n| n.fract() == 0.0 && *n >= 1.0 && *n <= f64::from(Grid::MAX)) + .map(|n| n as u32) + .ok_or_else(|| bad("minsert", format!("`{key}` must be an integer between 1 and {}", Grid::MAX))), + } + }; + // A distance given must be a number: `"15"` is refused, not taken as 0. + let spacing = |key: &str| -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(0.0), + Some(v) => v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("minsert", format!("`{key}` must be a number"))), + } + }; + let grid = Grid::new(count("rows")?, count("columns")?, spacing("rowSpacing")?, spacing("columnSpacing")?); + insert_json(s, p, "minsert", grid) +} + +/// INSERT's and MINSERT's JSON form. +fn insert_json(s: &mut Session, p: &Value, cmd: &str, grid: Grid) -> Result { let p = &insert_file::json_params(s, p)?; - let name = str_param(p, "name").ok_or_else(|| bad("insert", "`name` is required"))?.to_string(); - let at = point_req("insert", p, "at")?; + let name = str_param(p, "name").ok_or_else(|| bad(cmd, "`name` is required"))?.to_string(); + let at = point_req(cmd, p, "at")?; // `scale`: one factor, or [x, y] for different X and Y scale factors. let scale = match p.get("scale") { - Some(v) if v.is_array() => point_value(v).ok_or_else(|| bad("insert", "`scale` must be a number or [x, y]"))?, + Some(v) if v.is_array() => point_value(v).ok_or_else(|| bad(cmd, "`scale` must be a number or [x, y]"))?, _ => { let f = f64_or(p, "scale", 1.0); Vec2::new(f, f) } }; if scale.x == 0.0 || scale.y == 0.0 { - return Err(bad("insert", "scale cannot be 0")); + return Err(bad(cmd, "scale cannot be 0")); } let rot = f64_or(p, "rotation", 0.0).to_radians(); let vals = p.get("attribs").and_then(Value::as_object).cloned().unwrap_or_default(); - let h = insert_with(s, &name, at, scale, rot, point_param(p, "basePoint"), &vals)?; - if bool_or(p, "explode", false) { + let h = insert_scaled(s, &name, at, Vec3::new(scale.x, scale.y, scale.x), rot, point_param(p, "basePoint"), &vals, grid)?; + if cmd == "insert" && bool_or(p, "explode", false) { // The EXPLODE command body, not `execute`: INSERT records the one undo step. let explode = find_command("explode").ok_or_else(|| EngineError::UnknownCommand("explode".into()))?; return (explode.run)(s, &json!({ "handles": [h.hex()] })); @@ -560,6 +622,15 @@ enum InsStage { /// XYZ: the Z scale factor, after X and Y. ZScale, Rotation, + /// MINSERT: the number of rows, then of columns. + Rows, + Cols, + /// MINSERT: the distance between rows, or a unit cell's first corner. + RowSpacing, + /// MINSERT: the unit cell's opposite corner (its width between columns, its height between + /// rows). + Cell(Vec2), + ColSpacing, Attribs, /// A Verify attribute asked again. Verify, @@ -592,6 +663,12 @@ struct InsertM { explode: bool, /// The file waiting for the Redefine answer. file: Option, + /// MINSERT: after the rotation, the grid's rows and columns and the distances between them. + minsert: bool, + rows: Option, + cols: Option, + row_spacing: Option, + col_spacing: Option, } impl InsertM { @@ -601,6 +678,8 @@ impl InsertM { if self.explode { InsStage::PresetScale } else { InsStage::XScale } } else if self.rotation.is_none() { InsStage::Rotation + } else if let Some(g) = self.grid_stage() { + g } else { InsStage::Attribs }; @@ -619,7 +698,7 @@ impl InsertM { && self.values.len() >= self.attdefs.len() && let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation) { - let h = insert_scaled(s, &n, a, self.scale3(sc), r, self.base, &self.values)?; + let h = insert_scaled(s, &n, a, self.scale3(sc), r, self.base, &self.values, self.grid())?; if self.explode { insert_file::explode_insert(s, h)?; } @@ -628,6 +707,30 @@ impl InsertM { Ok(Step::Continue) } + /// MINSERT's next grid prompt, if any is left (as AutoCAD 2024 asks them): the rows, the + /// columns, then the distance between rows when there is more than one row and between + /// columns when there is more than one column. A unit cell gives both distances. + fn grid_stage(&self) -> Option { + if !self.minsert { + return None; + } + let (Some(rows), Some(cols)) = (self.rows, self.cols) else { + return Some(if self.rows.is_none() { InsStage::Rows } else { InsStage::Cols }); + }; + if rows > 1 && self.row_spacing.is_none() { + Some(InsStage::RowSpacing) + } else if cols > 1 && self.col_spacing.is_none() { + Some(InsStage::ColSpacing) + } else { + None + } + } + + /// The grid answered so far (one copy for INSERT). + fn grid(&self) -> Grid { + Grid::new(self.rows.unwrap_or(1), self.cols.unwrap_or(1), self.row_spacing.unwrap_or(0.0), self.col_spacing.unwrap_or(0.0)) + } + /// The Verify attributes asked for. fn verifying(&self) -> Vec<&(String, String, String, bool)> { self.attdefs.iter().filter(|a| a.3).collect() @@ -698,13 +801,18 @@ impl InsertM { } } +/// A distance typed at MINSERT's grid prompts: any finite number, negative or 0 too. +fn distance(t: &str) -> Result { + number(t).filter(|v| v.is_finite()).ok_or_else(|| EngineError::Other("Requires a distance.".into())) +} + fn nonzero(t: &str) -> Result { number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into())) } impl Interactive for InsertM { fn name(&self) -> &'static str { - "INSERT" + if self.minsert { "MINSERT" } else { "INSERT" } } fn prompt(&self, s: &Session) -> Prompt { let at = self.at.unwrap_or_default(); @@ -731,9 +839,16 @@ impl Interactive for InsertM { InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"), InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"), InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at), + InsStage::Rows => Prompt::new("Enter number of rows (---)", Accept::NUMBER).default("1"), + InsStage::Cols => Prompt::new("Enter number of columns (|||)", Accept::NUMBER).default("1"), + InsStage::RowSpacing => Prompt::new("Enter distance between rows or specify unit cell (---)", Accept::POINT_OR_NUMBER), + InsStage::Cell(a) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a), + InsStage::ColSpacing => Prompt::new("Specify distance between columns (|||)", Accept::NUMBER), InsStage::Attribs => { let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); - Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT).default(default) + let p = Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT); + // No default shown when there is none ("Value:", AutoCAD 2024), not "<>". + if default.is_empty() { p } else { p.default(default) } } InsStage::Verify => { let (tag, prompt) = self.verifying().get(self.verified).map(|a| (a.0.clone(), a.1.clone())).unwrap_or_default(); @@ -755,9 +870,9 @@ impl Interactive for InsertM { s.echo(format!("Defined blocks: {}", names.join(", "))); return Ok(Step::Continue); } - // `*name`: insert exploded. - self.explode = n.starts_with('*'); - let n = n.strip_prefix('*').map_or(n.as_str(), str::trim).to_string(); + // `*name`: insert exploded (INSERT only: a grid has no exploded form). + self.explode = !self.minsert && n.starts_with('*'); + let n = if self.explode { n.strip_prefix('*').map_or(n.as_str(), str::trim).to_string() } else { n }; match insert_file::file_ref(s, &n) { Some(f) if f.ask_redefine(s) => { self.file = Some(f); @@ -897,6 +1012,45 @@ impl Interactive for InsertM { }); return self.advance(s); } + InsStage::Rows | InsStage::Cols => { + let n = match i { + Input::Text(t) => t + .trim() + .parse::() + .ok() + .filter(|v| v.fract() == 0.0 && *v >= 1.0 && *v <= f64::from(Grid::MAX)) + .map(|v| v as u32) + .ok_or_else(|| EngineError::Other(format!("Requires an integer between 1 and {}.", Grid::MAX)))?, + Input::Enter => 1, + _ => return Ok(Step::Continue), + }; + if self.stage == InsStage::Rows { + self.rows = Some(n); + } else { + self.cols = Some(n); + } + return self.advance(s); + } + InsStage::RowSpacing => match i { + Input::Point(a) => self.stage = InsStage::Cell(a), + Input::Text(t) => { + self.row_spacing = Some(distance(&t)?); + return self.advance(s); + } + _ => {} + }, + InsStage::Cell(a) => { + if let Input::Point(b) = i { + (self.col_spacing, self.row_spacing) = (Some(b.x - a.x), Some(b.y - a.y)); + return self.advance(s); + } + } + InsStage::ColSpacing => { + if let Input::Text(t) = i { + self.col_spacing = Some(distance(&t)?); + return self.advance(s); + } + } InsStage::Attribs => { let (tag, _, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); let v = match i { @@ -937,7 +1091,9 @@ impl Interactive for InsertM { _ => Vec2::new(1.0, 1.0), }); let rot = self.rotation.unwrap_or(if self.stage == InsStage::Rotation { at.angle_to(c) } else { 0.0 }); - vec![EntityKind::Insert(insert_entity(b, at, self.scale3(scale), rot, self.base))] + let mut ins = insert_entity(b, at, self.scale3(scale), rot, self.base); + self.grid().apply(&mut ins); + vec![EntityKind::Insert(ins)] } } diff --git a/crates/engine/src/cmd/modify/explode.rs b/crates/engine/src/cmd/modify/explode.rs index b4edc2e80..21051fffc 100644 --- a/crates/engine/src/cmd/modify/explode.rs +++ b/crates/engine/src/cmd/modify/explode.rs @@ -55,6 +55,10 @@ fn explode_block_ref(d: &cadcraft_doc::Drawing, e: &Entity, ins: &cadcraft_doc:: if let Some(items) = crate::cmd::array::explode_array(d, e) { return Some(items); } + // A MINSERT grid stays whole, as in AutoCAD 2024 (see `explode`). + if minserted(ins) { + return None; + } let blk = d.block(&ins.block)?; let m = ins.transform(blk.base.xy()); let stretched = m.similarity_scale().is_none(); @@ -223,9 +227,24 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option Result> { + // AutoCAD 2024 refuses a MINSERT grid: "The object is minserted." (Locked ones are left + // without a word, as `explode_with` leaves them.) + let d = s.doc()?; + let grids = hs + .iter() + .filter(|h| !crate::cmd::curves::is_locked(s, **h) && d.entity(**h).is_some_and(|e| matches!(&e.kind, EntityKind::Insert(i) if minserted(i)))) + .count(); + for _ in 0..grids { + s.echo("The object is minserted."); + } explode_with(s, hs, explode_kind) } +/// A block reference with more than one row or column (MINSERT). +fn minserted(i: &cadcraft_doc::Insert) -> bool { + i.rows > 1 || i.cols > 1 +} + /// Replace each of `hs` (off locked layers) by the pieces `pieces` gives for it; objects it gives /// none for are left alone. EXPLODE, and BURST with its own pieces for block references. pub(crate) fn explode_with( diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 9e014d4b1..957513621 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -81,6 +81,7 @@ mod malformed_handles; mod matchprop; mod measure_distance_snapping; mod metric_linetypes; +mod minsert; mod mirror_degenerate_line; mod mleader_content; mod mleader_remember; diff --git a/crates/engine/tests/it/minsert.rs b/crates/engine/tests/it/minsert.rs new file mode 100644 index 000000000..e123876df --- /dev/null +++ b/crates/engine/tests/it/minsert.rs @@ -0,0 +1,218 @@ +//! MINSERT, one block reference repeated in rows and columns, as AutoCAD 2024 makes and edits it +//! (accoreconsole: the prompts, and `entget` of the reference after MINSERT, EXPLODE, MIRROR, +//! SCALE and ROTATE). + +use std::f64::consts::PI; + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Insert}; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> String { + v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned() +} + +/// A session with block B (a line from (0, 0) to (10, 0) and a circle of radius 3 round (5, 5), +/// base point (0, 0)), after the AutoLISP `code`. +fn run(code: &str) -> Session { + let mut s = Session::new(); + let a = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()); + let c = handle(&s.execute("circle", &json!({"center": [5, 5], "radius": 3})).unwrap()); + s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [a, c]})).unwrap(); + s.cmdline(code).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + s +} + +fn inserts(s: &Session) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Insert(i) => Some(i.clone()), + _ => None, + }) + .collect() +} + +/// The grid as `entget` gives it: 70 columns, 71 rows, 44 between columns, 45 between rows (a +/// plain reference, one row and one column, as 1/1/0/0). +fn grid(i: &Insert) -> (u32, u32, f64, f64) { + (i.cols, i.rows, i.col_spacing, i.row_spacing) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +#[test] +fn the_grid_is_stored_as_autocad_2024_stores_it() { + // (MINSERT's answers after the block name and insertion point, the grid AutoCAD stored.) + let cases = [ + // One row: no distance between rows asked, and 0 stored for it. + ("1 \"\" 0 1 3 20.0", (3, 1, 20.0, 0.0)), + ("1 \"\" 0 3 1 15.0", (1, 3, 0.0, 15.0)), + // One of each: a plain reference. + ("1 \"\" 0 1 1", (1, 1, 0.0, 0.0)), + // A unit cell: its width between columns, its height between rows, signed. + ("1 \"\" 0 2 3 '(0.0 0.0) '(25.0 12.0)", (3, 2, 25.0, 12.0)), + ("1 \"\" 0 2 3 '(25.0 12.0) '(0.0 0.0)", (3, 2, -25.0, -12.0)), + // Its sides along the drawing's axes, the reference rotated or not. + ("1 \"\" 30 2 3 '(0.0 0.0) '(25.0 12.0)", (3, 2, 25.0, 12.0)), + // Typed distances are kept as typed, negative or 0 too. + ("1 \"\" 0 2 2 -15.0 -20.0", (2, 2, -20.0, -15.0)), + ("1 \"\" 0 2 2 0.0 20.0", (2, 2, 20.0, 0.0)), + // The distances are not scaled with the reference. + ("2 \"\" 30 2 2 15.0 20.0", (2, 2, 20.0, 15.0)), + ]; + for (answers, want) in cases { + let s = run(&format!("(command \"_.MINSERT\" \"B\" '(20.0 10.0) {answers})")); + let [i] = inserts(&s).try_into().unwrap(); + let got = grid(&i); + assert!(got.0 == want.0 && got.1 == want.1 && near(got.2, want.2) && near(got.3, want.3), "{answers}: {got:?}"); + assert!(near(i.insert.x, 20.0) && near(i.insert.y, 10.0)); + } + let s = run("(command \"_.MINSERT\" \"B\" '(20.0 10.0) 2 \"\" 30 2 2 15.0 20.0)"); + let [i] = inserts(&s).try_into().unwrap(); + assert!(near(i.scale.x, 2.0) && near(i.scale.y, 2.0) && near(i.rotation, PI / 6.0)); +} + +#[test] +fn the_prompts_follow_autocad_2024() { + let mut s = Session::new(); + let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()); + s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap(); + // Each prompt, and what was written to the command line on the way to it. + let mut asked = Vec::new(); + for input in ["minsert", "B", "20,10", "1", "", "0", "0", "2", "3", "x", "15", "20"] { + let logged = s.log.len(); + s.cmdline(input).unwrap(); + asked.extend(s.log.iter().skip(logged).filter(|l| l.starts_with("Requires")).cloned()); + if let Some(p) = s.current_prompt() { + asked.push(p.display()); + } + } + // The grid's prompts and messages are AutoCAD 2024's; the ones before are INSERT's. + assert_eq!( + asked, + [ + "Enter block name or [?]:", + "Specify insertion point or [Basepoint/Scale/X/Y/Z/Rotate]:", + "Enter X scale factor, specify opposite corner or [Corner/XYZ] <1>:", + "Enter Y scale factor :", + "Specify rotation angle <0>:", + "Enter number of rows (---) <1>:", + "Requires an integer between 1 and 32767.", + "Enter number of rows (---) <1>:", + "Enter number of columns (|||) <1>:", + "Enter distance between rows or specify unit cell (---):", + "Requires a distance.", + "Enter distance between rows or specify unit cell (---):", + "Specify distance between columns (|||):", + ] + ); + assert!(s.running.is_none()); + let [i] = inserts(&s).try_into().unwrap(); + assert_eq!(grid(&i), (3, 2, 20.0, 15.0)); +} + +#[test] +fn counts_run_from_1_to_32767() { + // AutoCAD 2024: "Requires an integer between 1 and 32767." + let mut s = Session::new(); + let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()); + s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap(); + for input in ["minsert", "B", "0,0", "1", "", "0", "32768", "32767", "1", "2"] { + s.cmdline(input).unwrap(); + } + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(s.log.iter().filter(|l| l.starts_with("Requires an integer between 1 and 32767.")).count(), 1, "{:?}", s.log); + let [i] = inserts(&s).try_into().unwrap(); + assert_eq!(grid(&i), (1, 32767, 0.0, 2.0)); +} + +#[test] +fn attribute_values_are_asked_once_after_the_grid() { + let mut s = Session::new(); + let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()); + let a = handle(&s.execute("attdef", &json!({"tag": "TAG", "prompt": "Value", "at": [0, 2], "height": 1})).unwrap()); + s.execute("-block", &json!({"name": "BA", "base": [0, 0], "handles": [l, a]})).unwrap(); + for input in ["minsert", "BA", "0,700", "1", "", "0", "5", "4", "15", "20"] { + s.cmdline(input).unwrap(); + } + // After the grid, with no "<>" for an empty default (AutoCAD 2024: "Value: hello"). + assert_eq!(s.current_prompt().unwrap().display(), "Value:"); + s.cmdline("hello").unwrap(); + assert!(s.running.is_none()); + let [i] = inserts(&s).try_into().unwrap(); + assert_eq!(grid(&i), (4, 5, 20.0, 15.0)); + assert_eq!(i.attribs.iter().map(|a| a.text.value.as_str()).collect::>(), ["hello"]); +} + +#[test] +fn explode_leaves_a_grid_whole() { + let s = run("(progn (command \"_.MINSERT\" \"B\" '(20.0 10.0) 1 \"\" 0 2 2 15.0 20.0) (command \"_.EXPLODE\" (entlast) \"\"))"); + let [i] = inserts(&s).try_into().unwrap(); + assert_eq!(grid(&i), (2, 2, 20.0, 15.0)); + assert_eq!(s.doc().unwrap().model.iter().count(), 1); + assert!(s.log.iter().any(|l| l.contains("The object is minserted.")), "{:?}", s.log); +} + +#[test] +fn edits_carry_the_grid_as_in_autocad_2024() { + let made = "(command \"_.MINSERT\" \"B\" '(20.0 10.0) 1 \"\" 0 2 2 15.0 20.0)"; + // (the edit, the copy it leaves last: insertion point, X and Y scale, rotation, grid) + let cases = [ + ("(command \"_.SCALE\" (entlast) \"\" '(20.0 10.0) 2)", ([20.0, 10.0], [2.0, 2.0], 0.0, (2, 2, 40.0, 30.0))), + ("(command \"_.ROTATE\" (entlast) \"\" '(20.0 10.0) 30)", ([20.0, 10.0], [1.0, 1.0], PI / 6.0, (2, 2, 20.0, 15.0))), + ("(command \"_.MOVE\" (entlast) \"\" '(20.0 10.0) '(25.0 13.0))", ([25.0, 13.0], [1.0, 1.0], 0.0, (2, 2, 20.0, 15.0))), + // Mirrored about the vertical through the insertion point, and about the horizontal: X + // scale -1, and the columns run the other way. + ("(command \"_.MIRROR\" (entlast) \"\" '(20.0 10.0) '(20.0 30.0) \"_N\")", ([20.0, 10.0], [-1.0, 1.0], 0.0, (2, 2, -20.0, 15.0))), + ("(command \"_.MIRROR\" (entlast) \"\" '(20.0 10.0) '(40.0 10.0) \"_N\")", ([20.0, 10.0], [-1.0, 1.0], PI, (2, 2, -20.0, 15.0))), + ]; + for (edit, (at, scale, rot, want)) in cases { + let s = run(&format!("(progn {made} {edit})")); + let i = inserts(&s).pop().unwrap(); + let got = grid(&i); + assert!( + near(i.insert.x, at[0]) + && near(i.insert.y, at[1]) + && near(i.scale.x, scale[0]) + && near(i.scale.y, scale[1]) + && near(i.rotation, rot) + && got.0 == want.0 + && got.1 == want.1 + && near(got.2, want.2) + && near(got.3, want.3), + "{edit}: {i:?}" + ); + } +} + +#[test] +fn the_json_form_makes_the_same_grid() { + let mut s = Session::new(); + let l = handle(&s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap()); + s.execute("-block", &json!({"name": "B", "base": [0, 0], "handles": [l]})).unwrap(); + s.execute("minsert", &json!({"name": "B", "at": [20, 10], "rows": 2, "columns": 3, "rowSpacing": 15, "columnSpacing": 20})).unwrap(); + // One row: its distance is not kept. + s.execute("minsert", &json!({"name": "B", "at": [20, 100], "rows": 1, "columns": 3, "rowSpacing": 15, "columnSpacing": 20})).unwrap(); + let got: Vec<_> = inserts(&s).iter().map(grid).collect(); + assert_eq!(got, [(3, 2, 20.0, 15.0), (3, 1, 20.0, 0.0)]); + for bad in [ + json!({"name": "B", "at": [0, 0], "rows": 0}), + json!({"name": "B", "at": [0, 0], "columns": 32768}), + json!({"name": "B", "at": [0, 0], "rows": 2.5}), + // A distance that is not a number is refused, not taken as 0. + json!({"name": "B", "at": [0, 0], "rows": 2, "rowSpacing": "15"}), + json!({"name": "B", "at": [0, 0], "columns": 2, "columnSpacing": true}), + ] { + assert!(s.execute("minsert", &bad).is_err(), "{bad}"); + } + // A whole number written as 2.0 is a count; `explode` is INSERT's and leaves the grid made. + let r = s.execute("minsert", &json!({"name": "B", "at": [0, 200], "rows": 2.0, "rowSpacing": 15, "explode": true})).unwrap(); + assert!(r["handle"].is_string(), "{r}"); + assert_eq!(inserts(&s).last().map(grid), Some((1, 2, 0.0, 15.0))); +} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 34eb084eb..91ed70cf7 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -533,6 +533,7 @@ Multiline Text Chữ nhiều dòng Multiline Text... Chữ nhiều dòng... Multiple Nhiều + Multiple Insert Chèn nhiều Multiple Point Nhiều điểm My Của tôi My properties: not available yet Thuộc tính của tôi: chưa khả dụng diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index a8d979efa..eae92cc14 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -448,6 +448,7 @@ Multiline Text 多行文字 Multiline Text... 多行文字... Multiple 多个 + Multiple Insert 多重插入 Multiple Point 多点 My 我的 My properties: not available yet 我的属性:暂不可用 From ffc2c553e87ee494c2e7905468e2c1c65534bd00 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:07:02 +0100 Subject: [PATCH 480/900] Drop missing files from the recent list when opening them fails (#2706) * Drop missing files from the recent list when opening them fails Fixes #2700 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 * Keep a recent file whose existence can't be checked (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Haiku 5.5 Co-authored-by: Brandon Thomas --- crates/ui-egui/src/lib.rs | 8 +++++++- crates/ui-egui/tests/recent_files.rs | 12 ++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3e635ea2f..d27712da2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -570,7 +570,13 @@ impl CadApp { /// Add the files whose background read has finished; report the ones that failed as a failed /// OPEN is reported. Called every frame. pub fn finish_opening(&mut self) { - for (_, outcome) in self.opening.poll() { + for (path, outcome) in self.opening.poll() { + // A recent file that is gone can never be opened again: drop it from the list. A path + // whose existence can't be checked (a folder that denies access) stays. + if outcome.is_err() && matches!(path.try_exists(), Ok(false)) { + let path = path.to_string_lossy(); + self.ui.recent_files.retain(|p| *p != path); + } let r = match outcome { Ok(f) => self.session.finish_open(f).map_err(|e| e.to_string()), Err(e) => Err(e), diff --git a/crates/ui-egui/tests/recent_files.rs b/crates/ui-egui/tests/recent_files.rs index 34d460255..34aa6e2e8 100644 --- a/crates/ui-egui/tests/recent_files.rs +++ b/crates/ui-egui/tests/recent_files.rs @@ -135,3 +135,15 @@ fn start_page_lists_recent_files_and_opens_one_on_click() { assert_eq!(app.session.state().ok().and_then(|s| s.path.clone()), Some(plan.clone())); assert_eq!(app.ui.recent_files, [plan, section]); } + +#[test] +fn a_recent_file_that_no_longer_exists_is_dropped_when_opening_it_fails() { + let (_dir, plan, _section) = drawings("missing"); + let mut app = CadApp::new(Session::empty(), Services::default()); + let gone = "/nonexistent/dir/gone.dxf".to_string(); + app.ui.recent_files = vec![gone.clone(), plan.clone()]; + let id = open_recent(&app).into_iter().find(|(l, _)| l == "gone.dxf").map(|(_, id)| id).unwrap_or_default(); + menus::activate(&mut app, &id); + settle(&mut app); + assert_eq!(app.ui.recent_files, [plan], "the stale entry is removed, the others stay"); +} From 1619e24381a09c72495117e6bd3b19bbb13a3cd7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 09:07:07 -0500 Subject: [PATCH 481/900] fix(io): DXF import looks up linetype, style and entity layer names in a set (#2707) LTYPE records scanned every linetype read so far, STYLE records every text style, and each entity's layer went through Drawing::ensure_layer's scan of the layer table, so a DXF with many distinct names read in quadratic time. These now use indexes built once per pass, as LAYER records already did; first-LTYPE-wins and last-STYLE-wins are unchanged. --- crates/io/src/dxf_read/document.rs | 23 +++++++++++++++++++++-- crates/io/src/dxf_read/tables.rs | 13 ++++++++++--- crates/io/src/tests.rs | 22 ++++++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index 6f61e3415..ef35212a8 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -178,14 +178,32 @@ pub(super) fn setup_layouts(d: &mut Drawing, layout_objs: &mut [LayoutDef], rx: (paper_block_for, first_layout) } +/// The drawing's layer names (lower-cased), so adding the layer an entity names is a set lookup +/// rather than a scan of the layer table per entity: many distinct names made that quadratic +/// (CWE-407). +struct LayerSet(std::collections::HashSet); + +impl LayerSet { + fn new(d: &Drawing) -> Self { + Self(d.layers.iter().map(|l| l.name.to_ascii_lowercase()).collect()) + } + /// [`Drawing::ensure_layer`] through the set. + fn ensure(&mut self, d: &mut Drawing, name: &str) { + if self.0.insert(name.to_ascii_lowercase()) { + d.layers.push(cadcraft_doc::Layer::new(name)); + } + } +} + /// Place the BLOCKS entities: model and paper space blocks go to their space, the rest become /// block definitions. pub(super) fn place_blocks(d: &mut Drawing, blocks: Vec, rx: &mut Rx, paper_block_for: &HashMap, first_layout: &str) { + let mut layers = LayerSet::new(d); for (name, base, description, ents, xref) in blocks { let up = name.to_ascii_uppercase(); if up == "*MODEL_SPACE" { for (_, _, e) in ents { - d.ensure_layer(&e.common.layer); + layers.ensure(d, &e.common.layer); d.model.push(e); } continue; @@ -241,8 +259,9 @@ pub(super) fn place_entities( paper_block_for: &HashMap, first_layout: &str, ) { + let mut layers = LayerSet::new(d); for (owner, paper, e) in entities { - d.ensure_layer(&e.common.layer); + layers.ensure(d, &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 { diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index c914ea9f5..f05a7307e 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -110,6 +110,9 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { // appends in O(1) instead of scanning the growing layer list — otherwise many distinct layer // names make import quadratic (CWE-407). let mut layer_index: HashMap = d.layers.iter().enumerate().map(|(i, l)| (l.name.to_ascii_lowercase(), i)).collect(); + // The same for linetypes (first definition wins) and text styles (last definition wins). + let mut linetype_names: std::collections::HashSet = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect(); + let mut style_index: HashMap = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect(); for (kind, tg) in recs { let t = T(&tg); match kind.as_str() { @@ -159,9 +162,10 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { } "LTYPE" => { let name = t.s(2).unwrap_or_default(); - if name.is_empty() || d.linetype(&name).is_some() || d.linetypes.len() >= MAX_OBJECTS { + if name.is_empty() || linetype_names.contains(&name.to_ascii_lowercase()) || d.linetypes.len() >= MAX_OBJECTS { continue; } + linetype_names.insert(name.to_ascii_lowercase()); let pattern = ltype_pattern(&tg, <ype_styles); d.linetypes.push(Linetype { name, description: t.s(3).unwrap_or_default(), pattern }); } @@ -184,9 +188,12 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { vertical: t.i(70).unwrap_or(0) & 4 != 0, annotative: annotative(&tg), }; - match d.text_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(&name)) { + match style_index.get(&name.to_ascii_lowercase()).and_then(|&i| d.text_styles.get_mut(i)) { Some(x) => *x = st, - None => d.text_styles.push(st), + None => { + style_index.insert(name.to_ascii_lowercase(), d.text_styles.len()); + d.text_styles.push(st); + } } } // The first *ACTIVE viewport holds the current snap/grid settings. diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 46536f24e..f9353481e 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -337,6 +337,28 @@ fn entity_transparency_roundtrips_as_group_440() { assert_eq!(d.model.iter().map(|e| e.common.transparency).collect::>(), [Transparency::ByLayer, Transparency::Percent(90)]); } +/// Many distinct layer, linetype and style names (in the tables and on entities) read in linear +/// time, with the duplicate rules kept: first LTYPE wins, last STYLE wins, layers case-insensitive. +#[test] +fn many_distinct_symbol_names_read_quickly() { + const N: usize = 40_000; + let mut t = String::from("0\nSECTION\n2\nTABLES\n"); + for i in 0..N { + t.push_str(&format!("0\nLTYPE\n2\nLT{i}\n3\nfirst\n0\nSTYLE\n2\nST{i}\n40\n1\n")); + } + t.push_str("0\nLTYPE\n2\nlt0\n3\nsecond\n0\nSTYLE\n2\nst0\n40\n2\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"); + for i in 0..N { + t.push_str(&format!("0\nLINE\n8\nL{i}\n10\n0\n20\n0\n11\n1\n21\n1\n")); + } + t.push_str("0\nLINE\n8\nl0\n10\n0\n20\n0\n11\n1\n21\n1\n0\nENDSEC\n0\nEOF\n"); + let started = std::time::Instant::now(); + let d = read(t.as_bytes(), "many.dxf").unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(20), "took {:?}", started.elapsed()); + assert!(d.layers.len() > N && d.layers.len() < N + 3, "{}", d.layers.len()); + assert_eq!(d.linetype("LT0").map(|l| l.description.as_str()), Some("first")); + assert_eq!(d.text_style("ST0").map(|s| s.height), Some(2.0)); +} + #[test] fn hostile_dxf_does_not_panic() { for t in [ From f2afcd4f0226090bbf19873a2464da9f55b6549c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 09:07:10 -0500 Subject: [PATCH 482/900] fix(engine): look names up in an index in AUDIT, layer-state restore and CAL (#2712) AUDIT checked every layer's linetype and every style's text style by scanning the table; LAYERSTATE restore and restoring a named view's layer snapshot scanned the layer table for every saved layer; CAL scanned the variable map for every case-insensitive reference. Each now builds its name index once, keeping the same first-match and exact-match rules. --- crates/engine/src/audit.rs | 9 +++--- crates/engine/src/cmd/layer.rs | 36 ++++++++++++++++++++--- crates/engine/src/cmd/utility/calc.rs | 32 +++++++++++++++++--- crates/engine/src/cmd/view/named_views.rs | 8 +---- 4 files changed, 66 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/audit.rs b/crates/engine/src/audit.rs index c055bff25..5940a96c1 100644 --- a/crates/engine/src/audit.rs +++ b/crates/engine/src/audit.rs @@ -234,9 +234,10 @@ fn tables(d: &mut Drawing, out: &mut Vec) { missing("table style", "Standard", out); d.table_styles.insert(0, TableStyle::default()); } - let linetypes: Vec = d.linetypes.iter().map(|l| l.name.clone()).collect(); + // Name sets built once: both tables come from the drawing, so a scan per reference is quadratic. + let linetypes: HashSet = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect(); for l in &mut d.layers { - if !linetypes.iter().any(|n| n.eq_ignore_ascii_case(&l.linetype)) { + if !linetypes.contains(&l.linetype.to_ascii_lowercase()) { out.push(issue( "missingLinetype", "tables", @@ -247,8 +248,8 @@ fn tables(d: &mut Drawing, out: &mut Vec) { l.linetype = "Continuous".into(); } } - let styles: Vec = d.text_styles.iter().map(|s| s.name.clone()).collect(); - let known = |n: &str| styles.iter().any(|s| s.eq_ignore_ascii_case(n)); + let styles: HashSet = d.text_styles.iter().map(|s| s.name.to_ascii_lowercase()).collect(); + let known = |n: &str| styles.contains(&n.to_ascii_lowercase()); for s in &mut d.dim_styles { if !known(&s.text_style) { out.push(issue( diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5fa89403..41c58febe 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -408,12 +408,24 @@ fn run_state_restore(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("layerstate.restore", "`name` is required"))?; let d = s.doc_mut()?; let st = d.layer_states.iter().find(|st| st.name == name).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?; - for saved in st.layers { - if let Some(l) = d.layer_mut(&saved.name) { - *l = saved; + restore_layers(d, st.layers); + ok() +} + +/// Put the saved layers back over the drawing's layers of the same name (without regard to case); +/// saved layers the drawing no longer has are skipped. Both lists can come from a file, so the +/// drawing's layers are looked up in an index rather than scanned per saved layer. +pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec) { + let mut index: std::collections::HashMap = std::collections::HashMap::with_capacity(d.layers.len()); + for (i, l) in d.layers.iter().enumerate() { + // The first of names that differ only in case, as `Drawing::layer_mut` finds it. + index.entry(l.name.to_ascii_lowercase()).or_insert(i); + } + for layer in saved { + if let Some(l) = index.get(&layer.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) { + *l = layer; } } - ok() } fn run_state_list(s: &mut Session, _p: &Value) -> Result { @@ -461,6 +473,22 @@ mod tests { use crate::Session; + /// Restoring many saved layers, most of them missing, takes one pass and matches without case. + #[test] + fn restore_layers_matches_by_name_in_linear_time() { + let mut d = cadcraft_doc::Drawing::new_imperial(); + d.layers = (0..20_000).map(|i| cadcraft_doc::Layer::new(&format!("L{i}"))).collect(); + let mut saved: Vec = (0..20_000).map(|i| cadcraft_doc::Layer::new(&format!("missing{i}"))).collect(); + let mut back = cadcraft_doc::Layer::new("l7"); + back.frozen = true; + saved.push(back); + let started = std::time::Instant::now(); + super::restore_layers(&mut d, saved); + assert!(started.elapsed() < std::time::Duration::from_secs(2)); + assert!(d.layer("L7").is_some_and(|l| l.frozen)); + assert_eq!(d.layers.len(), 20_000); + } + #[test] fn layer_states_save_list_restore_delete() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/utility/calc.rs b/crates/engine/src/cmd/utility/calc.rs index 0c0d29b32..bcba8052a 100644 --- a/crates/engine/src/cmd/utility/calc.rs +++ b/crates/engine/src/cmd/utility/calc.rs @@ -1,6 +1,8 @@ //! The CAL / QuickCalc evaluator: numbers and points (`[x,y]`, `[d { s: &'a [u8], i: usize, vars: &'a Map, + /// `vars` by ASCII-lower-cased name (the first of names that differ only in case), so a + /// case-insensitive lookup is not a scan of the map per reference. + folded: HashMap, depth: usize, unary_depth: usize, } @@ -230,7 +235,7 @@ impl Parser<'_> { match name.as_str() { "pi" => Ok(Val::Num(std::f64::consts::PI)), "e" => Ok(Val::Num(std::f64::consts::E)), - _ => var(self.vars, &name).ok_or_else(|| format!("unknown name `{name}`")), + _ => var(self.vars, &self.folded, &name).ok_or_else(|| format!("unknown name `{name}`")), } } _ => Err("expected a number".into()), @@ -239,8 +244,8 @@ impl Parser<'_> { } /// A variable: a number, or a point as `[x, y]`. Names are case-insensitive. -fn var(vars: &Map, name: &str) -> Option { - let v = vars.get(name).or_else(|| vars.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))?; +fn var(vars: &Map, folded: &HashMap, name: &str) -> Option { + let v = vars.get(name).or_else(|| folded.get(&name.to_ascii_lowercase()).copied())?; if let Some(n) = v.as_f64() { return Some(Val::Num(n)); } @@ -411,7 +416,11 @@ pub fn eval_val(expr: &str, vars: &Map) -> Result { if expr.len() > MAX_LEN { return Err("expression too long".into()); } - let mut p = Parser { s: expr.as_bytes(), i: 0, vars, depth: 0, unary_depth: 0 }; + let mut folded = HashMap::with_capacity(vars.len()); + for (k, v) in vars { + folded.entry(k.to_ascii_lowercase()).or_insert(v); + } + let mut p = Parser { s: expr.as_bytes(), i: 0, vars, folded, depth: 0, unary_depth: 0 }; let v = p.expr()?; if p.peek().is_some() { return Err(format!("unexpected `{}`", expr.get(p.i..).unwrap_or(""))); @@ -587,6 +596,21 @@ mod tests { eval_val(s, &Map::new()) } + /// Variables are found without regard to case; an exact match wins over a case variant. + /// (Names are read lower-cased, so `X` finds `x` too.) + #[test] + fn variables_ignore_case_and_prefer_exact_names() { + let mut vars = Map::new(); + for i in 0..10_000 { + vars.insert(format!("v{i}"), json!(i)); + } + vars.insert("X".into(), json!(1)); + vars.insert("x".into(), json!(2)); + assert!(matches!(eval_val("V9999 + 1", &vars), Ok(Val::Num(n)) if n == 10_000.0)); + assert!(matches!(eval_val("x", &vars), Ok(Val::Num(n)) if n == 2.0)); + assert!(eval_val("nope", &vars).is_err()); + } + #[test] fn points_and_vectors() { assert_eq!(ev("[1,2]+[3,4]*2"), Ok(Val::Pt(Vec2::new(7.0, 10.0)))); diff --git a/crates/engine/src/cmd/view/named_views.rs b/crates/engine/src/cmd/view/named_views.rs index f88d240db..c89b8cadb 100644 --- a/crates/engine/src/cmd/view/named_views.rs +++ b/crates/engine/src/cmd/view/named_views.rs @@ -185,13 +185,7 @@ fn restore(s: &mut Session, name: &str) -> Result { if let Some(state) = &v.layer_state { let d = s.doc_mut()?; match d.layer_states.iter().find(|l| l.name.eq_ignore_ascii_case(state)).cloned() { - Some(saved) => { - for layer in saved.layers { - if let Some(l) = d.layer_mut(&layer.name) { - *l = layer; - } - } - } + Some(saved) => super::super::layer::restore_layers(d, saved.layers), None => msg.push_str(&format!(" Its layer snapshot \"{state}\" is missing.")), } } From 578da3ba9c3ff38090d10c6bef3c01c4f9892e5a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 09:07:46 -0500 Subject: [PATCH 483/900] fix(io): an ACAD_TABLE with no rows or no columns reads as an empty table (#2708) * fix(io): an ACAD_TABLE with no rows or no columns reads as an empty table The table cell budget charges rows x columns, which is zero when either dimension is, so a table declaring 10 000 rows and no columns still allocated row heights and empty row vectors for free, once per record. Such a table now keeps neither dimension. * Test: assert the empty table is read (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/io/src/dxf_read/entities.rs | 4 +++- crates/io/src/tests.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 6ca0f30d1..b5002bb3d 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -299,7 +299,9 @@ pub(super) fn acad_table(tags: &[Tag], table_cells_left: &mut usize) -> Table { // Large declared sizes must be backed by cell records (no allocation from a bare count). let n_cells = tail.iter().filter(|x| x.code == 171).count(); let declared = rows.saturating_mul(cols); - if declared > MAX_CELLS || (declared > 10_000 && n_cells < declared) { + // A table with no rows or no columns has no cells: keep neither dimension, so its row heights + // and column widths (allocated per dimension, outside the cell budget) are not allocated. + if declared == 0 || declared > MAX_CELLS || (declared > 10_000 && n_cells < declared) { rows = 0; cols = 0; } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index f9353481e..ede2afce9 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -337,6 +337,20 @@ fn entity_transparency_roundtrips_as_group_440() { assert_eq!(d.model.iter().map(|e| e.common.transparency).collect::>(), [Transparency::ByLayer, Transparency::Percent(90)]); } +/// A table declaring 10 000 rows and no columns (or the reverse) is read as an empty table. +#[test] +fn table_with_an_empty_dimension_allocates_nothing() { + for (rows, cols) in [(10_000, 0), (0, 10_000)] { + let t = format!("0\nSECTION\n2\nENTITIES\n0\nACAD_TABLE\n100\nAcDbTable\n91\n{rows}\n92\n{cols}\n0\nENDSEC\n0\nEOF\n"); + let d = read(t.as_bytes(), "t.dxf").unwrap(); + let tables: Vec<_> = d.model.iter().filter_map(|e| if let EntityKind::Table(t) = &e.kind { Some(t) } else { None }).collect(); + assert_eq!(tables.len(), 1, "the table is read"); + for t in tables { + assert!(t.row_heights.is_empty() && t.col_widths.is_empty() && t.cells.is_empty()); + } + } +} + /// Many distinct layer, linetype and style names (in the tables and on entities) read in linear /// time, with the duplicate rules kept: first LTYPE wins, last STYLE wins, layers case-insensitive. #[test] From b639b18f69bfefd58f866fd0dc04940d0c6aa6e6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 09:08:07 -0500 Subject: [PATCH 484/900] fix(io): sort each space once when a DXF has several SORTENTSTABLEs for it (#2709) Every SORTENTSTABLE rebuilt its whole entity store, so many small tables naming one large space made import quadratic. Each space is now sorted once, by the last table naming it, which already decided its order. Co-authored-by: Brandon Thomas --- crates/io/src/dxf_read/document.rs | 12 +++++++++++- crates/io/src/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_read/document.rs b/crates/io/src/dxf_read/document.rs index ef35212a8..7d22e95d1 100644 --- a/crates/io/src/dxf_read/document.rs +++ b/crates/io/src/dxf_read/document.rs @@ -333,7 +333,17 @@ pub(super) fn apply_sortents( paper_for: &HashMap, first_layout: &str, ) { - for (owner, map) in tables { + // Each sort rebuilds its whole space, so a space named by many tables is sorted once, by the + // last of them (which decided its order anyway); repeated tables made import quadratic. + let target = |owner: &String| { + let up = brs.get(owner)?.to_ascii_uppercase(); + Some(if up.starts_with("*PAPER_SPACE") { paper_for.get(&up).cloned().unwrap_or_else(|| first_layout.to_string()) + "\0paper" } else { up }) + }; + let last: HashMap = tables.iter().enumerate().filter_map(|(i, (owner, _))| Some((target(owner)?, i))).collect(); + for (i, (owner, map)) in tables.iter().enumerate() { + if target(owner).and_then(|t| last.get(&t)) != Some(&i) { + continue; + } let Some(name) = brs.get(owner) else { continue }; let up = name.to_ascii_uppercase(); // A sort handle of 0 draws last (ezdxf `reorder`, which notes AutoCAD defines it, undocumented). diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index ede2afce9..ecfc43ca7 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -337,6 +337,28 @@ fn entity_transparency_roundtrips_as_group_440() { assert_eq!(d.model.iter().map(|e| e.common.transparency).collect::>(), [Transparency::ByLayer, Transparency::Percent(90)]); } +/// Several SORTENTSTABLEs for one space sort it once, in the last table's order. +#[test] +fn repeated_sortents_tables_use_the_last() { + let table = + |a: u32, b: u32| format!("0\nSORTENTSTABLE\n5\n{:X}\n100\nAcDbSortentsTable\n330\n1F\n331\nA\n5\n{a:X}\n331\nB\n5\n{b:X}\n", 0x100 + a); + let mut t = String::from( + "0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nBLOCK_RECORD\n0\nBLOCK_RECORD\n5\n1F\n2\n*Model_Space\n0\nENDTAB\n0\nENDSEC\n\ + 0\nSECTION\n2\nENTITIES\n0\nLINE\n5\nA\n330\n1F\n10\n0\n20\n0\n11\n1\n21\n1\n0\nLINE\n5\nB\n330\n1F\n10\n0\n20\n0\n11\n2\n21\n2\n0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nC\n", + ); + for _ in 0..1000 { + t.push_str(&table(2, 1)); + } + t.push_str(&table(1, 2)); + t.push_str("0\nENDSEC\n0\nEOF\n"); + let d = read(t.as_bytes(), "s.dxf").unwrap(); + assert_eq!(d.model.iter().map(|e| e.handle.0).collect::>(), [0xA, 0xB]); + let reversed = t.replacen(&table(1, 2), &table(2, 1), 1); + let d = read(reversed.as_bytes(), "s.dxf").unwrap(); + assert_eq!(d.model.iter().map(|e| e.handle.0).collect::>(), [0xB, 0xA]); +} + /// A table declaring 10 000 rows and no columns (or the reverse) is read as an empty table. #[test] fn table_with_an_empty_dimension_allocates_nothing() { From 41f9e394b90b30d327c30a2fc95a8c0eb8e45063 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:42:49 +0100 Subject: [PATCH 485/900] fix(io): draw a tilted 2D POLYLINE as seen from above, like LWPOLYLINE (follow-up to #2584) --- crates/io/src/dxf_read/entities.rs | 24 ++++++++++---- crates/io/src/tests.rs | 51 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 6 deletions(-) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 3636d32a9..083cdc14d 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -539,7 +539,7 @@ pub(super) fn polyline_entity(recs: &[(String, Vec)], i: &mut usize, t: &T) break; } } - let c = common(t); + let mut c = common(t); let mut extra: Vec = Vec::new(); let k = if flags & (16 | 64) != 0 { // Polyface (64) and polygon (16) meshes become 3D faces; the first takes the @@ -552,13 +552,25 @@ pub(super) fn polyline_entity(recs: &[(String, Vec)], i: &mut usize, t: &T) } else if flags & 8 != 0 { EntityKind::Polyline3d(Polyline3d { points: pts.iter().map(|p| p.0).collect(), closed: flags & 1 != 0 }) } else { - // A 2D polyline's vertices are in its OCS: mirrored like LWPOLYLINE. - let m = if c.extrusion.z < 0.0 { -1.0 } else { 1.0 }; + // A 2D polyline's vertices are in its OCS, at the elevation of the POLYLINE's own point: + // in a tilted plane drawn as seen from above like LWPOLYLINE, else mirrored like it. + let closed = flags & 1 != 0; + let mut vertices: Vec = pts.iter().map(|p| PolyVertex { p: p.0.xy(), bulge: p.1, start_width: p.2, end_width: p.3 }).collect(); + let mut elevation = t.p(10).z; + if tilted(c.extrusion, run_points(&vertices, elevation, closed)) { + (vertices, elevation) = plan_of_tilted(c.extrusion, elevation, &vertices, closed); + c.extrusion = Vec3::Z; + } else if c.extrusion.z < 0.0 { + for v in &mut vertices { + v.p.x = -v.p.x; + v.bulge = -v.bulge; + } + } EntityKind::LwPolyline(LwPolyline { - vertices: pts.iter().map(|p| PolyVertex { p: Vec2::new(m * p.0.x, p.0.y), bulge: m * p.1, start_width: p.2, end_width: p.3 }).collect(), - closed: flags & 1 != 0, + vertices, + closed, const_width: t.fd(40, 0.0).min(t.fd(41, 0.0)).max(0.0), - elevation: t.p(10).z, + elevation, plinegen: flags & 128 != 0, }) }; diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 2f5206971..3a34f1572 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2238,6 +2238,57 @@ fn tilted_lwpolyline_is_drawn_as_seen_from_above() { assert_eq!(p.vertices.iter().map(|v| v.bulge).collect::>(), vec![1.0, 1.0]); } +/// A 2D POLYLINE (heavy polyline) in a tilted plane is drawn as seen from above, like a +/// LWPOLYLINE: before, its OCS points were taken for world coordinates. With extrusion +/// (0, 0.5, -√3/2) the OCS axes are x = (-1,0,0) and y = (0, √3/2, 1/2), and the elevation of 2 +/// moves the plane by twice the normal, (0, 1, -√3): the square (1,0)..(3,2) lies over +/// (-3,1)..(-1,1+√3), its corners at a mean height of 1/2 - √3. +#[test] +fn tilted_2d_polyline_is_drawn_as_seen_from_above() { + let square = |n: &str| { + format!( + "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n2\n70\n1\n{n}\ + 0\nVERTEX\n8\n0\n10\n1\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n0\n0\nVERTEX\n8\n0\n10\n3\n20\n2\n\ + 0\nVERTEX\n8\n0\n10\n1\n20\n2\n0\nSEQEND\n0\nENDSEC\n0\nEOF\n" + ) + }; + let d = read(square("210\n0\n220\n0.5\n230\n-0.8660254037844386\n").as_bytes(), "p.dxf").unwrap(); + let b = d.extents(&Space::Model); + let r3 = 3f64.sqrt(); + for (got, want) in [(b.min.x, -3.0), (b.min.y, 1.0), (b.max.x, -1.0), (b.max.y, 1.0 + r3)] { + 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::LwPolyline(p) = &e.kind else { panic!("not a polyline") }; + assert!((p.elevation - (0.5 - r3)).abs() < 1e-9, "the mean height of its corners: {}", p.elevation); + // In plan and in the mirrored plane the polyline stays as it was: mirrored only in x. + let plain = read(square("").as_bytes(), "p.dxf").unwrap(); + let b = plain.extents(&Space::Model); + assert!((b.min.x - 1.0).abs() < 1e-9 && (b.max.y - 2.0).abs() < 1e-9, "extents {b:?}"); + let mirrored = read(square("210\n0\n220\n0\n230\n-1\n").as_bytes(), "p.dxf").unwrap(); + let b = mirrored.extents(&Space::Model); + assert!((b.min.x + 3.0).abs() < 1e-9 && (b.max.x + 1.0).abs() < 1e-9, "extents {b:?}"); + assert_eq!(mirrored.model.iter().next().unwrap().common.extrusion, Vec3::new(0.0, 0.0, -1.0)); +} + +/// A tilted 2D POLYLINE with an arc keeps its shape as seen from above: the half circle from +/// (0,0) to (2,0) is flattened into its half ellipse, in plan x from -2 to 0 and reaching √3/2. +#[test] +fn tilted_2d_polyline_arc_is_flattened() { + let text = "0\nSECTION\n2\nENTITIES\n0\nPOLYLINE\n8\n0\n66\n1\n10\n0\n20\n0\n30\n0\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n\ + 0\nVERTEX\n8\n0\n10\n0\n20\n0\n42\n1\n0\nVERTEX\n8\n0\n10\n2\n20\n0\n0\nSEQEND\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 && p.vertices.iter().all(|v| v.bulge == 0.0), "{} vertices", p.vertices.len()); + let b = d.extents(&Space::Model); + // Bulge 1 turns counter-clockwise from (0,0) to (2,0), so the arc runs below its chord, down + // to OCS y -1: plan y -√3/2. + for (got, want) in [(b.min.x, -2.0), (b.max.x, 0.0), (b.min.y, -(3f64.sqrt()) / 2.0), (b.max.y, 0.0)] { + assert!((got - want).abs() < 5e-3, "extents {b:?}"); + } +} + /// 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(); 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 486/900] 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 487/900] 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 488/900] 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 489/900] 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 490/900] 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 491/900] 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 f7494840dc04ee9e9cb3d15302a82a3ea09e0ac9 Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:31:05 +0200 Subject: [PATCH 492/900] A layout viewport keeps its view twist through DXF and DWG (part of #1316) VIEWPORT group 51 was not read, so a twisted viewport came back untwisted and a DXF or DWG saved by CADCraft wrote it without its twist; AutoCAD then showed the sheet rotated. The twist is now read (finite angles only, brought into one turn) and written when it isn't zero; the DWG bridge already carries group 51 both ways. The display and plots don't apply it yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG --- crates/doc/src/entity/layout.rs | 5 ++ crates/engine/src/cmd/modify2/tests.rs | 1 + .../tests/it/measure_distance_snapping.rs | 1 + crates/io/src/dxf_read/entities.rs | 1 + crates/io/src/dxf_write/entity.rs | 3 ++ crates/io/src/tests.rs | 4 ++ crates/io/tests/it/dwg_roundtrip_losses.rs | 53 +++++++++++++++++++ crates/io/tests/it/paperview_marker.rs | 1 + crates/io/tests/it/pdf_layers.rs | 1 + crates/io/tests/pdf_text.rs | 1 + crates/render/src/tests.rs | 1 + crates/render/tests/it/plot_line_styles.rs | 1 + crates/render/tests/it/psltscale.rs | 1 + crates/render/tests/it/render_props.rs | 1 + .../render/tests/it/viewport_frozen_layer.rs | 1 + .../tests/it/measure_distance_snapping.rs | 1 + .../ui-egui/tests/it/mspace_viewport_view.rs | 1 + 17 files changed, 78 insertions(+) diff --git a/crates/doc/src/entity/layout.rs b/crates/doc/src/entity/layout.rs index be1b9584d..b698585fe 100644 --- a/crates/doc/src/entity/layout.rs +++ b/crates/doc/src/entity/layout.rs @@ -25,6 +25,10 @@ pub struct Viewport { /// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space. #[serde(default = "yes")] pub on: bool, + /// View twist (DXF group 51; radians, counterclockwise): kept through files, not yet applied + /// to the display or plots. + #[serde(default)] + pub twist: f64, } impl Default for Viewport { @@ -41,6 +45,7 @@ impl Default for Viewport { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, } } } diff --git a/crates/engine/src/cmd/modify2/tests.rs b/crates/engine/src/cmd/modify2/tests.rs index 98b2f40d9..5f65026a9 100644 --- a/crates/engine/src/cmd/modify2/tests.rs +++ b/crates/engine/src/cmd/modify2/tests.rs @@ -411,6 +411,7 @@ fn chspace_json_and_command_line() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Default::default(), EntityKind::Viewport(vp)).unwrap(); let r = s.execute("chspace", &json!({"handles": [l]})).unwrap(); diff --git a/crates/engine/tests/it/measure_distance_snapping.rs b/crates/engine/tests/it/measure_distance_snapping.rs index 9842b65e0..25f12c9a0 100644 --- a/crates/engine/tests/it/measure_distance_snapping.rs +++ b/crates/engine/tests/it/measure_distance_snapping.rs @@ -27,6 +27,7 @@ fn drawing() -> (Drawing, Space) { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }), ) .unwrap(); diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index b5002bb3d..b442e2434 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -257,6 +257,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef // Status flags: 65536 = non-rectangular clipping (by the 340 entity), 131072 = off. clip: t.s(340).and_then(|h| Handle::parse_hex(&h)).filter(|h| h.0 != 0 && t.i(90).unwrap_or(0) & 65536 != 0), on: t.i(90).unwrap_or(0) & 131072 == 0, + twist: t.f(51).filter(|a| a.is_finite()).map_or(0.0, |a| a.rem_euclid(360.0).to_radians()), }), "WIPEOUT" => { let o = t.p(10); diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 6e1d84270..1b86741ef 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -686,6 +686,9 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: w.i(69, i64::from(v.id)); w.p2(12, v.view_center); w.f(45, v.view_height); + if v.twist.is_finite() && v.twist != 0.0 { + w.f(51, v.twist.to_degrees()); + } // Status flags: 16384 = display locked, 32768 = always set, 65536 = clipped by the // 340 entity, 131072 = off. let clip = v.clip.filter(|h| *h != e.handle && d.entity(*h).is_some()); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index ecfc43ca7..98eb2fb99 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -540,6 +540,7 @@ fn pdf_layout_one_to_one_with_viewport() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }), ) .unwrap(); @@ -646,6 +647,7 @@ fn viewport_frozen_layers_roundtrip() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }) }; d.add(&paper, Common::default(), vp(2, vec!["Walls".into(), "A B".into()])).unwrap(); @@ -688,6 +690,7 @@ fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }); d.add(&paper, Common::default(), vp).unwrap(); let text = dxf_2018(&d); @@ -830,6 +833,7 @@ fn viewport_layer_colors_roundtrip() { layer_colors: colors, clip: None, on: true, + twist: 0.0, }) }; let colors = vec![("Walls".to_string(), Color::Index(5)), ("A B".to_string(), Color::True(cadcraft_color::Rgb(255, 128, 0)))]; diff --git a/crates/io/tests/it/dwg_roundtrip_losses.rs b/crates/io/tests/it/dwg_roundtrip_losses.rs index aa00458a6..0cf3d4553 100644 --- a/crates/io/tests/it/dwg_roundtrip_losses.rs +++ b/crates/io/tests/it/dwg_roundtrip_losses.rs @@ -27,6 +27,7 @@ fn viewport(id: u32) -> EntityKind { layer_colors: vec![], clip: None, on: true, + twist: 0.0, }) } @@ -182,3 +183,55 @@ fn the_added_paper_viewport_follows_the_plot_scale() { assert!((sheet_width(49.6, true) - 420.0).abs() < 1e-9, "scaled to fit: the scale means nothing"); assert!((sheet_width(f64::NAN, false) - 420.0).abs() < 1e-9, "an unusable scale is 1"); } + +/// A layout viewport's view twist (group 51, #1316) is read and written, so DXF and DWG keep it; +/// a hostile angle reads as no twist and never panics. +#[test] +fn viewport_twist_survives_dxf_and_dwg() { + let mut d = Drawing::new_metric(); + let name = d.layouts[0].name.clone(); + let space = Space::Paper(name.clone()); + let twist = 30f64.to_radians(); + let EntityKind::Viewport(mut vp) = viewport(2) else { unreachable!() }; + vp.twist = twist; + let h = d.add(&space, Common::default(), EntityKind::Viewport(vp)).unwrap(); + let twist_of = |d: &Drawing| { + let l = d.layouts.iter().find(|l| l.name == name).unwrap(); + l.entities + .iter() + .find_map(|e| { + if let EntityKind::Viewport(v) = &e.kind + && v.id == 2 + { + Some(v.twist) + } else { + None + } + }) + .unwrap() + }; + + let dxf = cadcraft_io::write(&d, "x.dxf").unwrap(); + let text = String::from_utf8_lossy(&dxf).to_string(); + let rec = records(&text, "VIEWPORT").into_iter().find(|r| group(r, "5") == Some(h.hex().as_str())).unwrap(); + assert_eq!(group(&rec, "51").and_then(|v| v.parse::().ok()).map(f64::round), Some(30.0), "{rec:?}"); + assert!((twist_of(&cadcraft_io::read(&dxf, "x.dxf").unwrap()) - twist).abs() < 1e-9); + assert!((twist_of(&through_dwg(&d)) - twist).abs() < 1e-9); + + // An untwisted viewport writes no group 51. + let plain = records(&String::from_utf8_lossy(&cadcraft_io::write(&Drawing::new_metric(), "x.dxf").unwrap()), "VIEWPORT"); + assert!(plain.iter().all(|r| group(r, "51").is_none())); + + // Hostile angles: not a number reads as 0, a huge one is brought into one turn. + for (value, want) in [("nan", Some(0.0)), ("1e400", Some(0.0)), ("-330", Some(30f64.to_radians())), ("7200000000000000000030", None)] { + let mut lines: Vec = text.lines().map(str::to_string).collect(); + let at = lines.windows(2).position(|w| w[0].trim() == "51" && Some(w[1].trim()) == group(&rec, "51")).unwrap(); + lines[at + 1] = value.to_string(); + let bad = lines.join("\n"); + let back = twist_of(&cadcraft_io::read(bad.as_bytes(), "x.dxf").unwrap()); + assert!(back.is_finite() && (0.0..std::f64::consts::TAU).contains(&back), "{value}: {back}"); + if let Some(w) = want { + assert!((back - w).abs() < 1e-9, "{value}: {back}"); + } + } +} diff --git a/crates/io/tests/it/paperview_marker.rs b/crates/io/tests/it/paperview_marker.rs index 4159e14c3..283cfc8ac 100644 --- a/crates/io/tests/it/paperview_marker.rs +++ b/crates/io/tests/it/paperview_marker.rs @@ -18,6 +18,7 @@ fn viewport(id: u32, frozen_layers: Vec, layer_colors: Vec<(String, Colo layer_colors, clip: None, on: true, + twist: 0.0, }) } diff --git a/crates/io/tests/it/pdf_layers.rs b/crates/io/tests/it/pdf_layers.rs index f6da233ca..c463ca04a 100644 --- a/crates/io/tests/it/pdf_layers.rs +++ b/crates/io/tests/it/pdf_layers.rs @@ -149,6 +149,7 @@ fn viewport_contents_keep_their_layers() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&paper, Common { layer: "Viewports".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); add_line(&mut d, &paper, "Title", (10.0, 10.0), (50.0, 10.0)); diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index baba82f9d..a0f96dd67 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -335,6 +335,7 @@ fn text_seen_through_a_viewport_and_on_layers() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); text(&mut d, &paper, "Real", (20.0, 20.0), "B", (0.0, 1.0, 0.0)); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index e4b314ff5..5604a9ada 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -137,6 +137,7 @@ fn vp(center: Vec2, w: f64, h: f64, view_center: Vec2, view_height: f64, id: u32 layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, } } diff --git a/crates/render/tests/it/plot_line_styles.rs b/crates/render/tests/it/plot_line_styles.rs index 8cad7e3e5..b0abc6702 100644 --- a/crates/render/tests/it/plot_line_styles.rs +++ b/crates/render/tests/it/plot_line_styles.rs @@ -167,6 +167,7 @@ fn viewport_contents_get_their_pens() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; let space = Space::Paper("Layout1".into()); d.add(&space, Common::default(), EntityKind::Viewport(vp)).unwrap(); diff --git a/crates/render/tests/it/psltscale.rs b/crates/render/tests/it/psltscale.rs index dab134ec5..e0b47647c 100644 --- a/crates/render/tests/it/psltscale.rs +++ b/crates/render/tests/it/psltscale.rs @@ -25,6 +25,7 @@ fn drawing(psltscale: i64) -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); d diff --git a/crates/render/tests/it/render_props.rs b/crates/render/tests/it/render_props.rs index a40b1988d..a5e398fdd 100644 --- a/crates/render/tests/it/render_props.rs +++ b/crates/render/tests/it/render_props.rs @@ -63,6 +63,7 @@ fn dimensions_take_the_viewport_layer_colour() { layer_colors: vec![("a".into(), Color::Index(3))], clip: None, on: true, + twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); let l = build(&d, &Space::Paper("Layout1".into()), &Options::default()); diff --git a/crates/render/tests/it/viewport_frozen_layer.rs b/crates/render/tests/it/viewport_frozen_layer.rs index bce291635..876b33574 100644 --- a/crates/render/tests/it/viewport_frozen_layer.rs +++ b/crates/render/tests/it/viewport_frozen_layer.rs @@ -21,6 +21,7 @@ fn drawing() -> Drawing { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common { layer: "VPORTS".into(), ..Default::default() }, EntityKind::Viewport(vp)).unwrap(); d diff --git a/crates/ui-egui/tests/it/measure_distance_snapping.rs b/crates/ui-egui/tests/it/measure_distance_snapping.rs index 9f520b4ab..0deedcea4 100644 --- a/crates/ui-egui/tests/it/measure_distance_snapping.rs +++ b/crates/ui-egui/tests/it/measure_distance_snapping.rs @@ -30,6 +30,7 @@ fn harness(paper: bool, render: bool) -> Harness<'static, CadApp> { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }), ) .unwrap(); diff --git a/crates/ui-egui/tests/it/mspace_viewport_view.rs b/crates/ui-egui/tests/it/mspace_viewport_view.rs index 569665021..505a8afa3 100644 --- a/crates/ui-egui/tests/it/mspace_viewport_view.rs +++ b/crates/ui-egui/tests/it/mspace_viewport_view.rs @@ -37,6 +37,7 @@ fn harness(clipped: bool) -> Harness<'static, CadApp> { layer_colors: Vec::new(), clip, on: true, + twist: 0.0, }), ) .unwrap(); From c8e1671eb4c4010a7b4af6e989f08d69a63d4ca4 Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:27:50 +0200 Subject: [PATCH 493/900] Viewport twist: normalise with norm_angle on read and write; test the untwisted case on a real viewport From CodeRabbit's review: a tiny negative angle no longer reads as a full turn, a huge finite twist from JSON or MCP no longer writes an infinite group 51, and the "no group 51" check now looks at a viewport that exists. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG --- crates/io/src/dxf_read/entities.rs | 2 +- crates/io/src/dxf_write/entity.rs | 5 +++-- crates/io/tests/it/dwg_roundtrip_losses.rs | 20 ++++++++++++++++---- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index b442e2434..1930368f9 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -257,7 +257,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef // Status flags: 65536 = non-rectangular clipping (by the 340 entity), 131072 = off. clip: t.s(340).and_then(|h| Handle::parse_hex(&h)).filter(|h| h.0 != 0 && t.i(90).unwrap_or(0) & 65536 != 0), on: t.i(90).unwrap_or(0) & 131072 == 0, - twist: t.f(51).filter(|a| a.is_finite()).map_or(0.0, |a| a.rem_euclid(360.0).to_radians()), + twist: t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians())), }), "WIPEOUT" => { let o = t.p(10); diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 1b86741ef..452535794 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -686,8 +686,9 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: w.i(69, i64::from(v.id)); w.p2(12, v.view_center); w.f(45, v.view_height); - if v.twist.is_finite() && v.twist != 0.0 { - w.f(51, v.twist.to_degrees()); + let twist = cadcraft_geom::norm_angle(v.twist); + if twist != 0.0 { + w.f(51, twist.to_degrees()); } // Status flags: 16384 = display locked, 32768 = always set, 65536 = clipped by the // 340 entity, 131072 = off. diff --git a/crates/io/tests/it/dwg_roundtrip_losses.rs b/crates/io/tests/it/dwg_roundtrip_losses.rs index 0cf3d4553..d0577ef91 100644 --- a/crates/io/tests/it/dwg_roundtrip_losses.rs +++ b/crates/io/tests/it/dwg_roundtrip_losses.rs @@ -218,12 +218,24 @@ fn viewport_twist_survives_dxf_and_dwg() { assert!((twist_of(&cadcraft_io::read(&dxf, "x.dxf").unwrap()) - twist).abs() < 1e-9); assert!((twist_of(&through_dwg(&d)) - twist).abs() < 1e-9); - // An untwisted viewport writes no group 51. - let plain = records(&String::from_utf8_lossy(&cadcraft_io::write(&Drawing::new_metric(), "x.dxf").unwrap()), "VIEWPORT"); - assert!(plain.iter().all(|r| group(r, "51").is_none())); + // An untwisted viewport writes no group 51; a hostile twist (from JSON or MCP) writes a finite + // angle within one turn, or none. + for (value, want) in [(0.0, None), (f64::NAN, None), (f64::INFINITY, None), (1e300, Some(()))] { + let mut d = Drawing::new_metric(); + let EntityKind::Viewport(mut vp) = viewport(2) else { unreachable!() }; + vp.twist = value; + let h = d.add(&space, Common::default(), EntityKind::Viewport(vp)).unwrap(); + let text = String::from_utf8_lossy(&cadcraft_io::write(&d, "x.dxf").unwrap()).to_string(); + let rec = records(&text, "VIEWPORT").into_iter().find(|r| group(r, "5") == Some(h.hex().as_str())).unwrap(); + let written = group(&rec, "51").map(|v| v.parse::().unwrap()); + assert_eq!(written.map(|_| ()), want, "{value}: {rec:?}"); + assert!(written.is_none_or(|a| a.is_finite() && (0.0..360.0).contains(&a)), "{value}: {written:?}"); + } // Hostile angles: not a number reads as 0, a huge one is brought into one turn. - for (value, want) in [("nan", Some(0.0)), ("1e400", Some(0.0)), ("-330", Some(30f64.to_radians())), ("7200000000000000000030", None)] { + for (value, want) in + [("nan", Some(0.0)), ("1e400", Some(0.0)), ("-1e-20", Some(0.0)), ("-330", Some(30f64.to_radians())), ("7200000000000000000030", None)] + { let mut lines: Vec = text.lines().map(str::to_string).collect(); let at = lines.windows(2).position(|w| w[0].trim() == "51" && Some(w[1].trim()) == group(&rec, "51")).unwrap(); lines[at + 1] = value.to_string(); From 6d314919523401c2b31b8fd1b07fc8f40636a12f Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:35:48 +0100 Subject: [PATCH 494/900] Viewport twist: the viewport of main's block expansion test has no twist Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkJ8y75DE7yLZ7utxSRDeP --- crates/io/tests/it/block_expansion.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/io/tests/it/block_expansion.rs b/crates/io/tests/it/block_expansion.rs index 64fca189e..56f135957 100644 --- a/crates/io/tests/it/block_expansion.rs +++ b/crates/io/tests/it/block_expansion.rs @@ -117,6 +117,7 @@ fn an_empty_followup_viewport_does_not_mark_an_exact_budget_truncated() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; let paper = Space::Paper("Layout1".into()); d.add(&paper, Common::default(), EntityKind::Viewport(viewport(Vec3::new(50.0, 50.0, 0.0), Vec2::ZERO, vec!["FROZEN".into()]))).unwrap(); 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 495/900] 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 f04be0548fc3cfb54675262beaa5aee305cb085f Mon Sep 17 00:00:00 2001 From: mattlafy Date: Tue, 3 Nov 2026 14:56:46 -0500 Subject: [PATCH 496/900] fix: new Viewport, VportTile and Xf initializers from main set the view twist; DView has its Chinese label Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/it/block_expansion.rs | 1 + crates/io/tests/it/roundtrip/collections.rs | 4 ++-- crates/ui-egui/src/canvas/draw.rs | 4 ++-- crates/ui-egui/src/i18n/zh.tsv | 1 + 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/io/tests/it/block_expansion.rs b/crates/io/tests/it/block_expansion.rs index 64fca189e..56f135957 100644 --- a/crates/io/tests/it/block_expansion.rs +++ b/crates/io/tests/it/block_expansion.rs @@ -117,6 +117,7 @@ fn an_empty_followup_viewport_does_not_mark_an_exact_budget_truncated() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; let paper = Space::Paper("Layout1".into()); d.add(&paper, Common::default(), EntityKind::Viewport(viewport(Vec3::new(50.0, 50.0, 0.0), Vec2::ZERO, vec!["FROZEN".into()]))).unwrap(); diff --git a/crates/io/tests/it/roundtrip/collections.rs b/crates/io/tests/it/roundtrip/collections.rs index 9b9acf36b..81ed33641 100644 --- a/crates/io/tests/it/roundtrip/collections.rs +++ b/crates/io/tests/it/roundtrip/collections.rs @@ -145,8 +145,8 @@ pub(super) fn vports() -> Case { drawing.vports.push(VportConfig { name: "Split".into(), tiles: vec![ - VportTile { min: Vec2::ZERO, max: Vec2::new(0.5, 1.0), center: Vec2::new(2.0, 3.0), height: 20.0, aspect: 0.75 }, - VportTile { min: Vec2::new(0.5, 0.0), max: Vec2::new(1.0, 1.0), center: Vec2::new(7.0, 8.0), height: 30.0, aspect: 0.75 }, + VportTile { min: Vec2::ZERO, max: Vec2::new(0.5, 1.0), center: Vec2::new(2.0, 3.0), height: 20.0, aspect: 0.75, twist: 0.0 }, + VportTile { min: Vec2::new(0.5, 0.0), max: Vec2::new(1.0, 1.0), center: Vec2::new(7.0, 8.0), height: 30.0, aspect: 0.75, twist: 0.0 }, ], }); Case { name: "drawing/tiled-viewports".into(), drawing } diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index 3e2755901..45d828431 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -537,7 +537,7 @@ mod zoomed_highlight_tests { let list = line(Vec2::new(-1000.0, 0.0), Vec2::new(1000.0, 0.0)); // The smaller zoom first, so a regression fails here instead of filling memory at 1e9. for scale in [1e3, 1e9] { - let n = dashes_of(&list, &Xf { rect: SCREEN, center: Vec2::new(0.3, 0.0), scale }).len(); + let n = dashes_of(&list, &Xf { rect: SCREEN, center: Vec2::new(0.3, 0.0), scale, twist: 0.0 }).len(); assert!((50..=70).contains(&n), "scale {scale}: {n} dashes for 600 points of line"); } } @@ -548,7 +548,7 @@ mod zoomed_highlight_tests { fn clipped_dashes_stay_where_the_whole_line_puts_them() { let list = line(Vec2::new(0.0, 0.0), Vec2::new(1000.0, 0.0)); for x in [500.3, 512.9, 731.0] { - let xf = Xf { rect: SCREEN, center: Vec2::new(x, 0.0), scale: 1.0 }; + let xf = Xf { rect: SCREEN, center: Vec2::new(x, 0.0), scale: 1.0, twist: 0.0 }; let whole = Shape::dashed_line( &[xf.to_screen(Vec2::ZERO), xf.to_screen(Vec2::new(1000.0, 0.0))], Stroke::new(1.0, Color32::LIGHT_BLUE), diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index eae92cc14..7fbc636aa 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -149,6 +149,7 @@ Cut with Base Point 带基点剪切 Cyan 青色 Cylinder 圆柱体 + DView 动态视图 DWG DWG DXF DXF Dark 深色 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 497/900] 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 8b6c204fd805133dc77e10f5684195ae1d1dde06 Mon Sep 17 00:00:00 2001 From: lorie-capella Date: Tue, 3 Nov 2026 16:12:55 -0500 Subject: [PATCH 498/900] Windows: Keep portable settings beside the executable (#731) --- README.md | 13 ++++++ apps/cadcraft/src/env.rs | 52 ++++++++++++++++++++++- apps/cadcraft/src/main.rs | 12 ++++-- apps/cadcraft/src/portable.rs | 77 +++++++++++++++++++++++++++++++++++ packaging/windows/package.ps1 | 2 + 5 files changed, 151 insertions(+), 5 deletions(-) create mode 100644 apps/cadcraft/src/portable.rs diff --git a/README.md b/README.md index 611110c3c..efd66b502 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,19 @@ in the text style or set `FONTFALLBACK` (`CADCRAFT_FONTFALLBACK="Vazirmatn"`). F inside a word (an MTEXT colour change in the middle of a Persian word) break the joining at that point. +### Portable Windows ZIP + +The Windows portable ZIP includes `portable.txt` beside `cadcraft.exe`. With that +marker present, settings, logs, autosaves, workspace data, plotter files, and +eframe preferences/window state stay in `CADCraftData` beside the executable. +Keep that directory when replacing the binaries. The MSI does not include the +marker and continues to use the normal user profile. + +`CADCRAFT_CONFIG_DIR` takes precedence over the marker, including an empty or +blank value that disables the settings folder. If `CADCraftData` cannot be +created or written, CADCraft warns and uses the normal profile. Existing profile +settings are not automatically copied into the portable directory. + ### Logs The desktop app writes its `log` records to standard error and to `logs/cadcraft.log` in the diff --git a/apps/cadcraft/src/env.rs b/apps/cadcraft/src/env.rs index 76df8aa15..0ed6c9d52 100644 --- a/apps/cadcraft/src/env.rs +++ b/apps/cadcraft/src/env.rs @@ -33,8 +33,10 @@ pub(crate) const VARS: &[(&str, &str)] = &[ /// `CADCRAFT_CONFIG_DIR`. #[derive(Debug, PartialEq)] pub(crate) struct Env { + /// Portable eframe storage, kept with the other settings instead of the user profile. + pub(crate) portable_dir: Option, /// The settings folder (logs, autosave, workspace, plotters): `CADCRAFT_CONFIG_DIR`; else, when - /// that is unset, the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no + /// that is unset, the portable directory or the platform's (`cadcraft_engine::settings_dir::platform`). `None`: no /// folder, because the variable is empty or blank (the way to run without one) or the /// platform has none. pub(crate) config_dir: Option, @@ -58,7 +60,26 @@ pub(crate) struct Env { impl Env { pub(crate) fn read() -> Env { - Env::from_vars(|k| std::env::var_os(k)) + let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(PathBuf::from)); + Self::from_vars_and_exe(|k| std::env::var_os(k), exe_dir.as_deref()) + } + + fn from_vars_and_exe(var: impl Fn(&str) -> Option, exe_dir: Option<&std::path::Path>) -> Env { + let mut vars = Env::from_vars(&var); + // An explicit override (including blank, which disables settings) takes precedence. + if var(CONFIG_DIR).is_none() + && let Some(exe) = exe_dir + { + match crate::portable::directory_in(exe) { + Ok(Some(data)) => { + vars.config_dir = Some(data.clone()); + vars.portable_dir = Some(data); + } + Ok(None) => {} + Err(error) => log::warn!("portable settings cannot be written ({error}); using the user profile"), + } + } + vars } /// [`Env::read`] with `var` looking a variable up. @@ -66,6 +87,7 @@ impl Env { let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty()); let switch = |k: &str| Switch::parse(k, var(k).map(|v| v.to_string_lossy().into_owned()).as_deref()); Env { + portable_dir: None, config_dir: match var(CONFIG_DIR) { Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None, Some(dir) => Some(PathBuf::from(dir)), @@ -96,6 +118,31 @@ mod tests { use super::*; use std::cell::RefCell; + #[test] + fn portable_settings_and_eframe_storage_use_the_same_directory() { + let exe = std::env::temp_dir().join(format!("cadcraft-env-portable-{}", std::process::id())); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join("portable.txt"), "").unwrap(); + let vars = Env::from_vars_and_exe(env(&[("APPDATA", "/profile")]), Some(&exe)); + assert_eq!(vars.config_dir, Some(exe.join("CADCraftData"))); + assert_eq!(vars.portable_dir, vars.config_dir); + std::fs::remove_dir_all(exe).unwrap(); + } + + #[test] + fn explicit_override_skips_portable_probe() { + let exe = std::env::temp_dir().join(format!("cadcraft-env-override-{}", std::process::id())); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join("portable.txt"), "").unwrap(); + for value in ["/custom", "", " "] { + let vars = Env::from_vars_and_exe(env(&[(CONFIG_DIR, value)]), Some(&exe)); + assert_eq!(vars.config_dir, (!value.trim().is_empty()).then(|| PathBuf::from(value))); + assert_eq!(vars.portable_dir, None); + assert!(!exe.join("CADCraftData").exists()); + } + std::fs::remove_dir_all(exe).unwrap(); + } + fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v)) } @@ -139,6 +186,7 @@ mod tests { assert_eq!( read, Env { + portable_dir: None, config_dir: Some(PathBuf::from("/private/cc")), locale: Some("cs-CZ".into()), vsync: Switch::On, diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 71700095d..a9eb48fb4 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -23,6 +23,7 @@ mod launch_args; mod logging; #[cfg(target_os = "macos")] mod native_menu; +mod portable; mod spacemouse; mod system_animations; mod workspace; @@ -202,8 +203,12 @@ fn saved_window(app_ron: &str) -> bool { } /// The window state from the last session is saved and will be restored (#2595). -fn restores_window() -> bool { - eframe::storage_dir(APP_ID).and_then(|dir| std::fs::read_to_string(dir.join("app.ron")).ok()).is_some_and(|ron| saved_window(&ron)) +fn restores_window(portable: Option<&std::path::Path>) -> bool { + portable + .map(std::path::PathBuf::from) + .or_else(|| eframe::storage_dir(APP_ID)) + .and_then(|dir| std::fs::read_to_string(dir.join("app.ron")).ok()) + .is_some_and(|ron| saved_window(&ron)) } /// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state @@ -308,7 +313,8 @@ fn main() -> eframe::Result { // The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11 // swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync). wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface), - ..window_options(restores_window()) + persistence_path: vars.portable_dir.clone(), + ..window_options(restores_window(vars.portable_dir.as_deref())) }; if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); diff --git a/apps/cadcraft/src/portable.rs b/apps/cadcraft/src/portable.rs new file mode 100644 index 000000000..5879dad1d --- /dev/null +++ b/apps/cadcraft/src/portable.rs @@ -0,0 +1,77 @@ +//! Windows portable ZIP settings, selected by a marker beside the executable. + +use std::path::{Path, PathBuf}; + +/// A marker must be a file. Prove the data folder is writable before selecting it. +pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result> { + if !exe_dir.join("portable.txt").is_file() { + return Ok(None); + } + let data = exe_dir.join("CADCraftData"); + std::fs::create_dir_all(&data)?; + let probe = data.join(format!(".portable-write-test-{}", std::process::id())); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe)?; + Ok(Some(data)) +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Temp(PathBuf); + + impl Temp { + fn new(name: &str) -> Self { + let root = std::env::temp_dir().join(format!("cadcraft-portable-{}-{name}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + Self(root) + } + } + + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn absent_marker_and_directory_named_marker_do_not_enable_portable_mode() { + let temp = Temp::new("no-marker"); + assert_eq!(directory_in(&temp.0).unwrap(), None); + std::fs::create_dir(temp.0.join("portable.txt")).unwrap(); + assert_eq!(directory_in(&temp.0).unwrap(), None); + assert!(!temp.0.join("CADCraftData").exists()); + } + + #[test] + fn marker_selects_adjacent_data_and_preserves_existing_settings() { + let temp = Temp::new("settings-é"); + std::fs::write(temp.0.join("portable.txt"), "").unwrap(); + let data = directory_in(&temp.0).unwrap().unwrap(); + assert_eq!(data, temp.0.join("CADCraftData")); + assert_eq!(std::fs::read_dir(&data).unwrap().count(), 0); + std::fs::write(data.join("workspace.json"), "existing settings").unwrap(); + assert_eq!(directory_in(&temp.0).unwrap(), Some(data.clone())); + assert_eq!(std::fs::read_to_string(data.join("workspace.json")).unwrap(), "existing settings"); + } + + #[test] + fn blocked_data_folder_is_an_error() { + let temp = Temp::new("blocked"); + std::fs::write(temp.0.join("portable.txt"), "").unwrap(); + std::fs::write(temp.0.join("CADCraftData"), "a file blocks the directory").unwrap(); + assert!(directory_in(&temp.0).is_err()); + } + + #[test] + fn independent_copies_have_independent_settings() { + let a = Temp::new("copy-a"); + let b = Temp::new("copy-b"); + for temp in [&a, &b] { + std::fs::write(temp.0.join("portable.txt"), "").unwrap(); + } + assert_ne!(directory_in(&a.0).unwrap(), directory_in(&b.0).unwrap()); + } +} diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 042b46f73..a5e990e56 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -126,6 +126,8 @@ $Portable = Join-Path $TargetDir "windows-package\cadcraft-$Version-windows-$Arc Remove-Item -Recurse -Force $Portable -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Portable | Out-Null Copy-Item (Join-Path $Stage '*.exe') $Portable +# The ZIP is portable by default; keep the marker out of the MSI staging directory. +Set-Content -LiteralPath (Join-Path $Portable 'portable.txt') -Encoding Ascii -Value 'CADCraft portable mode: settings and logs are stored in CADCraftData beside the executable.' foreach ($f in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { $p = Join-Path $Root $f if (Test-Path $p) { Copy-Item $p $Portable } From 58bb1e065e31f89f3fa254d04a923aa38e9e995d Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 14:50:59 -0700 Subject: [PATCH 499/900] docs: date the view twist revision rows to the day they land --- docs/file-format-parity.md | 2 +- docs/gaps.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index cc2b3ea57..75061dd03 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -150,7 +150,7 @@ our output in AutoCAD black-box. | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | | 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-13 | minor | View twist (group 51) read and written for each tiled viewport (VPORT) and each layout viewport (VIEWPORT); named views' twist (VIEW group 50) now applied on Restore; a twisted view's centre (VIEWPORT and VPORT group 12, VIEW group 10) is read and written in display coordinates, turned by the twist | +| 2026-11-03 | minor | View twist (group 51) read and written for each tiled viewport (VPORT) and each layout viewport (VIEWPORT); named views' twist (VIEW group 50) now applied on Restore; a twisted view's centre (VIEWPORT and VPORT group 12, VIEW group 10) is read and written in display coordinates, turned by the twist | | 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 3115611b3..4a8894b60 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -167,7 +167,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-15 | minor | BREAKLINE (Tools ▸ Express Tools ▸ Break-line Symbol): one polyline between two points with a break symbol, Block/Size/Extension options, size times DIMSCALE: E3 narrowed | | 2026-10-15 | minor | TXT2MTXT (Tools ▸ Express Tools ▸ Convert Text to Mtext): selected TEXT, and MTEXT, combined into one MTEXT top-down or in selection order with optional word wrap, or one MTEXT per TEXT; SEttings remembered for the session: E3 narrowed | | 2026-10-13 | minor | Selection window gesture preference (PICKDRAG 0/2) added to Options ▸ Selection and saved in the profile (U6), with Portuguese and Ukrainian labels | -| 2026-10-13 | minor | View twist: DVIEW starts with "Select objects or :" then its option prompt (TWist, PAn, Zoom, Off and Undo on 2D views, the 3D options added to F1), on the Model tab and inside an active layout viewport, which keeps its own twist (DXF VIEWPORT group 51) and is drawn turned on screen and in plots; VIEWTWIST, each VPORTS tile (VPORT group 51) and named views keep it: U11 narrowed | +| 2026-11-03 | minor | View twist: DVIEW starts with "Select objects or :" then its option prompt (TWist, PAn, Zoom, Off and Undo on 2D views, the 3D options added to F1), on the Model tab and inside an active layout viewport, which keeps its own twist (DXF VIEWPORT group 51) and is drawn turned on screen and in plots; VIEWTWIST, each VPORTS tile (VPORT group 51) and named views keep it: U11 narrowed | | 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 | From 162cc4792b4855aa242e5176d284d4e764618460 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 14:58:37 -0700 Subject: [PATCH 500/900] View twist: read and write every twist within one turn, so #2022's hostile-angle checks hold MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A twist of -1e-20 degrees read as a full turn (2π), and a huge twist set from JSON or MCP was written as a huge angle. Readers and writers of VIEWPORT 51, VPORT 51 and VIEW 50 now go through norm_angle. --- crates/io/src/dxf_read/entities.rs | 2 +- crates/io/src/dxf_read/tables.rs | 4 ++-- crates/io/src/dxf_write/entity.rs | 8 +++++--- crates/io/src/dxf_write/layout.rs | 2 +- crates/io/src/dxf_write/sections.rs | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 7027e4750..6f547c145 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -245,7 +245,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef "ACAD_TABLE" => EntityKind::Table(acad_table(tags, table_cells_left)), "VIEWPORT" => EntityKind::Viewport({ // View twist (group 51, degrees). - let twist = t.f(51).filter(|a| a.is_finite()).map_or(0.0, |a| a.rem_euclid(360.0).to_radians()); + let twist = t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians())); Viewport { center: t.p(10), width: t.fd(40, 1.0), diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 6bc9e6178..518df8d3f 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -224,7 +224,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { if name.is_empty() || !(h.is_finite() && w.is_finite() && h > 0.0 && w > 0.0) || d.views.len() >= MAX_OBJECTS { continue; } - let twist = t.f(50).filter(|a| a.is_finite()).map_or(0.0, |a| a.rem_euclid(360.0).to_radians()); + let twist = t.f(50).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians())); // The view centre 10/20 is in display coordinates, whose origin is the target 12/22/32. let center = t.view_center(10, 12, twist); if !(center.x.is_finite() && center.y.is_finite()) { @@ -326,7 +326,7 @@ 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(); // View twist (group 51, degrees). - let twist = t.f(51).filter(|a| a.is_finite()).map_or(0.0, |a| a.rem_euclid(360.0).to_radians()); + let twist = t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians())); // The view centre 12/22 is in display coordinates, whose origin is the view target 17/27/37. let (min, max, center) = (t.p(10).xy(), t.p(11).xy(), t.view_center(12, 17, twist)); let height = t.fd(40, 0.0); diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 94a626f42..5d759e223 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -684,12 +684,14 @@ fn write_viewport_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: // Status 68: a positive value is "on" (the stacking order; 1 is the active viewport), 0 off. w.i(68, if v.on { i64::from(v.id.clamp(1, 32767)) } else { 0 }); w.i(69, i64::from(v.id)); + // Within one turn, so a hostile twist (from JSON or MCP) writes a sane angle. + let twist = cadcraft_geom::norm_angle(v.view_twist()); // The view centre in display coordinates (turned by the twist). - w.p2(12, dxf_ext::model_center_to_dcs(v.view_center, v.view_twist())); + w.p2(12, dxf_ext::model_center_to_dcs(v.view_center, twist)); w.f(45, v.view_height); // View twist (degrees), when the viewport has one. - if v.view_twist() != 0.0 { - w.f(51, v.view_twist().to_degrees()); + if twist != 0.0 { + w.f(51, twist.to_degrees()); } // Status flags: 16384 = display locked, 32768 = always set, 65536 = clipped by the // 340 entity, 131072 = off. diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 8a5c180dd..07698fb88 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -95,7 +95,7 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { w.i(70, 0); w.p2(10, finite(t.min, Vec2::ZERO)); w.p2(11, finite(t.max, Vec2::new(1.0, 1.0))); - let twist = if t.twist.is_finite() { t.twist } else { 0.0 }; + let twist = cadcraft_geom::norm_angle(t.twist); w.p2(12, dxf_ext::model_center_to_dcs(finite(t.center, Vec2::ZERO), twist)); // Snap grid origin and rotation (SNAPBASE, SNAPANG in degrees): R13+ files keep them here. w.p2(13, d.header.point("SNAPBASE").map(|p| p.xy()).filter(|p| p.is_finite()).unwrap_or(Vec2::ZERO)); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 295d063e6..e80adb408 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -136,7 +136,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap w.s(2, &v.name); w.i(70, i64::from(v.layout.is_some())); w.f(40, v.height); - let twist = if v.twist.is_finite() { v.twist } else { 0.0 }; + let twist = cadcraft_geom::norm_angle(v.twist); w.p2(10, dxf_ext::model_center_to_dcs(v.center, twist)); w.f(41, v.width); w.p(11, Vec3::Z); From f1312113d286fa6cefbf54fae8fd5bf07dd4e5c1 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 15:01:55 -0700 Subject: [PATCH 501/900] Images: format after the merge with main --- crates/io/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 6060af741..c44ab3a42 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -14,10 +14,10 @@ mod dxf_write; mod dxf_xref; pub mod pdf; pub mod plotter; -/// Open → save → reopen comparison and the real-file corpus harness (gaps FF1, FF5). -pub mod roundtrip; /// Raster image files (PNG, JPEG, BMP, TIFF) decoded to pixels. pub mod raster; +/// Open → save → reopen comparison and the real-file corpus harness (gaps FF1, FF5). +pub mod roundtrip; pub mod svg; mod svg_read; From 238aa1789c0f98dcdb5e4dcc128869d7f3707cd8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 15:03:06 -0700 Subject: [PATCH 502/900] Images: draw an IMAGE in its own function, under the complexity limit --- crates/render/src/draw.rs | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index b6645a6a9..1d2d69cb9 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -193,22 +193,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { } } EntityKind::Wipeout(w) => draw_wipeout(b, ctx, w, rgb, lw), - EntityKind::Image(i) => { - let o = i.insert.xy(); - let u = i.u.xy() * i.size.x; - let v = i.v.xy() * i.size.y; - // Display flag 1: show the image. Without pixels (file not found, not loaded yet, - // hidden) the rectangle is crossed out. - let raster = if i.display & 1 != 0 { ctx.d.rasters.get(&i.path) } else { None }; - if let Some(r) = raster { - b.image(ctx, rgb, i, r); - } - b.polyline(ctx, rgb, lw, &[o, o + u, o + u + v, o + v, o]); - if raster.is_none() { - b.polyline(ctx, rgb, lw, &[o, o + u + v]); - b.polyline(ctx, rgb, lw, &[o + u, o + v]); - } - } + EntityKind::Image(i) => draw_image(b, ctx, i, rgb, lw), EntityKind::Table(t) => table(b, ctx, t, rgb, lw), EntityKind::Tolerance(t) => tolerance::draw(b, ctx, e, t, lw, tol), EntityKind::Leader(l) => { @@ -297,6 +282,23 @@ fn draw_mleader(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &cadcraft_doc::MLeade } } +fn draw_image(b: &mut Builder, ctx: &Ctx, i: &cadcraft_doc::Image, rgb: Ink, lw: f32) { + let o = i.insert.xy(); + let u = i.u.xy() * i.size.x; + let v = i.v.xy() * i.size.y; + // Display flag 1: show the image. Without pixels (file not found, not loaded yet, hidden) + // the rectangle is crossed out. + let raster = if i.display & 1 != 0 { ctx.d.rasters.get(&i.path) } else { None }; + if let Some(r) = raster { + b.image(ctx, rgb, i, r); + } + b.polyline(ctx, rgb, lw, &[o, o + u, o + u + v, o + v, o]); + if raster.is_none() { + b.polyline(ctx, rgb, lw, &[o, o + u + v]); + b.polyline(ctx, rgb, lw, &[o + u, o + v]); + } +} + fn draw_wipeout(b: &mut Builder, ctx: &Ctx, w: &cadcraft_doc::Wipeout, rgb: Ink, lw: f32) { // Hide what was drawn before it (draw order), then the frame per WIPEOUTFRAME: // 0 = none, 1 = shown and plotted, 2 = shown but not plotted. From d3226e629e28d5a2a7a4451aa576be066cf8a847 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 15:04:12 -0700 Subject: [PATCH 503/900] Images: the highlight outline uses main's world-point line helper --- crates/ui-egui/src/canvas/draw.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/draw.rs b/crates/ui-egui/src/canvas/draw.rs index f8b6adf8a..8ac5745da 100644 --- a/crates/ui-egui/src/canvas/draw.rs +++ b/crates/ui-egui/src/canvas/draw.rs @@ -385,7 +385,7 @@ pub(crate) fn draw_highlight(p: &egui::Painter, xf: &Xf, list: &DisplayList, pri line(&outline, &mut shapes); } } - Kind::Image { .. } => line(pts.iter().chain(pts.first()).map(|q| xf.to_screen(*q)).collect(), &mut shapes), + Kind::Image { .. } => line(&pts.iter().chain(pts.first()).copied().collect::>(), &mut shapes), } } if !fill.is_empty() { From 15afc4729625bc032ed155563138c8d8686f02e7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 15:12:28 -0700 Subject: [PATCH 504/900] Images: Chinese labels for IMAGEATTACH and IMAGE --- crates/ui-egui/src/i18n/zh.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index eae92cc14..f0564315c 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -593,6 +593,8 @@ Quit CADCraft 退出 CADCraft Radius 半径 Raster Image 光栅图像 + Raster Image Reference... 光栅图像参照... + Raster Images 光栅图像 Ray 射线 Read-only 只读 Real name 真实姓名 From 457fc2319ecb10fc707adba305945ae9dc1c2eba Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 15:14:10 -0700 Subject: [PATCH 505/900] View twist: review fixes - Every engine twist (DVIEW, view.set, opening a drawing, the untiled view) goes through norm_angle, so a tiny negative twist is 0, not a full turn. - VIEW Window in a twisted view stores the window's size along the view's axes (View::twisted_box), so a restore shows all of it. - A deferred tangent or perpendicular snap on an arc in a twisted layout viewport turns the arc's angles with its centre. - The active viewport's cached drawing is rebuilt when its twist changes; moving and scaling it can't turn it. --- crates/engine/src/cmd/view.rs | 2 +- crates/engine/src/cmd/view/dview.rs | 3 +-- crates/engine/src/cmd/view/named_views.rs | 6 ++++-- crates/engine/src/doc_state.rs | 2 +- crates/engine/src/session/files.rs | 4 +--- crates/engine/src/snap/viewport.rs | 4 +++- crates/ui-egui/src/canvas/viewport.rs | 5 ++++- 7 files changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 29581f79e..7161308df 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -293,7 +293,7 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result { dview::set_twist(s, t, twist)?; s.state()?.view().twist } - Some(dview::Target::Model) => twist.rem_euclid(std::f64::consts::TAU), + Some(dview::Target::Model) => cadcraft_geom::norm_angle(twist), None => 0.0, }; if !s.state_mut()?.set_view(View { center: c, height: h, twist }) { diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs index 5c1b1e1c5..9a421c8a9 100644 --- a/crates/engine/src/cmd/view/dview.rs +++ b/crates/engine/src/cmd/view/dview.rs @@ -13,7 +13,6 @@ //! ZOOM (view history, not undo). A layout viewport's twist belongs to the viewport entity, so a //! DVIEW that changed it is one undo step. -use std::f64::consts::TAU; use std::sync::Arc; use cadcraft_doc::{Entity, EntityKind, Handle, Insert, Line, Space}; @@ -69,7 +68,7 @@ pub(super) fn target(s: &Session) -> Result { /// A twist kept as files hold it: [0, 2π). fn normal(twist: f64) -> f64 { - twist.rem_euclid(TAU) + cadcraft_geom::norm_angle(twist) } /// The active viewport's twist, if it is `h`. diff --git a/crates/engine/src/cmd/view/named_views.rs b/crates/engine/src/cmd/view/named_views.rs index 34908fe23..e7c055fe2 100644 --- a/crates/engine/src/cmd/view/named_views.rs +++ b/crates/engine/src/cmd/view/named_views.rs @@ -119,7 +119,9 @@ fn save(s: &mut Session, name: &str, window: Option, snapshot: bool) -> if !(b.width() > 1e-12 && b.height() > 1e-12 && b.min.is_finite() && b.max.is_finite()) { return Err(EngineError::Other("The window has no area.".into())); } - (b.center(), b.height(), b.width()) + // In a twisted view the window's box on screen is larger than its world box. + let (center, width, height) = crate::View::twisted_box(b, twist); + (center, height, width) } None => { let f = frame; @@ -184,7 +186,7 @@ fn restore(s: &mut Session, name: &str) -> Result { // In an unlocked MSPACE viewport the saved twist turns the viewport (an edit of the // viewport, recorded as the command's undo step). let aspect = st.zoom_aspect(w / h.max(1.0)).max(1e-9); - let twist = if v.twist.is_finite() { v.twist.rem_euclid(std::f64::consts::TAU) } else { 0.0 }; + let twist = cadcraft_geom::norm_angle(v.twist); st.set_zoom_frame(View { center: v.center, height: v.height.max(v.width / aspect), twist }); } } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 411e160d2..f3862f90a 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -203,7 +203,7 @@ impl DocState { } fn keep_untiled_twist(&mut self, v: View) { use cadcraft_doc::{VportConfig, VportTile}; - let twist = if v.twist.is_finite() { v.twist.rem_euclid(std::f64::consts::TAU) } else { 0.0 }; + let twist = cadcraft_geom::norm_angle(v.twist); let active = self.doc.vports.iter().find(|c| c.is_active()); if active.is_some_and(|c| c.tiles.len() > 1) { return; diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 961dabea4..6704b2674 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -19,9 +19,7 @@ impl Session { let mut st = DocState::new(d, title, path); let ext = st.doc.extents(&Space::Model); // The current tile (the first), or the lone untiled view, keeps its saved twist. - let twist = - st.doc.vports.iter().find(|c| c.is_active()).and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist).rem_euclid(std::f64::consts::TAU); - let twist = if twist.is_finite() { twist } else { 0.0 }; + let twist = cadcraft_geom::norm_angle(st.doc.vports.iter().find(|c| c.is_active()).and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist)); if ext.is_empty() { st.set_view_quiet(View { twist, ..st.view() }); } else { diff --git a/crates/engine/src/snap/viewport.rs b/crates/engine/src/snap/viewport.rs index 20decf8d4..c6ef9963c 100644 --- a/crates/engine/src/snap/viewport.rs +++ b/crates/engine/src/snap/viewport.rs @@ -77,7 +77,9 @@ impl<'a> Projection<'a> { if !(center.is_finite() && radius.is_finite() && radius > 0.0) { return None; } - SnapCurve::Arc { center, radius, start, end } + // The arc turns on the sheet with the viewport's twist. + let twist = self.viewport.view_twist(); + SnapCurve::Arc { center, radius, start: start + twist, end: end + twist } } SnapCurve::Line { a, b } => { let (a, b) = (self.to_paper(a), self.to_paper(b)); diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index 6eafc6a33..db1f42642 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -35,6 +35,8 @@ pub(super) struct VpContent { pub(super) key: Option<(u64, u64, usize, Handle, i32, bool, bool)>, /// The viewport's view (centre, height) the list was built for, and the paper area it covers. view: (Vec2, f64), + /// The view twist it was built for: [`vp_motion`] moves and scales a list, it can't turn it. + twist: f64, area: Bounds2, /// The view on the previous frame and when it last changed (ms). last_view: (Vec2, f64), @@ -106,7 +108,7 @@ pub(super) fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Con c.last_view = view; c.moved_at = now; } - let rebuild = match vp_motion(&vp, c.view).filter(|_| c.key == Some(key)) { + let rebuild = match vp_motion(&vp, c.view).filter(|_| c.key == Some(key) && c.twist == vp.view_twist()) { Some((k, b)) => { // The viewport in the list's own coordinates. let visible = Bounds2::new((rect.min - b) / k, (rect.max - b) / k); @@ -141,6 +143,7 @@ pub(super) fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Con c.list = cadcraft_render::viewport_content(&st.doc, &st.space, h, area, &opts); c.key = Some(key); c.view = view; + c.twist = vp.view_twist(); c.area = area; c.builds = c.builds.wrapping_add(1); app.canvas.build_ms = crate::now_ms() - t0; From 757601780dcec01a45fcb0bb7eea2052ba34561e Mon Sep 17 00:00:00 2001 From: mo <131036780+mbolling@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:26:52 -0500 Subject: [PATCH 506/900] Try FreeSerif before Unifont for missing glyphs Unifont has no mark-to-mark positioning, so taking it ahead of GNU FreeSerif drew Thai and Indic text with marks on top of each other; FreeSerif shapes those scripts properly. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/ttf.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 9ed7ae11a..4b048f0f0 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -127,9 +127,11 @@ const MAX_CACHED_CHARS: usize = 50_000; pub(crate) const MAX_SHAPED_POINTS: usize = 8_000_000; /// Fonts known to cover many scripts (CJK first), tried first for missing glyphs. Matched as -/// substrings of the normalised file stem. Unifont (every BMP character, as bitmap-like -/// outlines) comes last: a last resort before the alphabetical rest, which the bounded search -/// never gets through, and the only CJK-capable font of NixOS's default font set. +/// substrings of the normalised file stem. The last two are the wide nets: GNU FreeSerif (most +/// non-CJK scripts, with real OpenType shaping; in the default font set of NixOS and many +/// distributions), then Unifont (every BMP character, as bitmap-like outlines; the only +/// CJK-capable font of NixOS's default set) for what FreeSerif lacks. Both come before the +/// alphabetical rest, which the bounded search never gets through. const PREFERRED_FALLBACK: &[&str] = &[ "notosanscjk", "sourcehansans", @@ -153,6 +155,7 @@ const PREFERRED_FALLBACK: &[&str] = &[ "dejavusans", "segoeui", "arial", + "freeserif", "unifont", ]; /// Fonts known to cover a right-to-left script, tried before the general search for its From 82322908308df98ef177e53f3bd76a8694455fcc Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 15:40:39 -0700 Subject: [PATCH 507/900] View twist: a window too large to turn saves no view, and the saved one stays --- crates/engine/src/cmd/view/named_views.rs | 4 ++++ crates/engine/tests/it/named_views.rs | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/crates/engine/src/cmd/view/named_views.rs b/crates/engine/src/cmd/view/named_views.rs index e7c055fe2..b7f7a90d0 100644 --- a/crates/engine/src/cmd/view/named_views.rs +++ b/crates/engine/src/cmd/view/named_views.rs @@ -121,6 +121,10 @@ fn save(s: &mut Session, name: &str, window: Option, snapshot: bool) -> } // In a twisted view the window's box on screen is larger than its world box. let (center, width, height) = crate::View::twisted_box(b, twist); + // Turning corners near the number limit can overflow: save no view that can't be restored. + if !(center.is_finite() && width.is_finite() && height.is_finite() && width > 1e-12 && height > 1e-12) { + return Err(EngineError::Other("The window is too large for a twisted view.".into())); + } (center, height, width) } None => { diff --git a/crates/engine/tests/it/named_views.rs b/crates/engine/tests/it/named_views.rs index 606e531bd..bccc253b1 100644 --- a/crates/engine/tests/it/named_views.rs +++ b/crates/engine/tests/it/named_views.rs @@ -84,6 +84,20 @@ fn window_option_and_json_forms() { assert!(s.execute("view", &json!({ "option": "orthographic" })).is_err()); } +#[test] +fn a_window_saved_in_a_twisted_view_restores_whole() { + let mut s = session(); + s.execute("view.set", &json!({ "center": [0, 0], "height": 10, "twist": 45 })).unwrap(); + s.execute("view", &json!({ "option": "window", "name": "Turned", "p1": [0, 0], "p2": [10, 10] })).unwrap(); + let v = s.doc().unwrap().views.first().cloned().unwrap(); + // A 10 x 10 world square seen at 45° is 10√2 across on screen. + assert!(close(v.width, 200f64.sqrt()) && close(v.height, 200f64.sqrt()), "{} x {}", v.width, v.height); + // Corners near the number limit overflow when turned: an error, and the saved view stays. + let huge = json!({ "option": "window", "name": "Turned", "p1": [1.4e308, 1.4e308], "p2": [1.5e308, 1.5e308] }); + assert!(s.execute("view", &huge).is_err()); + assert!(close(s.doc().unwrap().views.first().unwrap().width, 200f64.sqrt())); +} + #[test] fn layer_snapshot_restores_layers_and_the_setting_turns_it_off() { let mut s = session(); From 0e19f9d1d1ea0b4c94c2385d274321a52fd2a5e0 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 15:41:48 -0700 Subject: [PATCH 508/900] SHX fonts: build on main (a bottom-justified SHX text sits a third of the height down; explicit render imports after #2239) --- crates/fonts/src/lib.rs | 3 ++- crates/render/src/dim_draw.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 29b5a14ee..456769caa 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -587,7 +587,8 @@ pub fn baseline_start(font: &TextFont, s: &str, p: &TextParams) -> Vec2 { fn bottom_depth(font: &TextFont, height: f64) -> f64 { match font { TextFont::Outline(face) => ttf::descent_ratio(face).map_or(height / 3.0, |r| r * height), - TextFont::Stroke => height / 3.0, + // AutoCAD places it a third of the height down with SHX fonts. + TextFont::Stroke | TextFont::Shx(_) => height / 3.0, } } diff --git a/crates/render/src/dim_draw.rs b/crates/render/src/dim_draw.rs index aaf3bc409..011dfcc73 100644 --- a/crates/render/src/dim_draw.rs +++ b/crates/render/src/dim_draw.rs @@ -1,7 +1,7 @@ use super::display::Kind; use super::draw::stroke_with; use super::props::default_lineweight; -use super::text_entity::{layout_mtext_entity, place_text_entity, text_style}; +use super::text_entity::{layout_mtext_entity, place_text_entity, style_font, text_style}; use super::{Builder, Color, Ctx, DimGeometry, DimText, Drawing, Entity, EntityKind, LineRole, Lineweight, Vec2, dim, ink}; /// The font settings of a dimension style's text style. From b1b3754ffa0317edb72431d2ec5f994f55748f47 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 18:11:06 -0500 Subject: [PATCH 509/900] fix(engine): autosave files are owner-only and lock files are never written through a link (#2717) The heartbeat opened .lock with a create-and-truncate that followed symlinks, and fell back to std::fs::write, so another account sharing SAVEFILEPATH could plant a link and have the app truncate a file of the victim's. The lock is now opened with O_NOFOLLOW|O_NONBLOCK and must be a plain file, and unlocked writes replace the file through the atomic writer. Autosave files are created 0600 regardless of umask. Lock pruning parses the folder's autosave names once instead of once per lock. --- crates/engine/src/autosave.rs | 64 +++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/autosave.rs b/crates/engine/src/autosave.rs index 0caac6143..f23d3159f 100644 --- a/crates/engine/src/autosave.rs +++ b/crates/engine/src/autosave.rs @@ -405,10 +405,11 @@ mod native { pub fn prune_locks(dir: &Path) { let Ok(entries) = std::fs::read_dir(dir) else { return }; let names: Vec = entries.flatten().take(10_000).map(|e| e.file_name().to_string_lossy().to_string()).collect(); + // The instances that own autosave files, parsed once rather than once per lock file. + let with_files: std::collections::HashSet<&str> = names.iter().filter_map(|f| parse_file_name(f)).map(|(_, i, _)| i).collect(); for n in &names { let Some(instance) = parse_lock_name(n) else { continue }; - let has_files = names.iter().any(|f| parse_file_name(f).is_some_and(|(_, i, _)| i == instance)); - if !has_files && !owner_alive(dir, instance) { + if !with_files.contains(instance) && !owner_alive(dir, instance) { let _ = std::fs::remove_file(dir.join(n)); } } @@ -435,7 +436,22 @@ mod native { } // Create a fresh temporary file exclusively and rename it into place, so a planted // `.tmp` symlink in a shared autosave directory cannot redirect the write (CWE-59). - crate::atomic_write::write_atomic(Path::new(path), &bytes).map_err(|e| e.to_string()) + // The file holds unsaved work: owner-only from its creation, whatever the umask. + crate::atomic_write::write_atomic_with(Path::new(path), private_mode(), |f| f.write_all(&bytes)).map_err(|e| e.to_string()) + } + + /// Owner read/write only (`None` where file modes don't exist). + fn private_mode() -> Option { + #[cfg(unix)] + return Some(std::os::unix::fs::PermissionsExt::from_mode(0o600)); + #[cfg(not(unix))] + None + } + + /// Write this app's lock file at `path` without following a link planted there: the file is + /// replaced (exclusive temporary file, then rename), never written through (CWE-59). + fn write_lock(path: &Path, id: u32) -> std::io::Result<()> { + crate::atomic_write::write_atomic_with(path, private_mode(), |f| f.write_all(id.to_string().as_bytes())) } impl Autosaver { @@ -586,7 +602,7 @@ mod native { for (held, file) in &self.locks { let refreshed = match file { Some(file) => file.set_modified(SystemTime::now()), - None => std::fs::write(held, id.to_string()), + None => write_lock(held, id), }; if held == path { current = Some(refreshed); @@ -595,10 +611,22 @@ mod native { if let Some(refreshed) = current { return refreshed; } - let mut file = OpenOptions::new().write(true).create(true).truncate(false).open(path)?; + let mut options = OpenOptions::new(); + options.write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // A symlink planted at the lock path must not be opened (and truncated) through, + // nor a FIFO wait for a reader. + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).mode(0o600); + } + let mut file = options.open(path)?; + if !file.metadata()?.is_file() { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "the lock file is not a plain file")); + } if file.try_lock().is_err() { self.locks.push((path.to_path_buf(), None)); - return std::fs::write(path, id.to_string()); + return write_lock(path, id); } file.set_len(0)?; file.write_all(format!("{id}{LOCK_HELD}").as_bytes())?; @@ -627,6 +655,30 @@ mod native { } } } + + #[cfg(all(test, unix))] + mod tests { + use super::*; + + /// A symlink planted at the lock path is neither opened through nor written through. + #[test] + fn lock_writes_do_not_follow_a_planted_link() { + let dir = std::env::temp_dir().join(format!("cadcraft-lock-link-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let victim = dir.join("victim.txt"); + std::fs::write(&victim, b"precious").unwrap(); + let link = dir.join("1-a.lock"); + std::os::unix::fs::symlink(&victim, &link).unwrap(); + let mut a = Autosaver::new("1-a"); + assert!(a.refresh_lock(&link).is_err()); + assert_eq!(std::fs::read(&victim).unwrap(), b"precious"); + write_lock(&link, 42).unwrap(); + assert_eq!(std::fs::read(&victim).unwrap(), b"precious"); + assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(&link).unwrap(), b"42"); + std::fs::remove_dir_all(dir).unwrap(); + } + } } #[cfg(test)] From dad7d1c138f585f9b4b21db7ea4f3d545a66fc54 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 18:11:23 -0500 Subject: [PATCH 510/900] fix(render): charge every block entry, index attribute definitions, and walk dashes and outlines in linear time (#2724) * fix(render): charge every block entry, index attribute definitions, and walk dashes and outlines in linear time Array copies skipped ATTDEF entries before charging the expansion budget, each attribute searched its block for a definition, each dash scanned every centreline sample, and outline chaining searched a vertex's segment list from its start on every visit. Each is now charged, indexed or cursored. * address review: drop wall-clock bound from outline test --- crates/render/src/blocks.rs | 26 +++++++++++++++++--------- crates/render/src/outline.rs | 32 ++++++++++++++++++++++++++++---- crates/render/src/wide.rs | 4 +++- 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index ad4689682..ca8304eb0 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -56,13 +56,15 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: 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) }; for be in blk.entities.iter() { + // Every visit is charged, drawn or not, so a block of definitions can't make + // the copies loop free. + if !b.expand() { + break 'copies; + } // Constant/visible attribute definitions inside blocks are not drawn; attribs are. if matches!(be.kind, EntityKind::AttDef(_)) { continue; } - if !b.expand() { - break 'copies; - } entity(b, &sub, be); } } @@ -73,6 +75,17 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: let attmode = ctx.d.header.i64("ATTMODE", 1); // The reference's transparency; each attribute draws with its own. let reference = b.transparency; + // The block's first definition per tag (without case), built once for all the attributes. + let mut defs: std::collections::HashMap = std::collections::HashMap::new(); + if !ins.attribs.is_empty() + && let Some(blk) = ctx.d.block(&ins.block) + { + for be in blk.entities.iter() { + if let EntityKind::AttDef(d) = &be.kind { + defs.entry(d.tag.to_ascii_lowercase()).or_insert(be.as_ref()); + } + } + } for a in &ins.attribs { if attmode == 0 || (a.invisible && attmode != 2) { continue; @@ -83,7 +96,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: // Properties of the attribute's definition (as AutoCAD copies them to the attribute // on insertion), except those set on the attribute itself: ByBlock = the reference's, // layer 0 = the reference's layer. - let def = ctx.d.block(&ins.block).and_then(|blk| blk.entities.iter().find(|be| attdef_tag(be, &a.tag))); + let def = defs.get(&a.tag.to_ascii_lowercase()).copied(); let (ink, lw, shown, t) = match (def, a.props.is_empty()) { (None, true) => (rgb, resolve(ctx, e, b.plotting).1, true, reference), (def, _) => { @@ -117,8 +130,3 @@ fn by_block() -> cadcraft_doc::Common { ..cadcraft_doc::Common::default() } } - -/// The attribute definition with tag `tag` (any case). -fn attdef_tag(e: &Entity, tag: &str) -> bool { - matches!(&e.kind, EntityKind::AttDef(d) if d.tag.eq_ignore_ascii_case(tag)) -} diff --git a/crates/render/src/outline.rs b/crates/render/src/outline.rs index 730d7fb39..96244fc01 100644 --- a/crates/render/src/outline.rs +++ b/crates/render/src/outline.rs @@ -106,10 +106,12 @@ fn chain(mut segs: Vec<(Vec2, Vec2)>) -> Vec> { } } segs.sort_unstable_by(|(a, b), (c, d)| cmp(*a, *c).then_with(|| cmp(*b, *d))); - let mut at: HashMap> = HashMap::new(); + // Segments at each vertex with a cursor past the used ones, so many segments meeting at one + // vertex are each examined once rather than from the start on every visit. + let mut at: HashMap, usize)> = HashMap::new(); for (i, (a, b)) in segs.iter().enumerate() { - at.entry(key(*a)).or_default().push(i); - at.entry(key(*b)).or_default().push(i); + at.entry(key(*a)).or_default().0.push(i); + at.entry(key(*b)).or_default().0.push(i); } let mut used = vec![false; segs.len()]; let mut out = Vec::new(); @@ -125,7 +127,15 @@ fn chain(mut segs: Vec<(Vec2, Vec2)>) -> Vec> { let mut end = b; // Each step uses one segment, so the walk ends within `segs.len()` steps. loop { - let next = at.get(&key(end)).and_then(|ids| ids.iter().copied().find(|&i| !used.get(i).copied().unwrap_or(true))); + let next = at.get_mut(&key(end)).and_then(|(ids, cursor)| { + while let Some(&i) = ids.get(*cursor) { + if !used.get(i).copied().unwrap_or(true) { + return Some(i); + } + *cursor += 1; + } + None + }); let Some(i) = next else { break }; let Some(&(p, q)) = segs.get(i) else { break }; if let Some(u) = used.get_mut(i) { @@ -147,6 +157,20 @@ mod tests { lines.iter().flat_map(|l| l.windows(2).map(|w| w[0].dist(w[1]))).sum() } + /// Thousands of lobes meeting at one vertex chain in one pass over that vertex's segments. + #[test] + fn many_lobes_at_one_vertex_chain_quickly() { + let mut tris = Vec::new(); + for i in 0..20_000 { + let x = f64::from(i + 1); + tris.extend_from_slice(&[Vec2::ZERO, Vec2::new(x, 1.0), Vec2::new(x + 0.5, 2.0)]); + } + // No wall-clock bound (flaky on loaded runners): a quadratic scan would make this test crawl + // rather than fail, so check the output is complete instead. + let lines = fill_outlines(&tris); + assert_eq!(lines.iter().map(|l| l.len() - 1).sum::(), 60_000, "every triangle edge is emitted once"); + } + #[test] fn a_square_of_two_triangles_is_one_loop() { let (a, b, c, d) = (Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(2.0, 1.0), Vec2::new(0.0, 1.0)); diff --git a/crates/render/src/wide.rs b/crates/render/src/wide.rs index d0d874d3f..5df6f42f3 100644 --- a/crates/render/src/wide.rs +++ b/crates/render/src/wide.rs @@ -95,7 +95,9 @@ pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern: continue; } let (Some(first), Some(last)) = (at(run, a), at(run, b)) else { continue }; - let inner = run.iter().filter(|x| x.s > a && x.s < b).copied(); + // The samples strictly between a and b: `run` is ordered by `s`, so a slice, not a scan. + let (lo, hi) = (run.partition_point(|x| x.s <= a), run.partition_point(|x| x.s < b)); + let inner = run.get(lo..hi.max(lo)).unwrap_or_default().iter().copied(); let pts: Vec = std::iter::once(first).chain(inner).chain(std::iter::once(last)).collect(); for w in pts.windows(2) { if let [x, y] = w { From f10e41409ddde31adf4e01111478ff44aaaed4ca Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 16:52:11 -0700 Subject: [PATCH 511/900] Images: read no more than the limit, keep plot bounds to what a viewport shows, free textures with no images left Review fixes from CodeRabbit on #2749: - the image file is read through read_capped, so a file that grows after the size check can't exhaust memory - an image cut by a layout viewport widens the sheet's bounds only by the part inside it, as other primitives do - uploaded tiles of closed drawings are dropped also when the next list has no images --- crates/engine/src/cmd/image.rs | 6 +++++- crates/render/src/viewports.rs | 20 ++++++++++++-------- crates/render/tests/raster_image.rs | 3 +++ crates/ui-egui/src/canvas/images.rs | 26 ++++++++++++++++++-------- 4 files changed, 38 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index 240664891..daf46557b 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -79,7 +79,11 @@ fn read_file(path: &str, host: Option<&str>) -> std::result::Result, Str if len > MAX_IMAGE_BYTES { return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20)); } - std::fs::read(&file).map_err(|e| e.to_string()) + // Read no more than the limit: the file can grow or change after the check above. + let limit = usize::try_from(MAX_IMAGE_BYTES).unwrap_or(usize::MAX); + crate::capped_read::read_capped(&file, limit).map_err(|e| { + if e.kind() == std::io::ErrorKind::InvalidData { format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20) } else { e.to_string() } + }) } #[cfg(target_arch = "wasm32")] { diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 6b501e840..f6e8c8cb0 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -255,20 +255,24 @@ fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { /// Append image `img` (primitive `p`, corners `corners`) to `dst`, to be cut to `clip` when it /// is drawn: the picture is not cut here, the outline is added to those it carries. fn push_clipped_image(dst: &mut DisplayList, p: &DPrim, img: &DImage, corners: &[Vec2], clip: &Clip) { - let outline = match clip { - Clip::Rect(rect) => { - if !Bounds2::from_points(corners.iter().copied()).intersects(rect) { - return; - } - vec![rect.min, Vec2::new(rect.max.x, rect.min.y), rect.max, Vec2::new(rect.min.x, rect.max.y)] - } - Clip::Poly(c) => c.polygon().to_vec(), + 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()), }; + let own = Bounds2::from_points(corners.iter().copied()); + if !own.intersects(&area) { + return; + } let Ok(index) = u32::try_from(dst.images.len()) else { return }; let mut img = img.clone(); img.clips.push(outline); dst.images.push(img); + // The list's bounds take only the part inside the clip, as for the other primitives. + let before = dst.bounds; push_raw(dst, p, Kind::Image { index }, corners); + dst.bounds = before; + dst.bounds.add(own.min.max(area.min)); + dst.bounds.add(own.max.min(area.max)); } fn push_raw(dst: &mut DisplayList, p: &DPrim, kind: Kind, pts: &[Vec2]) { diff --git a/crates/render/tests/raster_image.rs b/crates/render/tests/raster_image.rs index 8cc2d09e8..bdf03dd44 100644 --- a/crates/render/tests/raster_image.rs +++ b/crates/render/tests/raster_image.rs @@ -269,6 +269,9 @@ fn a_layout_viewport_cuts_the_image_to_its_outline() { assert_eq!(img.clips[1], [Vec2::new(15.0, 10.0), Vec2::new(105.0, 10.0), Vec2::new(105.0, 110.0), Vec2::new(15.0, 110.0)]); let p = list.prims.iter().find(|p| matches!(p.kind, Kind::Image { index: 0 })).unwrap(); assert_eq!(list.points(p).len(), 4); + // The image (10..110 across) is wider than the viewport (15..105): only what shows counts + // towards the sheet's bounds, which a plot fits to. + assert!(list.bounds.min.x >= 15.0 - 1e-9 && list.bounds.max.x <= 105.0 + 1e-9, "{:?}", list.bounds); // Drawn: inside the viewport and the image's top row there is the picture; outside the // viewport, or in the clipped-away bottom row, there is none. diff --git a/crates/ui-egui/src/canvas/images.rs b/crates/ui-egui/src/canvas/images.rs index 4818c079d..afde7bee3 100644 --- a/crates/ui-egui/src/canvas/images.rs +++ b/crates/ui-egui/src/canvas/images.rs @@ -158,6 +158,11 @@ fn axis_rect(outline: &[Vec2]) -> Option { /// Draw the images of `list`. pub(super) fn draw(p: &egui::Painter, xf: &Xf, list: &DisplayList) { + // Pyramids whose pixels are gone (drawing closed, image undone) go, also when the list has + // no images left to draw. + if let Ok(mut pyramids) = textures(p.ctx()).0.lock() { + pyramids.retain(|_, pyramid| pyramid.pixels.strong_count() > 0); + } if list.images.is_empty() { return; } @@ -172,6 +177,11 @@ pub(super) fn draw(p: &egui::Painter, xf: &Xf, list: &DisplayList) { } } +/// The image tiles uploaded so far, kept between frames. +fn textures(ctx: &egui::Context) -> Textures { + ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("cadcraft-raster-textures")).clone()) +} + /// Draw one image as textured meshes, one per tile on screen: its rectangle, or the outline it is /// clipped to. fn draw_one(p: &egui::Painter, xf: &Xf, img: &DImage, alpha: u8) { @@ -184,10 +194,8 @@ fn draw_one(p: &egui::Painter, xf: &Xf, img: &DImage, alpha: u8) { // Where in the raster the triangles are. let Some(tris) = triangles(img, cut.outline).iter().map(|q| img.pixel_of(*q)).collect::>>() else { return }; let color = Color32::from_white_alpha((img.opacity(alpha) * 255.0) as u8); - let textures = ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("cadcraft-raster-textures")).clone()); + let textures = textures(ctx); let Ok(mut pyramids) = textures.0.lock() else { return }; - // Pyramids whose pixels are gone (drawing closed, image undone) go too. - pyramids.retain(|_, pyramid| pyramid.pixels.strong_count() > 0); let key = Arc::as_ptr(raster) as usize; let pyramid = match pyramids.entry(key) { Entry::Occupied(e) => e.into_mut(), @@ -484,15 +492,17 @@ mod tests { assert!(frame(&l) >= 1, "the first frame also uploads the font atlas"); assert_eq!(frame(&l), 0, "already uploaded"); // The pixels gone (drawing closed, image undone): the pyramid goes on the next draw. - let count = |ctx: &egui::Context| { - let t = ctx.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("cadcraft-raster-textures")).clone()); - t.0.lock().unwrap().len() - }; + let count = |ctx: &egui::Context| textures(ctx).0.lock().unwrap().len(); assert_eq!(count(&ctx), 1); drop(l); drop(r); - frame(&list(|_| {})); + let next = list(|_| {}); + frame(&next); assert_eq!(count(&ctx), 1, "only the new image's"); + // A list with no images still lets go of the pictures that are gone. + drop(next); + frame(&DisplayList::default()); + assert_eq!(count(&ctx), 0); } /// A known limit, kept visible here: on screen images are painted first, so they lie under From 26e96cfb566600b093fcce86053fe52238028153 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 17:10:20 -0700 Subject: [PATCH 512/900] View twist: a locked viewport keeps its twist; the untwisted file view fits the extents as the turned view sees them Review fixes from CodeRabbit on #2748: - DVIEW TWist and view.set refuse to turn a locked active viewport ("The viewport is locked.") - the untiled *Active VPORT record fits the extents rotated by the twist it writes, with the twist normalised --- crates/engine/src/cmd/view/dview.rs | 4 ++++ crates/engine/tests/dview.rs | 22 ++++++++++++++++++++++ crates/io/src/dxf_write/layout.rs | 25 +++++++++++++++++-------- 3 files changed, 43 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/view/dview.rs b/crates/engine/src/cmd/view/dview.rs index 9a421c8a9..221459c3c 100644 --- a/crates/engine/src/cmd/view/dview.rs +++ b/crates/engine/src/cmd/view/dview.rs @@ -94,6 +94,10 @@ pub(super) fn set_twist(s: &mut Session, target: Target, twist: f64) -> Result<( if viewport_twist(s, h) == Some(twist) { return Ok(()); } + // A locked viewport keeps its view, the twist with it. + if s.state()?.active_viewport().is_some_and(|(vh, vp)| vh == h && vp.locked) { + return Err(EngineError::Other("The viewport is locked.".into())); + } let space = s.state()?.space.clone(); let d = s.doc_mut()?; if let Some(store) = d.space_mut(&space) { diff --git a/crates/engine/tests/dview.rs b/crates/engine/tests/dview.rs index f0e6d9b0a..266421b2f 100644 --- a/crates/engine/tests/dview.rs +++ b/crates/engine/tests/dview.rs @@ -249,6 +249,28 @@ fn inside_an_active_viewport_it_twists_that_viewport_as_one_undo_step() { assert_eq!(s.cmdline("dview").unwrap_err().to_string(), PAPER); } +#[test] +fn a_locked_viewport_keeps_its_twist() { + let (mut s, h) = layout_session(); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + if let EntityKind::Viewport(v) = &mut e.kind { + v.locked = true; + } + }) + .unwrap(); + s.execute("mspace", &json!({ "handle": h.hex() })).unwrap(); + let undo = s.state().unwrap().undo.len(); + assert!(s.execute("dview", &json!({ "twist": 30 })).is_err()); + let v = view(&s); + assert!(s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height, "twist": 30 })).is_err()); + assert_eq!(vp(&s, h).twist, 0.0); + assert_eq!(s.state().unwrap().undo.len(), undo); + // A view with the twist it already has is fine. + s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height })).unwrap(); +} + #[test] fn escape_inside_an_active_viewport_keeps_the_twist_as_one_undo_step() { let (mut s, h) = layout_session(); diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 07698fb88..1341f8ec2 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -72,15 +72,24 @@ 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, - // An untiled view's twist: the lone `*Active` tile the editor keeps for it. - twist: d.vports.iter().find(|c| c.is_active() && c.tiles.len() == 1).and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist), + // An untiled view's twist: the lone `*Active` tile the editor keeps for it. + let twist = d + .vports + .iter() + .find(|c| c.is_active() && c.tiles.len() == 1) + .and_then(|c| c.tiles.first()) + .map_or(0.0, |t| cadcraft_geom::norm_angle(t.twist)); + // The extents fitted as the turned view sees them. + let (center, height) = if ext.is_empty() { + (Vec2::new(6.0, 4.5), 9.0) + } else if twist == 0.0 { + (ext.center(), (ext.height() * 1.1).max(1e-6)) + } else { + let r = Bounds2::from_points(ext.corners().map(|p| p.rotate(twist))); + let height = r.height() * 1.1; + (r.center().rotate(-twist), if height.is_finite() { height.max(1e-6) } else { 9.0 }) }; + let single = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center, height, aspect: 1.6, twist }; 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(), From d1e6f4df9666cf32ba9697147251e2ddbc9814f7 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 17:22:36 -0700 Subject: [PATCH 513/900] 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 75049718c9770727c5c30637a43d430581338a70 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 17:35:23 -0700 Subject: [PATCH 514/900] View twist: build with raster images from main (an axis rectangle is turned on a twisted screen, so it cuts an image as an outline) --- crates/render/tests/raster_image.rs | 1 + crates/ui-egui/src/canvas/images.rs | 11 ++++++----- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/render/tests/raster_image.rs b/crates/render/tests/raster_image.rs index bdf03dd44..0d050f6a3 100644 --- a/crates/render/tests/raster_image.rs +++ b/crates/render/tests/raster_image.rs @@ -257,6 +257,7 @@ fn a_layout_viewport_cuts_the_image_to_its_outline() { layer_colors: Vec::new(), clip: None, on: true, + twist: 0.0, }; d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); let list = build(&d, &Space::Paper("Layout1".into()), &Options::default()); diff --git a/crates/ui-egui/src/canvas/images.rs b/crates/ui-egui/src/canvas/images.rs index afde7bee3..9cc61e981 100644 --- a/crates/ui-egui/src/canvas/images.rs +++ b/crates/ui-egui/src/canvas/images.rs @@ -264,7 +264,8 @@ struct Cut<'a> { fn cut<'a>(img: &'a DImage, xf: &Xf, canvas: Rect) -> Cut<'a> { let mut cut = Cut { rect: canvas, outline: None }; for outline in &img.clips { - match axis_rect(outline) { + // In a twisted view a rectangle along the drawing's axes is turned on screen. + match axis_rect(outline).filter(|_| xf.twist == 0.0) { Some(b) => cut.rect = cut.rect.intersect(Rect::from_two_pos(xf.to_screen(b.min), xf.to_screen(b.max))), None if cut.outline.is_none() => cut.outline = Some(outline), None => {} @@ -321,7 +322,7 @@ mod tests { fn painted(list: &DisplayList) -> (egui::Context, Vec) { let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); - let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0 }; + let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0, twist: 0.0 }; let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); draw(&painter, &xf, list); @@ -400,7 +401,7 @@ mod tests { let l = build(&d, &Space::Model, &Options::default()); let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(8192.0, 100.0)); - let xf = Xf { rect, center: v(side as f64 / 2.0, 0.5), scale: 2.0 }; + let xf = Xf { rect, center: v(side as f64 / 2.0, 0.5), scale: 2.0, twist: 0.0 }; let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), max_texture_side: Some(1 << 14), ..Default::default() }, |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); draw(&painter, &xf, &l); @@ -479,7 +480,7 @@ mod tests { l.images[0].raster = r.clone(); let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); - let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0 }; + let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0, twist: 0.0 }; let frame = |list: &DisplayList| { let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); @@ -529,7 +530,7 @@ mod tests { let l = build(&d, &Space::Model, &Options::default()); let ctx = egui::Context::default(); let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0)); - let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0 }; + let xf = Xf { rect, center: v(5.0, 5.0), scale: 10.0, twist: 0.0 }; let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); crate::canvas::draw_list(&painter, &xf, &l, cadcraft_color::Rgb(0, 0, 0), false); From 39ee2e596021e6849f62e8a12ae7c77d4bffdbc8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 17:59:52 -0700 Subject: [PATCH 515/900] SHX fonts: review fixes (search the current folder for a bare drawing name, one lock for the font cache generation, no split_paths on wasm, MTEXT \U+ upper case as the layout, a point budget for repeated linetype shapes, web picks report skipped files and cap bytes read at once) --- apps/cadcraft-web/src/upload.rs | 17 ++++++++++++++++- crates/engine/src/cmd/file.rs | 2 ++ crates/fonts/src/mtext.rs | 2 +- crates/fonts/src/shx/table.rs | 7 +++---- crates/render/src/linetype_text.rs | 26 +++++++++++++++++++++++++- 5 files changed, 47 insertions(+), 7 deletions(-) diff --git a/apps/cadcraft-web/src/upload.rs b/apps/cadcraft-web/src/upload.rs index 4b4f51829..333c4906b 100644 --- a/apps/cadcraft-web/src/upload.rs +++ b/apps/cadcraft-web/src/upload.rs @@ -22,6 +22,9 @@ const ACCEPT: &str = ".dxf,.dwg,.shx"; /// Most files taken from one pick. const MAX_PICKED: u32 = 64; +/// Most bytes being read at once, all files together: a large pick must not exhaust the page's +/// memory (each file is copied once more into the app). +const MAX_READING_BYTES: u64 = 512 << 20; /// A file read in the browser (name, contents), or why it couldn't be read. type Upload = Result<(String, Vec), String>; @@ -30,12 +33,14 @@ type Upload = Result<(String, Vec), String>; #[derive(Clone)] pub struct Inbox { files: Rc>>, + /// Bytes of the files being read now. + reading: Rc>, ctx: egui::Context, } impl Inbox { pub fn new(ctx: &egui::Context) -> Self { - Inbox { files: Rc::default(), ctx: ctx.clone() } + Inbox { files: Rc::default(), reading: Rc::default(), ctx: ctx.clone() } } /// Show the browser's file picker and return at once. A chosen file arrives through @@ -72,6 +77,10 @@ impl Inbox { inbox.read(file); } } + let skipped: Vec = (MAX_PICKED..files.length()).filter_map(|i| files.get(i)).map(|f| f.name()).collect(); + if !skipped.is_empty() { + inbox.push(Err(format!("Open: at most {MAX_PICKED} files at a time; not opened: {}", skipped.join(", ")))); + } } chosen.remove(); }); @@ -101,12 +110,18 @@ impl Inbox { if let Some(e) = CadApp::open_size_error(&name, len) { return self.push(Err(e)); } + let reading = self.reading.get(); + if reading.saturating_add(len) > MAX_READING_BYTES { + return self.push(Err(format!("Open: {name} was not read: the files being read together are too large; open it on its own"))); + } + self.reading.set(reading.saturating_add(len)); let inbox = self.clone(); wasm_bindgen_futures::spawn_local(async move { let r = match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await { Ok(buf) => Ok((name, js_sys::Uint8Array::new(&buf).to_vec())), Err(e) => Err(format!("Open: could not read {name}: {}", js_error(e))), }; + inbox.reading.set(inbox.reading.get().saturating_sub(len)); inbox.push(r); }); } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index af49e3351..606ad4e28 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -336,6 +336,8 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result String { } 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => i += 2, // `\U+XXXX`: a character by its Unicode code, as the layout reads it. - 'U' | 'u' if crate::unicode_escape(&chars, i).is_some() => { + 'U' if crate::unicode_escape(&chars, i).is_some() => { if let Some(u) = crate::unicode_escape(&chars, i) { out.push(u); } diff --git a/crates/fonts/src/shx/table.rs b/crates/fonts/src/shx/table.rs index 9a002afaa..4b44927d7 100644 --- a/crates/fonts/src/shx/table.rs +++ b/crates/fonts/src/shx/table.rs @@ -140,7 +140,7 @@ pub fn drawing_dirs() -> Vec { pub fn set_search_path(list: &str) { let dirs: Vec = list .split(';') - .flat_map(|p| if cfg!(windows) { vec![PathBuf::from(p)] } else { std::env::split_paths(p).collect() }) + .flat_map(|p| if cfg!(any(windows, target_arch = "wasm32")) { vec![PathBuf::from(p)] } else { std::env::split_paths(p).collect() }) .filter(|d| !d.as_os_str().is_empty() && !d.to_string_lossy().trim().is_empty()) .take(MAX_DIRS) .collect(); @@ -184,7 +184,7 @@ pub fn generation() -> u64 { /// The SHX font file a style or linetype names, if CADCraft can find and read it. pub fn find(name: &str) -> Option> { let mut k = key(name)?; - let (provider, dirs) = { + let (provider, dirs, generation) = { let t = table(); // The font map renames once (a map can't loop). if let Some(to) = t.map.iter().find(|(from, _)| *from == k).and_then(|(_, to)| key(to)) { @@ -197,9 +197,8 @@ pub fn find(name: &str) -> Option> { return r.clone(); } let dirs: Vec = t.drawing_dirs.iter().chain(t.search_path.iter()).cloned().collect(); - (t.provider.clone(), dirs) + (t.provider.clone(), dirs, t.generation) }; - let generation = generation(); let font = provider .and_then(|p| p.load(&k)) .or_else(|| read_from(&dirs, &k)) diff --git a/crates/render/src/linetype_text.rs b/crates/render/src/linetype_text.rs index 97770c2b2..9f753ed11 100644 --- a/crates/render/src/linetype_text.rs +++ b/crates/render/src/linetype_text.rs @@ -25,6 +25,9 @@ use cadcraft_geom::Vec2; /// Upper bound on the texts and shapes drawn along one run (hostile scales; `apply` caps the /// dashes). const MAX_TEXTS: usize = 10_000; +/// Most points all the placed texts and shapes of one polyline hold together (a large shape +/// repeated many times). +const MAX_POINTS: usize = 2_000_000; /// One text or shape element of the pattern, shaped once at the origin. struct Element { @@ -56,10 +59,12 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: } let mut walk = Walk { pts, i: 0, start: 0.0 }; let mut base = 0.0; + let mut points = 0usize; 'repeats: while base <= len { for el in &elements { let s = base + el.at; - if s > len + 1e-9 || out.len() >= MAX_TEXTS { + points = points.saturating_add(point_count(&el.local)); + if s > len + 1e-9 || out.len() >= MAX_TEXTS || points > MAX_POINTS { break 'repeats; } let Some((p, dir)) = walk.at(s) else { break 'repeats }; @@ -74,6 +79,10 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: out } +fn point_count(s: &Shaped) -> usize { + s.strokes.iter().map(Vec::len).chain(s.glyphs.iter().flatten().map(Vec::len)).fold(0, usize::saturating_add) +} + /// The shape element `el` at the origin (scaled by the element's and the linetype's scale), if /// its shape file is found and has the shape. fn shape(d: &Drawing, el: &cadcraft_doc::DashElement, scale: f64) -> Option { @@ -253,6 +262,21 @@ mod tests { assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], <, 1.0, 0.0).is_empty()); } + #[test] + fn a_large_shape_repeated_many_times_is_bounded() { + // A shape of 1,000 one-unit vectors there and back: about 1,000 points each time. + let body: Vec<&str> = (0..500).flat_map(|_| ["010", "018"]).collect(); + let src = format!("*131,1002,ZIGZAG\n1,{},0\n", body.join(",")); + cadcraft_fonts::shx::register("cadcraft-render-big.shx", &cadcraft_fonts::shx::compile(&src).unwrap()).unwrap(); + let d = Drawing::new_imperial(); + let mut lt = fence("cadcraft-render-big.shx"); + lt.pattern[1].shape = Some(131); + // 3,000 repeats would hold about 3 million points. + let t = texts(&d, &[Vec2::ZERO, Vec2::new(2850.0, 0.0)], <, 1.0, 0.0); + let points: usize = t.iter().map(point_count).sum(); + assert!(!t.is_empty() && t.len() < 3000 && points <= MAX_POINTS, "{} shapes, {points} points", t.len()); + } + #[test] fn text_in_an_shx_style_uses_the_font_metrics() { // A text font written for this test: A is 4 wide with a gap of 2, cap height 6. From e90a19736577ccbd815574a6f2291e9c19cd98b5 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Tue, 3 Nov 2026 18:07:00 -0700 Subject: [PATCH 516/900] 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 517/900] 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 518/900] 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 519/900] 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 520/900] 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 521/900] 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 522/900] 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 523/900] 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 524/900] 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 a801739ea7ed5ff811829003068e065fa597c4a1 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:10:41 +0200 Subject: [PATCH 525/900] DXF/DWG save: kept render settings take the declared version's class-version form Render settings store their AcDbRenderSettings class version in the form of the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one one lower, as acadrust reads and writes them. A kept RENDERSETTINGS, MENTALRAYRENDERSETTINGS or RAPIDRTRENDERSETTINGS object carried the form of the file it was read from into whatever file it was written to. The DWG bridge is an R2000 DXF for a 2018 DWG: a 2018 drawing's render settings went in with the 2018 form, the DWG writer raised it once more, and BricsCAD refused the DWG for an object of class version 3 (#907, one of two causes; the other is an empty constraint group written short, fixed in acadrust 0.6.6, hakanaktt/acadrust#146). The form the kept objects are in is the $ACADVER the file declared, recorded at read time in Foreign::acadver (the DWG bridge reads through the DXF reader, so it is set there too). The drawing's own $ACADVER is not used: SAVEAS changes it while the kept objects stay as read, so a 2018 drawing saved as 2000 and then as 2018 wrote class version 3 again. A file without $ACADVER records none, and its kept objects are written as read. Tests: the conversion is checked against acadrust itself (acadrust writes the fixture in four versions, and CADCraft, reading any of them and saving in any of them, stores what acadrust stores); SAVEAS 2000, QSAVE, then SAVEAS 2018 through the engine; a file without $ACADVER. Co-Authored-By: Claude Fable 5.1 Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/foreign.rs | 4 + crates/engine/tests/render_settings_saveas.rs | 55 ++++++++ crates/io/src/dxf_raw.rs | 49 ++++++- crates/io/src/dxf_write/sections.rs | 1 + crates/io/tests/it/main.rs | 2 + crates/io/tests/it/render_settings_version.rs | 133 ++++++++++++++++++ 6 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 crates/engine/tests/render_settings_saveas.rs create mode 100644 crates/io/tests/it/render_settings_version.rs diff --git a/crates/doc/src/foreign.rs b/crates/doc/src/foreign.rs index 406f4e12b..356c131c3 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` the file declared ("AC1032"), if any: the kept data is in that version's + /// form, whatever the drawing's `$ACADVER` says later (SAVEAS changes it). Saving into another + /// version converts what differs by version (render settings' class version). + pub acadver: Option, } impl Foreign { diff --git a/crates/engine/tests/render_settings_saveas.rs b/crates/engine/tests/render_settings_saveas.rs new file mode 100644 index 000000000..80d31e64c --- /dev/null +++ b/crates/engine/tests/render_settings_saveas.rs @@ -0,0 +1,55 @@ +//! Kept render settings are in the form of the file they were read from, whatever the drawing's +//! `$ACADVER` says after a SAVEAS to another version: saving a 2018 drawing down to 2000 and back +//! up to 2018 writes the class version the 2018 file had, not one higher (which BricsCAD refuses, +//! #907). + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as}; +use serde_json::json; + +/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the +/// 2013+ form). +const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\ + 0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\ + 0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\ + 0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\ + 100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n"; + +/// The `AcDbRenderSettings` class version in a written DXF. +fn class_version(path: &std::path::Path) -> Option { + let text = std::fs::read_to_string(path).unwrap(); + let l: Vec<&str> = text.lines().map(str::trim).collect(); + let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?; + let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at; + l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap()) +} + +#[test] +fn saveas_down_and_back_up_keeps_the_render_settings_class_version() { + set_io(IoHooks { + read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + set_write_as(|d, name, o| { + cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) + }); + let dir = std::env::temp_dir().join(format!("cadcraft-render-settings-saveas-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::empty(); + s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "render.dxf", None); + let save = |s: &mut Session, name: &str, version: &str| { + let path = dir.join(name); + s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap(); + class_version(&path) + }; + + assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read"); + assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower"); + s.execute("qsave", &json!({})).unwrap(); + assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form"); + assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 1a2c8696b..ea2dc2d14 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject}; use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown}; -use cadcraft_dxf::{Section, Tag}; +use cadcraft_dxf::{Section, Tag, Version}; /// Named object dictionary entries CADCraft writes itself from its model (plus every key that /// starts with `CADCRAFT`): they are read into the model, not kept raw. A change that starts @@ -452,10 +452,18 @@ 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.acadver = acadver(secs); d.foreign = Arc::new(f); } } +/// The `$ACADVER` the file's HEADER declares, if any. +fn acadver(secs: &[Section]) -> Option { + let header = &secs.iter().find(|s| s.name == "HEADER")?.tags; + let at = header.iter().position(|t| t.code == 9 && t.str().trim().eq_ignore_ascii_case("$ACADVER"))?; + header.get(at + 1).filter(|t| t.code == 1).map(|t| t.str().trim().to_ascii_uppercase()) +} + fn entity_types(drawing: &Drawing) -> HashMap { let mut types = HashMap::new(); for entity in all_entities(drawing) { @@ -845,6 +853,45 @@ fn unknown_handles(d: &Drawing) -> HashSet { all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect() } +/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store +/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of +/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one +/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's +/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test +/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A +/// kept object carries the form of the file it was read from ([`Foreign::acadver`], not the +/// drawing's `$ACADVER`, which SAVEAS changes); written into a file declaring another version, it +/// takes that version's form. Without this, the DWG bridge (an R2000 DXF for a 2018 DWG) handed +/// the 2018 form on as the 2000 one, the DWG writer raised it once more, and BricsCAD refused the +/// DWG for a render settings object of class version 3 (#907). +/// +/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own +/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version, +/// stored the same in every file version, and is left as read. +pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option, declared: Version) { + let Some(source) = source.filter(|s| *s != declared) else { return }; + let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) }; + let (mut kind, mut in_base) = (String::new(), false); + for t in tags.iter_mut() { + match t.code { + 0 => { + kind = up(&t.str()); + in_base = false; + } + 100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => { + in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings"); + } + 90 if in_base => { + let rapid = kind == "RAPIDRTRENDERSETTINGS"; + let logical = t.i64().saturating_sub(shift(rapid, source)); + *t = Tag::i(90, logical.saturating_add(shift(rapid, declared))); + in_base = false; + } + _ => {} + } + } +} + /// Put the drawing's foreign data back into a written file's tags (see the module comment). pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap>, modern: bool) { let f = d.foreign.as_ref(); diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index 68cf61b21..ee813d379 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -1140,6 +1140,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34 // Only a DXF declares the version it is written for: the DWG bridge writes R2000 text for the // DWG writer, which keeps SAT-text solids (#2334). crate::dxf_raw::finish(&mut w.t, d, &w.reactors, version >= Version::R2013); + crate::dxf_raw::render_settings_versions(&mut w.t, d.foreign.acadver.as_deref().and_then(Version::for_acadver), version); crate::dxf_raw::data_store(&mut w.t, d, target >= Version::R2013); add_class_instance_counts(&mut w.t, target); mark_xrefs(&mut w.t, d); diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 289e87806..657752d57 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -61,6 +61,8 @@ mod plot_styles; mod polyface_roundtrip; mod portable_fonts; mod region_roundtrip; +#[cfg(not(target_arch = "wasm32"))] +mod render_settings_version; mod roundtrip; mod roundtrip_audit; mod skipped_records; diff --git a/crates/io/tests/it/render_settings_version.rs b/crates/io/tests/it/render_settings_version.rs new file mode 100644 index 000000000..99025124f --- /dev/null +++ b/crates/io/tests/it/render_settings_version.rs @@ -0,0 +1,133 @@ +//! Render settings store their `AcDbRenderSettings` class version in the form of the file's +//! version: a 2013+ file stores it one higher (a 2013 file stores a rapid RT one one lower), as +//! acadrust reads and writes them. A kept object carries the form of the file it came from; written +//! into a file declaring another version, it takes that version's form. The DWG bridge is an R2000 +//! DXF for a 2018 DWG: without this, a 2018 drawing's MENTALRAYRENDERSETTINGS went in with the 2018 +//! form, the DWG writer raised it once more, and BricsCAD refused the DWG ("Object improperly +//! read", #907). + +use cadcraft_io::{SaveOptions, Version}; + +/// A DXF of `version` with a named object dictionary, its render settings dictionary and one +/// mental ray render settings object whose `AcDbRenderSettings` class version is `class_version`. +fn dxf(version: &str, kind: &str, class_version: i64) -> String { + let body = match kind { + "MENTALRAYRENDERSETTINGS" => { + "100\nAcDbMentalRayRenderSettings\n90\n2\n90\n0\n90\n1\n70\n2\n40\n3.0\n40\n3.0\n40\n0.05\n40\n0.05\n40\n0.05\n40\n0.05\n\ + 70\n0\n290\n0\n290\n1\n90\n5\n90\n5\n90\n5\n290\n0\n90\n500\n290\n0\n40\n1.0\n90\n10000\n90\n5\n90\n5\n90\n5\n290\n0\n\ + 90\n200\n290\n0\n290\n0\n290\n0\n40\n0.1\n40\n1.0\n40\n1500.0\n70\n0\n70\n0\n40\n10.0\n70\n0\n70\n0\n290\n0\n1\n\n\ + 90\n128\n70\n0\n90\n1048\n290\n0\n40\n1.0\n" + } + _ => "", + }; + let cpp = match kind { + "MENTALRAYRENDERSETTINGS" => "AcDbMentalRayRenderSettings", + "RAPIDRTRENDERSETTINGS" => "AcDbRapidRTRenderSettings", + _ => "AcDbRenderSettings", + }; + format!( + "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\n{version}\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\ + 0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n{kind}\n2\n{cpp}\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\ + 0\nSECTION\n2\nOBJECTS\n\ + 0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\ + 0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\ + 0\n{kind}\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n{class_version}\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n{body}\ + 0\nENDSEC\n0\nEOF\n" + ) +} + +/// The `AcDbRenderSettings` class version of the `kind` object in DXF text. +fn class_version(text: &str, kind: &str) -> Option { + let l: Vec<&str> = text.lines().map(str::trim).collect(); + let at = l.windows(2).position(|w| w == ["0", kind])?; + let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at; + l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap()) +} + +fn written(d: &cadcraft_doc::Drawing, version: Version) -> String { + String::from_utf8(cadcraft_io::write_with(d, "x.dxf", &SaveOptions { version: Some(version), binary: false }).unwrap()).unwrap() +} + +#[test] +fn render_settings_class_version_takes_the_declared_versions_form() { + let kind = "MENTALRAYRENDERSETTINGS"; + // From a 2018 file (stored 2 = class version 1 in the 2013+ form). + let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap(); + assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2), "same version: as read"); + assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(2)); + assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1), "2000 form: one lower"); + assert_eq!(class_version(&written(&d, Version::R2010), kind), Some(1)); + // From a 2000 file (stored 1), written as 2018: one higher. + let d = cadcraft_io::read_dxf(dxf("AC1015", kind, 1).as_bytes()).unwrap(); + assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1)); + assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2)); + // Rapid RT settings: the 2013 file alone stores one lower. + let kind = "RAPIDRTRENDERSETTINGS"; + let d = cadcraft_io::read_dxf(dxf("AC1027", kind, 1).as_bytes()).unwrap(); + assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(1)); + assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2)); + assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(2)); +} + +/// A file that declares no `$ACADVER` gives no source form: its kept objects are written as read, +/// not as if the new drawing's 2018 were their form. +#[test] +fn render_settings_without_a_declared_version_are_written_as_read() { + let kind = "MENTALRAYRENDERSETTINGS"; + let text = dxf("AC1032", kind, 1).replace("9\n$ACADVER\n1\nAC1032\n", ""); + assert!(!text.contains("$ACADVER")); + let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + assert_eq!(d.foreign.acadver, None); + assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1)); + assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(1)); +} + +/// Through the DWG bridge (an R2000 DXF for a 2018 DWG) and back, the class version is what the +/// 2018 file had: before, it came back one higher each time, and BricsCAD refused the DWG. +#[test] +fn render_settings_class_version_survives_the_dwg_bridge() { + let kind = "MENTALRAYRENDERSETTINGS"; + let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap(); + let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(class_version(&written(&back, Version::R2018), kind), Some(2), "{}", written(&back, Version::R2018)); + let dwg = cadcraft_io::write(&back, "x.dwg").unwrap(); + let again = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(class_version(&written(&again, Version::R2018), kind), Some(2)); +} + +/// The conversion mirrors how acadrust stores the value, so it is checked against acadrust itself: +/// acadrust reads the fixture and writes it in each version, and CADCraft, reading any of those +/// files and saving it in any version, stores what acadrust stores for that version. If acadrust +/// changes the encoding, this fails before the DWG bridge drifts. +#[test] +fn render_settings_class_version_matches_what_acadrust_writes() { + use acadrust::DxfVersion; + let versions = [ + (DxfVersion::AC1015, Version::R2000), + (DxfVersion::AC1024, Version::R2010), + (DxfVersion::AC1027, Version::R2013), + (DxfVersion::AC1032, Version::R2018), + ]; + // As a 2018 file stores them: mental ray one higher than its class version, rapid RT as is. + for (kind, stored) in [("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] { + let source = std::io::Cursor::new(dxf("AC1032", kind, stored).into_bytes()); + let mut doc = acadrust::DxfReader::from_reader(source).unwrap().read().unwrap(); + let by_acadrust: Vec<(Version, String)> = versions + .iter() + .map(|(theirs, ours)| { + doc.version = *theirs; + (*ours, String::from_utf8(acadrust::DxfWriter::new(&doc).write_to_vec().unwrap()).unwrap()) + }) + .collect(); + let forms: Vec> = by_acadrust.iter().map(|(_, text)| class_version(text, kind)).collect(); + let expected = if kind == "RAPIDRTRENDERSETTINGS" { [2, 2, 1, 2] } else { [1, 1, 2, 2] }; + assert_eq!(forms, expected.map(Some), "{kind}: acadrust's own forms for 2000, 2010, 2013, 2018"); + for (read_from, text) in &by_acadrust { + let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + for ((declared, _), form) in by_acadrust.iter().zip(&forms) { + assert_eq!(class_version(&written(&d, *declared), kind), *form, "{kind}: read from {read_from:?}, saved as {declared:?}"); + } + } + } +} From b6f17bd9be414029ef0b89041b32a0e57f0452df Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:51:32 +0100 Subject: [PATCH 526/900] REVCLOUD: test that Reverse direction Yes reverses the arcs (#1714) --- crates/engine/src/cmd/draw2/tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/src/cmd/draw2/tests.rs b/crates/engine/src/cmd/draw2/tests.rs index 674dbaefe..be89c5657 100644 --- a/crates/engine/src/cmd/draw2/tests.rs +++ b/crates/engine/src/cmd/draw2/tests.rs @@ -772,6 +772,14 @@ fn revcloud_arc_length_asks_max_and_object_asks_reverse() { assert!(s.running.is_some() && s.prompt_text().contains("Reverse direction"), "{}", s.prompt_text()); s.cmdline("n").unwrap(); assert!(s.running.is_none()); + // Yes reverses the arcs (negative bulges). + s.execute("rectang", &json!({"p1": [30, 30], "p2": [32, 32]})).unwrap(); + s.cmdline("revcloud o 30,31 y").unwrap(); + assert!(s.running.is_none()); + match last(&s) { + EntityKind::LwPolyline(p) => assert!(p.vertices.iter().all(|v| v.bulge < 0.0)), + k => panic!("{k:?}"), + } } // ---------------- BREAKLINE ---------------- 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 527/900] 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 e928316c4d38422e614fe19f995df426da1510f4 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:55:57 +0100 Subject: [PATCH 528/900] docs: leave file-format-parity.md to the maintainers (AGENTS.md); the rows are named in the PR description --- docs/file-format-parity.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c12279a8d..8085f422c 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; a LWPOLYLINE in a tilted plane is read as seen from above (arcs flattened, #1886) | round-trip tests | +| 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); 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,11 +81,11 @@ 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), its pattern and gradient turned with it; a pattern keeps the line spacing and dashes of its plane | | +| 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) | | -| 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) | +| VIEWPORT | yes | yes; frozen-layer lists kept (#150), also as standard group 341 layer handles that other programs read; view twist (51) | 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 | the picture is loaded from its file and drawn (#1756); brightness and contrast are kept but not applied (FF10) | | WIPEOUT | yes | yes (#147, fixes #79) | Implicit or explicit closure in memory; explicit closing point on save. Same logical grips and edit results before/after DXF/DWG round trips (#2256). | | MLINE (+ MLINESTYLE), HELIX, TOLERANCE | yes (#510, #420) | yes | | @@ -93,7 +93,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | 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); a proxy entity's class number (group 91) is renumbered to its class's place in the written CLASSES (#1812); **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) with each tile's view twist (51), named views, UCSs | UCS elevation lost | | 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; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | @@ -140,7 +140,6 @@ 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-30 | minor | Raster images: the picture is loaded from its file when a drawing opens and drawn on screen and in PNG output (#1756, viewport part; based on #1029) | | 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. | @@ -152,6 +151,7 @@ our output in AutoCAD black-box. | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | | 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-11-03 | minor | View twist (group 51) read and written for each tiled viewport (VPORT) and each layout viewport (VIEWPORT); named views' twist (VIEW group 50) now applied on Restore; a twisted view's centre (VIEWPORT and VPORT group 12, VIEW group 10) is read and written in display coordinates, turned by the twist | | 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) | 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 529/900] 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 530/900] 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 531/900] 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 532/900] 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 533/900] 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 534/900] 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 535/900] 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 536/900] 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 537/900] 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 538/900] 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 539/900] 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 540/900] 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 541/900] 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 542/900] 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 543/900] 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 544/900] 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 545/900] 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 0bd4d54f4ad3c31fa7bd5dcd4eae9f9efdb9e030 Mon Sep 17 00:00:00 2001 From: okereke-dev <293682657+okereke-dev@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:02:24 -0500 Subject: [PATCH 546/900] HATCHGENERATEBOUNDARY: Generate Boundary in the right-click menu of a hatch (#2801) A closed polyline around every boundary loop (outer and islands) of the selected hatches, which stay as they are: an associative hatch keeps its own boundary objects and is not linked to the new polylines. Runs at once on a pickfirst selection, otherwise asks for objects; one undo step. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/hatch.rs | 5 + crates/engine/src/cmd/hatch/edit.rs | 36 ++++- .../tests/it/hatch_generate_boundary.rs | 124 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/context_menu.rs | 6 +- crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/zh.tsv | 1 + 7 files changed, 170 insertions(+), 4 deletions(-) create mode 100644 crates/engine/tests/it/hatch_generate_boundary.rs diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index a362a3502..2402823a6 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -1,4 +1,5 @@ //! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects. +//! HATCHGENERATEBOUNDARY: polylines around existing hatches. mod patfile; pub use patfile::{PatternChoice, pattern_choices}; @@ -10,6 +11,7 @@ use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon}; use serde_json::{Value, json}; use super::helpers::lwpoly; +use super::machines::SelectRun; use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_param, str_param, targets}; use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step}; @@ -29,6 +31,9 @@ pub fn specs() -> Vec { CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))), CommandSpec::new("region", "Region", run_region).menu(&["Draw", "Region"]).alias(&["reg"]).params("{handles?}"), CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))), + CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary) + .params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles") + .interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))), CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick) .params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing") .enabled(has_doc) diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index c0f5c7440..49ddaf3b2 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -20,15 +20,49 @@ const MAX_EDITED: usize = 10_000; const MAX_LOOPS: usize = 2000; fn hatches(s: &Session, p: &Value) -> Result> { + hatches_for(s, p, "hatchedit") +} + +/// The hatches among the targets of command `cmd` (an error names `cmd` when there are none). +fn hatches_for(s: &Session, p: &Value, cmd: &str) -> Result> { let hs = targets(s, p)?; let d = s.doc()?; let out: Vec = hs.into_iter().filter(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(_)))).take(MAX_EDITED).collect(); if out.is_empty() { - return Err(bad("hatchedit", "select one or more hatches")); + return Err(bad(cmd, "select one or more hatches")); } Ok(out) } +/// Most polylines one HATCHGENERATEBOUNDARY call creates. +const MAX_GENERATED: usize = 10_000; + +/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of +/// the selected hatches. The hatches are not changed: an associative hatch stays linked to its +/// own boundary objects and is not linked to the new polylines. +pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result { + let hs = hatches_for(s, p, "hatchgenerateboundary")?; + let mut loops = Vec::new(); + { + let d = s.doc()?; + for h in &hs { + if let Some(EntityKind::Hatch(x)) = d.entity(*h).map(|e| &e.kind) { + loops.extend(x.loops.iter().map(|l| l.vertices.clone())); + } + } + } + // Refused before anything is added, so a refused call leaves no partial result behind. + if loops.len() > MAX_GENERATED { + return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches"))); + } + let mut created = Vec::new(); + for vs in loops { + created.push(s.add_entity(lwpoly(vs, true))?.hex()); + } + let n = created.len(); + Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") })) +} + fn outline(l: &HatchLoop) -> Vec { Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3) } diff --git a/crates/engine/tests/it/hatch_generate_boundary.rs b/crates/engine/tests/it/hatch_generate_boundary.rs new file mode 100644 index 000000000..030f35031 --- /dev/null +++ b/crates/engine/tests/it/hatch_generate_boundary.rs @@ -0,0 +1,124 @@ +//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are. + +use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn hatch(s: &Session, h: &str) -> Hatch { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::Hatch(x) => x.clone(), + k => panic!("not a hatch: {k:?}"), + } +} + +fn poly(s: &Session, h: &str) -> LwPolyline { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::LwPolyline(p) => p.clone(), + k => panic!("not a polyline: {k:?}"), + } +} + +fn handle(v: &Value) -> String { + v["handle"].as_str().unwrap().to_string() +} + +fn handles(v: &Value) -> Vec { + v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect() +} + +fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String { + handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap()) +} + +fn count(s: &Session) -> usize { + s.doc().unwrap().model.iter().count() +} + +#[test] +fn generates_a_closed_polyline_around_a_hatch_without_its_outline() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap()); + s.execute("erase", &json!({ "handles": [r] })).unwrap(); + let before = hatch(&s, &h); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap(); + let new = handles(&v); + assert_eq!(new.len(), 1); + let p = poly(&s, &new[0]); + assert!(p.closed); + assert_eq!(p.vertices, before.loops[0].vertices); + assert_eq!(hatch(&s, &h), before, "the hatch is not changed"); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(count(&s), 1, "one undo step removes what was generated"); +} + +#[test] +fn islands_get_their_own_polylines() { + let mut s = Session::new(); + rect(&mut s, [0.0, 0.0], [20.0, 20.0]); + rect(&mut s, [5.0, 5.0], [10.0, 10.0]); + let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap()); + assert_eq!(hatch(&s, &h).loops.len(), 2); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap(); + assert_eq!(handles(&v).len(), 2); +} + +#[test] +fn every_selected_hatch_gets_its_boundary() { + let mut s = Session::new(); + let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]); + let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap()); + let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap()); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap(); + assert_eq!(handles(&v).len(), 2); +} + +#[test] +fn an_associative_hatch_stays_linked_to_its_own_boundary() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap()); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap(); + let p = handles(&v)[0].clone(); + // Moving the generated polyline leaves the hatch where it is. + s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap(); + assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0); + // Moving the original rectangle still moves the hatch. + s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap(); + assert!(hatch(&s, &h).associative); + assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0); +} + +#[test] +fn needs_a_hatch() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err()); + assert_eq!(count(&s), 1, "nothing is added"); +} + +#[test] +fn runs_at_once_on_selected_hatches() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap()); + s.set_selection(vec![Handle::parse_hex(&h).unwrap()]); + s.start("hatchgenerateboundary").unwrap(); + assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt"); + assert_eq!(count(&s), 3); +} + +#[test] +fn asks_for_hatches_without_a_selection() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap()); + s.set_selection(Vec::new()); + s.start("hatchgenerateboundary").unwrap(); + assert!(s.current_prompt().is_some()); + s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.current_prompt().is_none()); + assert_eq!(count(&s), 3); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3a1537bee..694633f92 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -58,6 +58,7 @@ mod group_selection; mod groups; mod hatch_assoc; mod hatch_dialog_helpers; +mod hatch_generate_boundary; mod hatch_numeric_validation; mod hatch_options; mod helix; diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbaf48df3..e93f91494 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -122,8 +122,8 @@ pub fn entries(app: &CadApp) -> Vec> { } /// The edit commands of the selected objects' type (when they are all of one type), with their -/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit, -/// Polyline Edit, Spline Edit… +/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit +/// and Generate Boundary for hatches, Polyline Edit, Spline Edit… fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { let Ok(d) = app.session.doc() else { return Vec::new() }; let sel = app.session.selection(); @@ -142,7 +142,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { } v } - EntityKind::Hatch(_) => vec![("hatchedit", None)], + EntityKind::Hatch(_) => vec![("hatchedit", None), ("hatchgenerateboundary", None)], EntityKind::LwPolyline(_) | EntityKind::Polyline3d(_) => vec![("pedit", Some("Polyline Edit"))], EntityKind::Spline(_) => vec![("splinedit", Some("Spline Edit"))], EntityKind::Dimension(_) => vec![("dimtedit", None)], diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0e6471ee..b2d44f309 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -372,6 +372,7 @@ From Desde From Template... Desde plantilla... General General + Generate Boundary Generar contorno Geometric Center Centro geométrico Geometric Constraint Restricción geométrica Geometric Constraints Restricciones geométricas diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index a07b4f027..ed4b9c6b4 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -294,6 +294,7 @@ Freeze/Thaw in the current viewport 在当前视口中冻结/解冻 From 自 General 常规 + Generate Boundary 生成边界 Geometric Center 几何中心 Geometric Constraint 几何约束 Geometric Constraints 几何约束 From 1947e4e09e9b326a16faf9bb13b29eb0690e97d2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 19:13:39 -0700 Subject: [PATCH 547/900] 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 548/900] 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 f7c4c148a3a9287761ed59aa6b93bfb823d66062 Mon Sep 17 00:00:00 2001 From: okereke-dev <293682657+okereke-dev@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:25:18 -0500 Subject: [PATCH 549/900] HATCHGENERATEBOUNDARY: keep the hatch elevation, refuse other spaces and over-limit calls (CodeRabbit on #2804) Each polyline takes its hatch's elevation; a hatch outside the current space is refused with a clear message; every selected hatch counts toward the 10,000-polyline limit, refused before anything is added. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/hatch/edit.rs | 43 +++++++++------- .../tests/it/hatch_generate_boundary.rs | 49 +++++++++++++++++++ 2 files changed, 75 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index 49ddaf3b2..00725df0c 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -20,16 +20,11 @@ const MAX_EDITED: usize = 10_000; const MAX_LOOPS: usize = 2000; fn hatches(s: &Session, p: &Value) -> Result> { - hatches_for(s, p, "hatchedit") -} - -/// The hatches among the targets of command `cmd` (an error names `cmd` when there are none). -fn hatches_for(s: &Session, p: &Value, cmd: &str) -> Result> { let hs = targets(s, p)?; let d = s.doc()?; let out: Vec = hs.into_iter().filter(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(_)))).take(MAX_EDITED).collect(); if out.is_empty() { - return Err(bad(cmd, "select one or more hatches")); + return Err(bad("hatchedit", "select one or more hatches")); } Ok(out) } @@ -38,26 +33,40 @@ fn hatches_for(s: &Session, p: &Value, cmd: &str) -> Result> { const MAX_GENERATED: usize = 10_000; /// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of -/// the selected hatches. The hatches are not changed: an associative hatch stays linked to its -/// own boundary objects and is not linked to the new polylines. +/// the selected hatches, at each hatch's elevation. The hatches are not changed: an associative +/// hatch stays linked to its own boundary objects and is not linked to the new polylines. pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result { - let hs = hatches_for(s, p, "hatchgenerateboundary")?; + let selected = targets(s, p)?; + // The polylines go to the current space, so every hatch must be there too. + let space = s.space(); let mut loops = Vec::new(); + let mut found = false; { let d = s.doc()?; - for h in &hs { - if let Some(EntityKind::Hatch(x)) = d.entity(*h).map(|e| &e.kind) { - loops.extend(x.loops.iter().map(|l| l.vertices.clone())); + for h in selected { + let Some(EntityKind::Hatch(x)) = d.entity(h).map(|e| &e.kind) else { continue }; + found = true; + if d.space_of(h).as_ref() != Some(&space) { + return Err(bad("hatchgenerateboundary", format!("hatch {} is not in the current space; switch to its layout first", h.hex()))); } + // Every selected hatch counts: none is left out of a call that succeeds. + if loops.len() + x.loops.len() > MAX_GENERATED { + return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches"))); + } + loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), x.elevation))); } } - // Refused before anything is added, so a refused call leaves no partial result behind. - if loops.len() > MAX_GENERATED { - return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches"))); + if !found { + return Err(bad("hatchgenerateboundary", "select one or more hatches")); } + // Everything is checked before anything is added, so a refused call leaves nothing behind. let mut created = Vec::new(); - for vs in loops { - created.push(s.add_entity(lwpoly(vs, true))?.hex()); + for (vs, elevation) in loops { + let mut kind = lwpoly(vs, true); + if let EntityKind::LwPolyline(pl) = &mut kind { + pl.elevation = elevation; + } + created.push(s.add_entity(kind)?.hex()); } let n = created.len(); Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") })) diff --git a/crates/engine/tests/it/hatch_generate_boundary.rs b/crates/engine/tests/it/hatch_generate_boundary.rs index 030f35031..07d1d5443 100644 --- a/crates/engine/tests/it/hatch_generate_boundary.rs +++ b/crates/engine/tests/it/hatch_generate_boundary.rs @@ -90,6 +90,55 @@ fn an_associative_hatch_stays_linked_to_its_own_boundary() { assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0); } +#[test] +fn boundaries_keep_the_hatch_elevation() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap()); + s.doc_mut() + .unwrap() + .modify_entity(Handle::parse_hex(&h).unwrap(), |e| { + if let EntityKind::Hatch(x) = &mut e.kind { + x.elevation = 300.0; + } + }) + .unwrap(); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap(); + assert_eq!(poly(&s, &handles(&v)[0]).elevation, 300.0); +} + +#[test] +fn refuses_a_hatch_in_another_space_and_adds_nothing() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap()); + s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap(); + let before = s.doc().unwrap().entity_count(); + let e = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap_err(); + assert!(e.to_string().contains("not in the current space"), "{e}"); + assert_eq!(s.doc().unwrap().entity_count(), before); +} + +#[test] +fn refuses_more_boundaries_than_the_limit_and_adds_nothing() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap()); + // One hatch with more loops than one call may turn into polylines. + s.doc_mut() + .unwrap() + .modify_entity(Handle::parse_hex(&h).unwrap(), |e| { + if let EntityKind::Hatch(x) = &mut e.kind { + let l = x.loops[0].clone(); + x.loops = vec![l; 10_001]; + } + }) + .unwrap(); + let before = count(&s); + assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).is_err()); + assert_eq!(count(&s), before); +} + #[test] fn needs_a_hatch() { let mut s = Session::new(); From 5b2c7bb0fbd48c632480f885a39b840ce5cf5d08 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 4 Nov 2026 19:34:32 -0700 Subject: [PATCH 550/900] 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 6412e9c99a0aea028dd2281fae5d10c05e7cb282 Mon Sep 17 00:00:00 2001 From: okereke-dev <293682657+okereke-dev@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:36:46 -0500 Subject: [PATCH 551/900] HATCHGENERATEBOUNDARY: a hatch named twice gets one boundary (CodeRabbit on #2804) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/hatch/edit.rs | 5 +++++ crates/engine/tests/it/hatch_generate_boundary.rs | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index 00725df0c..884ce9fbb 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -41,10 +41,15 @@ pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result Date: Wed, 4 Nov 2026 21:53:26 -0500 Subject: [PATCH 552/900] HATCHGENERATEBOUNDARY: compare the loop count with the room left, so it can't overflow (CodeRabbit on #2804) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/hatch/edit.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index 884ce9fbb..854c80513 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -54,8 +54,9 @@ pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result MAX_GENERATED { + // Every selected hatch counts: none is left out of a call that succeeds. Compared + // against the room left, so a hostile loop count can't overflow the sum. + if x.loops.len() > MAX_GENERATED.saturating_sub(loops.len()) { return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches"))); } loops.extend(x.loops.iter().map(|l| (l.vertices.clone(), x.elevation))); From c397ab1e9e1f212887ae243084794c59cf78971e Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 13:55:27 +1100 Subject: [PATCH 553/900] 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 554/900] 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 555/900] 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 556/900] 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 557/900] 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 558/900] 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 559/900] 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 560/900] 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 561/900] 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 562/900] 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 563/900] 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 564/900] 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 565/900] 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 => ("`