From 7003c5b9309f5e92c2f5b5fcb2e8b34be2840e22 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Tue, 13 Oct 2026 10:50:32 -0600 Subject: [PATCH 001/185] 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/185] 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/185] 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/185] 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/185] 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/185] 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/185] 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/185] 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 1d29b626e66cc1a06999ba36dfb40e441929b3f6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 14 Oct 2026 23:49:44 +0200 Subject: [PATCH 009/185] 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 6c72999361ac1b3cdf2c592f1f244243beeb2dea Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 02:23:44 +0400 Subject: [PATCH 010/185] i18n: add Georgian (ka) interface language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a Georgian catalog (ka.tsv, 1,383 rows): the union of the existing catalogs, four menu headings (ზომების დატანა for the Dimension menu, ზომა for the object) and single-form counts, since a Georgian noun stays singular after a numeral. No marked UI literal falls back to English. Prompts read "მიუთითეთ …" for Specify and "შეიყვანეთ …" for Enter; clickable keywords keep the spelling the engine accepts. No Mtavruli. Register the language (Preference::Georgian, `ka`, ქართული) and add locale, preference, count, menu-heading, live-switch, dialog and no-Mtavruli tests. Docs, README and ATTRIBUTION list it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- ATTRIBUTION.md | 1 + README.md | 2 +- ROADMAP.md | 1 + crates/ui-egui/src/i18n/ka.tsv | 1399 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/mod.rs | 23 +- crates/ui-egui/src/i18n/tests.rs | 111 ++- crates/ui-egui/src/options/mod.rs | 2 +- docs/localization-parity.md | 4 +- docs/localization.md | 20 +- 9 files changed, 1554 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/i18n/ka.tsv diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 264c7430f..3779b71bc 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -71,3 +71,4 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker | | `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending | +| `crates/ui-egui/src/i18n/ka.tsv` | @devius with Claude (AI-assisted) | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; no font assets added (the Georgian face comes from craft-fonts) | diff --git a/README.md b/README.md index 655b944f5..c762a223e 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ numbers): | Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF | | Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit | | Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror | -| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar) and Turkish (Türkçe), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | +| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | | Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) | ## Quick start diff --git a/ROADMAP.md b/ROADMAP.md index d54f3bf8b..93b3a701e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,6 +95,7 @@ Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity. | Indonesian | none | 0% | | Japanese | none | 0% | | Greek | complete current catalog | 1,330 current source keys; independent proofreading pending | +| Georgian | complete current catalog | 1,383 rows; native proofreading pending | | German | partial | ≈ 100% of the catalog (989 rows) | | Korean | none | 0% | | Vietnamese | none | 0% | diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv new file mode 100644 index 000000000..25512c91f --- /dev/null +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -0,0 +1,1399 @@ +# CADCraft Georgian (ქართული) interface catalog — original translations by the CADCraft contributors. +# License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE). +# Written from CADCraft's English strings; no proprietary translations were copied. +# Clean room: every entry is written from the plain meaning of the English label in ordinary +# Georgian computing and technical-drawing (ხაზვა) vocabulary (შრე, ზომა, დაშტრიხვა, მომრგვალება, +# ფასკა, წანაცვლება, მოკვეთა, ობიექტზე მიბმა, ხედვის არე, განლაგება). No other product's Georgian +# interface, string table or terminology database was consulted, and no other catalog is used as a source. +# UTF-8: contextEnglish sourceGeorgian translation. +# Empty context = ordinary label; @plural = one form with {n} (a Georgian noun stays singular after +# a numeral: "5 კომიტი"); menu = a menu heading where it differs from the label. +# Commands are verbal nouns (შენახვა, შემობრუნება); prompts read "მიუთითეთ …" for Specify, +# "შეიყვანეთ …" for Enter and "მონიშნეთ …" for Select. Georgian has no letter case: nothing is +# capitalised and Mtavruli is never used. +# Keep command IDs, keywords (Top, Zero, Bottom, _tan to, nX/nXP, Multiple, PICKADD, QPMODE), +# technology/product names and user data unchanged. + + Apply გამოყენება + Attach DWG... DWG-ის მიმაგრება... + Bind ჩაშენება + Detach მოხსნა + Loaded ჩატვირთულია + Make it a block of this drawing, keeping its layer names ამ ნახაზის ბლოკად ქცევა, შრეების სახელების შენარჩუნებით + Make it a block of this drawing; its layers become NAME$0$LAYER ამ ნახაზის ბლოკად ქცევა; შრეების სახელები გახდება NAME$0$LAYER + No external references are attached. გარე მიმართვები მიმაგრებული არ არის. + Not Found ვერ მოიძებნა + Not loaded არ არის ჩატვირთული + Open გახსნა + Overlay ზედდება + Reference Manager მიმართვების მენეჯერი + Reference Name მიმართვის სახელი + References: {n} მიმართვა: {n} + Reload ხელახლა ჩატვირთვა + Reload All ყველას ხელახლა ჩატვირთვა + Saved Path შენახული გზა + Unload განტვირთვა + Unloaded განტვირთულია + Unreferenced მიმართვის გარეშე + Unresolved დაუდგენელი + Cancel გაუქმება + OK OK + or [ ან [ + % of all commits ყველა კომიტის % + * Wildcard Match * შაბლონით დამთხვევა + *VARIES* *სხვადასხვა* + + | Top | 2D Wireframe + | ზედა | 2D კარკასი + +Bin +Bin + +LOC +LOC + 1 Viewport 1 ხედვის არე + 2 Points 2 წერტილი + 2 Viewports 2 ხედვის არე + 2D Solid 2D შევსებული არე + 3 Points 3 წერტილი + 3 Viewports 3 ხედვის არე + 3D Face 3D წახნაგი + 3D Operations 3D ოპერაციები + 3D Polyline 3D ტეხილი + 4 Viewports 4 ხედვის არე + < Less than < ნაკლებია + <> Not Equal <> არ უდრის + = Equals = უდრის + > Greater than > მეტია + A variable name starts with a letter and has only letters, digits and _ ცვლადის სახელი ასოთი იწყება და მხოლოდ ასოებს, ციფრებსა და _-ს შეიცავს + About პროგრამის შესახებ + About CADCraft CADCraft-ის შესახებ + Absolute აბსოლუტური + Add Leader მიმთითებლის დამატება + Additional angles დამატებითი კუთხეები + Align სწორება + Align Text ტექსტის სწორება + Aligned გასწორებული + All ყველა + All Annotation Objects ყველა ანოტაციური ობიექტი + All Used Layers ყველა გამოყენებული შრე + All files ყველა ფაილი + Angle კუთხე + Angular კუთხური + Annotation Visibility ანოტაციის ხილვადობა + Annotation scale ანოტაციის მასშტაბი + Apparent Intersection ხილული გადაკვეთა + Append to current selection set მიმდინარე მონიშნულზე დამატება + Apply to: გამოყენება: + Apply true color ნამდვილი ფერის გამოყენება + Arc რკალი + Arc Length რკალის სიგრძე + Area ფართობი + Arrange Panel პანელის დალაგება + Array მასივი + Attach მიმაგრება + Attribute ატრიბუტი + Attribute Definition ატრიბუტის განსაზღვრა + Attribute Display ატრიბუტების ჩვენება + Audit აუდიტი + Auto (system language) ავტომატური (სისტემის ენა) + Auto Constrain ავტომატური შეზღუდვა + AutoConstrain ავტოშეზღუდვა + Axis, End ღერძი, ბოლო + Base საბაზო წერტილი + Baseline საბაზისო ხაზი + Batch Publish პაკეტური გამოქვეყნება + Binary assets added დამატებული ბინარული ფაილები + Binary assets removed წაშლილი ბინარული ფაილები + Bind... ჩაშენება... + Blend გადასვლა + Block ბლოკი + Block Attribute Manager... ბლოკის ატრიბუტების მენეჯერი... + Block Editor ბლოკის რედაქტორი + Block Reference ბლოკის ჩასმა + Block... ბლოკი... + Blocks ბლოკები + Blue ლურჯი + Bold მუქი + Boolean ლოგიკური + Boundary საზღვარი + Boundary... საზღვარი... + Box პარალელეპიპედი + Break გაწყვეტა + Break At Point წერტილში გაწყვეტა + Break-line Symbol წყვეტის ხაზის სიმბოლო + Bring Above Objects ობიექტებზე ზემოთ გადატანა + Bring Annotations to Front ანოტაციების წინა პლანზე გადმოტანა + Bring to Front წინა პლანზე გადმოტანა + Bulleted list ბურთულებიანი სია + ByBlock ბლოკის მიხედვით + ByColor ფერის მიხედვით + ByLayer შრის მიხედვით + CADCraft Help CADCraft-ის დახმარება + Cancel გაუქმება + Cartesian (x, y) დეკარტული (x, y) + Center ცენტრი + Center Line ღერძული ხაზი + Center Mark ცენტრის ნიშანი + Center X ცენტრი X + Center Y ცენტრი Y + Center Z ცენტრი Z + Center, Diameter ცენტრი, დიამეტრი + Center, Radius ცენტრი, რადიუსი + Center, Start, Angle ცენტრი, დასაწყისი, კუთხე + Center, Start, End ცენტრი, დასაწყისი, ბოლო + Center, Start, Length ცენტრი, დასაწყისი, სიგრძე + Chamfer ფასკა + Change Space სივრცის შეცვლა + Change to Current Layer მიმდინარე შრეზე გადატანა + Changed: {n} შეცვლილი: {n} + Circle წრე + Circumference წრეწირის სიგრძე + Clear History ისტორიის გასუფთავება + Clear გასუფთავება + Clip მოჭრა + Clip Viewport ხედვის არის მოჭრა + Clipboard გაცვლის ბუფერი + Close დახურვა + Close All ყველას დახურვა + Close All Other Drawings ყველა სხვა ნახაზის დახურვა + Closed შეკრული + Close Comparison შედარების დახურვა + Coincident დამთხვევა + Collapse Palettes პალიტრების ჩაკეცვა + Collapse Tool Sets ხელსაწყოთა ნაკრებების ჩაკეცვა + Collinear კოლინეარობა + Color ფერი + Color 8 ფერი 8 + Color 9 ფერი 9 + Color Index ფერის ინდექსი + Color... ფერი... + Command Aliases ბრძანებების ფსევდონიმები + Command History ბრძანებების ისტორია + Clear Command History ბრძანებების ისტორიის გასუფთავება + Command Line ბრძანების სტრიქონი + Command Line History Lines ბრძანების სტრიქონის ისტორიის სტრიქონები + Command Reference ბრძანებების ცნობარი + Commits კომიტები + Company კომპანია + Compare Drawings... ნახაზების შედარება... + Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust. კომპიუტერული დაპროექტება და ხაზვა: ღია კოდის CAD აპლიკაცია, შექმნილი „სუფთა ოთახის“ მეთოდით და დაწერილი სუფთა Rust-ზე. + Concentric კონცენტრულობა + Cone კონუსი + Constraint Bars შეზღუდვების ზოლები + Constraint Settings შეზღუდვების პარამეტრები + Construction Line დამხმარე ხაზი + Contents შიგთავსი + Continue გაგრძელება + Contributors მონაწილეები + Control Vertices მართვის წვეროები + Convert გარდაქმნა + Convert Text to Mtext ტექსტის Mtext-ად გარდაქმნა + Copy კოპირება + Copy Full File Path ფაილის სრული გზის კოპირება + Copy History ისტორიის კოპირება + Copy Layout განლაგების კოპირება + Copy Nested Objects ჩადგმული ობიექტების კოპირება + Copy Selection მონიშნულის კოპირება + Copy with Base Point კოპირება საბაზო წერტილით + Count დათვლა + Count List დათვლის სია + Count Table დათვლის ცხრილი + Create Block ბლოკის შექმნა + Creates a user parameter ქმნის მომხმარებლის პარამეტრს + Ctrl+Enter to finish დასასრულებლად: Ctrl+Enter + Current layer მიმდინარე შრე + Current selection მიმდინარე მონიშნული + Current: {color} მიმდინარე: {color} + Cut ამოჭრა + Cyan ცისფერი + Cylinder ცილინდრი + DWG DWG + DWG Reference... DWG მიმართვა... + DXF DXF + Dark ბნელი + Data Extraction... მონაცემების ამოღება... + Default ნაგულისხმევი + Data Link... მონაცემთა კავშირი... + Default Save Format შენახვის ნაგულისხმევი ფორმატი + Default Save Version შენახვის ნაგულისხმევი ვერსია + Define Attributes ატრიბუტების განსაზღვრა + Define Attributes... ატრიბუტების განსაზღვრა... + Defined width განსაზღვრული სიგანე + Degree გრადუსი + Degrees of Freedom თავისუფლების ხარისხები + Degrees of freedom: {n} თავისუფლების ხარისხი: {n} + Delete წაშლა + Delete Column სვეტის წაშლა + Delete Constraints შეზღუდვების წაშლა + Delete Dimension Style ზომის სტილის წაშლა + Delete Duplicate Objects დუბლიკატი ობიექტების წაშლა + Delete Layer შრის წაშლა + Delete Layer State შრეების მდგომარეობის წაშლა + Delete Layout განლაგების წაშლა + Delete Row სტრიქონის წაშლა + Delete Text Style ტექსტის სტილის წაშლა + Delta X დელტა X + Delta Y დელტა Y + Description აღწერა + Deselect All ყველა მონიშვნის მოხსნა + Diameter დიამეტრი + Dim style ზომის სტილი + Dimension Break ზომის გაწყვეტა + Dimension Edit ზომის რედაქტირება + Dimension ზომა + Dimension Objects Only მხოლოდ ზომის ობიექტები + Dimension Space ზომების დაშორება + Dimension Style Override ზომის სტილის გადაფარვა + Dimension Style... ზომის სტილი... + Dimension Text Edit ზომის ტექსტის რედაქტირება + Dimension style ზომის სტილი + Dimensional Constraint ზომითი შეზღუდვა + Dimensional Constraint Parameters ზომითი შეზღუდვის პარამეტრები + Dimensional Constraints ზომითი შეზღუდვები + Disassociate Dimensions ზომების ასოციაციის მოხსნა + Display name საჩვენებელი სახელი + Distance მანძილი + Divide დაყოფა + Do not plot (click: plot) არ იბეჭდება (დაწკაპეთ: ბეჭდვა) + Donut რგოლი + Double-click to edit the description ორჯერ დაწკაპეთ აღწერის რედაქტირებისთვის + Down ქვემოთ + Drafting ხაზვა + Drafting Settings ხაზვის პარამეტრები + Drafting Settings... ხაზვის პარამეტრები... + Draw ხაზვა + Draw Order ხაზვის რიგი + Drawing (DWG) ნახაზი (DWG) + Drawing (DXF) ნახაზი (DXF) + Drawing Limits ნახაზის ზღვრები + Drawing Template (DWT) ნახაზის შაბლონი (DWT) + Drawing Utilities ნახაზის უტილიტები + Drawings (DWG, DXF) ნახაზები (DWG, DXF) + SVG drawings (SVG, SVGZ) SVG ნახაზები (SVG, SVGZ) + Dynamic დინამიკური + Dynamic Dimensions დინამიკური ზომები + Dynamic Input დინამიკური შეყვანა + Dynamic Input (F12) დინამიკური შეყვანა (F12) + E ა + Edit რედაქტირება + Edit Attributes... ატრიბუტების რედაქტირება... + Edit Text... ტექსტის რედაქტირება... + Edit Table Cell ცხრილის უჯრის რედაქტირება + Elevation ნიშნული + Ellipse ელიფსი + Elliptical Arc ელიფსური რკალი + Enable Dynamic Input (F12) დინამიკური შეყვანის ჩართვა (F12) + End Object Isolation ობიექტების იზოლირების დასრულება + End Width ბოლო სიგანე + End X ბოლო X + End Y ბოლო Y + End angle ბოლო კუთხე + Endpoint ბოლო წერტილი + Enter შეყვანა + Enter Top, Zero or Bottom. შეიყვანეთ Top, Zero ან Bottom. + Enter a fit data option შეიყვანეთ მისადაგების მონაცემების ვარიანტი + Enter a pattern name შეიყვანეთ ნიმუშის სახელი + Enter a vertex editing option შეიყვანეთ წვეროს რედაქტირების ვარიანტი + Enter an option შეიყვანეთ ვარიანტი + Enter angle of xline შეიყვანეთ დამხმარე ხაზის კუთხე + Enter angle of xline (0) or შეიყვანეთ დამხმარე ხაზის კუთხე (0) ან + Enter area of rectangle in current units შეიყვანეთ მართკუთხედის ფართობი მიმდინარე ერთეულებში + Enter attribute prompt შეიყვანეთ ატრიბუტის მოთხოვნა + Enter attribute tag name შეიყვანეთ ატრიბუტის ტეგის სახელი + Enter attribute value შეიყვანეთ ატრიბუტის მნიშვნელობა + Enter block name შეიყვანეთ ბლოკის სახელი + Enter constraint type შეიყვანეთ შეზღუდვის ტიპი + Enter continuity შეიყვანეთ უწყვეტობის ტიპი + Enter default attribute value შეიყვანეთ ატრიბუტის ნაგულისხმევი მნიშვნელობა + Enter degree of spline შეიყვანეთ სპლაინის ხარისხი + Enter delta angle შეიყვანეთ კუთხის ნამატი + Enter delta length or შეიყვანეთ სიგრძის ნამატი ან + Enter dimension text შეიყვანეთ ზომის ტექსტი + Enter dimension text (<> = measurement) შეიყვანეთ ზომის ტექსტი (<> = გაზომილი მნიშვნელობა) + Enter dimension value or [name=expression] შეიყვანეთ ზომის მნიშვნელობა ან [name=expression] + Enter dimension variable name to override შეიყვანეთ გადასაფარავი ზომის ცვლადის სახელი + Enter justification type შეიყვანეთ სწორების ტიპი + Enter leader text შეიყვანეთ მიმთითებლის ტექსტი + Enter mline scale შეიყვანეთ მულტიხაზის მასშტაბი + Enter mode შეიყვანეთ რეჟიმი + Enter name of block to insert შეიყვანეთ ჩასასმელი ბლოკის სახელი + Enter new text შეიყვანეთ ახალი ტექსტი + Enter next point შეიყვანეთ შემდეგი წერტილი + Enter number of columns შეიყვანეთ სვეტების რაოდენობა + Enter number of data rows შეიყვანეთ მონაცემების სტრიქონების რაოდენობა + Enter number of items შეიყვანეთ ელემენტების რაოდენობა + Enter number of items along path შეიყვანეთ ელემენტების რაოდენობა ტრაექტორიის გასწვრივ + Enter number of sides შეიყვანეთ გვერდების რაოდენობა + Enter number of turns შეიყვანეთ ხვიების რაოდენობა + Enter percentage length შეიყვანეთ სიგრძე პროცენტებში + Enter rectangle length შეიყვანეთ მართკუთხედის სიგრძე + Enter rectangle width შეიყვანეთ მართკუთხედის სიგანე + Enter scale factor შეიყვანეთ მასშტაბის კოეფიციენტი + Enter text შეიყვანეთ ტექსტი + Enter text (use \P for new paragraphs) შეიყვანეთ ტექსტი (ახალი აბზაცისთვის გამოიყენეთ \P) + Enter the number of segments შეიყვანეთ სეგმენტების რაოდენობა + Enter twist direction of helix შეიყვანეთ სპირალის დახვევის მიმართულება + Entire drawing მთელი ნახაზი + Equal ტოლობა + Erase წაშლა + Evaluate გამოთვლა + Evaluate LISP LISP-ის გამოთვლა + Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა + Explode დაშლა + Explode Attributes to Text ატრიბუტების ტექსტად დაშლა + Export ექსპორტი + Export Table ცხრილის ექსპორტი + Export to PDF... PDF-ად ექსპორტი... + Express Tools Express Tools + Expression ექსპრესია + Extend გაგრძელება + Extension გაგრძელება + Extents საზღვრები + External Reference გარე მიმართვა + External References გარე მიმართვები + Extrude ამოწევა + File ფაილი + File Tab ფაილის ჩანართი + Fillet მომრგვალება + Filter ფილტრი + Filters ფილტრები + Find and Replace ძებნა და ჩანაცვლება + Find... ძებნა... + First პირველი + First commit პირველი კომიტი + Fit Points მისადაგების წერტილები + Fix ფიქსაცია + Flatten Objects ობიექტების გაბრტყელება + Format ფორმატი + Freehand ხელით ხაზვა + Freeze გაყინვა + Freeze Layer შრის გაყინვა + Freeze in new viewports გაყინვა ახალ ხედვის არეებში + Freeze/Thaw გაყინვა/გალღობა + Freeze/Thaw in all viewports გაყინვა/გალღობა ყველა ხედვის არეში + Freeze/Thaw in the current viewport გაყინვა/გალღობა მიმდინარე ხედვის არეში + From ათვლის წერტილიდან + From Template... შაბლონიდან... + General ზოგადი + Geometric Center გეომეტრიული ცენტრი + Geometric Constraint გეომეტრიული შეზღუდვა + Geometric Constraints გეომეტრიული შეზღუდვები + Geometry გეომეტრია + Get from the Drawing ნახაზიდან აღება + Get Variable ცვლადის მიღება + Get View ხედის მიღება + Global გლობალური + Global width საერთო სიგანე + Grab bag სხვადასხვა + Gradient გრადიენტი + Gradient... გრადიენტი... + Green მწვანე + Grid (F7) ბადე (F7) + Grid Display ბადის ჩვენება + Grid On (F7) ბადის ჩართვა (F7) + Grid snap ბადეზე მიბმა + Grid spacing ბადის ბიჯი + Grip Edit სახელურით რედაქტირება + Grip Mirror სახელურით არეკვლა + Grip Option სახელურის პარამეტრი + Grip Rotate სახელურით შემობრუნება + Grip Scale სახელურით მასშტაბირება + Grip Stretch სახელურით გაწელვა + Group დაჯგუფება + Group Edit ჯგუფის რედაქტირება + Group Options დაჯგუფების პარამეტრები + Group Selection ჯგუფის მონიშვნა + Hatch დაშტრიხვა + Hatch Edit დაშტრიხვის რედაქტირება + Hatch Patterns დაშტრიხვის ნიმუშები + Hatch... დაშტრიხვა... + Height სიმაღლე + Height: {height} სიმაღლე: {height} + Helix სპირალი + Help დახმარება + Hide All ყველას დამალვა + Hide All Constraint Bars შეზღუდვების ყველა ზოლის დამალვა + Hide All Dynamic Dimensions ყველა დინამიკური ზომის დამალვა + Hide Layer List შრეების სიის დამალვა + Hide Objects ობიექტების დამალვა + Hide Palettes პალიტრების დამალვა + History ისტორია + Home საწყისი პოზიცია + Horizontal ჰორიზონტალური + HorizontalDistance ჰორიზონტალური მანძილი + How to apply: გამოყენების წესი: + ID Point წერტილის კოორდინატები + Import იმპორტი + Align Multileaders მულტიმიმთითებლების სწორება + Collect შეგროვება + Collect Multileaders მულტიმიმთითებლების შეგროვება + Edit Multileader მულტიმიმთითებლის რედაქტირება + In გადიდება + In-window Menu Bar მენიუს ზოლი ფანჯარაში + Include in new selection set ახალ მონიშნულ ნაკრებში ჩართვა + Increment angle კუთხის ბიჯი + Index Color ინდექსური ფერი + Index color: {index} ინდექსური ფერი: {index} + Infer Constraints შეზღუდვების ავტომატური დადგენა + Inquiry ინფორმაცია + Insert ჩასმა + Insert Block ბლოკის ჩასმა + Insert Column სვეტის ჩასმა + Insert Row სტრიქონის ჩასმა + Insert tab ტაბულაციის ჩასმა + Insert this block ამ ბლოკის ჩასმა + Insert Table Formula ცხრილში ფორმულის ჩასმა + Insertion ჩასმის წერტილი + Insertion X ჩასმის წერტილი X + Insertion Y ჩასმის წერტილი Y + Insertion Z ჩასმის წერტილი Z + Inspect Constraints შეზღუდვების შემოწმება + Inspect Drawing ნახაზის შემოწმება + Inspection შემოწმება + Interface Language ინტერფეისის ენა + Interface Theme ინტერფეისის თემა + Intersect გადაკვეთა + Intersection გადაკვეთა + Isolate იზოლირება + Isolate Layer შრის იზოლირება + Isolate Objects ობიექტების იზოლირება + Isometric Drafting იზომეტრიული ხაზვა + Jogged გატეხილი + Jogged Linear გატეხილი წრფივი + Join შეერთება + Join the ArtCraft Discord… შემოუერთდით ArtCraft-ის Discord-ს… + Join us on Discord შემოგვიერთდით Discord-ზე + Isometric Plane იზომეტრიული სიბრტყე + Isometric snap იზომეტრიული მიბმა + Language ენა + Last ბოლო + Last commit ბოლო კომიტი + Layer შრე + Layer Delete შრის წაშლა + Layer Match შრის მისადაგება + Layer Merge შრეების შერწყმა + Layer Off შრის გამორთვა + Layer Properties შრის თვისებები + Layer Properties Manager შრის თვისებების მენეჯერი + Layer Properties Manager — current viewport შრის თვისებების მენეჯერი — მიმდინარე ხედვის არე + Layer State შრის მდგომარეობა + Layer States Manager... შრის მდგომარეობების მენეჯერი... + Layer Tools შრის ხელსაწყოები + Layer contains objects (double-click to make current) შრეში ობიექტებია (მიმდინარედ გასახდომად ორჯერ დაწკაპეთ) + Layer is empty (double-click to make current) შრე ცარიელია (მიმდინარედ გასახდომად ორჯერ დაწკაპეთ) + Layers შრეები + Layers Palette შრეების პალიტრა + Hide Palette პალიტრის დამალვა + Layers displayed: {shown} of {total}. Current layer: {layer} ნაჩვენები შრეები: {shown} / {total}. მიმდინარე შრე: {layer} + Layout განლაგება + Layout list განლაგებების სია + Leader მიმთითებელი + Leaders Only მხოლოდ მიმთითებლები + Left მარცხნივ + Length სიგრძე + Length X სიგრძე X + Length Y სიგრძე Y + Lengthen დაგრძელება + Light ღია + Line ხაზი + Line delta სტრიქონების სხვაობა + Linear წრფივი + Lines +/− სტრიქონები +/− + Lines added დამატებული სტრიქონები + Lines deleted წაშლილი სტრიქონები + Lines of Command History ბრძანებების ისტორიის სტრიქონები + Linetype ხაზის ტიპი + Linetype Scale ხაზის ტიპის მასშტაბი + Linetype scale ხაზის ტიპის მასშტაბი + Ltscale ხაზის ტიპის მასშტაბი + Linetype... ხაზის ტიპი... + Lineweight ხაზის სისქე + Lineweight... ხაზის სისქე... + List სია + List Blocks ბლოკების სია + List Dimension Styles ზომის სტილების სია + List Groups ჯგუფების სია + List Layer States შრის მდგომარეობების სია + List Layouts განლაგებების სია + List System Variables სისტემური ცვლადების სია + List Text Styles ტექსტის სტილების სია + Load all ყველას ჩატვირთვა + Load... ჩატვირთვა... + Load Application... აპლიკაციის ჩატვირთვა... + Loaded linetypes ჩატვირთული ხაზის ტიპები + Lock ჩაკეტვა + Lock Layer შრის ჩაკეტვა + Lock viewport ხედვის არის ჩაკეტვა + Lock/Unlock ჩაკეტვა/განბლოკვა + Loft კვეთებით აგება + MIT OR Apache-2.0. Not affiliated with Autodesk, Inc. MIT OR Apache-2.0. Autodesk, Inc.-თან კავშირი არ აქვს. + MODEL მოდელი + MText MText + Magenta მეწამული + Major line every მთავარი ხაზის ბიჯი + Make Current მიმდინარედ დაყენება + Make Object's Layer Current ობიექტის შრის მიმდინარედ დაყენება + Make... შექმნა... + Match Layer შრის მისადაგება + Match Properties თვისებების გადატანა + Measure გაზომვა + Measure Distance მანძილის გაზომვა + Measure Geometry გეომეტრიის გაზომვა + Merge Cells უჯრების შერწყმა + Merged PRs გაერთიანებული PR-ები + Mid Between 2 Points შუა 2 წერტილს შორის + Midpoint შუა წერტილი + Mirror არეკვლა + Model მოდელი + Model Space (in viewport) მოდელის სივრცე (ხედვის არეში) + Modeling მოდელირება + Models მოდელები + Modify შეცვლა + Move გადაადგილება + Move/Copy/Rotate გადაადგილება/კოპირება/შემობრუნება + Multileader მულტიმიმთითებელი + Multileader Style... მულტიმიმთითებლის სტილი... + Multileader style მულტიმიმთითებლის სტილი + Multiline მულტიხაზი + Multiline Text მრავალსტრიქონიანი ტექსტი + Multiline Text... მრავალსტრიქონიანი ტექსტი... + Multiple რამდენიმე + Multiple Point რამდენიმე წერტილი + My ჩემი + My properties: not available yet ჩემი თვისებები: ჯერ ხელმისაწვდომი არ არის + N ჩ + Name სახელი + Name (A–Z) სახელი (ა–ჰ) + Named Views... დასახელებული ხედები... + Nearest უახლოესი + New ახალი + New (metric) ახალი (მეტრული) + New Drawing ახალი ნახაზი + New Drawing (⌘N) ახალი ნახაზი (⌘N) + New Drawing... ახალი ნახაზი... + New Layer ახალი შრე + New Layout ახალი განლაგება + New VP Freeze გაყინვა ახალ ხედვის არეებში + New Viewports... ახალი ხედვის არეები... + New from Template... ახალი შაბლონიდან... + New layout ახალი განლაგება + New state name მდგომარეობის ახალი სახელი + Next Change შემდეგი ცვლილება + No არა + No blocks defined in this drawing. ამ ნახაზში ბლოკები არ არის განსაზღვრული. + No contributor data was built into this copy. ამ ასლში მონაწილეების მონაცემები არ არის ჩაშენებული. + No model credits were built into this copy. ამ ასლში მოდელების მონაცემები არ არის ჩაშენებული. + No saved layer states შრის შენახული მდგომარეობები არ არის + No selection მონიშნული არაფერია + Node კვანძი + None არცერთი + Not available მიუწვდომელია + Not available yet ჯერ ხელმისაწვდომი არ არის + Numbered list დანომრილი სია + OK OK + Object ობიექტი + Object Snap ობიექტზე მიბმა + Object Snap (F3) ობიექტზე მიბმა (F3) + Object Snap On (F3) ობიექტზე მიბმის ჩართვა (F3) + Object Snap Tracking მიბმის მიდევნება + Object Snap Tracking (F11) მიბმის მიდევნება (F11) + Object Snap Tracking Settings მიბმის მიდევნების პარამეტრები + Object type: ობიექტის ტიპი: + Oblique დახრა + Off გამორთული + Offset წანაცვლება + On ჩართული + On/Off ჩართვა/გამორთვა + One of the Crafting Apps by the ArtCraft team and community. ArtCraft-ის გუნდისა და საზოგადოების ერთ-ერთი Crafting App. + Only in this drawing: {n} მხოლოდ ამ ნახაზში: {n} + Only in {name}: {n} მხოლოდ ფაილში {name}: {n} + Open (⌘O) გახსნა (⌘O) + Open Sample Drawing სანიმუშო ნახაზის გახსნა + Open sample drawing სანიმუშო ნახაზის გახსნა + Open Xref გარე მიმართვის გახსნა + Open... გახსნა... + Open Recent ბოლოს გახსნილი ფაილების გახსნა + Clear Recent Files ბოლოს გახსნილი ფაილების სიის გასუფთავება + Operator: ოპერატორი: + Orbit ორბიტა + Ordinate კოორდინატული + Ortho (F8) ორთო (F8) + Ortho Mode ორთო რეჟიმი + Ortho Mode (F8) ორთო რეჟიმი (F8) + Osnap Settings... ობიექტზე მიბმის პარამეტრები... + Out დაპატარავება + Over-constrained ზედმეტად შეზღუდული + Override გადაფარვა + PAPER ფურცელი + Percent პროცენტი + Polar (distance < angle) პოლარული (მანძილი < კუთხე) + PRs PR-ები + Page Setup Manager გვერდის პარამეტრების მენეჯერი + Page Setup Manager... გვერდის პარამეტრების მენეჯერი... + Pan პანორამა + Pan Down პანორამა ქვემოთ + Pan Left პანორამა მარცხნივ + Pan Right პანორამა მარჯვნივ + Pan Up პანორამა ზემოთ + Paper Space ფურცლის სივრცე + Parallel პარალელური + Parameters Manager პარამეტრების მენეჯერი + Parametric პარამეტრული + Paste ჩასმა + Paste as Block ბლოკად ჩასმა + Paste to Command Line ბრძანების სტრიქონში ჩასმა + Paste to Original Coordinates საწყის კოორდინატებზე ჩასმა + Path Array ტრაექტორიული მასივი + Pattern ნიმუში + Perpendicular მართობი + Plot დაბეჭდვა + Plot (click: do not plot) იბეჭდება (დაწკაპეთ, რომ არ დაიბეჭდოს) + Plot Preview ნახვა ამობეჭდვამდე + Plot Window ბეჭდვის ფანჯარა + Plot style ბეჭდვის სტილი + Plot style attached to მიმაგრებული ბეჭდვის სტილი + Plot style table ბეჭდვის სტილების ცხრილი + Plot Style... ბეჭდვის სტილი... + Plot Style Manager ბეჭდვის სტილების მენეჯერი + Plot Style Manager... ბეჭდვის სტილების მენეჯერი... + Plot Styles... ბეჭდვის სტილები... + Plotter Manager პლოტერების მენეჯერი + Plotter Manager... პლოტერების მენეჯერი... + New CTB ახალი CTB + New STB ახალი STB + New style ახალი სტილი + Reset Panel Layout პანელების განლაგების ჩამოყრა + Send Hatches to Back დაშტრიხვების უკანა პლანზე გადატანა + Send Under Objects ობიექტების ქვეშ გადატანა + Text Objects Only მხოლოდ ტექსტური ობიექტები + Use for this layout ამ განლაგებისთვის გამოყენება + Display plot styles ბეჭდვის სტილების ჩვენება + No plot style tables. ბეჭდვის სტილების ცხრილები არ არის. + A built-in table: editing it keeps an edited copy in the drawing. ჩაშენებული ცხრილი: რედაქტირებისას შეცვლილი ასლი ნახაზში ინახება. + Keep an editable copy of this table in the drawing ამ ცხრილის რედაქტირებადი ასლის ნახაზში შენახვა + Layout {name}: {table} განლაგება {name}: {table} + Grayscale ნაცრისფერი ტონები + Screening ფერის ინტენსივობა + Use object linetype ობიექტის ხაზის ტიპის გამოყენება + Use object lineweight ობიექტის ხაზის სისქის გამოყენება + Remove წაშლა + Add დამატება + Open a drawing first. ჯერ გახსენით ნახაზი. + Plot table type ბეჭდვის ცხრილის ტიპი + Color-dependent ფერზე დამოკიდებული + Named დასახელებული + Plus/minus პლუს/მინუს + Point წერტილი + Point Filters წერტილის ფილტრები + Point Style... წერტილის სტილი... + Polar Array პოლარული მასივი + Polar Tracking პოლარული მიდევნება + Polar Tracking (F10) პოლარული მიდევნება (F10) + Polar Tracking On (F10) პოლარული მიდევნების ჩართვა (F10) + Polar angle measurement პოლარული კუთხის ათვლა + Polar distance პოლარული მანძილი + Polar: {distance} < {angle}° პოლარული: {distance} < {angle}° + PolarSnap პოლარული მიბმა + Polygon მრავალკუთხედი + Polygonal მრავალკუთხა + Polygonal Viewport მრავალკუთხა ხედვის არე + Polyline ტეხილი + Polyline Edit ტეხილის რედაქტირება + Position X პოზიცია X + Position Y პოზიცია Y + Position Z პოზიცია Z + Previous წინა + Previous Change წინა ცვლილება + Previous Layer წინა შრე + Primitives პრიმიტივები + Print დაბეჭდვა + Print... დაბეჭდვა... + Properties თვისებები + Properties Inspector თვისებების ინსპექტორი + Properties: თვისებები: + Proxy პროქსი + Purge გაწმენდა + Pyramid პირამიდა + Quadrant კვადრანტი + Query Entities ობიექტების მოთხოვნა + Quick სწრაფი + Quick Dimension სწრაფი ზომა + Quick Properties სწრაფი თვისებები + Quick Select სწრაფი მონიშვნა + Quick Select Properties სწრაფი მონიშვნის თვისებები + Quick Select... სწრაფი მონიშვნა... + QuickCalc სწრაფი კალკულატორი + QuickCalc Pick სწრაფი კალკულატორი: არჩევა + Quit CADCraft CADCraft-იდან გასვლა + Radius რადიუსი + Raster Image რასტრული გამოსახულება + Ray სხივი + Read-only მხოლოდ წასაკითხი + Real name ნამდვილი სახელი + Realtime რეალურ დროში + Reassociate Dimensions ზომების ხელახლა მიბმა + Recent ბოლოდროინდელი + Recent Commands ბოლოდროინდელი ბრძანებები + Recent Input ბოლოდროინდელი შეყვანა + Recover... აღდგენა... + Rectangle მართკუთხედი + Recalculate Table Formulas ცხრილის ფორმულების გადათვლა + Rectangular მართკუთხა + Rectangular snap მართკუთხა მიბმა + Rectangular Array მართკუთხა მასივი + Red წითელი + Redo ხელახლა შესრულება + Redo (⇧⌘Z) ხელახლა შესრულება (⇧⌘Z) + Redraw გადახატვა + Regen რეგენერაცია + Regen All ყველაფრის რეგენერაცია + Region რეგიონი + Region/Mass Properties რეგიონის/მასის თვისებები + Reinitialize ხელახლა ინიციალიზება + Relative ფარდობითი + Relative to last segment ბოლო სეგმენტის მიმართ + Remove Leader მიმთითებლის მოცილება + Remove the viewport override ხედვის არის ცალკე პარამეტრის მოცილება + Rename Dimension Style ზომის სტილის სახელის შეცვლა + Rename Layer შრის სახელის შეცვლა + Rename Layer State შრეების მდგომარეობის სახელის შეცვლა + Rename Layout განლაგების სახელის შეცვლა + Rename Text Style ტექსტის სტილის სახელის შეცვლა + Rename... სახელის შეცვლა... + Repeat {command} გამეორება: {command} + Requires a point (x,y, @dx,dy or @d მიუთითეთ მეორე წერტილი ან <პირველი წერტილი გამოიყენეთ წანაცვლებად> + Specify second source point მიუთითეთ მეორე საწყისი წერტილი + Specify side to offset მიუთითეთ წანაცვლების მხარე + Specify start angle მიუთითეთ საწყისი კუთხე + Specify start point მიუთითეთ საწყისი წერტილი + Specify start point of arc მიუთითეთ რკალის საწყისი წერტილი + Specify start point of polyline მიუთითეთ ტეხილის საწყისი წერტილი + Specify start point of text მიუთითეთ ტექსტის საწყისი წერტილი + Specify starting width მიუთითეთ საწყისი სიგანე + Specify starting width for next segment მიუთითეთ შემდეგი სეგმენტის საწყისი სიგანე + Specify tangent direction for the start point of arc მიუთითეთ მხების მიმართულება რკალის საწყის წერტილში + Specify the elevation for rectangles მიუთითეთ მართკუთხედების დონე + Specify thickness for rectangles მიუთითეთ მართკუთხედების სისქე + Specify third point on circle მიუთითეთ წრის მესამე წერტილი + Specify third point on circle: _tan to მიუთითეთ წრის მესამე წერტილი: _tan to + Specify third source point or მიუთითეთ მესამე საწყისი წერტილი ან <გაგრძელება> + Specify through point მიუთითეთ გავლის წერტილი + Specify top diameter მიუთითეთ ზედა დიამეტრი + Specify top radius or მიუთითეთ ზედა რადიუსი ან + Specify total angle მიუთითეთ სრული კუთხე + Specify total length or მიუთითეთ სრული სიგრძე ან + Specify width for rectangles მიუთითეთ მართკუთხედების სიგანე + Sphere სფერო + Spline სპლაინი + Spline Edit სპლაინის რედაქტირება + Stack (type 1/2 then select) წილადი (აკრიფეთ 1/2 და მონიშნეთ) + Standard სტანდარტული + Start დასაწყისი + Start Width საწყისი სიგანე + Start X საწყისი X + Start Y საწყისი Y + Start angle საწყისი კუთხე + Start, Center, Angle დასაწყისი, ცენტრი, კუთხე + Start, Center, End დასაწყისი, ცენტრი, ბოლო + Start, Center, Length დასაწყისი, ცენტრი, სიგრძე + Start, End, Angle დასაწყისი, ბოლო, კუთხე + Start, End, Direction დასაწყისი, ბოლო, მიმართულება + Start, End, Radius დასაწყისი, ბოლო, რადიუსი + Status სტატუსი + Status Bar სტატუსის ზოლი + Stretch გაწელვა + Style: Standard სტილი: Standard + Subtract გამოკლება + Sweep ტრაექტორიით აგება + Switch Drawing ნახაზის გადართვა + Switch Layout განლაგების გადართვა + Switch between model space in a viewport and paper space გადართვა ხედვის არეში მოდელის სივრცესა და ფურცლის სივრცეს შორის + Symmetric სიმეტრია + Synchronize Attributes ატრიბუტების სინქრონიზაცია + To სადამდე + Toggle PICKADD (off: each pick replaces the selection) PICKADD-ის გადართვა (გამორთული: ყოველი არჩევა ცვლის მონიშნულს) + Toggle PICKADD (on: picks add to the selection) PICKADD-ის გადართვა (ჩართული: არჩეული ემატება მონიშნულს) + TOP ზედა + Table ცხრილი + Table Breaks ცხრილის გაწყვეტა + Table Cell Style ცხრილის უჯრის სტილი + Table Style... ცხრილის სტილი... + Table style ცხრილის სტილი + Table... ცხრილი... + Tan, Tan, Radius მხები, მხები, რადიუსი + Tan, Tan, Tan მხები, მხები, მხები + Tangent მხები + Temporary track point დროებითი მიდევნების წერტილი + Text ტექსტი + Text Editor ტექსტის რედაქტორი + Text Height ტექსტის სიმაღლე + Text Style... ტექსტის სტილი... + Text height ტექსტის სიმაღლე + Text override ტექსტის ჩანაცვლება + Text style ტექსტის სტილი + Thaw All Layers ყველა შრის გალღობა + Thaw Layer შრის გალღობა + There is nothing here yet. აქ ჯერ არაფერია. + Thickness სისქე + Time დრო + To get started, create or open a drawing. დასაწყებად შექმენით ან გახსენით ნახაზი. + Tool Bar ხელსაწყოთა ზოლი + Tool Sets ხელსაწყოთა ნაკრებები + Tools ხელსაწყოები + Torus ტორი + Trace სქელი ხაზი + Track orthogonally only მიდევნება მხოლოდ ორთოგონალურად + Track using all polar angle settings მიდევნება პოლარული კუთხის ყველა პარამეტრით + Transparency გამჭვირვალობა + Trim მოკვეთა + True Color ნამდვილი ფერი + Turn All Layers On ყველა შრის ჩართვა + Turn Off Layer შრის გამორთვა + Turn On Layer შრის ჩართვა + Turn Quick Properties off (QPMODE) სწრაფი თვისებების გამორთვა (QPMODE) + Type ტიპი + Type a command აკრიფეთ ბრძანება + Type text; Enter starts a new paragraph აკრიფეთ ტექსტი; Enter იწყებს ახალ აბზაცს + UCS Icon UCS-ის ხატულა + Undo დაბრუნება + Undo (⌘Z) დაბრუნება (⌘Z) + Ungroup დაჯგუფების მოხსნა + Union გაერთიანება + Unisolate Layer შრის იზოლირების მოხსნა + Units Conversion ერთეულების გარდაქმნა + Units... ერთეულები... + Unlock Layer შრის განბლოკვა + Unlock viewport ხედვის არის განბლოკვა + Unmerge Cells უჯრების შერწყმის გაუქმება + Unsaved Layer State შრეების შეუნახავი მდგომარეობა + Up ზემოთ + Update Data Links მონაცემთა ბმულების განახლება + Update განახლება + Use System Setting სისტემის პარამეტრის გამოყენება + User მომხმარებელი + User Parameters მომხმარებლის პარამეტრები + Username მომხმარებლის სახელი + Volume მოცულობა + VP Color ხედვის არის ფერი + VP Freeze ხედვის არეში გაყინვა + Value მნიშვნელობა + Value: მნიშვნელობა: + Variables ცვლადები + Version ვერსია + Version 2000 ვერსია 2000 + Version 2004 ვერსია 2004 + Version 2007 ვერსია 2007 + Version 2010 ვერსია 2010 + Version 2013 ვერსია 2013 + Version 2018 ვერსია 2018 + Version {version} ვერსია {version} + Vertical ვერტიკალური + VerticalDistance ვერტიკალური მანძილი + View ხედი + ViewCube ViewCube + Viewport ხედვის არე + Viewport Layer Freeze შრის გაყინვა ხედვის არეში + Viewport Properties ხედვის არის თვისებები + Viewport is locked ხედვის არე ჩაკეტილია + Viewport scale ხედვის არის მასშტაბი + Viewport {id} ხედვის არე {id} + Viewports ხედვის არეები + W დ + WCS WCS + White თეთრი + Width factor სიგანის კოეფიციენტი + Window ფანჯარა + Wipeout დამფარავი არე + Workspace Switching სამუშაო სივრცის გადართვა + Write Block ბლოკის ჩაწერა + Xline დამხმარე ხაზი + Yellow ყვითელი + Yes დიახ + Zoom მასშტაბი + Zoom All მასშტაბი: ყველაფერი + Zoom Dynamic მასშტაბი: დინამიკური + Zoom Extents მასშტაბი: საზღვრები + Zoom In გადიდება + Zoom Object მასშტაბი: ობიექტი + Zoom Out დაპატარავება + Zoom Previous მასშტაბი: წინა + Zoom Realtime მასშტაბი: რეალურ დროში + Zoom Window მასშტაბი: ფანჯარა + error შეცდომა + {contributors} · {commits} {contributors} · {commits} + {kind} (constraint {id}) {kind} (შეზღუდვა {id}) + {kind} constraint {name} = {expression} (double-click to edit) {kind} შეზღუდვა {name} = {expression} (ორმაგი დაწკაპება — რედაქტირება) + {name}: {distance} < {angle}° {name}: {distance} < {angle}° + ƒx New User Parameter ƒx ახალი მომხმარებლის პარამეტრი + ΔLOC ΔLOC + −Bin −Bin + −LOC −LOC + ⌘↩ to finish ⌘↩ — დასრულება +@plural {n} commit {n} კომიტი +@plural {n} contributor {n} მონაწილე + Drawing as bytes ნახაზი ბაიტებად + Services სერვისები + Hide CADCraft CADCraft-ის დამალვა + Hide Others სხვების დამალვა + Accessibility ხელმისაწვდომობა + Show System Cursor სისტემური კურსორის ჩვენება + Animation Effects ანიმაციის ეფექტები + Animation effects ანიმაციის ეფექტები + Interface scale ინტერფეისის მასშტაბი + Import... იმპორტი... + Export... ექსპორტი... + Batch Publish... პაკეტური გამოქვეყნება... + Scale List... მასშტაბების სია... + Annotative Object Scale ანოტაციური ობიექტის მასშტაბი + Add Current Scale მიმდინარე მასშტაბის დამატება + Delete Current Scale მიმდინარე მასშტაბის წაშლა + Add/Delete Scales... მასშტაბების დამატება/წაშლა... + Synchronize Multiple-scale Positions მრავალმასშტაბიანი პოზიციების სინქრონიზაცია + Annotative Update ანოტაციურის განახლება + Show Annotative Objects ანოტაციური ობიექტების ჩვენება + Current Scale Only მხოლოდ მიმდინარე მასშტაბი + All Scales ყველა მასშტაბი + Drawing Recovery Manager... ნახაზების აღდგენის მენეჯერი... + Tolerance... დაშვება... + Add Vertex წვეროს დამატება + Remove Vertex წვეროს მოშორება + Convert to Arc რკალად გარდაქმნა + Convert to Line ხაზად გარდაქმნა + Stretch Vertex წვეროს გაწელვა + Edit Array მასივის რედაქტირება + Close Array Editing მასივის რედაქტირების დახურვა + Multiline... მულტიხაზი... + Multiline Style... მულტიხაზის სტილი... + Solid Editing სხეულის რედაქტირება + 3D Mouse... 3D მაუსი... + 3D Mouse 3D მაუსი + Calibrate 3D Mouse 3D მაუსის კალიბრაცია + 3D Mouse Navigation 3D მაუსით ნავიგაცია + 3D mouse input is unavailable on this platform 3D მაუსის შეყვანა ამ პლატფორმაზე მიუწვდომელია + No supported 3D mouse found მხარდაჭერილი 3D მაუსი ვერ მოიძებნა + Release the 3D mouse to calibrate its resting position გაუშვით 3D მაუსი ხელიდან, რომ მისი უძრავი მდგომარეობა დაკალიბრდეს + 3D mouse connected 3D მაუსი დაკავშირებულია + 3D mouse busy, possibly 3DxWare or missing device permissions 3D მაუსი დაკავებულია: შესაძლოა, 3DxWare-ის ან მოწყობილობის ნებართვების არქონის გამო + 3D mouse disconnected 3D მაუსი გათიშულია + 3D mouse input could not be started 3D მაუსის შეყვანა ვერ ჩაირთო + Enable 3D mouse navigation 3D მაუსით ნავიგაციის ჩართვა + Pan sensitivity პანორამის მგრძნობელობა + Zoom sensitivity მასშტაბის მგრძნობელობა + Reverse zoom direction მასშტაბის მიმართულების შებრუნება + Calibrate კალიბრაცია + Move sideways to pan; push/pull or twist to zoom. გვერდზე გაწევით — პანორამა; მიწევით/გამოწევით ან მობრუნებით — მასშტაბი. + Left device button: zoom extents. Right device button: calibrate. მოწყობილობის მარცხენა ღილაკი: მასშტაბი საზღვრებით. მარჯვენა ღილაკი: კალიბრაცია. + More toolbar commands ხელსაწყოთა ზოლის სხვა ბრძანებები + Default save version შენახვის ნაგულისხმევი ვერსია + Automatic save every ავტომატური შენახვა ყოველ + min წთ + Automatic save file location ავტომატური შენახვის ფაილის მდებარეობა + Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. ჯერ ფაილის არმქონე ნახაზები ნაგულისხმევ ვერსიაში ინახება. 0 წუთი ავტომატურ შენახვას გამორთავს. + Time-sensitive right-click: a quick click is Enter, holding opens the menu დროზე დამოკიდებული მარჯვენა დაწკაპება: მოკლე დაწკაპება Enter-ია, დაჭერით გაიხსნება მენიუ + Turned off, a right-click while a command runs always opens the shortcut menu. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება ყოველთვის კონტექსტურ მენიუს ხსნის. + Hatch Pattern დაშტრიხვის ნიმუში + Search for pattern ნიმუშის ძიება + Run Script... სკრიპტის გაშვება... + Query Texts ტექსტების მოთხოვნა + Analyze Shapes ფიგურების ანალიზი + Hatch Pick დაშტრიხვის არჩევა + Hatch and Gradient დაშტრიხვა და გრადიენტი + Color 1 ფერი 1 + Color 2 ფერი 2 + Shape ფიგურა + Curved მრუდი + Spherical სფერული + Hemispherical ნახევარსფერული + Inverted შებრუნებული + Centered ცენტრში + Hatch origin დაშტრიხვის საწყისი წერტილი + Use current origin მიმდინარე საწყისი წერტილის გამოყენება + Specified origin მითითებული საწყისი წერტილი + Click to set new origin დაწკაპეთ ახალი საწყისი წერტილის დასაყენებლად + Default to boundary extents ნაგულისხმევად საზღვრის გაბარიტები + Bottom left ქვედა მარცხენა + Bottom right ქვედა მარჯვენა + Top left ზედა მარცხენა + Top right ზედა მარჯვენა + Boundaries საზღვრები + Add: Pick points დამატება: წერტილების არჩევა + Add: Select objects დამატება: ობიექტების მონიშვნა + Boundaries picked: {n} არჩეული საზღვრები: {n} + Select boundaries to remove მონიშნეთ მოსაშორებელი საზღვრები + Island კუნძული + Associative ასოციაციური + Create separate hatches ცალკეული დაშტრიხვების შექმნა + Island detection კუნძულების აღმოჩენა + Normal ჩვეულებრივი + Outer გარე + Ignore უგულებელყოფა + Origin: {x}, {y} საწყისი წერტილი: {x}, {y} + Sheet Books to PDF... ფურცლების წიგნები PDF-ში... + Not a number or distance: {text} არც რიცხვია და არც მანძილი: {text} + Dynamic Block Data დინამიკური ბლოკის მონაცემები + Custom მორგებული + Dynamic Block Reference დინამიკური ბლოკის ჩასმა + Set Dynamic Property დინამიკური თვისების დაყენება + Dynamic Block Grips დინამიკური ბლოკის სახელურები + Drag Dynamic Grip დინამიკური სახელურის გადათრევა + Save Block ბლოკის შენახვა + Save Block As ბლოკის შენახვა როგორც + Close Block Editor ბლოკის რედაქტორის დახურვა + Unsaved changes შეუნახავი ცვლილებები + Edit Block Definition ბლოკის განსაზღვრების რედაქტირება + Block to create or edit შესაქმნელი ან დასარედაქტირებელი ბლოკი + Open in Block Editor ბლოკის რედაქტორში გახსნა + This drawing ეს ნახაზი + contains authoring elements. Open in Block Editor? შეიცავს ბლოკის აგების ელემენტებს. გაიხსნას ბლოკის რედაქტორში? + New block ახალი ბლოკი + Italic დახრილი + Underline ხაზგასმული + Overline ზედა ხაზი + Justify ორმხრივი სწორება + Text color ტექსტის ფერი + Click the ruler to add a tab stop, right-click to remove one დაწკაპეთ სახაზავზე ტაბულაციის პოზიციის დასამატებლად, მარჯვენა დაწკაპებით — წასაშლელად + Select using two clicks only მონიშვნა მხოლოდ ორი დაწკაპებით + Define each corner of the selection window with a separate click. მონიშვნის ფანჯრის თითოეული კუთხე ცალკე დაწკაპებით განისაზღვრება. + Type an alias name. აკრიფეთ ფსევდონიმის სახელი. + Choose the command the alias starts. აირჩიეთ ბრძანება, რომელსაც ფსევდონიმი გაუშვებს. + {command} is an unknown command. {command} უცნობი ბრძანებაა. + {alias} is already defined; select it and use Edit. {alias} უკვე განსაზღვრულია; მონიშნეთ და გამოიყენეთ „რედაქტირება“. + More than {n} aliases. {n}-ზე მეტი ფსევდონიმი. + Alias file: {file} ფსევდონიმების ფაილი: {file} + No alias file loaded. REINIT replaces these aliases with a file's. ფსევდონიმების ფაილი არ არის ჩატვირთული. REINIT ამ ფსევდონიმებს ფაილიდან წაკითხულით ჩაანაცვლებს. + Alias ფსევდონიმი + Command ბრძანება + overrides built-in ჩაშენებულს ჩაანაცვლებს + built-in ჩაშენებული + Add… დამატება… + Edit… რედაქტირება… + Save alias ფსევდონიმის შენახვა + Discard მოშორება + Customize მორგება + Edit Command Aliases (PGP)... ბრძანებების ფსევდონიმების რედაქტირება (PGP)... + B B + CADCraft CADCraft + X X + Y Y +menu Dimension ზომების დატანა +menu Draw ხაზვა +menu Modify შეცვლა +menu View ხედი + Arrow size ისრის ზომა + Dim scale overall ზომის საერთო მასშტაბი + Precision სიზუსტე + Layouts განლაგებები + Printer/plotter პრინტერი/პლოტერი + Paper size ფურცლის ზომა + Orientation ორიენტაცია + Portrait ვერტიკალური + Landscape ჰორიზონტალური + Plot area ბეჭდვის არე + Fit to paper ფურცელში ჩატევა + Center the plot ნაბეჭდის ცენტრირება + Plot object lineweights ობიექტების ხაზის სისქეების ბეჭდვა + Plot transparency გამჭვირვალობის ბეჭდვა + Apply to Layout განლაგებაზე გამოყენება + Enter name of LISP file to load შეიყვანეთ ჩასატვირთი LISP ფაილის სახელი + Enter geometric characteristic შეიყვანეთ გეომეტრიული მახასიათებელი + Enter block names to extract შეიყვანეთ ამოსაღები ბლოკების სახელები + Limits ზღვრები + Plot offset ბეჭდვის წანაცვლება + X offset (mm) X წანაცვლება (მმ) + Y offset (mm) Y წანაცვლება (მმ) + First corner პირველი კუთხე + Opposite corner საპირისპირო კუთხე + Window < ფანჯარა < diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index a0bf590db..673ed2151 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -45,10 +45,12 @@ pub enum Preference { Hungarian, #[serde(rename = "tr")] Turkish, + #[serde(rename = "ka")] + Georgian, } impl Preference { - pub const ALL: [Self; 17] = [ + pub const ALL: [Self; 18] = [ Self::Auto, Self::English, Self::Greek, @@ -66,6 +68,7 @@ impl Preference { Self::Arabic, Self::Hungarian, Self::Turkish, + Self::Georgian, ]; /// The codes a preference can be given as, for messages ("auto, en or uk"). @@ -96,6 +99,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Georgian => "ka", } } @@ -124,6 +128,15 @@ impl Preference { Self::Arabic => "العربية", Self::Hungarian => "Magyar", Self::Turkish => "Türkçe", + // Georgian letters come from the craft-fonts Georgian face; a build without it shows + // the English name (as Korean does) and keeps the interface in English. + Self::Georgian => { + if crate::theme::can_show("ka") { + "ქართული" + } else { + "Georgian" + } + } } } @@ -154,6 +167,7 @@ impl Preference { Self::Arabic => "ar", Self::Hungarian => "hu", Self::Turkish => "tr", + Self::Georgian => "ka", Self::Auto => locales.iter().find_map(|s| locale_language(s)).unwrap_or("en"), } } @@ -170,7 +184,7 @@ pub struct Language { catalog: OnceLock>, } -pub static LANGUAGES: [Language; 16] = [ +pub static LANGUAGES: [Language; 17] = [ Language { code: "en", name: "English", source: "", plural: plural_en, plural_forms: 2, catalog: OnceLock::new() }, // Greek: one for exactly 1; other for zero and all other integer counts. Language { code: "el", name: "Ελληνικά", source: include_str!("el.tsv"), plural: plural_en, plural_forms: 2, catalog: OnceLock::new() }, @@ -211,6 +225,11 @@ pub static LANGUAGES: [Language; 16] = [ Language { code: "hu", name: "Magyar", source: include_str!("hu.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() }, // Turkish keeps a noun singular after a number ("3 commit"), so like Korean it has one form. Language { code: "tr", name: "Türkçe", source: include_str!("tr.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() }, + // Georgian keeps a noun singular after a numeral ("5 კომიტი"), so one form, the Korean rule. + // Its letters come from the craft-fonts `Geor` face (`theme::can_show`). + Language { + code: "ka", name: "ქართული", source: include_str!("ka.tsv"), plural: plural_ko, plural_forms: 1, catalog: OnceLock::new() + }, ]; /// BCP 47 and POSIX locale tags, including `uk-UA`, `uk_UA.UTF-8` and `pt_BR.UTF-8`. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index bbbcded39..052cae5fb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -39,7 +39,7 @@ fn catalog_is_valid_and_preserves_placeholders_and_ellipses() { /// to English for what they don't cover yet; their gaps are reported, not enforced, so adding a /// command doesn't require a row in every language. const REQUIRED: &[&str] = &["uk"]; -const REPORTED: &[&str] = &["pt-BR", "de", "es", "cs", "ru", "fr", "zh", "it", "ko", "sv", "ar", "hu", "tr", "el"]; +const REPORTED: &[&str] = &["pt-BR", "de", "es", "cs", "ru", "fr", "zh", "it", "ko", "sv", "ar", "hu", "tr", "el", "ka"]; fn check(language: &str, what: &str, missing: Vec) { if REQUIRED.contains(&language) { @@ -1172,3 +1172,112 @@ fn default_fonts_cover_all_greek_letters_in_the_catalog() { } }); } + +#[test] +fn georgian_locales_preferences_and_single_count_form() { + for tag in ["ka", "ka-GE", "ka_GE", "ka_GE.UTF-8", "KA-ge", " ka-GE "] { + assert_eq!(locale_language(tag), Some("ka"), "{tag}"); + } + // `kat`/`geo` are the three-letter codes and `kab` is Kabyle; none picks Georgian. + for tag in ["kat", "geo", "kab", "kartuli"] { + assert_eq!(locale_language(tag), None, "{tag}"); + } + assert_eq!(Preference::parse("ka"), Some(Preference::Georgian)); + assert_eq!(Preference::Georgian.code(), "ka"); + assert_eq!(Preference::Georgian.name(), if crate::theme::can_show("ka") { "ქართული" } else { "Georgian" }); + assert_eq!(Preference::Georgian.resolve(&["en-US".into()]), "ka"); + assert_eq!(Preference::Auto.resolve(&["pl-PL".into(), "ka-GE".into(), "en-US".into()]), "ka"); + let saved = serde_json::to_string(&Preference::Georgian).unwrap(); + assert_eq!(saved, "\"ka\""); + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.interface_language = Preference::Georgian; + let mut restored = CadApp::new(Session::new(), Services::default()); + restored.load_prefs(&app.prefs_json()); + assert_eq!(restored.ui.interface_language, Preference::Georgian); + with_language("ka", || { + // A Georgian noun stays singular after a numeral, 1 included. + for n in [0, 1, 2, 5, 21, u64::MAX] { + assert_eq!(count(n, "{n} contributor", "{n} contributors"), format!("{n} მონაწილე")); + assert_eq!(count(n, "{n} commit", "{n} commits"), format!("{n} კომიტი")); + } + assert_eq!(t("Open"), "გახსნა"); + assert_eq!(menu("Dimension"), "ზომების დატანა"); + assert_eq!(t("Dimension"), "ზომა"); + assert_eq!(menu("Draw"), "ხაზვა"); + assert_eq!(menu("File"), "ფაილი"); + }); + assert_eq!(t("Open"), "Open", "language must not leak outside a render scope"); +} + +#[test] +fn georgian_catalog_covers_marked_ui_literals_without_mtavruli() { + assert!(missing_marked_ui_literals("ka").is_empty(), "{:?}", missing_marked_ui_literals("ka")); + assert!(missing_commands_menus_tools_and_snap_labels("ka").is_empty(), "{:?}", missing_commands_menus_tools_and_snap_labels("ka")); + // Mtavruli (U+1C90–U+1CBF) is a display style, not upper-case Georgian: never in the catalog. + let mtavruli: Vec = include_str!("ka.tsv").chars().filter(|c| ('\u{1c90}'..='\u{1cbf}').contains(c)).collect(); + assert!(mtavruli.is_empty(), "{mtavruli:?}"); +} + +#[test] +fn georgian_live_switch_keeps_drawing_and_falls_back_without_font() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.in_window_menu = true; + app.session.state_mut().unwrap().title = "Open".into(); + let ctx = egui::Context::default(); + app.logic(&ctx); + assert!(render(&mut app, &ctx).contains("Properties")); + app.start("line"); + let prompt = crate::control::cmdline_state(&app); + let commands = crate::control::all_commands(&app); + let result = app.run("ui.language", json!({"lang": "ka"})).unwrap(); + let supported = crate::theme::can_show("ka"); + assert_eq!(result["shown"], if supported { "ka" } else { "en" }); + assert_eq!(app.ui.interface_language, Preference::Georgian); + app.logic(&ctx); + assert_eq!(app.fonts_language, Some(app.language())); + let text = render(&mut app, &ctx); + if supported { + for label in ["თვისებები", "ფაილი", "ხედი", "ხაზვა", "ზომების დატანა", "მიუთითეთ პირველი წერტილი"] + { + assert!(text.contains(label), "missing {label}: {text}"); + } + } else { + assert!(text.contains("Properties")); + } + assert_eq!(app.session.state().unwrap().title, "Open"); + assert_eq!(crate::control::cmdline_state(&app), prompt); + assert_eq!(crate::control::all_commands(&app), commands); + app.run("ui.language", json!({"lang": "en"})).unwrap(); + app.logic(&ctx); + assert!(render(&mut app, &ctx).contains("Properties")); +} + +#[test] +fn georgian_dialogs_render_with_stable_ids() { + if !crate::theme::can_show("ka") { + return; // The fallback path is covered above; do not claim glyph rendering here. + } + for (dialog, source) in [ + ("dsettings", "Drafting Settings"), + ("about", "About CADCraft"), + ("commands", "Command Reference"), + ("blocks", "Blocks"), + ("layers", "Layer Properties Manager"), + ("qselect", "Quick Select"), + ("parameters", "Parameters Manager"), + ("language", "Interface Language"), + ("options:preferences", "User Preferences"), + ] { + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.interface_language = Preference::Georgian; + app.ui.dialog = Some(dialog.into()); + let ctx = egui::Context::default(); + app.logic(&ctx); + let text = render(&mut app, &ctx); + assert!(text.contains(tr("ka", source)), "{dialog}: {text}"); + if dialog == "language" { + assert!(text.contains("ქართული"), "{dialog}: {text}"); + } + assert_eq!(app.ui.dialog.as_deref(), Some(dialog)); + } +} diff --git a/crates/ui-egui/src/options/mod.rs b/crates/ui-egui/src/options/mod.rs index d2f805aa6..a3fbd37fc 100644 --- a/crates/ui-egui/src/options/mod.rs +++ b/crates/ui-egui/src/options/mod.rs @@ -10,7 +10,7 @@ //! |---|---| //! | `theme` | `"system"`, `"light"` or `"dark"` | //! | `animations` | `"system"`, `"on"` or `"off"`: dialog and menu fades and smoothed scrolling | -//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"hu"`, `"tr"` or `"el"` | +//! | `interfaceLanguage` | `"auto"`, `"en"`, `"uk"`, `"pt-BR"`, `"de"`, `"es"`, `"cs"`, `"ru"`, `"fr"`, `"zh"`, `"it"`, `"ko"`, `"sv"`, `"ar"`, `"hu"`, `"tr"`, `"el"` or `"ka"` | //! | `saveFormat` | `"dxf"` or `"dwg"`: the format Save As suggests for new drawings | //! | `saveVersion` | `"2000"` … `"2018"`: the version drawings with no file yet are saved in | //! | `SAVETIME` | minutes between automatic saves, 0–600 (0: off) | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 3dbd01e22..a4ededd9b 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -70,9 +70,10 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | +| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | AI-assisted (Claude), written from the English strings with Georgian technical-drawing vocabulary; native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | -Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian and Turkish. +Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian, Turkish, Greek and Georgian. Czech, Swedish, Hungarian and Brazilian Portuguese cover the reference catalog and every marked UI literal; engine diagnostics and uncatalogued text remain English. AutoCAD for Mac ships 7 non-English languages (zh-Hans, es, fr, ja, de, ko, it); of those, CADCraft now ships German and Korean, @@ -86,6 +87,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | Georgian (`ka`) added: 1,383 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the craft-fonts `Geor` face in release and web builds (pin a71c20e3); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; native proofreading pending | | 2026-10-15 | minor | Greek (`el`) catalog: 1,330 rows, context/plural/locale/font tests; review pending | | 2026-10-14 | minor | Swedish completed: 95 rows for strings added since (Hatch and Gradient dialog, Block Editor, REFEDIT, multileader editing, Options selection settings, MTEXT editor, recent files); 1,330 rows, every key of the Ukrainian reference catalog | | 2026-10-18 | minor | Turkish added: 1,330 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; locale/preferences/menu/live-switch/dialog/font tests; no gaps in the marked UI literals; AI-assisted, the running app reviewed by a native speaker | diff --git a/docs/localization.md b/docs/localization.md index d3c6cc4e1..03af02bfb 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,7 +1,7 @@ # Interface languages Choose **Edit → Interface Language** and select **Auto (system language)**, **English**, -**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), or **Ελληνικά** (Greek). +**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), or **ქართული** (Georgian). The interface updates without restarting, including the native macOS menus. The choice is saved with the other interface preferences (`cadcraft.prefs`, beside the theme): eframe storage on the desktop, browser local storage on the web. Installations without a saved @@ -11,7 +11,7 @@ Auto uses the first supported language in the operating system's preferred local browser's `navigator.languages` on the web. BCP 47 and POSIX tags select their primary language: `uk-UA` → `uk`, `de_AT.UTF-8` → `de`, `es-MX` → `es`, `pt_BR.UTF-8` → `pt-BR`, `cs-CZ` and `cs_CZ.UTF-8` → `cs`, `it-IT` and `it_CH.UTF-8` → `it`, `ko-KR` and `ko_KR.UTF-8` → `ko`, -`sv-SE`, `sv-FI` and `sv_SE.UTF-8` → `sv`, `hu-HU` and `hu_HU.UTF-8` → `hu`, `tr-TR` and `tr_TR.UTF-8` → `tr`. Unsupported languages fall back to English. +`sv-SE`, `sv-FI` and `sv_SE.UTF-8` → `sv`, `hu-HU` and `hu_HU.UTF-8` → `hu`, `tr-TR` and `tr_TR.UTF-8` → `tr`, `ka-GE` and `ka_GE.UTF-8` → `ka`. Unsupported languages fall back to English. Set `CADCRAFT_LOCALE=cs-CZ` to override the desktop's locale for a launch. An explicit saved language choice takes precedence over that override. @@ -22,7 +22,7 @@ Automation can select the language through the existing control channel: ``` The `ui.set` method also accepts `{"interfaceLanguage":"cs"}`. Supported values are `auto`, -`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, and `el`; invalid values are rejected without changing the current +`en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el`, and `ka`; invalid values are rejected without changing the current selection. Resetting palettes keeps the language choice. ## Translation coverage @@ -115,6 +115,20 @@ original AI-assisted work contributed by @Camthalion77 with language review; it from Autodesk localization files. Independent native proofreading and visual checks remain follow-up work. +## Georgian (`ka`) interface + +Georgian has **1,383 rows**: 1,377 ordinary labels, four contextual menu headings (**ზომების +დატანა** for the Dimension menu, **ზომა** for the object; **ხაზვა** for Draw) and two single-form +count templates, since a Georgian noun stays singular after a numeral ("5 კომიტი"). It covers the +union of the existing catalogs, and no marked UI literal falls back to English. Commands are verbal +nouns (**შენახვა**, **შემობრუნება**); prompts read "მიუთითეთ …" for Specify, "შეიყვანეთ …" for +Enter and "მონიშნეთ …" for Select, and clickable keywords keep the spelling the engine accepts. +Georgian has no letter case, so nothing is capitalised, and Mtavruli (a display style, not upper +case) never appears; a test checks that. The translation is original, AI-assisted work written from +the English strings with Georgian technical-drawing vocabulary (შრე, დაშტრიხვა, მომრგვალება, ფასკა, +წანაცვლება, ობიექტზე მიბმა, ხედვის არე); no other product's localization was consulted. Native +proofreading of the running app is still to do. + ## Adding translations The implementation follows the display-time catalog pattern used by From 93e4ff10c47bbfafe2b807671465c3abc8e74107 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 02:23:44 +0400 Subject: [PATCH 011/185] fonts: draw the Georgian interface with the craft-fonts Georgian face MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bump craft-fonts-ref to a71c20e3, which adds Noto Sans Georgian (`Geor`), and build the web release with craft-fonts (`web-craft-fonts: true`). The interface loads the embedded `Geor` face after the CJK faces in every language (the picker names ქართული), and the web build embeds it too (232 KB). Without it `can_show("ka")` is false: the saved choice is kept, the interface stays English and the language command says why. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- .github/workflows/freebsd.yml | 2 +- .github/workflows/release.yml | 3 +- crates/fonts/build.rs | 10 +++---- crates/fonts/src/craft_fonts.rs | 3 +- crates/ui-egui/src/menus.rs | 12 +++++--- crates/ui-egui/src/theme.rs | 52 +++++++++++++++++++++++++++------ docs/control-protocol.md | 4 +-- docs/localization.md | 7 +++++ 8 files changed, 70 insertions(+), 23 deletions(-) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index e7a607181..b23a86341 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -26,4 +26,4 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: - craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 04206b9c8..12fc211ae 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,8 @@ jobs: with: app-name: cadcraft app-title: CADCraft - craft-fonts-ref: 3d9ab3a132ed0eff457e424226a435a901da30d3 + craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc + web-craft-fonts: true version: ${{ inputs.version }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} diff --git a/crates/fonts/build.rs b/crates/fonts/build.rs index 7eb2a784b..833ba6f63 100644 --- a/crates/fonts/build.rs +++ b/crates/fonts/build.rs @@ -3,9 +3,9 @@ //! empty, `CRAFT_FONTS` is empty and the build is unchanged. It only reads the local checkout //! (no network). A bad checkout is a warning, or an error with `CRAFT_FONTS_REQUIRED=1`. //! -//! On wasm32 it embeds only BIZ UDPGothic Regular and the `Arab` faces (about 5.5 MB), to keep the -//! web build within hosting limits (Cloudflare Pages: 25 MiB per file). The web build has no -//! system fonts, so these are its only fallback for Japanese and Arabic-script text. +//! On wasm32 it embeds only BIZ UDPGothic Regular and the `Arab` and `Geor` faces (about 5.7 MB), +//! to keep the web build within hosting limits (Cloudflare Pages: 25 MiB per file). The web build +//! has no system fonts, so these are its only fallback for Japanese, Arabic-script and Georgian text. use std::fmt::Write as _; use std::path::PathBuf; @@ -50,8 +50,8 @@ fn craft_fonts(dir: &std::path::Path) -> Result { println!("cargo::warning=craft-fonts: not embedding {family} {style} (AGENTS.md: no Adobe fonts)"); continue; } - let arabic = scripts.split(',').any(|s| s.trim() == "Arab"); - let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || arabic; + let web_script = scripts.split(',').any(|s| matches!(s.trim(), "Arab" | "Geor")); + let web_face = (*family == "BIZ UDPGothic" && *style == "Regular") || web_script; if wasm && !web_face { continue; } diff --git a/crates/fonts/src/craft_fonts.rs b/crates/fonts/src/craft_fonts.rs index fb290775f..713b6632a 100644 --- a/crates/fonts/src/craft_fonts.rs +++ b/crates/fonts/src/craft_fonts.rs @@ -1,7 +1,7 @@ //! Fonts from the optional craft-fonts build input (). //! //! Built with `CRAFT_FONTS_DIR=`, `build.rs` embeds the fonts listed in its -//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular and the Arabic faces). +//! `fonts/manifest.txt` (web builds: only BIZ UDPGothic Regular and the Arabic and Georgian faces). //! Without it [`CRAFT_FONTS`] is empty and nothing changes. The font table ([`crate::ttf`]) //! lists the embedded fonts with the installed ones, under [`CraftFont::stem`]. A text style //! can name one (`BIZ UDPGothic`), and they are fallbacks for characters a text's font lacks. @@ -84,6 +84,7 @@ mod tests { Some("Jpan") => '\u{3042}', Some("Arab") => '\u{0628}', Some("Hang" | "Kore") => '가', + Some("Geor") => 'ა', _ => 'A', }; assert!(face.is_some_and(|x| x.has_glyph(sample)), "{} lacks {sample}", f.family); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d4ac0d3e6..35e381c7a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -137,10 +137,14 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { + "No font covers the Korean interface, so it stays in English. Install a Hangul font (Malgun Gothic or Nanum Gothic), or build with a Hang/Kore craft-fonts face." + } + "ka" => "This build has no Georgian font, so the interface stays in English. Build with craft-fonts (its Geor face) to use Georgian.", + _ => { + "No Chinese font is installed, so the interface stays in English. Install one (Noto Sans CJK, for example) to use Chinese." + } }); } Ok(json!({"interfaceLanguage": preference.code(), "shown": shown})) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 6c8dd83d0..9105423c1 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -307,7 +307,8 @@ pub fn mono() -> FontId { /// language: file, layout and layer names can be Japanese or Chinese whatever the interface /// shows (#513). In a Chinese interface (`language` "zh…") the Chinese font comes first, else a /// Japanese one, so names take their own glyph forms; in an Arabic interface an installed -/// Arabic font follows. A font embedded from craft-fonts comes +/// Arabic font follows. The embedded Georgian face loads in every language, so the language +/// picker can show ქართული. A font embedded from craft-fonts comes /// last, for systems without any (and the web build, which has no system fonts). A Korean /// interface adds a Hangul font only when the CJK font found doesn't cover Hangul /// ([`korean_font`]). @@ -391,7 +392,8 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) { /// shows (#513), with the interface's own face leading. A sans-serif face reads best, and a /// Chinese interface takes the face with its own glyphs ahead of a Japanese one — a Japanese face /// shares most ideographs but lacks the simplified-only ones (图 园 测), which would be tofu. -/// العربية adds its Arabic face after those, egui's bundled faces carrying no Arabic glyphs. +/// The Georgian face follows in every language (egui's bundled faces carry no Georgian glyphs, and +/// the picker names the language ქართული); العربية adds its Arabic face after those. fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str) -> Vec<&'a cadcraft_fonts::CraftFont> { let cjk = |f: &&cadcraft_fonts::CraftFont| f.style == "Regular" && f.scripts.iter().any(|s| matches!(*s, "Jpan" | "Hans" | "Hant")); let mut out: Vec<_> = faces.iter().copied().filter(cjk).collect(); @@ -399,6 +401,7 @@ fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str if language.starts_with("zh") { out.sort_by_key(|f| !f.scripts.contains(&"Hans")); } + out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Geor"))); if language == "ar" { out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Arab"))); } @@ -636,11 +639,13 @@ pub fn shows_hangul(language: &str) -> bool { /// Whether the interface can show `language` without missing-glyph boxes: Chinese needs a font /// with its glyphs (installed, or the CJK face this build embedded from craft-fonts), Korean a -/// font with Hangul, العربية an installed Arabic font or the embedded Arabic face. +/// font with Hangul, العربية an installed Arabic font or the embedded Arabic face, ქართული the +/// embedded Georgian face. pub fn can_show(language: &str) -> bool { match language { "ko" => shows_hangul("ko"), "ar" => arabic_font().is_some() || embedded_script("Arab"), + "ka" => embedded_script("Geor"), l if l.starts_with("zh") => cjk_font().is_some() || embedded_script("Hans") || embedded_script("Hant"), _ => true, } @@ -738,13 +743,16 @@ mod tests { let japanese = face("BIZ UDPGothic", &["Jpan", "Latn"]); let chinese = face("Han Test Face", &["Hans", "Latn"]); let arabic = face("Noto Sans Arabic", &["Arab"]); - let faces = [&japanese, &chinese, &arabic]; + let georgian = face("Noto Sans Georgian", &["Geor"]); + let faces = [&japanese, &chinese, &arabic, &georgian]; // Every interface reads CJK names, so both CJK faces load, the sans-serif face first. - assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face"]); + // The Georgian face loads in every interface too, after them: the picker shows ქართული. + assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // A Chinese interface takes the Han face first: a Japanese face lacks 图 园 测. - assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic", "Noto Sans Georgian"]); // العربية adds the Arabic face, after the CJK ones egui's bundled faces have no glyphs for. - assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ka")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // Another weight is a style of a face, not an interface face of its own. let bold = CraftFont { family: "BIZ UDPGothic", style: "Bold", scripts: &["Jpan"], bytes: &[] }; assert!(super::embedded_ui_faces(&[&bold], "en").is_empty()); @@ -755,13 +763,39 @@ mod tests { /// leaving the installed-font answer the gate had before. #[test] fn embedded_faces_answer_for_their_scripts() { - let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"])]; - assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab")); + let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"]), face("Noto Sans Georgian", &["Geor"])]; + assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab") && super::any_script(&faces, "Geor")); assert!(!super::any_script(&faces, "Hans") && !super::any_script(&faces, "Hant")); // A `Bold`-only face is not the interface's, and a script code is matched whole. let bold = CraftFont { family: "Some Han Bold", style: "Bold", scripts: &["Hans"], bytes: &[] }; assert!(!super::any_script(&[bold], "Hans") && !super::any_script(&faces, "Ara")); assert!(!super::embedded_script("Hans") || super::can_show("zh")); + // ქართული rides on the embedded Georgian face alone. + assert_eq!(super::can_show("ka"), super::embedded_script("Geor")); assert!(super::can_show("en") && super::can_show("uk")); } + + /// With the craft-fonts Georgian face (release and web builds), every Mkhedruli letter and the + /// picker's ქართული render in both families, in a Georgian and in an English interface. + #[test] + fn embedded_georgian_face_covers_the_alphabet_in_every_interface() { + if !super::embedded_script("Geor") { + return; + } + let letters: Vec = ('ა'..='ჰ').chain("ქართული".chars()).collect(); + for language in ["ka", "en"] { + let ctx = egui::Context::default(); + super::install_fonts(&ctx, language); + let mut output = ctx.run_ui(Default::default(), |_| {}); + output.textures_delta.clear(); + ctx.fonts_mut(|view| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let mut font = view.fonts.font(&family); + for c in &letters { + assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + } + } + }); + } + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b1e91a52c..168e34b24 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -182,9 +182,9 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar` and `hu`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the -optional craft-fonts input or the operating system. Without a suitable font, the saved choice is +optional craft-fonts input or the operating system; Georgian needs the craft-fonts Georgian (`Geor`) face. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts `{"interfaceLanguage":"uk"}`; `ui.inspect` reports the saved choice in its UI state. Invalid choices leave the current language unchanged. Menus, command labels and prompt text diff --git a/docs/localization.md b/docs/localization.md index d3c6cc4e1..ec198bd02 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -98,6 +98,13 @@ catalog, the saved `ko` preference is kept but the interface falls back to Engli command reports that a font is needed, and the picker uses the readable label **Korean** wherever Hangul can't be shown. This change does not fix platform IME issues or localize engine output. +The bundled egui fonts have no Georgian letters. Georgian is drawn with the Noto Sans Georgian face +(`Geor`) of the craft-fonts build input, which release builds embed (`craft-fonts-ref` in the +workflows, and `web-craft-fonts` for the web build, whose embedded faces include it). The face loads +in every interface language, so the picker shows **ქართული**. A build without craft-fonts keeps the +saved `ka` choice but shows the interface in English, names the language **Georgian** in the picker, +and the language command reports that a Georgian font is needed. + ## Greek (`el`) interface The Greek translation covers all **1,330** distinct source keys collected from the existing From 096e20629e348361d8944a00a4935447eab45ec2 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 12:28:32 +0400 Subject: [PATCH 012/185] i18n(ka): apply the native speaker's terminology review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Draw = ხატვა, Bind = მიბმა, Elevation = დონე, zoom In/Out = მოახლოება/დაშორება, Latin ViewCube compass letters, and the other decided terms; credit the review. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- ATTRIBUTION.md | 2 +- ROADMAP.md | 2 +- crates/ui-egui/src/i18n/ka.tsv | 64 ++++++++++++++++---------------- crates/ui-egui/src/i18n/tests.rs | 4 +- docs/localization-parity.md | 4 +- docs/localization.md | 10 ++--- 6 files changed, 43 insertions(+), 43 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3779b71bc..e876c198c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -71,4 +71,4 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker | | `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending | -| `crates/ui-egui/src/i18n/ka.tsv` | @devius with Claude (AI-assisted) | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; no font assets added (the Georgian face comes from craft-fonts) | +| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) | diff --git a/ROADMAP.md b/ROADMAP.md index 93b3a701e..b093a478a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,7 +95,7 @@ Ukrainian and German. Detail: [localization-parity.md](docs/localization-parity. | Indonesian | none | 0% | | Japanese | none | 0% | | Greek | complete current catalog | 1,330 current source keys; independent proofreading pending | -| Georgian | complete current catalog | 1,383 rows; native proofreading pending | +| Georgian | complete current catalog | 1,383 rows; terminology decided by a native speaker | | German | partial | ≈ 100% of the catalog (989 rows) | | Korean | none | 0% | | Vietnamese | none | 0% | diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25512c91f..5a4d7b4bb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -16,7 +16,7 @@ Apply გამოყენება Attach DWG... DWG-ის მიმაგრება... - Bind ჩაშენება + Bind მიბმა Detach მოხსნა Loaded ჩატვირთულია Make it a block of this drawing, keeping its layer names ამ ნახაზის ბლოკად ქცევა, შრეების სახელების შენარჩუნებით @@ -94,12 +94,12 @@ Auto Constrain ავტომატური შეზღუდვა AutoConstrain ავტოშეზღუდვა Axis, End ღერძი, ბოლო - Base საბაზო წერტილი + Base ბაზა Baseline საბაზისო ხაზი Batch Publish პაკეტური გამოქვეყნება Binary assets added დამატებული ბინარული ფაილები Binary assets removed წაშლილი ბინარული ფაილები - Bind... ჩაშენება... + Bind... მიბმა... Blend გადასვლა Block ბლოკი Block Attribute Manager... ბლოკის ატრიბუტების მენეჯერი... @@ -256,8 +256,8 @@ Drafting ხაზვა Drafting Settings ხაზვის პარამეტრები Drafting Settings... ხაზვის პარამეტრები... - Draw ხაზვა - Draw Order ხაზვის რიგი + Draw ხატვა + Draw Order ხატვის რიგი Drawing (DWG) ნახაზი (DWG) Drawing (DXF) ნახაზი (DXF) Drawing Limits ნახაზის ზღვრები @@ -269,12 +269,12 @@ Dynamic Dimensions დინამიკური ზომები Dynamic Input დინამიკური შეყვანა Dynamic Input (F12) დინამიკური შეყვანა (F12) - E ა + E E Edit რედაქტირება Edit Attributes... ატრიბუტების რედაქტირება... Edit Text... ტექსტის რედაქტირება... Edit Table Cell ცხრილის უჯრის რედაქტირება - Elevation ნიშნული + Elevation დონე Ellipse ელიფსი Elliptical Arc ელიფსური რკალი Enable Dynamic Input (F12) დინამიკური შეყვანის ჩართვა (F12) @@ -340,7 +340,7 @@ Export Table ცხრილის ექსპორტი Export to PDF... PDF-ად ექსპორტი... Express Tools Express Tools - Expression ექსპრესია + Expression გამოსახულება Extend გაგრძელება Extension გაგრძელება Extents საზღვრები @@ -358,7 +358,7 @@ First commit პირველი კომიტი Fit Points მისადაგების წერტილები Fix ფიქსაცია - Flatten Objects ობიექტების გაბრტყელება + Flatten Objects ობიექტების სიბრტყეზე დაგეგმილება Format ფორმატი Freehand ხელით ხაზვა Freeze გაყინვა @@ -367,7 +367,7 @@ Freeze/Thaw გაყინვა/გალღობა Freeze/Thaw in all viewports გაყინვა/გალღობა ყველა ხედვის არეში Freeze/Thaw in the current viewport გაყინვა/გალღობა მიმდინარე ხედვის არეში - From ათვლის წერტილიდან + From წერტილიდან From Template... შაბლონიდან... General ზოგადი Geometric Center გეომეტრიული ცენტრი @@ -423,14 +423,14 @@ Collect შეგროვება Collect Multileaders მულტიმიმთითებლების შეგროვება Edit Multileader მულტიმიმთითებლის რედაქტირება - In გადიდება + In მოახლოება In-window Menu Bar მენიუს ზოლი ფანჯარაში Include in new selection set ახალ მონიშნულ ნაკრებში ჩართვა Increment angle კუთხის ბიჯი Index Color ინდექსური ფერი Index color: {index} ინდექსური ფერი: {index} Infer Constraints შეზღუდვების ავტომატური დადგენა - Inquiry ინფორმაცია + Inquiry მოთხოვნა Insert ჩასმა Insert Block ბლოკის ჩასმა Insert Column სვეტის ჩასმა @@ -510,7 +510,7 @@ List Groups ჯგუფების სია List Layer States შრის მდგომარეობების სია List Layouts განლაგებების სია - List System Variables სისტემური ცვლადების სია + List System Variables სისტემის ცვლადების სია List Text Styles ტექსტის სტილების სია Load all ყველას ჩატვირთვა Load... ჩატვირთვა... @@ -525,7 +525,7 @@ MODEL მოდელი MText MText Magenta მეწამული - Major line every მთავარი ხაზის ბიჯი + Major line every ყოველი N-ე ხაზი მთავარია Make Current მიმდინარედ დაყენება Make Object's Layer Current ობიექტის შრის მიმდინარედ დაყენება Make... შექმნა... @@ -556,7 +556,7 @@ Multiple Point რამდენიმე წერტილი My ჩემი My properties: not available yet ჩემი თვისებები: ჯერ ხელმისაწვდომი არ არის - N ჩ + N N Name სახელი Name (A–Z) სახელი (ა–ჰ) Named Views... დასახელებული ხედები... @@ -616,7 +616,7 @@ Ortho Mode ორთო რეჟიმი Ortho Mode (F8) ორთო რეჟიმი (F8) Osnap Settings... ობიექტზე მიბმის პარამეტრები... - Out დაპატარავება + Out დაშორება Over-constrained ზედმეტად შეზღუდული Override გადაფარვა PAPER ფურცელი @@ -646,7 +646,7 @@ Plot Preview ნახვა ამობეჭდვამდე Plot Window ბეჭდვის ფანჯარა Plot style ბეჭდვის სტილი - Plot style attached to მიმაგრებული ბეჭდვის სტილი + Plot style attached to ბეჭდვის სტილი მიმაგრებულია Plot style table ბეჭდვის სტილების ცხრილი Plot Style... ბეჭდვის სტილი... Plot Style Manager ბეჭდვის სტილების მენეჯერი @@ -710,7 +710,7 @@ Purge გაწმენდა Pyramid პირამიდა Quadrant კვადრანტი - Query Entities ობიექტების მოთხოვნა + Query Entities ობიექტების გამოთხოვნა Quick სწრაფი Quick Dimension სწრაფი ზომა Quick Properties სწრაფი თვისებები @@ -726,7 +726,7 @@ Read-only მხოლოდ წასაკითხი Real name ნამდვილი სახელი Realtime რეალურ დროში - Reassociate Dimensions ზომების ხელახლა მიბმა + Reassociate Dimensions ზომების ხელახლა ასოცირება Recent ბოლოდროინდელი Recent Commands ბოლოდროინდელი ბრძანებები Recent Input ბოლოდროინდელი შეყვანა @@ -767,7 +767,7 @@ Right მარჯვნივ Rotate შემობრუნება Rotation შემობრუნება - S ს + S S Save შენახვა Save (⌘S) შენახვა (⌘S) Save As შენახვა როგორც @@ -878,7 +878,7 @@ Single Line Text ერთსტრიქონიანი ტექსტი Single Point ერთი წერტილი Single... ცალკეული... - Smooth გლუვი შეერთება + Smooth დაგლუვება Snap მიბმა Snap Mode მიბმის რეჟიმი Snap Mode (F9) მიბმის რეჟიმი (F9) @@ -969,7 +969,7 @@ Indicate selection area მიუთითეთ მონიშვნის არე Interface language ინტერფეისის ენა Interface theme ინტერფეისის თემა - Keep the system cursor visible over the drawing area სისტემური კურსორი ნახაზის არეზე ხილული დარჩეს + Keep the system cursor visible over the drawing area სისტემის კურსორი ნახაზის არეზე ხილული დარჩეს Largest array ყველაზე დიდი მასივი Layout paper განლაგების ფურცელი Model background მოდელის ფონი @@ -988,7 +988,7 @@ Reset keeps the interface language. ჩამოყრის შემდეგ ინტერფეისის ენა უცვლელი რჩება. Reset to Defaults ნაგულისხმევზე დაბრუნება Save new drawings as ახალი ნახაზების შენახვა როგორც - Screen magnifiers, screen readers and recorders follow the system cursor. ეკრანის გამადიდებლები, ეკრანის წამკითხველები და ჩამწერები სისტემურ კურსორს მიჰყვება. + Screen magnifiers, screen readers and recorders follow the system cursor. ეკრანის გამადიდებლები, ეკრანის წამკითხველები და ჩამწერები სისტემის კურსორს მიჰყვება. Select objects first, then choose a command ჯერ მონიშნეთ ობიექტები, შემდეგ აირჩიეთ ბრძანება Selection მონიშვნა Selection Area Effect მონიშვნის არის ეფექტი @@ -1079,7 +1079,7 @@ Sphere სფერო Spline სპლაინი Spline Edit სპლაინის რედაქტირება - Stack (type 1/2 then select) წილადი (აკრიფეთ 1/2 და მონიშნეთ) + Stack (type 1/2 then select) დასტად დალაგება (აკრიფეთ 1/2 და მონიშნეთ) Standard სტანდარტული Start დასაწყისი Start Width საწყისი სიგანე @@ -1191,12 +1191,12 @@ Viewport scale ხედვის არის მასშტაბი Viewport {id} ხედვის არე {id} Viewports ხედვის არეები - W დ + W W WCS WCS White თეთრი Width factor სიგანის კოეფიციენტი Window ფანჯარა - Wipeout დამფარავი არე + Wipeout მასკირება Workspace Switching სამუშაო სივრცის გადართვა Write Block ბლოკის ჩაწერა Xline დამხმარე ხაზი @@ -1206,9 +1206,9 @@ Zoom All მასშტაბი: ყველაფერი Zoom Dynamic მასშტაბი: დინამიკური Zoom Extents მასშტაბი: საზღვრები - Zoom In გადიდება + Zoom In მოახლოება Zoom Object მასშტაბი: ობიექტი - Zoom Out დაპატარავება + Zoom Out დაშორება Zoom Previous მასშტაბი: წინა Zoom Realtime მასშტაბი: რეალურ დროში Zoom Window მასშტაბი: ფანჯარა @@ -1229,7 +1229,7 @@ Hide CADCraft CADCraft-ის დამალვა Hide Others სხვების დამალვა Accessibility ხელმისაწვდომობა - Show System Cursor სისტემური კურსორის ჩვენება + Show System Cursor სისტემის კურსორის ჩვენება Animation Effects ანიმაციის ეფექტები Animation effects ანიმაციის ეფექტები Interface scale ინტერფეისის მასშტაბი @@ -1242,7 +1242,7 @@ Delete Current Scale მიმდინარე მასშტაბის წაშლა Add/Delete Scales... მასშტაბების დამატება/წაშლა... Synchronize Multiple-scale Positions მრავალმასშტაბიანი პოზიციების სინქრონიზაცია - Annotative Update ანოტაციურის განახლება + Annotative Update ანოტაციური განახლება Show Annotative Objects ანოტაციური ობიექტების ჩვენება Current Scale Only მხოლოდ მიმდინარე მასშტაბი All Scales ყველა მასშტაბი @@ -1287,7 +1287,7 @@ Hatch Pattern დაშტრიხვის ნიმუში Search for pattern ნიმუშის ძიება Run Script... სკრიპტის გაშვება... - Query Texts ტექსტების მოთხოვნა + Query Texts ტექსტების გამოთხოვნა Analyze Shapes ფიგურების ანალიზი Hatch Pick დაშტრიხვის არჩევა Hatch and Gradient დაშტრიხვა და გრადიენტი @@ -1369,7 +1369,7 @@ X X Y Y menu Dimension ზომების დატანა -menu Draw ხაზვა +menu Draw ხატვა menu Modify შეცვლა menu View ხედი Arrow size ისრის ზომა diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 052cae5fb..9455b716b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1203,7 +1203,7 @@ fn georgian_locales_preferences_and_single_count_form() { assert_eq!(t("Open"), "გახსნა"); assert_eq!(menu("Dimension"), "ზომების დატანა"); assert_eq!(t("Dimension"), "ზომა"); - assert_eq!(menu("Draw"), "ხაზვა"); + assert_eq!(menu("Draw"), "ხატვა"); assert_eq!(menu("File"), "ფაილი"); }); assert_eq!(t("Open"), "Open", "language must not leak outside a render scope"); @@ -1237,7 +1237,7 @@ fn georgian_live_switch_keeps_drawing_and_falls_back_without_font() { assert_eq!(app.fonts_language, Some(app.language())); let text = render(&mut app, &ctx); if supported { - for label in ["თვისებები", "ფაილი", "ხედი", "ხაზვა", "ზომების დატანა", "მიუთითეთ პირველი წერტილი"] + for label in ["თვისებები", "ფაილი", "ხედი", "ხატვა", "ზომების დატანა", "მიუთითეთ პირველი წერტილი"] { assert!(text.contains(label), "missing {label}: {text}"); } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index a4ededd9b..0b2ae3745 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -70,7 +70,7 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | -| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | AI-assisted (Claude), written from the English strings with Georgian technical-drawing vocabulary; native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | +| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian, Turkish, Greek and Georgian. @@ -87,7 +87,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| -| 2026-10-23 | minor | Georgian (`ka`) added: 1,383 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the craft-fonts `Geor` face in release and web builds (pin a71c20e3); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; native proofreading pending | +| 2026-10-23 | minor | Georgian (`ka`) added: 1,383 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; the craft-fonts `Geor` face in release and web builds (pin a71c20e3); locale/preferences/menu/live-switch/dialog/font/no-Mtavruli tests; terminology decided by a native speaker | | 2026-10-15 | minor | Greek (`el`) catalog: 1,330 rows, context/plural/locale/font tests; review pending | | 2026-10-14 | minor | Swedish completed: 95 rows for strings added since (Hatch and Gradient dialog, Block Editor, REFEDIT, multileader editing, Options selection settings, MTEXT editor, recent files); 1,330 rows, every key of the Ukrainian reference catalog | | 2026-10-18 | minor | Turkish added: 1,330 rows (the existing catalog union), single count form, four menu headings, prompt keywords kept in English; locale/preferences/menu/live-switch/dialog/font tests; no gaps in the marked UI literals; AI-assisted, the running app reviewed by a native speaker | diff --git a/docs/localization.md b/docs/localization.md index 03af02bfb..7ebdea1a7 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -118,16 +118,16 @@ follow-up work. ## Georgian (`ka`) interface Georgian has **1,383 rows**: 1,377 ordinary labels, four contextual menu headings (**ზომების -დატანა** for the Dimension menu, **ზომა** for the object; **ხაზვა** for Draw) and two single-form +დატანა** for the Dimension menu, **ზომა** for the object; **ხატვა** for Draw) and two single-form count templates, since a Georgian noun stays singular after a numeral ("5 კომიტი"). It covers the union of the existing catalogs, and no marked UI literal falls back to English. Commands are verbal nouns (**შენახვა**, **შემობრუნება**); prompts read "მიუთითეთ …" for Specify, "შეიყვანეთ …" for Enter and "მონიშნეთ …" for Select, and clickable keywords keep the spelling the engine accepts. Georgian has no letter case, so nothing is capitalised, and Mtavruli (a display style, not upper -case) never appears; a test checks that. The translation is original, AI-assisted work written from -the English strings with Georgian technical-drawing vocabulary (შრე, დაშტრიხვა, მომრგვალება, ფასკა, -წანაცვლება, ობიექტზე მიბმა, ხედვის არე); no other product's localization was consulted. Native -proofreading of the running app is still to do. +case) never appears; a test checks that. The translation is original: written with Claude Code from +the meaning of each English string, with Georgian technical-drawing vocabulary (შრე, დაშტრიხვა, +მომრგვალება, ფასკა, წანაცვლება, ობიექტზე მიბმა, ხედვის არე); terminology and doubtful strings +were decided by a native Georgian speaker (@devius). No other product's localization was consulted. ## Adding translations From 85df54b88c098b2d9b7b7596b366d11b3af71b5b Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Fri, 23 Oct 2026 13:33:34 +0400 Subject: [PATCH 013/185] i18n(ka): apply the second terminology review Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5a4d7b4bb..d30ace406 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -35,7 +35,7 @@ Unload განტვირთვა Unloaded განტვირთულია Unreferenced მიმართვის გარეშე - Unresolved დაუდგენელი + Unresolved გადაუჭრელი Cancel გაუქმება OK OK or [ ან [ @@ -238,7 +238,7 @@ Dimension ზომა Dimension Objects Only მხოლოდ ზომის ობიექტები Dimension Space ზომების დაშორება - Dimension Style Override ზომის სტილის გადაფარვა + Dimension Style Override ზომის სტილის ლოკალური ცვლილება Dimension Style... ზომის სტილი... Dimension Text Edit ზომის ტექსტის რედაქტირება Dimension style ზომის სტილი @@ -413,7 +413,7 @@ Hide Objects ობიექტების დამალვა Hide Palettes პალიტრების დამალვა History ისტორია - Home საწყისი პოზიცია + Home საწყისი ხედი Horizontal ჰორიზონტალური HorizontalDistance ჰორიზონტალური მანძილი How to apply: გამოყენების წესი: @@ -611,7 +611,7 @@ Clear Recent Files ბოლოს გახსნილი ფაილების სიის გასუფთავება Operator: ოპერატორი: Orbit ორბიტა - Ordinate კოორდინატული + Ordinate ორდინატა Ortho (F8) ორთო (F8) Ortho Mode ორთო რეჟიმი Ortho Mode (F8) ორთო რეჟიმი (F8) @@ -668,7 +668,7 @@ Keep an editable copy of this table in the drawing ამ ცხრილის რედაქტირებადი ასლის ნახაზში შენახვა Layout {name}: {table} განლაგება {name}: {table} Grayscale ნაცრისფერი ტონები - Screening ფერის ინტენსივობა + Screening ტონირება Use object linetype ობიექტის ხაზის ტიპის გამოყენება Use object lineweight ობიექტის ხაზის სისქის გამოყენება Remove წაშლა From 2830c7c17621d6ea9e22468f6126aae6f1404f00 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Fri, 23 Oct 2026 11:41:26 -0600 Subject: [PATCH 014/185] Merge upstream/main into feat/mleader-text The multileader text test moves into tests/it (one test binary per crate, #1989). Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/{ => it}/mleader_text_edit.rs | 0 2 files changed, 1 insertion(+) rename crates/engine/tests/{ => it}/mleader_text_edit.rs (100%) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b6e088a13..fb51cf645 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -67,6 +67,7 @@ mod measure_distance_snapping; mod metric_linetypes; mod mleader_content; mod mleader_remember; +mod mleader_text_edit; mod mline; mod mocoro; mod modify_curves; diff --git a/crates/engine/tests/mleader_text_edit.rs b/crates/engine/tests/it/mleader_text_edit.rs similarity index 100% rename from crates/engine/tests/mleader_text_edit.rs rename to crates/engine/tests/it/mleader_text_edit.rs From a5391d6ebb6a7e9319dd8f0e0ebb13be722b6aa9 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 24 Oct 2026 00:12:13 +0400 Subject: [PATCH 015/185] fonts: load the embedded Georgian face where can_show accepts it; parity status line The same embedded_ui_faces lines as #1971, so a build whose craft-fonts has the Geor face draws Georgian instead of boxes whichever PR lands first (CodeRabbit). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/theme.rs | 7 +++++-- docs/localization-parity.md | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 7f93d43c2..47aaa3c67 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -307,7 +307,8 @@ pub fn mono() -> FontId { /// language: file, layout and layer names can be Japanese or Chinese whatever the interface /// shows (#513). In a Chinese interface (`language` "zh…") the Chinese font comes first, else a /// Japanese one, so names take their own glyph forms; in an Arabic interface an installed -/// Arabic font follows. A font embedded from craft-fonts comes +/// Arabic font follows. The embedded Georgian face loads in every language, so the language +/// picker can show ქართული. A font embedded from craft-fonts comes /// last, for systems without any (and the web build, which has no system fonts). A Korean /// interface adds a Hangul font only when the CJK font found doesn't cover Hangul /// ([`korean_font`]). @@ -391,7 +392,8 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) { /// shows (#513), with the interface's own face leading. A sans-serif face reads best, and a /// Chinese interface takes the face with its own glyphs ahead of a Japanese one — a Japanese face /// shares most ideographs but lacks the simplified-only ones (图 园 测), which would be tofu. -/// العربية adds its Arabic face after those, egui's bundled faces carrying no Arabic glyphs. +/// The Georgian face follows in every language (egui's bundled faces carry no Georgian glyphs, and +/// the picker names the language ქართული); العربية adds its Arabic face after those. fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str) -> Vec<&'a cadcraft_fonts::CraftFont> { let cjk = |f: &&cadcraft_fonts::CraftFont| f.style == "Regular" && f.scripts.iter().any(|s| matches!(*s, "Jpan" | "Hans" | "Hant")); let mut out: Vec<_> = faces.iter().copied().filter(cjk).collect(); @@ -399,6 +401,7 @@ fn embedded_ui_faces<'a>(faces: &[&'a cadcraft_fonts::CraftFont], language: &str if language.starts_with("zh") { out.sort_by_key(|f| !f.scripts.contains(&"Hans")); } + out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Geor"))); if language == "ar" { out.extend(faces.iter().copied().filter(|f| f.style == "Regular" && f.scripts.contains(&"Arab"))); } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 0b2ae3745..d34add571 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (Swedish catalog completed with the 95 strings added since; previously: Swedish catalog added: complete catalog, menu headings, native-speaker terminology review; previously: complete current Korean catalog with Hangul font coverage) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (Georgian catalog added: complete catalog, menu headings, single count form; previously: Swedish catalog completed with the 95 strings added since; previously: Swedish catalog added: complete catalog, menu headings, native-speaker terminology review; previously: complete current Korean catalog with Hangul font coverage) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How far CADCraft's interface and drawing text are from AutoCAD's languages. Summarised in [ROADMAP.md](../ROADMAP.md#languages); work items in [gaps.md](gaps.md#localization). From f84e458ccfe8e5f677f5d683fd4b6f1086a60469 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:18:29 -0300 Subject: [PATCH 016/185] Keep a landscape media's size order and rotation when saving DXF/DWG Page setups keep a portrait size and a landscape flag, so a layout read with 44 = 420, 45 = 297, 73 = 0 and the media ISO_full_bleed_A3_(420.00_x_297.00_MM) was written back as 297 x 420 with rotation 1. ZWCAD takes the media's size from its name and turns it a quarter on top, so the sheet plotted as a shrunk portrait page (#1463). When the media's name gives it wider than tall, write 44/45 in that order and the rotation relative to it. Other media are written as before. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/dxf_write.rs | 34 ++++++++++++++++++++++--- crates/io/src/tests.rs | 52 ++++++++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 1 + 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 34bee75b2..539f8b6ee 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -2559,13 +2559,14 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.s(2, if device.is_empty() || device.eq_ignore_ascii_case("None") { "none_device" } else { device }); w.s(4, page.paper.replace(' ', "_")); w.s(6, ""); + let (paper_w, paper_h, rotation) = plot_paper(page); for (c, v) in [ (40, page.margins_mm[0]), (41, page.margins_mm[1]), (42, page.margins_mm[2]), (43, page.margins_mm[3]), - (44, page.width_mm), - (45, page.height_mm), + (44, paper_w), + (45, paper_h), (46, 0.0), (47, 0.0), (48, page.plot_window[0]), @@ -2580,7 +2581,7 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.i(70, plot_flags); // Plot paper units: 1 millimetres, 0 inches (#1058). w.i(72, i64::from(cadcraft_render::paper::page_unit_mm(d, page) == 1.0)); - w.i(73, i64::from(page.landscape)); + w.i(73, rotation); w.i(74, plot_type); w.s(7, &page.plot_style_table); w.i(75, if page.scale_to_fit { 0 } else { 16 }); @@ -2639,6 +2640,33 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { /// Write DXF Reference group 91 on every CLASS record. Count records after `dxf_raw::finish` /// restores foreign classes and objects so every class gets its actual instance count. +/// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups +/// keep a portrait size and a landscape flag. A media whose name makes it wider than tall, such +/// as `ISO_full_bleed_A3_(420.00_x_297.00_MM)`, gets its size in that order and the rotation +/// relative to it, so readers that take the media's size from its name agree with groups 44 and +/// 45 (#1463). Other media are written as before. +fn plot_paper(page: &PageSetup) -> (f64, f64, i64) { + if media_is_landscape(&page.paper) { + let (short, long) = (page.width_mm.min(page.height_mm), page.width_mm.max(page.height_mm)); + (long, short, i64::from(!page.landscape)) + } else { + (page.width_mm, page.height_mm, i64::from(page.landscape)) + } +} + +/// Whether a media name ends in a size wider than tall, like `… (420.00 x 297.00 MM)`. +fn media_is_landscape(paper: &str) -> bool { + let name = paper.replace('_', " "); + let Some(open) = name.rfind('(') else { return false }; + let mut sides = name[open + 1..].splitn(2, ['x', 'X', '×']); + let num = |s: Option<&str>| { + let s = s?.trim_start(); + let end = s.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(s.len()); + s[..end].parse::().ok() + }; + matches!((num(sides.next()), num(sides.next())), (Some(w), Some(h)) if w > h) +} + fn add_class_instance_counts(tags: &mut Vec) { let mut counts: HashMap = HashMap::new(); for t in tags.iter().filter(|t| t.code == 0) { diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 2c741b803..cae9cc749 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -560,6 +560,58 @@ fn dxf_roundtrips_page_setup() { assert_eq!(p.paper, a3.name); } +/// Groups 44, 45 and 73 of a layout's AcDbPlotSettings in DXF text. +fn plot_paper_groups(dxf: &str, layout: &str) -> (f64, f64, i64) { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + let pairs: Vec<(&str, &str)> = lines.chunks(2).filter(|c| c.len() == 2).map(|c| (c[0], c[1])).collect(); + let name = pairs.windows(2).position(|w| w[0] == ("100", "AcDbLayout") && w[1] == ("1", layout)).unwrap_or_else(|| panic!("no LAYOUT {layout}")); + let start = pairs[..name].iter().rposition(|p| *p == ("100", "AcDbPlotSettings")).unwrap(); + let get = |code: &str| pairs[start..name].iter().find(|p| p.0 == code).map(|p| p.1).unwrap(); + (get("44").parse().unwrap(), get("45").parse().unwrap(), get("73").parse().unwrap()) +} + +#[test] +fn landscape_media_keeps_its_size_order_and_rotation() { + // A media defined wider than tall, as ZWCAD and AutoCAD name it (#1463). + let media = "ISO full bleed A3 (420.00 x 297.00 MM)"; + for (landscape, rotation) in [(true, 0), (false, 1)] { + let mut d = sample(); + { + let p = &mut d.layouts[0].page; + p.paper = media.into(); + p.width_mm = 297.0; + p.height_mm = 420.0; + p.landscape = landscape; + } + let dxf = write_dxf(&d); + assert_eq!(plot_paper_groups(&dxf, "Layout1"), (420.0, 297.0, rotation), "DXF, landscape {landscape}"); + let r = read_dxf(dxf.as_bytes()).unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (297.0, 420.0, landscape), "DXF read back"); + assert_eq!(p.paper, media); + + let dwg = write(&d, "t.dwg").unwrap(); + let back = String::from_utf8_lossy(&cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).into_owned(); + assert_eq!(plot_paper_groups(&back, "Layout1"), (420.0, 297.0, rotation), "DWG, landscape {landscape}"); + let r = read(&dwg, "t.dwg").unwrap(); + let p = &r.layout("Layout1").unwrap().page; + assert_eq!((p.width_mm, p.height_mm, p.landscape), (297.0, 420.0, landscape), "DWG read back"); + } +} + +#[test] +fn portrait_media_is_written_as_before() { + let mut d = sample(); + { + let p = &mut d.layouts[0].page; + p.paper = "ISO A3 (297.00 x 420.00 MM)".into(); + p.width_mm = 297.0; + p.height_mm = 420.0; + p.landscape = true; + } + assert_eq!(plot_paper_groups(&write_dxf(&d), "Layout1"), (297.0, 420.0, 1)); +} + // --------------------------------------------------------------------------------------------- // Round trips of styles, overrides, associativity, constraints and tables. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c598193d7..6c92c30a7 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -138,6 +138,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-23 | minor | DXF/DWG save: a layout whose media is named wider than tall (`ISO_full_bleed_A3_(420.00_x_297.00_MM)`) keeps its paper size in that order (44 = 420, 45 = 297) and its plot rotation relative to the media, instead of a portrait size with rotation 1 that ZWCAD plotted as a shrunk portrait page (#1463); other media are written as before | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | | 2026-10-12 | minor | PDF output: object transparency plotted as PDF alpha (`/ExtGState` `/ca` `/CA`) when the page setup's or the plot's "Plot transparency" is on; PNG plots blend it, SVG uses `opacity`; plots without it are unchanged byte for byte | | 2026-10-12 | minor | DXF/DWG save: the Model layout's plot settings are written as CADCraft plots model space, drawing extents scaled to fit (PLOTSETTINGS 74 = 1, 75 = 0), instead of plot type 5 "Layout information", which other programs' Plot dialogs can't use for model space | From 241aad2425938a4311733dc4b9087ed0c44cd286 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:35:10 -0300 Subject: [PATCH 017/185] docs: file-format parity status line for the page setup change Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/file-format-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6c92c30a7..9d4553ecb 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (DWG read leaves out orphaned DGN line style components) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (DXF/DWG save keeps a landscape media's paper size order and plot rotation) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds From 6a5e8eda3576a2eac375b190fd4fc8d75b5abbbb Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 24 Oct 2026 13:16:07 +0400 Subject: [PATCH 018/185] fonts: test the Georgian face in the face order and its glyphs in a ka and an en interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Same tests as #1971: embedded_ui_faces yields the Geor face for ka (and for every interface, which names the language ქართული in the picker), can_show("ka") follows the embedded face, and with a craft-fonts that carries Geor every Mkhedruli letter renders in both families. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/theme.rs | 41 +++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 47aaa3c67..9105423c1 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -743,13 +743,16 @@ mod tests { let japanese = face("BIZ UDPGothic", &["Jpan", "Latn"]); let chinese = face("Han Test Face", &["Hans", "Latn"]); let arabic = face("Noto Sans Arabic", &["Arab"]); - let faces = [&japanese, &chinese, &arabic]; + let georgian = face("Noto Sans Georgian", &["Geor"]); + let faces = [&japanese, &chinese, &arabic, &georgian]; // Every interface reads CJK names, so both CJK faces load, the sans-serif face first. - assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face"]); + // The Georgian face loads in every interface too, after them: the picker shows ქართული. + assert_eq!(families(&super::embedded_ui_faces(&faces, "en")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // A Chinese interface takes the Han face first: a Japanese face lacks 图 园 测. - assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "zh")), ["Han Test Face", "BIZ UDPGothic", "Noto Sans Georgian"]); // العربية adds the Arabic face, after the CJK ones egui's bundled faces have no glyphs for. - assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ar")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian", "Noto Sans Arabic"]); + assert_eq!(families(&super::embedded_ui_faces(&faces, "ka")), ["BIZ UDPGothic", "Han Test Face", "Noto Sans Georgian"]); // Another weight is a style of a face, not an interface face of its own. let bold = CraftFont { family: "BIZ UDPGothic", style: "Bold", scripts: &["Jpan"], bytes: &[] }; assert!(super::embedded_ui_faces(&[&bold], "en").is_empty()); @@ -760,13 +763,39 @@ mod tests { /// leaving the installed-font answer the gate had before. #[test] fn embedded_faces_answer_for_their_scripts() { - let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"])]; - assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab")); + let faces = [face("BIZ UDPGothic", &["Jpan", "Latn"]), face("Noto Sans Arabic", &["Arab"]), face("Noto Sans Georgian", &["Geor"])]; + assert!(super::any_script(&faces, "Jpan") && super::any_script(&faces, "Arab") && super::any_script(&faces, "Geor")); assert!(!super::any_script(&faces, "Hans") && !super::any_script(&faces, "Hant")); // A `Bold`-only face is not the interface's, and a script code is matched whole. let bold = CraftFont { family: "Some Han Bold", style: "Bold", scripts: &["Hans"], bytes: &[] }; assert!(!super::any_script(&[bold], "Hans") && !super::any_script(&faces, "Ara")); assert!(!super::embedded_script("Hans") || super::can_show("zh")); + // ქართული rides on the embedded Georgian face alone. + assert_eq!(super::can_show("ka"), super::embedded_script("Geor")); assert!(super::can_show("en") && super::can_show("uk")); } + + /// With the craft-fonts Georgian face (release and web builds), every Mkhedruli letter and the + /// picker's ქართული render in both families, in a Georgian and in an English interface. + #[test] + fn embedded_georgian_face_covers_the_alphabet_in_every_interface() { + if !super::embedded_script("Geor") { + return; + } + let letters: Vec = ('ა'..='ჰ').chain("ქართული".chars()).collect(); + for language in ["ka", "en"] { + let ctx = egui::Context::default(); + super::install_fonts(&ctx, language); + let mut output = ctx.run_ui(Default::default(), |_| {}); + output.textures_delta.clear(); + ctx.fonts_mut(|view| { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let mut font = view.fonts.font(&family); + for c in &letters { + assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + } + } + }); + } + } } From 2409afe7f00de47def4c3ce7bc7a05e52553a8c0 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 24 Oct 2026 14:15:14 +0400 Subject: [PATCH 019/185] i18n(ka): translate the six strings main added (Analyze Usage, Implied Loops, units of new drawings) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d30ace406..3db7c923a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -988,6 +988,10 @@ Reset keeps the interface language. ჩამოყრის შემდეგ ინტერფეისის ენა უცვლელი რჩება. Reset to Defaults ნაგულისხმევზე დაბრუნება Save new drawings as ახალი ნახაზების შენახვა როგორც + Units of new drawings ახალი ნახაზების ერთეულები + Imperial (inches) იმპერიული (დუიმები) + Metric (millimetres) მეტრული (მილიმეტრები) + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). ახალი ნახაზი და გაშვებისას გახსნილი პირველი ნახაზი ამ ერთეულებს იყენებს, თუ ნაგულისხმევი შაბლონი არ არის მითითებული (QNEWTEMPLATE). Screen magnifiers, screen readers and recorders follow the system cursor. ეკრანის გამადიდებლები, ეკრანის წამკითხველები და ჩამწერები სისტემის კურსორს მიჰყვება. Select objects first, then choose a command ჯერ მონიშნეთ ობიექტები, შემდეგ აირჩიეთ ბრძანება Selection მონიშვნა @@ -1289,6 +1293,8 @@ Run Script... სკრიპტის გაშვება... Query Texts ტექსტების გამოთხოვნა Analyze Shapes ფიგურების ანალიზი + Analyze Usage გამოყენების ანალიზი + Implied Loops არაცხადი შეკრული კონტურები Hatch Pick დაშტრიხვის არჩევა Hatch and Gradient დაშტრიხვა და გრადიენტი Color 1 ფერი 1 From b52d5fbdff20771f3ac5ec2560464a8bde23fa26 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:09:52 -0300 Subject: [PATCH 020/185] io: put the CLASS group 91 doc comment back on its function plot_paper had been inserted between add_class_instance_counts and its doc comment (review on #2028). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/io/src/dxf_write.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 43cca500d..0e4a6e916 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -2694,8 +2694,6 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.t } -/// Write DXF Reference group 91 on every CLASS record. Count records after `dxf_raw::finish` -/// restores foreign classes and objects so every class gets its actual instance count. /// Paper size (groups 44, 45) and plot rotation (group 73) for a LAYOUT object. Page setups /// keep a portrait size and a landscape flag. A media whose name makes it wider than tall, such /// as `ISO_full_bleed_A3_(420.00_x_297.00_MM)`, gets its size in that order and the rotation @@ -2723,6 +2721,8 @@ fn media_is_landscape(paper: &str) -> bool { matches!((num(sides.next()), num(sides.next())), (Some(w), Some(h)) if w > h) } +/// Write DXF Reference group 91 on every CLASS record. Count records after `dxf_raw::finish` +/// restores foreign classes and objects so every class gets its actual instance count. fn add_class_instance_counts(tags: &mut Vec) { let mut counts: HashMap = HashMap::new(); for t in tags.iter().filter(|t| t.code == 0) { From 84ba9a8040f239c5fb540d70c8ff2d853f974f91 Mon Sep 17 00:00:00 2001 From: assamaraleman <217119886+assamaraleman@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:19:43 -0300 Subject: [PATCH 021/185] DXF read: number viewports in file order when every id is unknown (#1463) ZWCAD writes every paper-space VIEWPORT with id (69) -1. The reader cast it to u32, so no viewport was the sheet (id 1); on save paper_views() added a second sheet viewport ahead of the real one, which DWG readers then numbered 2: a model viewport showing the whole sheet, inflating the layout's extents. A non-positive 69 now reads as 0, and a layout whose viewports all have id 0 gets them numbered in file order, the first being the sheet. A layout mixing known ids with -1 is left as before (pinned by a test). Co-Authored-By: Claude Fable 5.1 --- crates/io/src/dxf_read.rs | 17 +++++++++++++- crates/io/src/tests.rs | 48 ++++++++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 3 ++- 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 5860b1e03..65deabde3 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -492,7 +492,8 @@ fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_left: &mut usi height: t.fd(41, 1.0), view_center: Vec2::new(t.fd(12, 0.0), t.fd(22, 0.0)), view_height: t.fd(45, 1.0), - id: t.i(69).unwrap_or(0) as u32, + // ZWCAD writes -1 (unknown): 0 here, numbered in order below. + id: t.i(69).filter(|i| *i > 0).unwrap_or(0) as u32, locked: t.i(90).unwrap_or(0) & 16384 != 0, frozen_layers: crate::dxf_ext::read_frozen(tags), layer_colors: crate::dxf_ext::read_layer_colors(tags), @@ -1866,6 +1867,20 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { d.model.push(e); } } + // A layout whose viewports all lack an id (ZWCAD writes 69 = -1) gets them numbered in file + // order, as DWG readers do: its first viewport is the paper-space one (id 1), so saving does + // not add a second sheet viewport ahead of it (#1463). + for l in d.layouts.iter_mut() { + let vps: Vec = l.entities.iter().filter(|e| matches!(&e.kind, EntityKind::Viewport(_))).map(|e| (**e).clone()).collect(); + if vps.iter().all(|e| matches!(&e.kind, EntityKind::Viewport(v) if v.id == 0)) { + for (i, mut e) in vps.into_iter().enumerate() { + if let EntityKind::Viewport(v) = &mut e.kind { + v.id = i as u32 + 1; + } + l.entities.replace(e); + } + } + } apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); crate::dxf_image::resolve(&secs, &mut d); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 7b8f38385..33d4fd611 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -604,6 +604,54 @@ fn viewport_frozen_layers_roundtrip() { assert!(frozen.contains(&(3, Vec::new())), "{frozen:?}"); } +/// `Layout1` with viewports 1 (the sheet), 2 and 3, written to DXF and read back with the id (69) +/// of every viewport `blank` names replaced by -1 (ZWCAD's "unknown"): the ids and widths read. +fn viewport_ids_read_back(blank: impl Fn(&str) -> bool) -> (Drawing, Vec<(u32, f64)>) { + let mut d = sample(); + let paper = Space::Paper("Layout1".into()); + for (id, w) in [(1, 420.0), (2, 8.0), (3, 4.0)] { + let vp = Viewport { + center: Vec3::new(5.0, 4.0, 0.0), + width: w, + height: 6.0, + view_center: Vec2::new(5.0, 4.0), + view_height: 6.0, + id, + ..Viewport::default() + }; + d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap(); + } + let text = write_dxf(&d); + let mut lines: Vec = text.lines().map(String::from).collect(); + for i in (0..lines.len() - 1).step_by(2) { + if lines[i].trim() == "69" && blank(lines[i + 1].trim()) { + lines[i + 1] = "-1".into(); + } + } + let back = read_dxf(lines.join("\n").as_bytes()).unwrap(); + let ids = + back.layouts[0].entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some((v.id, v.width)) } else { None }).collect(); + (back, ids) +} + +/// ZWCAD writes every VIEWPORT with id (69) -1: they are numbered in file order, the first being +/// the paper-space viewport, so saving adds no second sheet viewport (#1463). +#[test] +fn viewport_ids_unknown_are_numbered_in_order() { + let (back, ids) = viewport_ids_read_back(|_| true); + assert_eq!(ids, [(1, 420.0), (2, 8.0), (3, 4.0)]); + assert!(!write_dxf(&back).contains("PAPERVIEW"), "the layout already has its paper-space viewport"); +} + +/// A layout that mixes known ids with -1 is left alone: the known ids stay, the unknown one reads +/// as 0 (not numbered), as before #1463. +#[test] +fn viewport_ids_mixed_are_kept() { + let (back, ids) = viewport_ids_read_back(|v| v == "2"); + assert_eq!(ids, [(1, 420.0), (0, 8.0), (3, 4.0)]); + assert!(!write_dxf(&back).contains("PAPERVIEW"), "viewport 1 is still the sheet"); +} + /// A layout with viewport 2 frozen on `Walls` and `A B` (both real layers), and its written DXF as /// (code, value) pairs. fn frozen_vp_dxf() -> (Drawing, Vec<(String, String)>) { diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6c852ba76..f9091e77d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (DIMASSOC objects for angular, diametric and radial dimensions) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (DXF read: viewports without ids numbered in file order) · **Target:** Autodesk AutoCAD 2027 Every format AutoCAD 2027 reads or writes, with CADCraft's support, fidelity and tests. Work items are in [gaps.md](gaps.md#file-formats); the weighted score feeds @@ -140,6 +140,7 @@ our output in AutoCAD black-box. | Date | Change | Summary | |---|---|---| +| 2026-10-24 | minor | DXF read: a layout whose VIEWPORTs all carry id (69) -1 (ZWCAD writes no ids) gets them numbered in file order, the first being the paper-space viewport, so a save no longer adds a second sheet viewport that turns the real one into a model viewport and inflates the drawing extents (#1463) | | 2026-10-22 | minor | DXF/DWG save: angular, diametric and radial dimensions get standard DIMASSOC objects (one centre reference to the circle for radial/diametric, the definition points for angular), so AutoCAD follows their geometry; the standard objects of those kinds are read back too, without CADCraft's xdata (#1651) | | 2026-10-19 | minor | DXF/DWG save: angular dimension block text honors DIMDSEP, including per-dimension overrides (#1646) | | 2026-10-19 | minor | A file's own arrowhead blocks with standard names (AutoCAD's `_Dot`, `_DotSmall`), named only by a dimension style, are kept and saved as they were instead of being replaced by CADCraft's solids; PURGE keeps arrowhead blocks dimension styles name | From 9431ad6ad9baf83207074ae8fc48ebf6d322c85e Mon Sep 17 00:00:00 2001 From: assamaraleman <217119886+assamaraleman@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:22:23 -0300 Subject: [PATCH 022/185] contributors: add assamaraleman Co-Authored-By: Claude Fable 5.1 --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 5c5d61005..ba968ffd3 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -87,3 +87,6 @@ real_name = "Richard Sauer" display_name = "Richard Sauer" sync_github_name = false +[people.assamaraleman] +real_name = "assamaral" +sync_github_name = false From d11c418fe608def4d28d8783c075ac8cc2336b4a Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:17:07 +0400 Subject: [PATCH 023/185] theme: the Georgian glyph test asks FontsView::has_glyph (egui 0.37 made its fonts field private) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/theme.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9627becb4..75dd4f6ac 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -813,9 +813,8 @@ mod tests { output.textures_delta.clear(); ctx.fonts_mut(|view| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - let mut font = view.fonts.font(&family); for c in &letters { - assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + assert!(view.has_glyph(&egui::FontId::new(12.0, family.clone()), *c), "{language}: missing Georgian glyph {c} in {family:?}"); } } }); From 8e84e57ac8e3712edcb26b03988f87c74c56add5 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:17:17 +0400 Subject: [PATCH 024/185] theme: the Georgian glyph test asks FontsView::has_glyph (egui 0.37 made its fonts field private) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/theme.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9627becb4..75dd4f6ac 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -813,9 +813,8 @@ mod tests { output.textures_delta.clear(); ctx.fonts_mut(|view| { for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { - let mut font = view.fonts.font(&family); for c in &letters { - assert!(font.characters().contains_key(c), "{language}: missing Georgian glyph {c} in {family:?}"); + assert!(view.has_glyph(&egui::FontId::new(12.0, family.clone()), *c), "{language}: missing Georgian glyph {c} in {family:?}"); } } }); From 9c8519da2f6675c30fdd81277697caedc938ba64 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:57:06 +0400 Subject: [PATCH 025/185] docs: ka among the supported ui.language values Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1c3f30626..f7fa57e4e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,7 +188,7 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar` and `hu`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the optional craft-fonts input or the operating system. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts From 4cd88a3815009417e159a27dc614a588d55739a9 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 19:57:06 +0400 Subject: [PATCH 026/185] docs: ka joins the supported ui.language values with the language PR, not this one (CodeRabbit) Co-Authored-By: Claude Opus 5.5 --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6e642497a..46e2d379d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,7 +188,7 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr` and `el`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the optional craft-fonts input or the operating system; Georgian needs the craft-fonts Georgian (`Geor`) face. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts From 963267abe856c39d11dcfecdc4857df645078eac Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 21:30:23 +0400 Subject: [PATCH 027/185] docs: list tr and el among the ui.language values Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f7fa57e4e..5bbd4b083 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -188,7 +188,7 @@ Select a language with `engine.execute` and the UI command `ui.language`: {"id":1,"method":"engine.execute","params":{"command":"ui.language","params":{"lang":"uk"}}} ``` -Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu` and `ka`. +Supported values are `auto`, `en`, `uk`, `pt-BR`, `de`, `es`, `cs`, `ru`, `fr`, `zh`, `it`, `ko`, `sv`, `ar`, `hu`, `tr`, `el` and `ka`. Chinese needs an installed CJK font, Arabic an installed Arabic font; Korean needs a font covering the Korean interface from the optional craft-fonts input or the operating system. Without a suitable font, the saved choice is retained and the result's `shown` is `en`. `ui.set` also accepts From 1fba38238f67ee97392d110468e7449e7e7bf6fb Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sun, 25 Oct 2026 22:09:24 +0400 Subject: [PATCH 028/185] i18n(ka): shorter wording for labels that were cut off Decided in the native-speaker review of the screens (all-t01). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3db7c923a..716a01417 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -572,7 +572,7 @@ New Viewports... ახალი ხედვის არეები... New from Template... ახალი შაბლონიდან... New layout ახალი განლაგება - New state name მდგომარეობის ახალი სახელი + New state name ახალი მდგომარეობა Next Change შემდეგი ცვლილება No არა No blocks defined in this drawing. ამ ნახაზში ბლოკები არ არის განსაზღვრული. From f02ac726baafff61a2a803f77694cb7a6c7b3b75 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sun, 25 Oct 2026 16:53:24 -0600 Subject: [PATCH 029/185] MTEXT editor: a state kept for another MTEXT is not reused The editor's state was kept between frames and only dropped by a frame with no text prompt, so TEXTEDIT moving to the next MTEXT within one frame (Enter, then a point) opened it with the first one's text, and OK wrote that text to it. The state now remembers the MTEXT it was made for (its insertion point and contents when it opened) and is made afresh for another. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/mtext_editor.rs | 60 +++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 6700b592e..4741491c0 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -76,6 +76,9 @@ struct State { /// The text box has had keyboard focus: it takes it once when the editor opens, so typing /// goes into the text, not to the command line. focused: bool, + /// The MTEXT the state was made for (its insertion point and contents when it opened): a + /// state kept for another one is not reused, so one MTEXT's text never goes to the next. + target: Option<(cadcraft_engine::geom::Vec3, String)>, } fn state_id() -> egui::Id { @@ -106,7 +109,9 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { }; let t = Tokens::get(); let (rect, scale) = app.canvas.xf.map_or((ctx.content_rect(), 20.0), |x| (x.rect, x.scale.max(1e-6))); - let mut st = ctx.data_mut(|d| d.get_temp::(state_id())).unwrap_or_else(|| { + let target = (mt.insert, mt.contents.clone()); + let kept = ctx.data_mut(|d| d.get_temp::(state_id())).filter(|st| st.target.as_ref() == Some(&target)); + let mut st = kept.unwrap_or_else(|| { // An existing MTEXT (TEXTEDIT) starts with its contents and their formats. let mut fmt = if mt.contents.is_empty() { Formatted::default() } else { Formatted::from_contents(&mt.contents) }; if let Some(f) = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).map(|s| s.font.clone())) { @@ -117,7 +122,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } // An existing text opens with the caret at its end. let caret = (!fmt.is_empty()).then(|| fmt.len()); - State { fmt, typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret, focused: false } + State { fmt, typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret, focused: false, target: Some(target.clone()) } }); let base_h = if mt.height > 0.0 { mt.height } else { 0.2 }; let px = ((base_h * scale) as f32).clamp(MIN_PX, MAX_PX); @@ -615,8 +620,16 @@ mod tests { /// Clicking Diameter inserts U+2300 into both the formatted text and `to_contents()`, selects it, and leaves no unnamed widget. #[test] fn diameter_insertion_keeps_real_text_and_renders_without_optional_fonts() { - let state = - State { fmt: Formatted::default(), typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None, focused: false }; + let state = State { + fmt: Formatted::default(), + typing: CharFmt::default(), + typing_at: 0, + top: 70.0, + sel: (0, 0), + caret: None, + focused: false, + target: None, + }; let mut harness = Harness::builder().with_size(vec2(1100.0, 300.0)).with_context_setup(install_diameter_glyph).build_ui_state( |ui, state| { toolbar(ui, state, 2.5); @@ -636,8 +649,16 @@ mod tests { /// The ten toolbar controls listed in the test are found by semantic name under the harness's default bundled fonts, and no toolbar widget is unnamed. #[test] fn the_whole_toolbar_uses_bundled_glyphs_and_names_its_controls() { - let mut state = - State { fmt: Formatted::default(), typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None, focused: false }; + let mut state = State { + fmt: Formatted::default(), + typing: CharFmt::default(), + typing_at: 0, + top: 70.0, + sel: (0, 0), + caret: None, + focused: false, + target: None, + }; let mut harness = Harness::builder().with_size(vec2(1100.0, 120.0)).build_ui(move |ui| toolbar(ui, &mut state, 2.5)); harness.run(); for name in ["Left", "Center", "Right", "Justify", "Bulleted list", "Numbered list", "Insert tab", "Diameter", "Text color", "Font"] { @@ -729,6 +750,33 @@ mod tests { /// #842: TEXTEDIT on an existing MTEXT (what a double-click starts) opens it in the editor /// with its text and formats; finishing writes the edited contents back to that MTEXT. + /// TEXTEDIT moving on to another MTEXT between two frames (Enter keeps the first, a point picks + /// the next) opens the next one with its own text, never the first one's. + #[test] + fn textedit_on_the_next_mtext_does_not_keep_the_first_ones_text() { + let ctx = egui::Context::default(); + let mut app = CadApp::new(Session::new(), Services::default()); + let frame = |app: &mut CadApp| { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }; + for _ in 0..2 { + let mut out = ctx.run_ui(input.clone(), |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + } + }; + app.run("mtext", serde_json::json!({ "at": [0, 20], "text": "first one", "height": 2.5, "width": 20 })).unwrap(); + app.run("mtext", serde_json::json!({ "at": [0, 60], "text": "second one", "height": 2.5, "width": 20 })).unwrap(); + app.start("textedit"); + app.session.input(cadcraft_engine::Input::Point(cadcraft_geom::Vec2::new(1.0, 19.0))).unwrap(); + frame(&mut app); + assert_eq!(ctx.data_mut(|d| d.get_temp::(state_id())).expect("editor open").fmt.text(), "first one"); + // Both inputs between two frames: the first MTEXT kept as it is, then the second picked. + app.session.input(cadcraft_engine::Input::Enter).unwrap(); + app.session.input(cadcraft_engine::Input::Point(cadcraft_geom::Vec2::new(1.0, 59.0))).unwrap(); + assert!(app.session.editing_mtext().is_some_and(|m| m.contents.contains("second")), "TEXTEDIT is on the second MTEXT"); + frame(&mut app); + assert_eq!(ctx.data_mut(|d| d.get_temp::(state_id())).expect("editor open").fmt.text(), "second one"); + } + #[test] fn textedit_opens_an_existing_mtext_with_its_contents() { let ctx = egui::Context::default(); From 36272cdd28b41bbfb0d6ad28af4fa27a576b4188 Mon Sep 17 00:00:00 2001 From: assamaral <217119886+assamaral@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:28:29 -0300 Subject: [PATCH 030/185] contributors: key the entry by the renamed username (assamaral) Co-Authored-By: Claude Fable 5.1 --- contributors/people.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributors/people.toml b/contributors/people.toml index ba968ffd3..53e50fb17 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -87,6 +87,6 @@ real_name = "Richard Sauer" display_name = "Richard Sauer" sync_github_name = false -[people.assamaraleman] +[people.assamaral] real_name = "assamaral" sync_github_name = false From 53c7d25ee04b98c12db17bf2424880f9ac9a8998 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 27 Oct 2026 15:43:32 +0400 Subject: [PATCH 031/185] i18n(ka): bring the Georgian catalog up to date Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 54 ++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 716a01417..1bd5d65fd 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -153,6 +153,7 @@ Close All Other Drawings ყველა სხვა ნახაზის დახურვა Closed შეკრული Close Comparison შედარების დახურვა + Export Comparison შედარების ექსპორტი Coincident დამთხვევა Collapse Palettes პალიტრების ჩაკეცვა Collapse Tool Sets ხელსაწყოთა ნაკრებების ჩაკეცვა @@ -200,6 +201,7 @@ Current selection მიმდინარე მონიშნული Current: {color} მიმდინარე: {color} Cut ამოჭრა + Cut with Base Point ამოჭრა საბაზო წერტილით Cyan ცისფერი Cylinder ცილინდრი DWG DWG @@ -264,6 +266,7 @@ Drawing Template (DWT) ნახაზის შაბლონი (DWT) Drawing Utilities ნახაზის უტილიტები Drawings (DWG, DXF) ნახაზები (DWG, DXF) + AutoLISP (LSP) AutoLISP (LSP) SVG drawings (SVG, SVGZ) SVG ნახაზები (SVG, SVGZ) Dynamic დინამიკური Dynamic Dimensions დინამიკური ზომები @@ -572,7 +575,7 @@ New Viewports... ახალი ხედვის არეები... New from Template... ახალი შაბლონიდან... New layout ახალი განლაგება - New state name ახალი მდგომარეობა + New state name მდგომარეობის ახალი სახელი Next Change შემდეგი ცვლილება No არა No blocks defined in this drawing. ამ ნახაზში ბლოკები არ არის განსაზღვრული. @@ -756,6 +759,7 @@ Rename Text Style ტექსტის სტილის სახელის შეცვლა Rename... სახელის შეცვლა... Repeat {command} გამეორება: {command} + Replace Block... ბლოკის ჩანაცვლება... Requires a point (x,y, @dx,dy or @d Date: Tue, 27 Oct 2026 16:09:18 +0400 Subject: [PATCH 032/185] i18n(ka): translate Font (the text editor's font field) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- crates/ui-egui/src/i18n/ka.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1bd5d65fd..205f5e821 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -362,6 +362,7 @@ Fit Points მისადაგების წერტილები Fix ფიქსაცია Flatten Objects ობიექტების სიბრტყეზე დაგეგმილება + Font შრიფტი Format ფორმატი Freehand ხელით ხაზვა Freeze გაყინვა From f948acd30b52e01826c85d7033e03485cca4a236 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 27 Oct 2026 23:32:16 +0400 Subject: [PATCH 033/185] 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 034/185] 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 d6cc051d99cdb9e3446e7957e6641034db3edcf0 Mon Sep 17 00:00:00 2001 From: assamaral Date: Wed, 28 Oct 2026 08:07:05 -0300 Subject: [PATCH 035/185] 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 474df8ede8c7f6a124a0e7727a0e74d87507765b Mon Sep 17 00:00:00 2001 From: assamaral Date: Wed, 28 Oct 2026 10:07:24 -0300 Subject: [PATCH 036/185] 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 d0ab457f317b5671b1bc8398b00f5a65b1af840e Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 09:24:29 -0600 Subject: [PATCH 037/185] 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 9244ffda5d109cf1a371ade4e367552bd8f48b10 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 20:50:16 +0500 Subject: [PATCH 038/185] Open a drawing on the view it was saved at (#1602) A drawing opened fitted to its extents, so one whose extents are dominated by far-off geometry opened at a view hundreds of times its content: the drawing was sub-pixel and there was no way to zoom in. Every other reader opens on the view the file was saved at. The saved view is read from HEADER (`VIEWCTR`/`VIEWSIZE`) and from the first `*ACTIVE` VPORT record, which is the newer of the two and wins -- as it already does for snap and grid spacing. A record that leaves the centre out has no view to give, so the header pair stands. The extents remain the fallback for a drawing that stores no view, and that fallback now fits the width too, through the aspect the record is written with: a drawing 100 wide and 10 tall was given a view 11 tall, a sliver of it, and a horizontal line got 1e-6. Writing keeps it, so a read-and-write round trip no longer loses the view. Rebased onto main, 310 commits on: `open_drawing` and `usable_view` are in engine/src/session/files.rs, the VPORT reading in io/src/dxf_read/tables.rs, the HEADER pair list in io/src/dxf_write/header.rs and the VPORT writing in io/src/dxf_write/layout.rs. The two io tests were already carried by their hunk, so only the engine one needed placing. --- crates/doc/src/header.rs | 17 ++++++++ crates/engine/src/session/files.rs | 14 +++++- crates/engine/src/tests.rs | 34 +++++++++++++++ crates/io/src/dxf_read/tables.rs | 12 +++++- crates/io/src/dxf_write/header.rs | 4 ++ crates/io/src/dxf_write/layout.rs | 16 ++++--- crates/io/src/tests.rs | 69 ++++++++++++++++++++++++++++++ 7 files changed, 158 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/header.rs b/crates/doc/src/header.rs index c6f17fd7e..52b9d34b1 100644 --- a/crates/doc/src/header.rs +++ b/crates/doc/src/header.rs @@ -90,6 +90,23 @@ impl Header { .filter(|p| p.is_finite() && if allow_zero { p.x >= 0.0 && p.y >= 0.0 } else { p.x > 0.0 && p.y > 0.0 }) .unwrap_or(Vec2::new(0.5, 0.5)) } + /// The model view the drawing was saved at: `$VIEWCTR` (centre) and `$VIEWSIZE` (height, in + /// drawing units), when both are present and usable. A DXF file keeps the pair in HEADER and + /// repeats it in the `*ACTIVE` VPORT record (12/22 and 40); a reader opens the drawing on it + /// rather than on the extents, so a drawing saved on one detail of a large sheet opens there. + pub fn saved_view(&self) -> Option<(Vec2, f64)> { + let center = self.point("VIEWCTR")?.xy(); + let height = self.get("VIEWSIZE").and_then(HVal::as_f64)?; + (center.is_finite() && height.is_finite() && height > 1e-9).then_some((center, height)) + } + /// Record the view the drawing is saved at (see [`Header::saved_view`]). A view that cannot + /// be shown is not recorded, so a usable stored view is never replaced by an unusable one. + pub fn set_saved_view(&mut self, center: Vec2, height: f64) { + if center.is_finite() && height.is_finite() && height > 1e-9 { + self.set("VIEWCTR", HVal::Point(center.to3(0.0))); + self.set_f64("VIEWSIZE", height); + } + } pub fn set_f64(&mut self, name: &str, v: f64) { self.set(name, HVal::Real(v)); } diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 95d439f8c..cf0f8a8c2 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -1,5 +1,10 @@ use super::{DocState, Drawing, EngineError, Result, Session, Space, Value, Vec2, View, cmd}; +/// Whether a stored view can be used: a drawing can record a degenerate or non-finite one. +fn usable_view(v: &View) -> bool { + v.center.is_finite() && v.height.is_finite() && v.height > 1e-12 +} + impl Session { /// Append a new untitled drawing (`DrawingN`, metric or imperial default view), end a running command, make it active, bump the document epoch and return its index. pub fn new_drawing(&mut self, metric: bool) -> usize { @@ -17,8 +22,15 @@ impl Session { /// Append a loaded drawing, fit the view to its model extents (aspect-corrected, minimum height 1e-6) when non-empty, end a running command, make it active, bump the epoch and return its index. pub fn open_drawing(&mut self, d: Drawing, title: &str, path: Option) -> usize { let mut st = DocState::new(d, title, path); + // The view the file was saved at is the one every other reader opens on. Fitting the + // extents instead showed a drawing whose extents are dominated by far-off geometry at a + // view hundreds of times its content, with the drawing sub-pixel and no way to zoom in + // (#1602). The extents remain the fallback for a drawing that stores no view. + let saved = st.doc.header.saved_view().map(|(center, height)| View { center, height }).filter(usable_view); let ext = st.doc.extents(&Space::Model); - if !ext.is_empty() { + if let Some(v) = saved { + st.set_view_quiet(v); + } else if !ext.is_empty() { st.set_view_quiet(View { center: ext.center(), height: (ext.height().max(ext.width() * self.viewport_px.1 / self.viewport_px.0.max(1.0)) * 1.1).max(1e-6), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8c590dd97..0a77680dc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -179,6 +179,40 @@ fn json_execute_and_errors() { assert_eq!(s.state().unwrap().undo.len(), 1); } +/// A drawing is opened on the view it was saved at, as every other reader opens it. Fitting the +/// extents instead showed a drawing whose extents are dominated by far-off geometry at a view +/// hundreds of thousands of times its content: sub-pixel, and `ZOOM Extents` fits the same box +/// (#1602). The extents are still the fallback for a drawing that stores no view. +#[test] +fn a_drawing_opens_on_the_view_it_was_saved_at() { + let mut d = cadcraft_doc::Drawing::new_metric(); + for (a, b) in [([0.0, 0.0], [100.0, 60.0]), ([5e6, 5e6], [5e6 + 100.0, 5e6 + 60.0])] { + let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(a[0], a[1], 0.0), b: cadcraft_geom::Vec3::new(b[0], b[1], 0.0) }; + d.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + } + d.header.set_saved_view(Vec2::new(50.0, 50.0), 20.0); + + let mut s = Session::new(); + s.open_drawing(d.clone(), "saved-view.dxf", None); + assert_eq!(s.state().unwrap().view(), View { center: Vec2::new(50.0, 50.0), height: 20.0 }); + + // No stored view: the extents, as before. They are what makes this drawing unusable without + // the stored one -- the fit is more than a hundred thousand times taller than the detail. + let mut plain = d.clone(); + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + let mut s = Session::new(); + s.open_drawing(plain, "no-view.dxf", None); + assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); + + // A stored view that cannot be shown is no view at all. + let mut broken = d; + broken.header.set("VIEWSIZE", cadcraft_doc::HVal::Real(0.0)); + let mut s = Session::new(); + s.open_drawing(broken, "broken-view.dxf", None); + assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); +} + #[test] fn move_with_pickfirst_and_window_selection() { let mut s = Session::new(); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 8a57f7f9e..001944b86 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -276,7 +276,8 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { _ => {} } } - // One *Active viewport is no tiling: the view is the editor's (it zooms to the extents). + // One *Active viewport is no tiling: its single tile is not a configuration to switch to. + // Its view was kept in the HEADER pair as it was read (see `vport_record`). d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active())); } @@ -315,6 +316,12 @@ const MAX_VPORT_TILES: usize = 64; fn vport_record(d: &mut Drawing, t: &T) { let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default(); let (min, max, center) = (t.p(10).xy(), t.p(11).xy(), t.p(12).xy()); + // A modern file keeps the view it was saved at in the first `*ACTIVE` record (12/22 centre, + // 40 height) as well as in the HEADER pair, and as with the snap and grid spacing the record + // is the newer of the two and wins (#1602). A record that leaves the centre out has no view + // to give -- `p` reads a missing coordinate as zero -- so the header pair stays. + let first_active = name.eq_ignore_ascii_case(VportConfig::ACTIVE) && !d.vports.iter().any(|c| c.is_active()); + let centred = t.f(12).is_some() && t.f(22).is_some(); let height = t.fd(40, 0.0); let unit = |v: f64| v.is_finite() && (-1e-9..=1.0 + 1e-9).contains(&v); let ok = [min.x, min.y, max.x, max.y].into_iter().all(unit) @@ -326,6 +333,9 @@ fn vport_record(d: &mut Drawing, t: &T) { if name.is_empty() || !ok { return; } + if first_active && centred { + d.header.set_saved_view(center, height); + } let aspect = t.f(41).filter(|a| a.is_finite() && *a > 0.0).unwrap_or(0.0); let clamp = |p: Vec2| Vec2::new(p.x.clamp(0.0, 1.0), p.y.clamp(0.0, 1.0)); let tile = VportTile { min: clamp(min), max: clamp(max), center, height, aspect }; diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index b628a5c3d..6a9c63032 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -44,6 +44,10 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("INSUNITS", 70), ("MEASUREMENT", 70), ("PSLTSCALE", 70), + // The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT + // record below repeats it). Written so a drawing opened on its saved view saves it back. + ("VIEWCTR", -2), + ("VIEWSIZE", 40), ]; /// The current dimension style's variables as header variables (`$DIMTXT`, `$DIMDEC`…), after diff --git a/crates/io/src/dxf_write/layout.rs b/crates/io/src/dxf_write/layout.rs index 4ad19ffbb..7384fb766 100644 --- a/crates/io/src/dxf_write/layout.rs +++ b/crates/io/src/dxf_write/layout.rs @@ -63,13 +63,17 @@ pub(super) fn paper_view(w: &mut W, d: &Drawing, e: &Entity, owner: &str, cx: &C /// The VPORT table: the `*Active` model space tiles (one viewport on the extents when there is no /// tiled configuration) and the saved configurations, each tile a record, the current one first. pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) { - let single = VportTile { - min: Vec2::ZERO, - max: Vec2::new(1.0, 1.0), - center: if ext.is_empty() { Vec2::new(6.0, 4.5) } else { ext.center() }, - height: if ext.is_empty() { 9.0 } else { (ext.height() * 1.1).max(1e-6) }, - aspect: 1.6, + // The view the drawing is saved at, so that reading a drawing and writing it back keeps it; + // a drawing that stores none is written on its extents. The fallback fits the width as well, + // through the aspect the record is written with: a drawing 100 wide and 10 tall otherwise got + // a view 11 tall, which shows a sliver of it, and a horizontal line got 1e-6 (#1602). + const ASPECT: f64 = 1.6; + let (center, height) = match d.header.saved_view() { + Some(v) => v, + None if ext.is_empty() => (Vec2::new(6.0, 4.5), 9.0), + None => (ext.center(), (ext.height().max(ext.width() / ASPECT) * 1.1).max(1e-6)), }; + let single = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center, height, aspect: ASPECT }; let tiled = d.vports.iter().find(|c| c.is_active() && c.tiles.len() > 1); let mut records: Vec<(&str, &VportTile)> = match tiled { Some(c) => c.tiles.iter().map(|t| (VportConfig::ACTIVE, t)).collect(), diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 977a7c184..230c202f7 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -518,6 +518,75 @@ fn pdf_hostile_options_and_empty() { } } +/// The view a drawing was saved at is the `*ACTIVE` VPORT record's centre and height, repeated in +/// the `$VIEWCTR`/`$VIEWSIZE` header pair. It used to be dropped on read and replaced on write by +/// a fit of the geometry extents, so a drawing with far-off geometry opened hundreds of times too +/// far out, and a conversion replaced wherever the drawing had been left (#1602). +#[test] +fn dxf_keeps_the_view_the_drawing_was_saved_at() { + const SAVED: &str = "\ +0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1027\n9\n$VIEWCTR\n10\n50.0\n20\n50.0\n30\n0.0\n9\n$VIEWSIZE\n40\n20.0\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n\ +12\n50.0\n22\n50.0\n40\n20.0\n41\n1.5\n0\nENDTAB\n0\nENDSEC\n\ +0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n100.0\n21\n60.0\n31\n0.0\n\ +0\nLINE\n8\n0\n10\n5000000.0\n20\n5000000.0\n30\n0.0\n11\n5000100.0\n21\n5000060.0\n31\n0.0\n0\nENDSEC\n0\nEOF\n"; + + // The stored view survives the read, far-away geometry and all: the extents here are + // 5 000 100 x 5 000 060, a fit of which is 275 000 times the height the drawing was saved at. + let d = read_dxf(SAVED.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0))); + assert!(d.extents(&Space::Model).max.x > 5e6, "the far-off line is read too"); + + // And writing the drawing back keeps it, in both places a reader looks. + let text = write_dxf(&d); + let back = read_dxf(text.as_bytes()).unwrap(); + assert_eq!(back.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0))); + let active = text.replace("\r\n", "\n"); + let active = active.split("*Active").nth(1).unwrap_or_default(); + for group in ["\n 12\n50", "\n 22\n50", "\n 40\n20"] { + assert!(active.contains(group), "the *ACTIVE record keeps {group:?}: {}", &active[..active.len().min(400)]); + } + + // A drawing that stores no view is still written on its extents. + let mut plain = d.clone(); + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + assert_eq!(plain.header.saved_view(), None); + let fitted = read_dxf(write_dxf(&plain).as_bytes()).unwrap(); + let (center, height) = fitted.header.saved_view().unwrap(); + assert!(center.x > 2.4e6 && height > 5e6, "the extents fit: {center:?} {height}"); + + // That fit covers the width as well: a wide, flat drawing opened on its height alone would + // show a sliver of it, and a drawing with no height at all would have no view. + let mut wide = cadcraft_doc::Drawing::new_metric(); + for (a, b) in [([0.0, 0.0], [100.0, 10.0]), ([0.0, 10.0], [100.0, 10.0])] { + let line = cadcraft_doc::Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }; + wide.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + } + let back = read_dxf(write_dxf(&wide).as_bytes()).unwrap(); + let (_, height) = back.header.saved_view().unwrap(); + assert!(height > 60.0, "a 100 x 10 drawing needs more than its height: {height}"); + + let mut flat = cadcraft_doc::Drawing::new_metric(); + let line = cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(100.0, 0.0, 0.0) }; + flat.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + let back = read_dxf(write_dxf(&flat).as_bytes()).unwrap(); + let (_, height) = back.header.saved_view().unwrap(); + assert!(height > 60.0, "a horizontal line needs a view with width in it: {height}"); +} + +/// A `*ACTIVE` record that leaves its view centre out (no 12/22) is not a view: `$VIEWCTR` and +/// `$VIEWSIZE` stay, rather than being replaced by the zero the missing groups read as. +#[test] +fn a_viewport_record_without_a_centre_keeps_the_header_view() { + const NO_CENTRE: &str = "\ +0\nSECTION\n2\nHEADER\n9\n$VIEWCTR\n10\n50.0\n20\n50.0\n9\n$VIEWSIZE\n40\n20.0\n0\nENDSEC\n\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n\ +40\n99.0\n0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n11\n9.0\n21\n9.0\n0\nENDSEC\n0\nEOF\n"; + let d = read_dxf(NO_CENTRE.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the header pair is kept"); +} + #[test] fn dxf_roundtrips_page_setup() { let mut d = sample(); From 1e02e6f2630e8af40c002dc66f8f1b8941065810 Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Wed, 28 Oct 2026 10:10:04 -0600 Subject: [PATCH 039/185] 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 b5f0890b95dcda79ab4f8e27ac017ab96da4a52a Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Thu, 29 Oct 2026 00:58:26 +0400 Subject: [PATCH 040/185] 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 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 041/185] 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 042/185] 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 043/185] 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 044/185] 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 045/185] 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 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 046/185] 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 047/185] 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 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 048/185] fix(dwg): scan the bridge header in one pass; leave out proxies of a binary DXF header_value kept an offset for every line up to the first ENDSEC: an input without one cost about 24 bytes per line (0.8 GB for 32 MiB of short lines, some 25 GB at the 1 GiB input limit). It now reads (group code, value) pairs in one pass and stops at 0/ENDSEC, so memory no longer grows with the input (36 MB for the same 32 MiB, the input itself). dxf_class_names doesn't read a binary DXF's CLASSES, so its proxies kept their DXF numbers, which name other classes in the DWG. CADCraft's own bridge is always ASCII; for a binary DXF given to the conversion functions, the proxies are now left out, as a pre-2013 DWG leaves them, instead of naming the wrong classes. Both reported by CodeRabbit on #2471. --- crates/dwg/src/lib.rs | 109 +++++++++++++++++++++++++---------------- crates/io/src/tests.rs | 20 ++++++++ 2 files changed, 88 insertions(+), 41 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index ce4133569..cd260baa4 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -588,22 +588,28 @@ mod native { } /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value - /// line after the group code that follows the `9` group naming it. Only the HEADER section - /// (up to the first `ENDSEC`) is searched; lines may end in `\r\n`. + /// of the group that follows the `9` group naming it. The file is read as (group code, + /// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end + /// of the HEADER section: a large input without one costs time, not memory (a line index of + /// a 32 MiB file used 0.8 GB). Lines may end in `\r\n`. fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> { - let mut lines: Vec<(usize, &[u8])> = Vec::new(); let mut offset = 0usize; - for line in dxf.split(|b| *b == b'\n') { - let trimmed = line.trim_ascii(); - let lead = line.len() - line.trim_ascii_start().len(); - lines.push((offset.saturating_add(lead), trimmed)); + let mut lines = dxf.split(|b| *b == b'\n').map(|line| { + let at = offset.saturating_add(line.len() - line.trim_ascii_start().len()); offset = offset.saturating_add(line.len()).saturating_add(1); - if trimmed == b"ENDSEC" { - break; + (at, line.trim_ascii()) + }); + while let (Some((_, code)), Some((_, value))) = (lines.next(), lines.next()) { + if code == b"0" && value == b"ENDSEC" { + return None; + } + if code == b"9" && value == name { + let (_, code) = lines.next()?; + let (at, value) = lines.next()?; + return (code != b"0" && code != b"9").then_some((at, value)); } } - let at = lines.windows(2).position(|w| w[0].1 == b"9" && w[1].1 == name)?; - lines.get(at.checked_add(3)?).copied() + None } /// The current dimension and text styles' names from their handles: a DWG stores the @@ -642,11 +648,13 @@ mod native { /// The DXF names of an ASCII DXF's CLASS records, in CLASSES order: a proxy's class number /// (group 91) is 500 plus its class's place here (DXF Reference, ACAD_PROXY_OBJECT). Empty for - /// a binary DXF or one without a CLASSES section. - pub(super) fn dxf_class_names(dxf: &[u8]) -> Vec { + /// one without a CLASSES section. `None` for a binary DXF, whose classes this doesn't read: + /// CADCraft's own bridge DXF is always ASCII, and only a binary DXF given to the public + /// conversion functions comes here. + pub(super) fn dxf_class_names(dxf: &[u8]) -> Option> { let mut names = Vec::new(); if dxf.starts_with(b"AutoCAD Binary DXF") { - return names; + return None; } let mut lines = dxf.split(|b| *b == b'\n').map(|l| l.trim_ascii()); let (mut in_classes, mut in_class) = (false, false); @@ -662,7 +670,7 @@ mod native { _ => {} } } - names + Some(names) } /// Proxy objects' and entities' class numbers as the DWG numbers its classes. A DXF proxy @@ -676,28 +684,33 @@ mod native { /// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses /// the file: "No ClassId") or, by its old number, some other class. Such a DWG leaves the /// proxies out instead, as it does other programs' data it can't write (`not_saved` reports - /// the entities). Returns how many proxies were left out. - fn proxy_classes(doc: &mut acadrust::CadDocument, classes: &[String]) -> usize { - if doc.version < acadrust::DxfVersion::AC1027 { - let entities: Vec = doc - .entities() - .filter_map(|e| match e { - acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { - Some(x.common.handle) - } - _ => None, - }) - .collect(); - let objects: Vec = - doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); - for h in &entities { - doc.remove_entity(*h); + /// the entities). So does a DXF whose classes are unknown (`classes` is `None`, a binary + /// DXF): its proxies' numbers can't be mapped, and kept as they are they would name the + /// wrong classes and the ODA would refuse the file. Returns how many proxies were left out. + fn proxy_classes(doc: &mut acadrust::CadDocument, classes: Option<&[String]>) -> usize { + let classes = match classes { + Some(c) if doc.version >= acadrust::DxfVersion::AC1027 => c, + _ => { + let entities: Vec = doc + .entities() + .filter_map(|e| match e { + acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => { + Some(x.common.handle) + } + _ => None, + }) + .collect(); + let objects: Vec = + doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect(); + for h in &entities { + doc.remove_entity(*h); + } + for h in &objects { + doc.objects.remove(h); + } + return entities.len() + objects.len(); } - for h in &objects { - doc.objects.remove(h); - } - return entities.len() + objects.len(); - } + }; let number = |id: i32| -> Option { let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) @@ -737,7 +750,6 @@ mod native { 0 } - /// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG /// stores the handle of the layer, and the one read with the DXF needn't be the layer's in /// the document, so the drawing reopened with layer "0" current (#2252). @@ -789,7 +801,7 @@ mod native { // The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash. guarded(AssertUnwindSafe(|| { super::fail_in_test("convert"); - proxy_classes(&mut doc, &classes); + proxy_classes(&mut doc, classes.as_deref()); other_layout_owners(&mut doc); table_style_rows(&mut doc, true); dimension_flags(&mut doc); @@ -1286,6 +1298,21 @@ mod tests { } /// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER` + /// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER` + /// name whose value would come after it, or a file that never ends its HEADER, is no version + /// to replace, and `\r\n` lines keep the value's offset right. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn declare_version_reads_the_header_in_pairs_up_to_endsec() { + let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n"; + assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None); + let endless = vec![b'\n'; 1 << 20]; + assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None); + let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n"; + let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap(); + assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n"); + } + /// are read as they are. #[cfg(not(target_arch = "wasm32"))] #[test] @@ -1338,8 +1365,8 @@ mod tests { #[test] fn dxf_class_names_in_classes_order() { let dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nWIDGETA\r\n 2\r\nAcDbWidgetA\r\n 3\r\nApp\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 2\r\nAcDbWidgetB\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\nNOT_A_CLASS\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; - assert_eq!(native::dxf_class_names(dxf), ["WIDGETA", "WIDGETB"]); - assert!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n").is_empty()); - assert!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0").is_empty()); + assert_eq!(native::dxf_class_names(dxf).unwrap(), ["WIDGETA", "WIDGETB"]); + assert_eq!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n"), Some(Vec::new())); + assert_eq!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0"), None); } } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index ec29cc0fa..7ffd02398 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -2858,6 +2858,26 @@ fn proxies_keep_their_class_in_dwg() { } } +/// A binary DXF given to the DWG conversion directly: its CLASSES aren't read, so the proxies' +/// numbers can't be mapped to the DWG's classes. Kept as they were, they named other classes +/// (the ODA refuses such a file), so the DWG leaves them out, as a pre-2013 DWG does, and the +/// rest of the drawing is written. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_binary_dxf_leaves_its_proxies_out_of_the_dwg() { + use acadrust::entities::{EntityType, ExtendedEntityData}; + use acadrust::objects::ObjectType; + let d = read(&proxy_file(), "p.dxf").unwrap(); + let binary = write_with(&d, "p.dxf", &SaveOptions { version: Some(Version::R2018), binary: true }).unwrap(); + assert!(binary.starts_with(b"AutoCAD Binary DXF")); + let dwg = cadcraft_dwg::dxf_to_dwg_as(&binary, "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let proxies = doc.objects.values().filter(|o| matches!(o, ObjectType::ProxyObject(_))).count() + + doc.entities().filter(|e| matches!(e, EntityType::Extended(x) if matches!(x.data, ExtendedEntityData::Proxy(_)))).count(); + assert_eq!(proxies, 0, "no proxy with an unmapped class number"); + assert!(doc.layers.get("0").is_some(), "the drawing itself is written"); +} + /// A name that isn't valid Unicode still picks its format by extension. #[cfg(unix)] #[test] From cef9ee4b10ee899d9561fe985a579b71899e2231 Mon Sep 17 00:00:00 2001 From: ffishman <20211677+ffishman@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:42:40 -0300 Subject: [PATCH 049/185] 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 050/185] fix(io): take the kept groups' version from the file's own HEADER A new drawing starts with $ACADVER AC1032, and the reader applies the file's header over it, so a file without $ACADVER left AC1032 in Foreign::version and the bridge read its kept groups with 2018 rules. The version now comes from the file's HEADER section, and is None when the file has no $ACADVER (the bridge then reads the kept groups as R2000, as before). Reported by CodeRabbit on #2471. --- crates/io/src/dxf_raw.rs | 12 +++++++++++- crates/io/tests/dwg_kept_object_versions.rs | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 9f6718c08..7857d3be3 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -452,11 +452,21 @@ pub(crate) fn read(secs: &[Section], d: &mut Drawing) { f.data_store = ds.tags.iter().take(MAX_DATA_STORE_GROUPS).map(raw).collect(); } if !f.is_empty() { - f.version = d.header.get("ACADVER").and_then(cadcraft_doc::HVal::as_str).map(str::to_string); + f.version = file_version(secs); d.foreign = Arc::new(f); } } +/// The `$ACADVER` the file's own HEADER section declares, if it does. Not the drawing's: a new +/// drawing starts as AC1032, and a file without the variable would leave that default there. +fn file_version(secs: &[Section]) -> Option { + let header = secs.iter().find(|s| s.name.eq_ignore_ascii_case("HEADER"))?; + let at = header.tags.iter().position(|t| t.code == 9 && t.str().trim().eq_ignore_ascii_case("$ACADVER"))?; + let value = header.tags.get(at + 1).filter(|t| t.code != 9)?.str(); + let value = value.trim(); + (!value.is_empty()).then(|| value.to_string()) +} + fn entity_types(drawing: &Drawing) -> HashMap { let mut types = HashMap::new(); for entity in all_entities(drawing) { diff --git a/crates/io/tests/dwg_kept_object_versions.rs b/crates/io/tests/dwg_kept_object_versions.rs index 8d03c1d75..787470705 100644 --- a/crates/io/tests/dwg_kept_object_versions.rs +++ b/crates/io/tests/dwg_kept_object_versions.rs @@ -260,6 +260,20 @@ fn kept_groups_keep_their_version_across_saves() { } } +/// A DXF without `$ACADVER` has no version for its kept groups: the drawing's own `$ACADVER` +/// is then the default a new drawing starts with (AC1032), which says nothing about the file, so +/// the kept groups are read as the bridge's R2000, as before. +#[test] +fn a_file_without_acadver_records_no_version() { + let dxf = synthetic("AC1032").replacen(" 9\r\n$ACADVER\r\n 1\r\nAC1032\r\n", "", 1); + assert!(!dxf.contains("$ACADVER")); + let d = read(dxf.as_bytes(), "kept.dxf").unwrap(); + assert!(!d.foreign.objects.is_empty(), "the render settings and the field are kept"); + assert_eq!(d.foreign.version, None); + let with = read(synthetic("AC1032").as_bytes(), "kept.dxf").unwrap(); + assert_eq!(with.foreign.version.as_deref(), Some("AC1032")); +} + #[test] fn a_2018_files_kept_objects_reach_a_2018_dwg() { kept_objects_survive("AC1032", Version::R2018); From 66f65b763e579502ca61cf8e913d8e2f263487ba Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 31 Oct 2026 04:38:42 +0400 Subject: [PATCH 051/185] 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 052/185] docs: Greek and Bosnian in the language lists; Georgian on the web comes with #1971 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- README.md | 2 +- docs/localization-parity.md | 2 +- docs/localization.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1752ac3a4..078c53511 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ numbers): | Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF | | Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit | | Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror | -| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | +| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) | | Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) | ## Quick start diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 637a156f2..884cc3389 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -73,7 +73,7 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | -| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release and web builds; English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | +| Georgian | ka | 1,383 catalog rows (1,377 ordinary, 4 menu, 2 count); the existing catalog union, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (ზომების დატანა / ზომა); command reference searchable in Georgian | Georgian (Mkhedruli): the craft-fonts Noto Sans Georgian (`Geor`) face, embedded in release builds (web builds too once #1971 adds it to the web faces); English fallback without it; Mtavruli never used (tested) | Written with Claude Code from the meaning of each English string; terminology and doubtful strings decided by a native Georgian speaker (@devius) | complete current catalog; English-only interface gaps remain | shared English-only UI work | | Turkish | tr | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings (Ölçülendirme / Ölçü); command reference searchable in Turkish | Latin: yes (bundled egui proportional and monospace fonts; Ç Ğ İ Ö Ş Ü ç ğ ı ö ş ü tested) | AI-assisted by @ogzhnklvz, written from the English strings with Turkish desktop-CAD vocabulary; the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Bosnian | bs | 1,442 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes | Latin: yes (bundled egui fonts) | AI-assisted; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | diff --git a/docs/localization.md b/docs/localization.md index 3e8090993..a916c00e6 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -1,7 +1,7 @@ # Interface languages Choose **Edit → Interface Language** and select **Auto (system language)**, **English**, -**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), or **ქართული** (Georgian). +**Українська**, **Português (Brasil)**, **Deutsch**, **Español**, **Čeština** (Czech), **Русский**, **Français**, **简体中文**, **Italiano**, **한국어** (Korean), **Svenska** (Swedish), **العربية** (Arabic), **Magyar** (Hungarian), **Türkçe** (Turkish), **Ελληνικά** (Greek), **Bosanski** (Bosnian), or **ქართული** (Georgian). The interface updates without restarting, including the native macOS menus. The choice is saved with the other interface preferences (`cadcraft.prefs`, beside the theme): eframe storage on the desktop, browser local storage on the web. Installations without a saved From 5f6dbede5ca24082119edf164286b500519e7cea Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 31 Oct 2026 06:00:43 +0400 Subject: [PATCH 053/185] 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 4caf26ee60346262fedfe269b62e56f21754edd5 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:27:48 +1100 Subject: [PATCH 054/185] 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 055/185] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 53ffffc96..f842c51a9 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,10 +1,10 @@ # Parity checklist -> **Generated:** 2026-10-30 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-10-31 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. -**Menu breadth: 298 / 491 items (61%)** · 444 registered commands. +**Menu breadth: 298 / 491 items (61%)** · 446 registered commands. | Menu | Items | Covered | % | |---|---|---|---| From 74ddfb377fb2f2b1c093b58d9589b820e32d66be Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sat, 31 Oct 2026 14:49:13 +1100 Subject: [PATCH 056/185] 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 057/185] CLI: an OLE2FRAME is not reported as undrawn by an image export (#2422) Found end to end: convert to PNG drew the frame outline but still said '1 entity not drawn (OLE2FRAME: 1)'. --- apps/cadcraft-cli/src/output.rs | 5 ++++- apps/cadcraft-cli/tests/it/undrawn_entities.rs | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/cadcraft-cli/src/output.rs b/apps/cadcraft-cli/src/output.rs index d783267dc..d7471e7b1 100644 --- a/apps/cadcraft-cli/src/output.rs +++ b/apps/cadcraft-cli/src/output.rs @@ -151,7 +151,10 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option, io pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option { let mut types: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); for e in d.model.iter() { - if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind { + // An OLE2FRAME's frame outline is drawn (the OLE content is not), so it isn't reported. + if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind + && !u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") + { let n = types.entry(u.dxf_type.as_str()).or_insert(0); *n = n.saturating_add(1); } diff --git a/apps/cadcraft-cli/tests/it/undrawn_entities.rs b/apps/cadcraft-cli/tests/it/undrawn_entities.rs index 7e7189379..bf626a7d5 100644 --- a/apps/cadcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/cadcraft-cli/tests/it/undrawn_entities.rs @@ -51,3 +51,17 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() { assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); let _ = std::fs::remove_dir_all(&dir); } + +/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it undrawn (#2422). +#[test] +fn an_ole_frame_is_not_reported_as_undrawn() { + let dir = std::env::temp_dir().join(format!("cc-cli-ole-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let input = dir.join("ole.dxf"); + let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n11\n5\n21\n-3\n31\n0\n0\nENDSEC\n0\nEOF\n"; + std::fs::write(&input, ole).unwrap(); + let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]); + assert!(out.status.success()); + assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr)); + let _ = std::fs::remove_dir_all(&dir); +} From c223550cb355fbe481cd959c35dc42edf58dd64e Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:44:17 +0100 Subject: [PATCH 058/185] 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 059/185] 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 060/185] 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 061/185] 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 062/185] 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 62e70432e7f5f46a6d7f88373d70877c0426c487 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 11:05:33 +1100 Subject: [PATCH 063/185] 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 064/185] 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 065/185] 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 c22700d3aff6c3f8939e337404abc7ef2f6e5e60 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 15:27:09 +1100 Subject: [PATCH 066/185] 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 067/185] 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 068/185] 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 069/185] 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 070/185] Parity checklist: regenerated after merging main --- docs/parity-checklist.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index f842c51a9..5fb179f5a 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Parity checklist -> **Generated:** 2026-10-31 by `cargo xtask parity`. Do not edit by hand. +> **Generated:** 2026-11-01 by `cargo xtask parity`. Do not edit by hand. Menu-breadth parity: a reference menu item counts as covered when a CADCraft command is registered under the same menu label. It measures breadth, not depth; see [target-app-parity.md](target-app-parity.md) for the weighted assessment. From 8dc927e01c8b8c860b09c1fd6d7d82f2b2daf4cc Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 16:57:17 +1100 Subject: [PATCH 071/185] 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 072/185] 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 073/185] OLE2FRAME: corners skip application groups; MOVE/COPY carry the frame, rotate/scale/mirror refuse it (review on #2587) ole_frame read 10/20 and 11/21 from inside 102 groups; it now skips them as the DXF reader does. A window-selected OLE2FRAME was left in place by MOVE/COPY. A DWG save writes the position from the corner groups (checked by write + read-back), so MOVE/COPY now shift them; transforms that would not keep it axis aligned return an error before anything changes. --- crates/doc/src/entity.rs | 1 + crates/doc/src/extents.rs | 75 +++++++++++++++++++++- crates/doc/src/lib.rs | 2 +- crates/engine/src/cmd/modify/transform.rs | 11 ++++ crates/engine/tests/ole_frame_transform.rs | 57 ++++++++++++++++ crates/io/tests/it/ole_frame.rs | 15 +++++ 6 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 crates/engine/tests/ole_frame_transform.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index d13b82722..a32fb820a 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -461,6 +461,7 @@ impl EntityKind { let a = if mirror { t.rotation() } else { t.rotation() + rot }; t.dir = Vec2::from_angle(cadcraft_geom::norm_angle(a)).to3(0.0); } + EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME") => crate::ole_frame_transform(&mut u.tags, m), EntityKind::Unknown(_) => {} } } diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index fbbb4824a..4bbdf3cf9 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -9,14 +9,63 @@ use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim}; /// Nested block references deeper than this are ignored (cyclic or hostile files). pub const MAX_BLOCK_DEPTH: usize = 16; +/// Positions in `tags` of the groups outside application-defined `102 {` .. `102 }` groups, whose +/// codes are the application's own and not the entity's. +fn outside_app(tags: &[crate::RawTag]) -> Vec { + let mut in_app = false; + let mut out = Vec::new(); + for (i, t) in tags.iter().enumerate() { + if t.code == 102 { + in_app = t.value.starts_with('{'); + } else if !in_app { + out.push(i); + } + } + out +} + +/// The positions of the frame's corner groups 10, 20, 11, 21 (in that order) and their values. +fn ole_corner_groups(tags: &[crate::RawTag]) -> Option<[(usize, f64); 4]> { + let own = outside_app(tags); + let find = |code: i32| { + let i = own.iter().copied().find(|&i| tags.get(i).is_some_and(|t| t.code == code))?; + let v = tags.get(i)?.value.trim().parse::().ok().filter(|v| v.is_finite())?; + Some((i, v)) + }; + Some([find(10)?, find(20)?, find(11)?, find(21)?]) +} + /// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right /// (groups 11, 21) corners (DXF Reference, OLE2FRAME); `None` when either is missing or not finite. pub fn ole_frame(tags: &[crate::RawTag]) -> Option<[Vec2; 5]> { - let get = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()); - let (a, b) = (Vec2::new(get(10)?, get(20)?), Vec2::new(get(11)?, get(21)?)); + let [(_, x1), (_, y1), (_, x2), (_, y2)] = ole_corner_groups(tags)?; + let (a, b) = (Vec2::new(x1, y1), Vec2::new(x2, y2)); Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a]) } +/// Move an OLE2FRAME by `m`, a translation: its two corners are mapped through `m` (a DWG save +/// writes the frame's position from these groups). Other transforms do not keep a frame axis +/// aligned, so callers refuse them (see [`ole_frame_accepts`]). A frame with no usable corners is +/// left alone. +pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) { + let Some([(ix1, x1), (iy1, y1), (ix2, x2), (iy2, y2)]) = ole_corner_groups(tags) else { return }; + let (a, b) = (m.apply(Vec2::new(x1, y1)), m.apply(Vec2::new(x2, y2))); + if !(a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { + return; + } + for (i, v) in [(ix1, a.x), (iy1, a.y), (ix2, b.x), (iy2, b.y)] { + if let Some(t) = tags.get_mut(i) { + t.value = v.to_string(); + } + } +} + +/// Whether `m` can move an OLE2FRAME: only a translation (move, copy, stretch of the whole frame). +pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool { + const T: f64 = 1e-12; + (m.a - 1.0).abs() < T && m.b.abs() < T && m.c.abs() < T && (m.d - 1.0).abs() < T +} + /// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification /// the same way the renderer places it (the stroke font is about 0.88 of the height per character). fn text_box(t: &crate::Text, len: usize) -> Bounds2 { @@ -461,4 +510,26 @@ mod tests { assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty()); assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty()); } + + /// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not + /// to the frame: the real corners come after it (review on #2587). + #[test] + fn ole_frame_skips_application_groups() { + let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() }; + let tags = vec![ + tag(102, "{ACAD_REACTORS"), + tag(10, "900"), + tag(20, "900"), + tag(11, "901"), + tag(21, "901"), + tag(102, "}"), + tag(10, "30"), + tag(20, "-19"), + tag(11, "35"), + tag(21, "-22"), + ]; + let q = ole_frame(&tags).expect("frame"); + assert_eq!((q[0], q[2]), (Vec2::new(30.0, -19.0), Vec2::new(35.0, -22.0))); + assert!(ole_frame(&tags[..6]).is_none(), "corners only inside the group are not a frame"); + } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 55169219f..748f2c9e8 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -27,7 +27,7 @@ pub use cadcraft_color as color; pub use cadcraft_geom as geom; pub use constraint::*; pub use entity::*; -pub use extents::{MAX_BLOCK_DEPTH, entity_bounds, extent_bounds, ole_frame}; +pub use extents::{MAX_BLOCK_DEPTH, entity_bounds, extent_bounds, ole_frame, ole_frame_accepts, ole_frame_transform}; pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 5a86d9e07..c4a507262 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -4,6 +4,17 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, f6 pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { let d = s.doc_mut()?; + // An OLE2FRAME only translates (its corners stay axis aligned); refuse the rest before anything + // changes, instead of reporting success and leaving the frame where it was. + if !cadcraft_doc::ole_frame_accepts(m) + && hs.iter().any(|h| { + d.entity(*h).is_some_and(|e| matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.dxf_type.eq_ignore_ascii_case("OLE2FRAME"))) + }) + { + return Err(crate::EngineError::Other( + "An OLE object can only be moved or copied; rotating, scaling and mirroring it are not supported.".into(), + )); + } let mut out = Vec::new(); for h in hs { let Some(sp) = d.space_of(*h) else { continue }; diff --git a/crates/engine/tests/ole_frame_transform.rs b/crates/engine/tests/ole_frame_transform.rs new file mode 100644 index 000000000..0c0fade22 --- /dev/null +++ b/crates/engine/tests/ole_frame_transform.rs @@ -0,0 +1,57 @@ +//! An OLE2FRAME is window-selectable (it counts in the extents, #2422): MOVE and COPY carry it by +//! the offset, and the transforms that would not keep it axis aligned are refused before anything +//! reports success (review on #2587). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Common, Drawing, EntityKind, RawTag, Space, Unknown}; +use serde_json::json; + +fn session() -> (Session, String) { + let tag = |code: i32, v: &str| RawTag { code, value: v.into() }; + let mut d = Drawing::new_imperial(); + let kind = + EntityKind::Unknown(Unknown { dxf_type: "OLE2FRAME".into(), tags: vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")] }); + let h = d.add(&Space::Model, Common::default(), kind).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "ole.dxf", None); + (s, h.hex()) +} + +fn corners(s: &Session) -> Vec<(i32, String)> { + let d = s.doc().unwrap(); + d.model + .iter() + .filter_map(|e| { + if let EntityKind::Unknown(u) = &e.kind { Some(u.tags.iter().map(|t| (t.code, t.value.clone())).collect::>()) } else { None } + }) + .flatten() + .collect() +} + +#[test] +fn move_and_copy_carry_an_ole_frame() { + let (mut s, h) = session(); + s.execute("move", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let want: Vec<(i32, String)> = [(10, "40"), (20, "-14"), (11, "45"), (21, "-17")].iter().map(|(c, v)| (*c, v.to_string())).collect(); + assert_eq!(corners(&s), want); + s.execute("copy", &json!({ "handles": [h], "delta": [10, 5] })).unwrap(); + let all = corners(&s); + assert_eq!(all.len(), 8); + assert_eq!(all[4..].iter().map(|(_, v)| v.as_str()).collect::>(), ["50", "-9", "55", "-12"]); +} + +#[test] +fn rotate_scale_and_mirror_refuse_an_ole_frame() { + let (mut s, h) = session(); + let before = corners(&s); + for (cmd, p) in [ + ("rotate", json!({ "handles": [h], "base": [0, 0], "angle": 30 })), + ("scale", json!({ "handles": [h], "base": [0, 0], "factor": 2 })), + ("mirror", json!({ "handles": [h], "p1": [0, 0], "p2": [1, 0] })), + ] { + let e = s.execute(cmd, &p).expect_err(cmd); + assert!(e.to_string().contains("OLE object"), "{cmd}: {e}"); + } + assert_eq!(corners(&s), before); + assert_eq!(s.doc().unwrap().model.len(), 1, "nothing was copied"); +} diff --git a/crates/io/tests/it/ole_frame.rs b/crates/io/tests/it/ole_frame.rs index c8c8c73a0..0ca0bc23e 100644 --- a/crates/io/tests/it/ole_frame.rs +++ b/crates/io/tests/it/ole_frame.rs @@ -60,3 +60,18 @@ fn a_dwg_keeps_an_ole_frame_with_its_data_and_position() { assert_eq!((corner(10), corner(20), corner(11), corner(21)), (Some(UL.0), Some(UL.1), Some(LR.0), Some(LR.1)), "{v:?}: frame corners"); } } + +/// A frame moved through its corner tags (what MOVE does) keeps the new position in a DWG save +/// and read-back (review on #2587). +#[test] +fn a_moved_ole_frame_keeps_its_position_in_a_dwg() { + let mut d = read_dxf(dxf().as_bytes()).unwrap(); + for h in d.model.handles() { + d.model.modify(h, |e| e.kind.transform(&cadcraft_geom::Mat3::translate(cadcraft_geom::Vec2::new(100.0, -50.0)))); + } + let dwg = write_with(&d, "x.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap(); + let u = ole(&read(&dwg, "x.dwg").unwrap()).unwrap(); + let c = |code: i32| u.tags.iter().find(|t| t.code == code).and_then(|t| t.value.trim().parse::().ok()).unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + assert!(near(c(10), UL.0 + 100.0) && near(c(20), UL.1 - 50.0) && near(c(11), LR.0 + 100.0) && near(c(21), LR.1 - 50.0), "{:?}", u.tags); +} From 09b5fb9328fbf706aa58aec54ba0277facf4aad2 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 1 Nov 2026 18:40:45 +1100 Subject: [PATCH 074/185] 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 075/185] 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 076/185] 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 077/185] 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 078/185] 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 079/185] 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 080/185] 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 081/185] 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 082/185] fix(ui): Properties palette tells values apart that the display rounds alike The shared values of several objects were compared as the text each row shows, so a text height of 7 and one of 7.000001 (both "7.0000") read as one common value. Numeric rows now carry the number they were formatted from and compare it to 12 significant digits, which separates anything the display could show at 8 decimals and ignores float noise. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/palettes.rs | 111 +++++++++++++++++++++++---------- 1 file changed, 78 insertions(+), 33 deletions(-) diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 2485e8a60..f6ef6e5a5 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -762,6 +762,22 @@ fn selection_memo(ui: &egui::Ui, app: &CadApp, sel: &[cadcraft_engine::doc::Hand memo } +/// Separates what a numeric row shows from the value it was worked out from, so that two objects +/// whose values differ by less than the display shows still count as different. The value is +/// compared to 12 significant digits, which keeps float noise (a length that comes out as +/// 5.000000000000001) from reading as a difference. +const EXACT_SEP: char = '\u{1f}'; + +/// `shown`, tagged with the number `v` it was formatted from. +fn exact(shown: String, v: f64) -> String { + format!("{shown}{EXACT_SEP}{:.11e}", v + 0.0) +} + +/// What a row shows of a value that [`exact`] tagged (a plain string is shown as it is). +fn shown_part(s: &str) -> String { + s.split(EXACT_SEP).next().unwrap_or_default().to_string() +} + /// Properties palette: the selection's common properties, or the current defaults when nothing is selected; formats lengths per drawing units and dispatches setter commands. pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -773,6 +789,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { // Lengths are shown as the drawing's units say (UNITS), and read back in any format. let (lu, lp) = (h.i64("LUNITS", 2), h.i64("LUPREC", 4)); let len = |v: f64| cadcraft_engine::units::format_distance(v, lu, lp); + let lenx = |v: f64| exact(len(v), v); let mut bad: Option = None; if sel.is_empty() { // Current properties for new objects; each row runs the command that sets it. @@ -1058,6 +1075,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); let real = |v: f64| format!("{v:.4}"); + let realx = |v: f64| exact(real(v), v); // Rotations show as the drawing measures directions (ANGBASE, ANGDIR). let angles = app.session.angle_settings(); let num = |ui: &mut egui::Ui, label: &str, key: &str, shown: String, set: &mut Option, bad: &mut Option, ids: &Vec| { @@ -1244,7 +1262,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }) .collect(); match vals.first() { - Some(v0) if vals.iter().all(|v| v == v0) => v0.clone(), + Some(v0) if vals.iter().all(|v| v == v0) => shown_part(v0), _ => VARIES.into(), } }) @@ -1262,9 +1280,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); let numbers = [ - ("Text height", "textHeight", shared("dim.text_height", &|_, st| len(st.text_height))), - ("Arrow size", "arrowSize", shared("dim.arrow_size", &|_, st| len(st.arrow_size))), - ("Dim scale overall", "dimScale", shared("dim.scale", &|_, st| real(st.scale))), + ("Text height", "textHeight", shared("dim.text_height", &|_, st| lenx(st.text_height))), + ("Arrow size", "arrowSize", shared("dim.arrow_size", &|_, st| lenx(st.arrow_size))), + ("Dim scale overall", "dimScale", shared("dim.scale", &|_, st| realx(st.scale))), ]; for (label, key, shown) in numbers { prop_row(ui, label, |ui| { @@ -1288,31 +1306,32 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { memo.get(key, || { let vals: Vec> = sel.iter().filter_map(|h| d.entity(*h)).map(|x| f(&x.kind)).collect(); match vals.first() { - Some(Some(v0)) if vals.iter().all(|v| v.as_ref() == Some(v0)) => v0.clone(), + Some(Some(v0)) if vals.iter().all(|v| v.as_ref() == Some(v0)) => shown_part(v0), _ => VARIES.into(), } }) }; let deg = |v: f64| real(angles.shown(v).to_degrees()); + let degx = |v: f64| exact(deg(v), angles.shown(v).to_degrees()); match &e.kind { EntityKind::Line(_) => { let line = |k: &EntityKind| if let EntityKind::Line(l) = k { Some(l.clone()) } else { None }; for (label, value) in [ - ("Start X", shared("line.ax", &|k| line(k).map(|l| len(l.a.x)))), - ("Start Y", shared("line.ay", &|k| line(k).map(|l| len(l.a.y)))), - ("End X", shared("line.bx", &|k| line(k).map(|l| len(l.b.x)))), - ("End Y", shared("line.by", &|k| line(k).map(|l| len(l.b.y)))), - ("Delta X", shared("line.dx", &|k| line(k).map(|l| len(l.b.x - l.a.x)))), - ("Delta Y", shared("line.dy", &|k| line(k).map(|l| len(l.b.y - l.a.y)))), + ("Start X", shared("line.ax", &|k| line(k).map(|l| lenx(l.a.x)))), + ("Start Y", shared("line.ay", &|k| line(k).map(|l| lenx(l.a.y)))), + ("End X", shared("line.bx", &|k| line(k).map(|l| lenx(l.b.x)))), + ("End Y", shared("line.by", &|k| line(k).map(|l| lenx(l.b.y)))), + ("Delta X", shared("line.dx", &|k| line(k).map(|l| lenx(l.b.x - l.a.x)))), + ("Delta Y", shared("line.dy", &|k| line(k).map(|l| lenx(l.b.y - l.a.y)))), ] { prop_row(ui, label, |ui| read_only(ui, &value)); } - num(ui, "Length", "length", shared("line.length", &|k| line(k).map(|l| len((l.b.xy() - l.a.xy()).len()))), &mut set, &mut bad, ids); + num(ui, "Length", "length", shared("line.length", &|k| line(k).map(|l| lenx((l.b.xy() - l.a.xy()).len()))), &mut set, &mut bad, ids); num( ui, "Angle", "angle", - shared("line.angle", &|k| line(k).map(|l| real((l.b.xy() - l.a.xy()).angle().to_degrees()))), + shared("line.angle", &|k| line(k).map(|l| realx((l.b.xy() - l.a.xy()).angle().to_degrees()))), &mut set, &mut bad, ids, @@ -1320,15 +1339,15 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } EntityKind::Circle(_) => { let circle = |k: &EntityKind| if let EntityKind::Circle(c) = k { Some(c.clone()) } else { None }; - prop_row(ui, "Center X", |ui| read_only(ui, &shared("circle.cx", &|k| circle(k).map(|c| len(c.center.x))))); - prop_row(ui, "Center Y", |ui| read_only(ui, &shared("circle.cy", &|k| circle(k).map(|c| len(c.center.y))))); - num(ui, "Radius", "radius", shared("circle.radius", &|k| circle(k).map(|c| len(c.radius))), &mut set, &mut bad, ids); - num(ui, "Diameter", "diameter", shared("circle.diameter", &|k| circle(k).map(|c| len(c.radius * 2.0))), &mut set, &mut bad, ids); + prop_row(ui, "Center X", |ui| read_only(ui, &shared("circle.cx", &|k| circle(k).map(|c| lenx(c.center.x))))); + prop_row(ui, "Center Y", |ui| read_only(ui, &shared("circle.cy", &|k| circle(k).map(|c| lenx(c.center.y))))); + num(ui, "Radius", "radius", shared("circle.radius", &|k| circle(k).map(|c| lenx(c.radius))), &mut set, &mut bad, ids); + num(ui, "Diameter", "diameter", shared("circle.diameter", &|k| circle(k).map(|c| lenx(c.radius * 2.0))), &mut set, &mut bad, ids); num( ui, "Circumference", "circumference", - shared("circle.circumference", &|k| circle(k).map(|c| len(c.radius * std::f64::consts::TAU))), + shared("circle.circumference", &|k| circle(k).map(|c| lenx(c.radius * std::f64::consts::TAU))), &mut set, &mut bad, ids, @@ -1337,7 +1356,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { ui, "Area", "area", - shared("circle.area", &|k| circle(k).map(|c| real(c.radius * c.radius * std::f64::consts::PI))), + shared("circle.area", &|k| circle(k).map(|c| realx(c.radius * c.radius * std::f64::consts::PI))), &mut set, &mut bad, ids, @@ -1345,9 +1364,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } EntityKind::Arc(_) => { let arc = |k: &EntityKind| if let EntityKind::Arc(a) = k { Some(a.clone()) } else { None }; - num(ui, "Radius", "radius", shared("arc.radius", &|k| arc(k).map(|a| len(a.radius))), &mut set, &mut bad, ids); - num(ui, "Start angle", "startAngle", shared("arc.start", &|k| arc(k).map(|a| real(a.start.to_degrees()))), &mut set, &mut bad, ids); - num(ui, "End angle", "endAngle", shared("arc.end", &|k| arc(k).map(|a| real(a.end.to_degrees()))), &mut set, &mut bad, ids); + num(ui, "Radius", "radius", shared("arc.radius", &|k| arc(k).map(|a| lenx(a.radius))), &mut set, &mut bad, ids); + num(ui, "Start angle", "startAngle", shared("arc.start", &|k| arc(k).map(|a| realx(a.start.to_degrees()))), &mut set, &mut bad, ids); + num(ui, "End angle", "endAngle", shared("arc.end", &|k| arc(k).map(|a| realx(a.end.to_degrees()))), &mut set, &mut bad, ids); } EntityKind::Text(_) => { let contents = shared("text.value", &|k| if let EntityKind::Text(t) = k { Some(t.value.clone()) } else { None }); @@ -1356,11 +1375,11 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { set = Some(json!({ "handles": ids, "text": s })); } }); - let height = shared("text.height", &|k| if let EntityKind::Text(t) = k { Some(len(t.height)) } else { None }); + let height = shared("text.height", &|k| if let EntityKind::Text(t) = k { Some(lenx(t.height)) } else { None }); num(ui, "Height", "height", height, &mut set, &mut bad, ids); - let rotation = shared("text.rotation", &|k| if let EntityKind::Text(t) = k { Some(deg(t.rotation)) } else { None }); + let rotation = shared("text.rotation", &|k| if let EntityKind::Text(t) = k { Some(degx(t.rotation)) } else { None }); num(ui, "Rotation", "rotation", rotation, &mut set, &mut bad, ids); - let width_factor = shared("text.width_factor", &|k| if let EntityKind::Text(t) = k { Some(real(t.width_factor)) } else { None }); + let width_factor = shared("text.width_factor", &|k| if let EntityKind::Text(t) = k { Some(realx(t.width_factor)) } else { None }); num(ui, "Width factor", "widthFactor", width_factor, &mut set, &mut bad, ids); } EntityKind::MText(_) => { @@ -1370,17 +1389,17 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { set = Some(json!({ "handles": ids, "text": s })); } }); - let height = shared("mtext.height", &|k| if let EntityKind::MText(t) = k { Some(len(t.height)) } else { None }); + let height = shared("mtext.height", &|k| if let EntityKind::MText(t) = k { Some(lenx(t.height)) } else { None }); num(ui, "Text height", "height", height, &mut set, &mut bad, ids); - let width = shared("mtext.width", &|k| if let EntityKind::MText(t) = k { Some(len(t.width)) } else { None }); + let width = shared("mtext.width", &|k| if let EntityKind::MText(t) = k { Some(lenx(t.width)) } else { None }); num(ui, "Defined width", "width", width, &mut set, &mut bad, ids); } EntityKind::LwPolyline(_) => { // Only Length and Area need the vertices; the other rows read one field. let geom = |p: &cadcraft_doc::LwPolyline| cadcraft_geom::Polyline { vertices: p.vertices.clone(), closed: p.closed }; - let width = shared("poly.width", &|k| if let EntityKind::LwPolyline(p) = k { Some(len(p.const_width)) } else { None }); + let width = shared("poly.width", &|k| if let EntityKind::LwPolyline(p) = k { Some(lenx(p.const_width)) } else { None }); num(ui, "Global width", "width", width, &mut set, &mut bad, ids); - let length = shared("poly.length", &|k| if let EntityKind::LwPolyline(p) = k { Some(len(geom(p).len())) } else { None }); + let length = shared("poly.length", &|k| if let EntityKind::LwPolyline(p) = k { Some(lenx(geom(p).len())) } else { None }); prop_row(ui, "Length", |ui| read_only(ui, &length)); let area = shared("poly.area", &|k| { if let EntityKind::LwPolyline(p) = k { Some(if p.closed { real(geom(p).area().abs()) } else { String::new() }) } else { None } @@ -1407,9 +1426,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); }); - let scale = shared("hatch.scale", &|k| if let EntityKind::Hatch(h) = k { Some(real(h.scale)) } else { None }); + let scale = shared("hatch.scale", &|k| if let EntityKind::Hatch(h) = k { Some(realx(h.scale)) } else { None }); num(ui, "Scale", "scale", scale, &mut set, &mut bad, ids); - let angle = shared("hatch.angle", &|k| if let EntityKind::Hatch(h) = k { Some(real(h.angle.to_degrees())) } else { None }); + let angle = shared("hatch.angle", &|k| if let EntityKind::Hatch(h) = k { Some(realx(h.angle.to_degrees())) } else { None }); num(ui, "Angle", "angle", angle, &mut set, &mut bad, ids); } EntityKind::Insert(_) => { @@ -1439,9 +1458,9 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { ] { prop_row(ui, label, |ui| read_only(ui, &value)); } - let rotation = shared("insert.rotation", &|k| if let EntityKind::Insert(i) = k { Some(deg(i.rotation)) } else { None }); + let rotation = shared("insert.rotation", &|k| if let EntityKind::Insert(i) = k { Some(degx(i.rotation)) } else { None }); num(ui, "Rotation", "rotation", rotation, &mut set, &mut bad, ids); - let scale = shared("insert.scale", &|k| if let EntityKind::Insert(i) = k { Some(real(i.scale.x)) } else { None }); + let scale = shared("insert.scale", &|k| if let EntityKind::Insert(i) = k { Some(realx(i.scale.x)) } else { None }); num(ui, "Scale", "scale", scale, &mut set, &mut bad, ids); } _ => {} @@ -1543,6 +1562,32 @@ mod tests { assert!(texts.iter().any(|t| t == "7.0000" || t == "7"), "the common text height is shown; painted: {texts:?}"); } + /// Values the display rounds alike still count as different: two dimensions whose text heights + /// differ by a millionth show `*VARIES*`, as do two circles whose radii do. Float noise (a + /// ten-trillionth) is not a difference. + #[test] + fn values_that_differ_below_the_display_precision_still_vary() { + let mut app = CadApp::new(Session::default(), Services::default()); + let dims: Vec = [10, 20] + .map(|x| app.run("dimlinear", json!({ "p1": [0, 0], "p2": [x, 0], "at": [5, 3] })).unwrap()["handle"].as_str().unwrap().to_string()) + .to_vec(); + app.run("select", json!({ "handles": dims.clone() })).unwrap(); + app.run("properties.set", json!({ "handles": [dims[0].clone()], "textHeight": 7.0 })).unwrap(); + app.run("properties.set", json!({ "handles": [dims[1].clone()], "textHeight": 7.0 + 1e-13 })).unwrap(); + let texts = painted_texts(&mut app, properties_section); + assert!(!texts.iter().any(|t| t == VARIES), "noise below 12 digits is not a difference; painted: {texts:?}"); + app.run("properties.set", json!({ "handles": [dims[1].clone()], "textHeight": 7.000001 })).unwrap(); + let texts = painted_texts(&mut app, properties_section); + assert!(texts.iter().any(|t| t == VARIES), "7 and 7.000001 differ although both show as 7.0000; painted: {texts:?}"); + + let mut app = CadApp::new(Session::default(), Services::default()); + let circles = circles(&mut app, &[2, 2], json!({})); + app.run("select", json!({ "handles": circles.clone() })).unwrap(); + app.run("properties.set", json!({ "handles": [circles[1].clone()], "radius": 2.000001 })).unwrap(); + let h = palette(app); + assert!(h.query_all_by_value(VARIES).count() > 0, "radii 2 and 2.000001 vary"); + } + /// Two objects of each type, selected together: the palette shows the type's properties (not /// just General), `*VARIES*` for the ones that differ, and an edit reaches both objects. #[test] From 90806a74769ba0b3002bf69ea9407810afbecf5a Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sun, 1 Nov 2026 06:25:21 -0600 Subject: [PATCH 083/185] 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 084/185] 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 085/185] 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 086/185] 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 087/185] 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 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 088/185] 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 0dcdf8d7a9b8ee5995643b550f05c04f25d446b9 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 12:02:37 -0500 Subject: [PATCH 089/185] properties.set leaves objects on locked layers out and says how many The Properties palette, Quick Properties and CHPROP's JSON form all edit through properties.set, which changed objects on locked layers. It now leaves them out and changes the rest, as CHPROP, MATCHPROP, MOVE and CUTCLIP already do. During REFEDIT, objects outside the working set are left out too, instead of the whole edit being refused. The result gains `locked`, and a `message`, which app.run shows at the command line, says how many were left out. When every object is left out, the drawing doesn't change and no undo step is added. CHPROP's JSON form was properties.set on the unlocked objects; it is now properties.set itself. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 68 +++++++++++- crates/engine/src/cmd/props/chprop.rs | 28 ----- crates/engine/tests/it/main.rs | 1 + .../engine/tests/it/properties_set_locked.rs | 104 ++++++++++++++++++ 4 files changed, 169 insertions(+), 32 deletions(-) create mode 100644 crates/engine/tests/it/properties_set_locked.rs diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 8afaddb3d..ea2b1405b 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -10,7 +10,7 @@ mod rename; pub use matchprop::MatchProps; use cadcraft_color::Color; -use cadcraft_doc::{EntityKind, Lineweight, Transparency}; +use cadcraft_doc::{EntityKind, Handle, Lineweight, Transparency}; use cadcraft_geom::Vec3; use serde_json::{Value, json}; @@ -21,8 +21,8 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)}"), - CommandSpec::new("chprop", "Change Properties", chprop::run_chprop) + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)} → {changed, locked, message?}: objects on locked layers (and, during REFEDIT, outside the working set) are left out, and `message` says how many"), + CommandSpec::new("chprop", "Change Properties", run_set) .params("as properties.set, leaving out objects on locked layers → {changed, locked} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)") .interactive(|_| Ok(Box::new(chprop::ChpropM::new()))), CommandSpec::new("change", "Change", change::run_change) @@ -196,11 +196,67 @@ fn set_xy(p: &mut Vec3, v: &Value) { } } +/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked +/// layers and, while a reference is edited in place, those outside the working set. +#[derive(Default)] +struct LeftOut { + locked: usize, + outside: usize, +} + +impl LeftOut { + /// `hs` without the objects that can't be edited, and how many those were. + fn split(s: &Session, hs: Vec) -> Result<(Vec, LeftOut)> { + let d = s.doc()?; + let mut out = LeftOut::default(); + let hs = hs + .into_iter() + .filter(|h| { + if super::blocks::refedit::locked(d, *h) { + out.outside += 1; + } else if super::curves::is_locked(s, *h) { + out.locked += 1; + } else { + return true; + } + false + }) + .collect(); + Ok((hs, out)) + } + + /// `{changed, locked}`, and a message saying how many were left out when any were. + fn result(&self, changed: usize) -> Value { + let mut notes = Vec::new(); + match self.locked { + 0 => {} + 1 => notes.push("1 object was on a locked layer.".to_string()), + n => notes.push(format!("{n} objects were on a locked layer.")), + } + match self.outside { + 0 => {} + 1 => notes.push("1 object was not in the working set.".to_string()), + n => notes.push(format!("{n} objects were not in the working set.")), + } + if changed == 0 && !notes.is_empty() { + notes.push("Nothing was changed.".to_string()); + } + let mut r = json!({ "changed": changed, "locked": self.locked + self.outside }); + if !notes.is_empty() + && let Some(o) = r.as_object_mut() + { + o.insert("message".into(), json!(notes.join(" "))); + } + r + } +} + fn run_set(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; if hs.is_empty() { return Err(bad("properties.set", "nothing selected")); } + let (hs, left_out) = LeftOut::split(s, hs)?; let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?; let transparency = p .get("transparency") @@ -211,6 +267,10 @@ fn run_set(s: &mut Session, p: &Value) -> Result { .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) .transpose()?; let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; + if hs.is_empty() { + // Every object was left out: the drawing stays as it was, with no undo step. + return Ok(left_out.result(0)); + } let d = s.doc_mut()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). let linetype = str_param(p, "linetype") @@ -237,7 +297,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { apply_kind_properties(e, p, dim_style.as_ref(), &dim_over); })?; } - Ok(json!({ "changed": hs.len() })) + Ok(left_out.result(hs.len())) } fn apply_kind_properties( diff --git a/crates/engine/src/cmd/props/chprop.rs b/crates/engine/src/cmd/props/chprop.rs index fac500ecd..66488f02d 100644 --- a/crates/engine/src/cmd/props/chprop.rs +++ b/crates/engine/src/cmd/props/chprop.rs @@ -23,7 +23,6 @@ use serde_json::{Value, json}; use super::super::curves::{KW, is_locked}; use super::super::machines::{SelOutcome, SelectPhase, number}; -use super::super::targets; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; const PROPERTIES: [&str; 7] = ["Color", "LAyer", "LType", "ltScale", "LWeight", "Thickness", "TRansparency"]; @@ -237,33 +236,6 @@ pub(super) fn feed_unlocked(select: &mut SelectPhase, s: &mut Session, i: Input) Ok(outcome) } -/// CHPROP's JSON form: `properties.set` on the objects that are not on locked layers, which the -/// command leaves out too; "locked" says how many were. -pub(super) fn run_chprop(s: &mut Session, p: &Value) -> Result { - let hs = targets(s, p)?; - let locked = locked(s, &hs); - if locked.is_empty() { - return super::run_set(s, p).map(|r| with_locked(r, 0)); - } - let free: Vec = hs.into_iter().filter(|h| !locked.contains(h)).collect(); - let r = if free.is_empty() { - json!({ "changed": 0 }) - } else { - let mut q = p.as_object().cloned().unwrap_or_default(); - q.insert("handles".into(), json!(free.iter().map(|h| h.hex()).collect::>())); - super::run_set(s, &Value::Object(q))? - }; - Ok(with_locked(r, locked.len())) -} - -/// `r` with how many objects were left out on locked layers. -fn with_locked(mut r: Value, n: usize) -> Value { - if let Some(o) = r.as_object_mut() { - o.insert("locked".into(), json!(n)); - } - r -} - /// A colour typed at CHPROP: 1–255, a name, BYLAYER or BYBLOCK (not 0 or 256, which COLOR takes). fn color(t: &str) -> Option { if t.bytes().all(|b| b.is_ascii_digit()) { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 0763ee6eb..0e1fb0a5b 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -102,6 +102,7 @@ mod plot_styles; mod point_modifiers; mod post_command_passes; mod prompt_keywords; +mod properties_set_locked; mod props_bad_lineweight; mod props_insert_scale_attribs; mod purge_mlinestyles; diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs new file mode 100644 index 000000000..11fd75830 --- /dev/null +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -0,0 +1,104 @@ +//! `properties.set`, which the Properties palette, Quick Properties and CHPROP edit through, leaves +//! objects on locked layers alone as CHPROP, MATCHPROP and MOVE do, and says how many it left out. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::color::Color; +use cadcraft_engine::doc::{Common, EntityKind, Handle, Insert, Space}; +use cadcraft_engine::geom::Vec3; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap() +} + +fn line(s: &mut Session, y: f64) -> Handle { + handle(&s.execute("line", &json!({ "points": [[0, y], [50, y]] })).unwrap()) +} + +/// Line a on layer 0 and lines b and c on the locked layer L1; their handles. +fn locked_drawing() -> (Session, [Handle; 3]) { + let mut s = Session::new(); + let hs = [line(&mut s, 0.0), line(&mut s, 20.0), line(&mut s, 40.0)]; + s.execute("properties.set", &json!({ "handles": [hs[1].hex(), hs[2].hex()], "layer": "L1" })).unwrap(); + s.execute("layer.set", &json!({ "name": "L1", "locked": true })).unwrap(); + (s, hs) +} + +fn counts(r: &Value) -> (Option, Option) { + (r["changed"].as_u64(), r["locked"].as_u64()) +} + +fn colors(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.common.color).collect() +} + +fn layers(s: &Session) -> Vec { + s.doc().unwrap().model.iter().map(|e| e.common.layer.clone()).collect() +} + +#[test] +fn objects_on_locked_layers_are_left_out() { + let (mut s, [a, b, c]) = locked_drawing(); + let r = s.execute("properties.set", &json!({ "handles": [a.hex()], "color": 2 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(0)), "{r}"); + assert!(r.get("message").is_none(), "{r}"); + let r = s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex()], "color": 3 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer."); + assert_eq!(colors(&s), [Color::Index(3), Color::ByLayer, Color::ByLayer]); + // The selection when no handles are given; a new layer leaves them on theirs. + s.set_selection(vec![a, b, c]); + let r = s.execute("properties.set", &json!({ "layer": "L2" })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(2)), "{r}"); + assert_eq!(r["message"], "2 objects were on a locked layer."); + assert_eq!(layers(&s), ["L2", "L1", "L1"]); +} + +#[test] +fn with_every_object_locked_nothing_changes() { + let (mut s, [_, b, c]) = locked_drawing(); + let undo = s.state().unwrap().undo.len(); + let r = s.execute("properties.set", &json!({ "handles": [b.hex(), c.hex()], "layer": "NEW", "color": 4 })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(2)), "{r}"); + assert_eq!(r["message"], "2 objects were on a locked layer. Nothing was changed."); + assert_eq!(colors(&s), [Color::ByLayer; 3]); + assert!(s.doc().unwrap().layer("NEW").is_none(), "no layer is made"); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); + // A bad value is still refused. + assert!(s.execute("properties.set", &json!({ "handles": [b.hex()], "color": "nonsense" })).is_err()); + // CHPROP's JSON form is properties.set. + let r = s.execute("chprop", &json!({ "handles": [b.hex()], "color": 4 })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer. Nothing was changed."); +} + +/// While a reference is edited in place, only its working set changes; before, an edit that +/// reached outside it was refused whole. +#[test] +fn during_refedit_objects_outside_the_working_set_are_left_out() { + let mut s = Session::new(); + let l = line(&mut s, 0.0); + s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [l.hex()], "keep": "delete" })).unwrap(); + let kind = EntityKind::Insert(Insert { + block: "B".into(), + insert: Vec3::new(100.0, 0.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }); + let a = s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap(); + let other = line(&mut s, 20.0); + let r = s.execute("refedit", &json!({ "handle": a.hex() })).unwrap(); + let copy = handle(&json!({ "handle": r["working"][0] })); + let r = s.execute("properties.set", &json!({ "handles": [copy.hex(), other.hex()], "color": 5 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was not in the working set."); + let d = s.doc().unwrap(); + assert_eq!(d.entity(copy).unwrap().common.color, Color::Index(5)); + assert_eq!(d.entity(other).unwrap().common.color, Color::ByLayer); + assert!(d.refedit.is_some(), "the edit goes on"); +} From 5787b3634f7d663330af1855fc6a806c77de43f9 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 13:06:16 -0500 Subject: [PATCH 090/185] 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 091/185] 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 092/185] Review fix: properties.set counts each object once and refuses missing ones first `targets` keeps a handle listed twice, so it was counted twice as left out. During REFEDIT, a handle that names no object counted as outside the working set instead of being refused. properties.set now takes each object once, and refuses a handle that names no object before anything changes; before, the objects ahead of it in the list had already been changed when the error came. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 35 +++++++++++-------- .../engine/tests/it/properties_set_locked.rs | 17 +++++++++ 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 7297afad9..8f8aa454a 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -205,24 +205,29 @@ struct LeftOut { } impl LeftOut { - /// `hs` without the objects that can't be edited, and how many those were. + /// `hs` without the objects that can't be edited, each object once, and how many those were. A + /// handle that names no object is an error, before anything changes. fn split(s: &Session, hs: Vec) -> Result<(Vec, LeftOut)> { let d = s.doc()?; + let mut seen = std::collections::HashSet::new(); let mut out = LeftOut::default(); - let hs = hs - .into_iter() - .filter(|h| { - if super::blocks::refedit::locked(d, *h) { - out.outside += 1; - } else if super::curves::is_locked(s, *h) { - out.locked += 1; - } else { - return true; - } - false - }) - .collect(); - Ok((hs, out)) + let mut free = Vec::new(); + for h in hs { + if d.entity(h).is_none() { + return Err(cadcraft_doc::DocError::NoEntity(h).into()); + } + if !seen.insert(h) { + continue; + } + if super::blocks::refedit::locked(d, h) { + out.outside += 1; + } else if super::curves::is_locked(s, h) { + out.locked += 1; + } else { + free.push(h); + } + } + Ok((free, out)) } /// `{changed, locked}`, and a message saying how many were left out when any were. diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index 267727a4f..258294d79 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -52,6 +52,20 @@ fn objects_on_locked_layers_are_left_out() { assert_eq!(counts(&r), (Some(1), Some(2)), "{r}"); assert_eq!(r["message"], "2 objects were on a locked layer."); assert_eq!(layers(&s), ["L2", "L1", "L1"]); + // An object listed twice counts once. + let r = s.execute("properties.set", &json!({ "handles": [a.hex(), a.hex(), b.hex(), b.hex()], "color": 6 })).unwrap(); + assert_eq!(counts(&r), (Some(1), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was on a locked layer."); +} + +/// A handle that names no object is refused before anything changes. +#[test] +fn a_missing_object_is_refused_before_any_change() { + let (mut s, [a, b, _]) = locked_drawing(); + let undo = s.state().unwrap().undo.len(); + assert!(s.execute("properties.set", &json!({ "handles": [a.hex(), b.hex(), "FFFFF"], "color": 7 })).is_err()); + assert_eq!(colors(&s), [Color::ByLayer; 3]); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); } #[test] @@ -111,4 +125,7 @@ fn during_refedit_objects_outside_the_working_set_are_left_out() { assert_eq!(d.entity(copy).unwrap().common.color, Color::Index(5)); assert_eq!(d.entity(other).unwrap().common.color, Color::ByLayer); assert!(d.refedit.is_some(), "the edit goes on"); + // A handle that names no object isn't counted as outside the working set: it's refused. + assert!(s.execute("properties.set", &json!({ "handles": [copy.hex(), "FFFFF"], "color": 6 })).is_err()); + assert_eq!(s.doc().unwrap().entity(copy).unwrap().common.color, Color::Index(5)); } From 8b91646795aa3a3e135cf79c076eefa7b85fbb74 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 14:10:07 -0500 Subject: [PATCH 093/185] Review fix: CHPROP says what it left out; the working set is read once Interactive CHPROP threw away properties.set's message, so an edit to an object it had just moved onto a locked layer was left out without a word. It now shows the message. properties.set looked each object up in REFEDIT's working set, a list, twice; it now builds the set once and checks the layer directly. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/props.rs | 10 ++++++---- crates/engine/src/cmd/props/chprop.rs | 9 +++++++-- crates/engine/tests/it/properties_set_locked.rs | 14 ++++++++++++++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 8f8aa454a..5c7a349b2 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -209,19 +209,21 @@ impl LeftOut { /// handle that names no object is an error, before anything changes. fn split(s: &Session, hs: Vec) -> Result<(Vec, LeftOut)> { let d = s.doc()?; + // The working set, once: `RefEdit::is_working` searches a list. + let working: Option> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect()); let mut seen = std::collections::HashSet::new(); let mut out = LeftOut::default(); let mut free = Vec::new(); for h in hs { - if d.entity(h).is_none() { + let Some(e) = d.entity(h) else { return Err(cadcraft_doc::DocError::NoEntity(h).into()); - } + }; if !seen.insert(h) { continue; } - if super::blocks::refedit::locked(d, h) { + if working.as_ref().is_some_and(|w| !w.contains(&h)) { out.outside += 1; - } else if super::curves::is_locked(s, h) { + } else if d.layer(&e.common.layer).is_some_and(|l| l.locked) { out.locked += 1; } else { free.push(h); diff --git a/crates/engine/src/cmd/props/chprop.rs b/crates/engine/src/cmd/props/chprop.rs index 66488f02d..50fb94597 100644 --- a/crates/engine/src/cmd/props/chprop.rs +++ b/crates/engine/src/cmd/props/chprop.rs @@ -89,13 +89,18 @@ impl ChpropM { if vals.all(|v| v == first) { first } else { "varies".into() } } - /// Apply `props` to the selection through `properties.set`. + /// Apply `props` to the selection through `properties.set`, saying what it left out: objects + /// this command moved onto a locked layer, say. fn apply(&self, s: &mut Session, props: Value) -> Result<()> { let mut p = json!({ "handles": self.handles.iter().map(|h| h.hex()).collect::>() }); if let (Some(p), Value::Object(props)) = (p.as_object_mut(), props) { p.extend(props); } - super::run_set(s, &p).map(|_| ()) + let r = super::run_set(s, &p)?; + if let Some(m) = r.get("message").and_then(Value::as_str) { + s.echo(m.to_string()); + } + Ok(()) } /// Take an answer to `ask`; `false` when it was refused (the prompt comes again). diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index 258294d79..b8356a504 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -58,6 +58,20 @@ fn objects_on_locked_layers_are_left_out() { assert_eq!(r["message"], "1 object was on a locked layer."); } +/// CHPROP says so when it leaves an edit out: an object it moved onto a locked layer keeps its +/// color. +#[test] +fn chprop_says_when_it_leaves_an_object_it_moved_onto_a_locked_layer_alone() { + let (mut s, _) = locked_drawing(); + let d = line(&mut s, 60.0); + s.cmdline("(setq d (entlast))").unwrap(); + s.log.clear(); + s.cmdline("(command \"_.CHPROP\" d \"\" \"_LA\" \"L1\" \"_C\" 3 \"\")").unwrap(); + let e = s.doc().unwrap().entity(d).unwrap().common.clone(); + assert_eq!((e.layer.as_str(), e.color), ("L1", Color::ByLayer)); + assert!(s.log.iter().any(|l| l == "1 object was on a locked layer. Nothing was changed."), "{:?}", s.log); +} + /// A handle that names no object is refused before anything changes. #[test] fn a_missing_object_is_refused_before_any_change() { From 7e386a2cc4761eeee217c8190c5d3d752765cf77 Mon Sep 17 00:00:00 2001 From: Slopapalooza Date: Sun, 1 Nov 2026 14:38:15 -0500 Subject: [PATCH 094/185] Review fix: test that an edit only outside the working set changes nothing Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/it/properties_set_locked.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index b8356a504..5277f48bd 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -139,6 +139,14 @@ fn during_refedit_objects_outside_the_working_set_are_left_out() { assert_eq!(d.entity(copy).unwrap().common.color, Color::Index(5)); assert_eq!(d.entity(other).unwrap().common.color, Color::ByLayer); assert!(d.refedit.is_some(), "the edit goes on"); + // With only objects outside the working set, nothing changes: no layer, no undo step. + let undo = s.state().unwrap().undo.len(); + let r = s.execute("properties.set", &json!({ "handles": [other.hex()], "color": 6, "layer": "NEW" })).unwrap(); + assert_eq!(counts(&r), (Some(0), Some(1)), "{r}"); + assert_eq!(r["message"], "1 object was not in the working set. Nothing was changed."); + assert_eq!(s.doc().unwrap().entity(other).unwrap().common.color, Color::ByLayer); + assert!(s.doc().unwrap().layer("NEW").is_none(), "no layer is made"); + assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step"); // A handle that names no object isn't counted as outside the working set: it's refused. assert!(s.execute("properties.set", &json!({ "handles": [copy.hex(), "FFFFF"], "color": 6 })).is_err()); assert_eq!(s.doc().unwrap().entity(copy).unwrap().common.color, Color::Index(5)); From df26fc51975cbbcefae2f04e25b97ef56769d1d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=81=E4=BC=AA?= <56018602+r4x2t7@users.noreply.github.com> Date: Mon, 2 Nov 2026 06:34:15 +0800 Subject: [PATCH 095/185] 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 096/185] TEXTEDIT: the context-menu test follows the window entry, several texts keep the command --- crates/ui-egui/src/context_menu.rs | 8 +------ crates/ui-egui/tests/it/context_menus.rs | 28 ++++++++++++++++++------ 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 0b00d933c..3f1c98ebf 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -160,13 +160,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { pub fn object_entries(app: &CadApp) -> Vec { object_commands(app) .into_iter() - .filter_map(|(id, label)| { - if id == "textedit" { - edit_text_window_entry(app).or_else(|| item(app, id, label)) - } else { - item(app, id, label) - } - }) + .filter_map(|(id, label)| if id == "textedit" { edit_text_window_entry(app).or_else(|| item(app, id, label)) } else { item(app, id, label) }) .collect() } diff --git a/crates/ui-egui/tests/it/context_menus.rs b/crates/ui-egui/tests/it/context_menus.rs index 3134b8d3c..fbd39f930 100644 --- a/crates/ui-egui/tests/it/context_menus.rs +++ b/crates/ui-egui/tests/it/context_menus.rs @@ -133,7 +133,8 @@ fn idle_menu_lists_recent_commands_and_selection_commands() { #[test] fn selection_menu_has_the_object_types_edit_commands() { let cases = [ - ("text", json!({ "at": [0, 0], "text": "hi" }), "textedit"), + // A single text's Edit Text opens the Edit Text window: the id carries the handle. + ("text", json!({ "at": [0, 0], "text": "hi" }), "textedit:"), ("pline", json!({ "vertices": [[0, 0], [10, 0], [10, 5]] }), "pedit"), ("spline", json!({ "fit": [[0, 0], [5, 5], [10, 0]] }), "splinedit"), ]; @@ -142,14 +143,27 @@ fn selection_menu_has_the_object_types_edit_commands() { app.run(cmd, params).unwrap(); select_all(&mut app); let g = vec![context_menu::object_entries(&app)]; - assert!(ids(&g).iter().any(|i| i == edit), "{cmd}: {edit} missing from {:?}", labels(&g)); - assert!(ids(&context_menu::entries(&app)).iter().any(|i| i == edit)); + let hit = ids(&g).iter().find(|i| i.starts_with(edit)).cloned(); + assert!(hit.is_some(), "{cmd}: {edit} missing from {:?}", labels(&g)); + assert!(ids(&context_menu::entries(&app)).iter().any(|i| i.starts_with(edit))); + // Choosing the window's entry opens the dialog on the object; the double-click keeps its + // in-place editing (#842). + if let Some(id) = hit.filter(|i| i.starts_with("textedit:")) { + context_menu::choose(&mut app, &id); + assert_eq!(app.ui.dialog.as_deref(), Some(id.as_str())); + } } + // Several selected texts keep the TEXTEDIT command line: the window edits one object at a time. + let mut several = app(); + several.run("text", json!({ "at": [0, 0], "text": "hi" })).unwrap(); + several.run("text", json!({ "at": [0, 4], "text": "ho" })).unwrap(); + select_all(&mut several); + assert!(ids(&[context_menu::object_entries(&several)]).iter().any(|i| i == "textedit")); // Polyline Edit, not the command's bare "Polyline" label. - let mut app = app(); - app.run("pline", json!({ "vertices": [[0, 0], [10, 0]] })).unwrap(); - select_all(&mut app); - assert_eq!(labels(&[context_menu::object_entries(&app)]), ["Polyline Edit"]); + let mut pline = app(); + pline.run("pline", json!({ "vertices": [[0, 0], [10, 0]] })).unwrap(); + select_all(&mut pline); + assert_eq!(labels(&[context_menu::object_entries(&pline)]), ["Polyline Edit"]); } #[test] From 322c5e9bbfce895dbe7cc109d7393153ab77cf64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=81=E4=BC=AA?= <56018602+r4x2t7@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:52:05 +0800 Subject: [PATCH 097/185] 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 04f06a2f87769cdab0651c40c46b58d183a20bd3 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 2 Nov 2026 15:25:55 +0500 Subject: [PATCH 098/185] 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 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 099/185] 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 100/185] 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 101/185] 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 102/185] 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 fd3a0b9e150c82a24c9692ce08212b2ba83b5bf4 Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 05:20:20 -0700 Subject: [PATCH 103/185] 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 104/185] 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 105/185] 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 ff6b0e375bb3f31b203cae92c7dabb9345d03d8b Mon Sep 17 00:00:00 2001 From: Nicholas Gower Date: Thu, 22 Oct 2026 05:16:40 -0700 Subject: [PATCH 106/185] 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 107/185] 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 108/185] 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 109/185] 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 110/185] 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 4b532f6c24208b3bc481ca385f304f05c52527cc Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 3 Nov 2026 08:01:13 +0400 Subject: [PATCH 111/185] 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 9bd5c479e39be920139c223a4516d0e14d5bcb19 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 15:45:05 +1100 Subject: [PATCH 112/185] 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 113/185] 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 114/185] 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 0a0a820759852c7017f38e59b3e26a3394bbb595 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Tue, 3 Nov 2026 16:36:05 +1100 Subject: [PATCH 115/185] 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 116/185] 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 117/185] 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 e8408851cddf7e5ef94d69344a77c52e4f4dcde9 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Tue, 3 Nov 2026 11:17:59 +0400 Subject: [PATCH 118/185] 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 119/185] 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 120/185] 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 121/185] 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 122/185] 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 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 123/185] 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 124/185] 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 125/185] 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 126/185] 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 127/185] 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 128/185] Keyboard Shortcuts: the Chinese label of its menu item, as main's catalog test asks since #2510 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkJ8y75DE7yLZ7utxSRDeP --- crates/ui-egui/src/i18n/zh.tsv | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index eae92cc14..9488dcb03 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -361,6 +361,7 @@ Join 合并 Join the ArtCraft Discord… 加入 ArtCraft Discord… Join us on Discord 在 Discord 上加入我们 + Keyboard Shortcuts... 键盘快捷键... Language 语言 Last 最后 Last commit 最后提交 From cce67d27c7fe342212efff8f3a9cbae25fc2c21b Mon Sep 17 00:00:00 2001 From: ATARYS-LAB <342661122+ATARYS-LAB@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:45:14 +0100 Subject: [PATCH 129/185] Shortcuts: outside macOS Ctrl and Cmd are one key when checking who has a shortcut One Ctrl press runs a Ctrl and a Cmd shortcut alike on Windows and Linux, so two commands could hold Ctrl+K and Cmd+K and only the first would ever run. same() now compares them as one key there; macOS keeps Control apart. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XkJ8y75DE7yLZ7utxSRDeP --- crates/ui-egui/src/keys.rs | 40 +++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs index 8f7252c49..2fd7419bd 100644 --- a/crates/ui-egui/src/keys.rs +++ b/crates/ui-egui/src/keys.rs @@ -30,8 +30,17 @@ const FIXED: &[&str] = &["copyclip", "cutclip", "pasteclip", "copybase", "pasteb /// The dialog name in `UiState::dialog`. pub const DIALOG: &str = "shortcuts"; +/// Whether two shortcuts are one key press. Outside macOS Ctrl is the command key, and one Ctrl +/// press runs a Ctrl and a Cmd shortcut alike, so they are compared as Cmd. fn same(a: &KeyboardShortcut, b: &KeyboardShortcut) -> bool { - a.logical_key == b.logical_key && a.modifiers == b.modifiers + let pressed = |m: Modifiers| { + if !cfg!(target_os = "macos") && (m.ctrl || m.command || m.mac_cmd) { + Modifiers { ctrl: false, command: true, mac_cmd: false, ..m } + } else { + m + } + }; + a.logical_key == b.logical_key && pressed(a.modifiers) == pressed(b.modifiers) } /// A registry shortcut string ("Cmd+Shift+G", "Alt+4", "F3") as a shortcut; `None` when empty or @@ -521,16 +530,20 @@ mod tests { fn control_and_command_control_shortcuts_keep_their_control() { let mut user = UserKeys::new(); assert_eq!(assign(&mut user, "line", "Ctrl+K"), Ok(vec![])); - assert_eq!(assign(&mut user, "circle", "Cmd+Ctrl+K"), Ok(vec![])); - assert_eq!(user.get("line").map(String::as_str), Some("Ctrl+K")); + // Outside macOS both are one Ctrl press, so Circle takes it from Line. + let lost = if cfg!(target_os = "macos") { vec![] } else { vec!["line".to_string()] }; + assert_eq!(assign(&mut user, "circle", "Cmd+Ctrl+K"), Ok(lost)); assert_eq!(user.get("circle").map(String::as_str), Some("Cmd+Ctrl+K")); let eff = effective(&user); let of = |id: &str| eff.iter().find(|(_, i)| i == id).map(|(s, _)| s.modifiers); - assert_eq!(of("line"), Some(Modifiers::CTRL)); assert_eq!(of("circle"), Some(Modifiers { ctrl: true, command: true, mac_cmd: true, ..Modifiers::NONE })); - // Command+Control+K is tried before Control+K, which it holds too. - let at = |id: &str| eff.iter().position(|(_, i)| i == id); - assert!(at("circle") < at("line")); + if cfg!(target_os = "macos") { + assert_eq!(user.get("line").map(String::as_str), Some("Ctrl+K")); + assert_eq!(of("line"), Some(Modifiers::CTRL)); + // Command+Control+K is tried before Control+K, which it holds too. + let at = |id: &str| eff.iter().position(|(_, i)| i == id); + assert!(at("circle") < at("line")); + } } #[test] @@ -549,6 +562,19 @@ mod tests { assert_eq!(assign(&mut user, "line", "Cmd+8"), Ok(vec!["ui.toggle.quickcalc".to_string()])); } + /// On Windows and Linux one Ctrl press runs a Ctrl and a Cmd shortcut alike, so they are one + /// key: giving it takes it from the command that had it, and preferences keep it once. + #[test] + #[cfg(not(target_os = "macos"))] + fn ctrl_and_cmd_are_one_key_outside_macos() { + let mut user = UserKeys::new(); + assert_eq!(assign(&mut user, "line", "Ctrl+P"), Ok(vec!["plot".to_string()])); + assert_eq!(runs(&user, "Cmd+P").as_deref(), Some("line")); + assert_eq!(assign(&mut user, "circle", "Cmd+P"), Ok(vec!["line".to_string()])); + let user = from_prefs(&json!({"circle": "Cmd+K", "line": "Ctrl+K"})); + assert_eq!(user.values().filter(|k| !k.is_empty()).count(), 1, "{user:?}"); + } + #[test] fn a_new_shortcut_replaces_the_commands_own_and_clear_removes_it() { let mut user = UserKeys::new(); From bd639d320413f76eeb65260e1c8cc1366e77db3e Mon Sep 17 00:00:00 2001 From: lforgiarini <97414997+lforgiarini@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:31:03 +0100 Subject: [PATCH 130/185] 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 01e28fc0d4bf92e28e0cd3923760f4ed6f73721c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 02:12:01 +0100 Subject: [PATCH 131/185] 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 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 132/185] 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 b2ded208881f0fed4aa8a96cfe20ec7f9da7a7c6 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 12:36:59 +1100 Subject: [PATCH 133/185] 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 c397ab1e9e1f212887ae243084794c59cf78971e Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 13:55:27 +1100 Subject: [PATCH 134/185] 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 135/185] 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 485c74da6b7bb798805c743b636ebd2e9b0d6411 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 13:58:15 +1100 Subject: [PATCH 136/185] 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 95396c032d761369fb3275496ac131446a422200 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 15:34:08 +1100 Subject: [PATCH 137/185] 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 138/185] 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 139/185] 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 40f060018ddac180c762e368c2d90f3a370a952b Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Thu, 5 Nov 2026 09:01:04 +0400 Subject: [PATCH 140/185] Leave .github/workflows/release.yml to a maintainer CLAUDE.md: no CI changes in a feature or fix PR. The web-craft-fonts line is described in the PR description. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- .github/workflows/release.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4bfc4ffec..c2cf475e8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -69,7 +69,6 @@ jobs: app-name: cadcraft app-title: CADCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 - web-craft-fonts: true version: ${{ inputs.version }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} From fe67c048ec3639d892ae1ceaf019f2e9b0f58636 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Thu, 5 Nov 2026 09:01:04 +0400 Subject: [PATCH 141/185] Leave ROADMAP.md and docs/localization-parity.md to maintainers CLAUDE.md: PRs don't edit these docs. The affected rows are named in the PR description. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF --- ROADMAP.md | 1 - docs/localization-parity.md | 6 ++---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a731731f0..48bd33032 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,7 +95,6 @@ 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,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/docs/localization-parity.md b/docs/localization-parity.md index c41162eff..c6f43ee4a 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-30 · **Change:** minor (Bosnian added; previously: Georgian catalog added: complete catalog, menu headings, single count form; 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) +> **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). @@ -73,11 +73,10 @@ plus native review by a human; extending the catalog to the remaining English-on | Swedish | sv | 1,330 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Swedish | Latin: yes (bundled egui proportional and monospace fonts; å ä ö é and Swedish quotes tested) | AI-assisted (Claude Code) by @holmbom; terminology and the running app reviewed by a native speaker | complete current catalog; English-only interface gaps remain | line-by-line proofreading + shared English-only UI work | | Italian | it | 1,227 catalog rows; reference catalog and marked UI literals covered | dialogs and tooltips yes; contextual menu headings (Visualizza / Vista, Edita / Modifica); command reference searchable in Italian | Latin: yes (bundled egui fonts; accented letters tested) | AI-assisted by Emanuele Bottelli (Claude), written from the English strings with Italian desktop-CAD vocabulary; no native proofreading pass yet | complete current catalog; English-only interface gaps remain | native review + shared English-only UI work | | Hungarian | hu | 1,326 catalog rows; reference catalog, marked UI literals and menu headings covered (no gaps reported) | dialogs and tooltips yes; contextual menu headings; command reference searchable in Hungarian | Latin: yes (bundled egui proportional and monospace fonts; ő ű Ő Ű and the other accented letters tested) | translated by @Skaywalker from the English strings; independent native proofreading pending | complete current catalog; English-only interface gaps remain | native proofreading + shared English-only UI work | -| Georgian | ka | 1,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 | -Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian, Turkish, Bosnian and Georgian. +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, @@ -92,7 +91,6 @@ 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,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 | From 62d1c806f7fcfd4b9e68b53bc0254b2a325f73d9 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Thu, 5 Nov 2026 16:06:13 +1100 Subject: [PATCH 142/185] OLE2FRAME: a frame with no width or height is picked as the line it is drawn as (review) The renderer draws a zero-width frame as a line, so leaving it out of the hit geometry made a visible object unpickable. Also corrects where the corner tolerance switches to ulps (4 ulps pass 1e-6 near 1.1e9). --- crates/doc/src/extents.rs | 6 +++--- crates/engine/src/select.rs | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 4cffb359f..101c69ff0 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -181,9 +181,9 @@ fn recase(chunk: &[u8], old: &str) -> String { } /// 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. +/// header holds the same f64 the frame groups print, so they agree to a few ulps. Up to about 1.1e9 +/// a fixed tolerance of at most this decides, so that distinct geometry does not match; above that, +/// four ulps of the coordinate (`4 * EPSILON * |x|`) exceed it and 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 diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index c8a689194..1ce7ecc52 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -37,11 +37,11 @@ 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. + // the renderer use); a frame with no width or height is drawn as a line, so it is picked as + // one. 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(), + Some(q) => vec![q.to_vec()], + None => Vec::new(), }, kind => { let mut out = Vec::new(); @@ -523,12 +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(); + let line = 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"); + assert_eq!(pick(&d, &Space::Model, Vec2::new(60.0, -20.0), 0.2), Some(line), "a frame with no width is drawn as a line and picked as one"); } /// A block holding a diagonal dashed line, inserted at `scale`. From 017cc9b1fcc1ee50df965036340e1cc6bb1c6356 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Thu, 5 Nov 2026 11:20:52 +0600 Subject: [PATCH 143/185] fix(mcp): render takes a background and a plot style (#803) The MCP render tool and ui.render, in the app and headless, always drew on the dark canvas with no plot style, so a PNG placed on a page needed the SVG export instead. They now take `background` ("dark", the default; "white", "paper" or "#rrggbb") and `plot_style` (a built-in plot style table such as monochrome.ctb or grayscale.ctb, or one the drawing holds). Colour 7 is drawn black on a light background and white on a dark one, as on a plot. An unknown value is refused with what is accepted. Both copies of ui.render read the options through one function in the engine (render_look). The render tool's description also says it returns an image block, not text. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/render_look.rs | 129 +++++++++++++++++++++++++++++++ crates/mcp/Cargo.toml | 4 + crates/mcp/src/backend.rs | 14 +++- crates/mcp/src/tests.rs | 107 +++++++++++++++++++++++++ crates/mcp/src/tools.rs | 4 +- crates/ui-egui/src/control.rs | 73 +++++++++++++++-- docs/control-protocol.md | 2 +- docs/mcp.md | 2 +- 10 files changed, 325 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/render_look.rs diff --git a/Cargo.lock b/Cargo.lock index c08b8f4bd..ac733f45d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -776,6 +776,7 @@ dependencies = [ "getrandom 0.4.3", "log", "serde_json", + "tiny-skia", ] [[package]] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ccb93ef4f..2e02831dd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -27,6 +27,7 @@ pub mod mtext_edit; pub mod pointmod; pub mod prompt; mod recent; +pub mod render_look; pub mod sample; pub mod select; pub mod settings_dir; diff --git a/crates/engine/src/render_look.rs b/crates/engine/src/render_look.rs new file mode 100644 index 000000000..531807953 --- /dev/null +++ b/crates/engine/src/render_look.rs @@ -0,0 +1,129 @@ +//! How a render request draws: its `background` and `plot_style` (#803). The app's control +//! channel and the headless MCP backend both answer `ui.render`, and both read these here. +//! +//! Colour 7 (white/black) follows the background, as on a plot: the rasteriser draws it white on +//! a dark background and black on a light one ([`cadcraft_color::display_rgb`]). + +use std::sync::Arc; + +use cadcraft_color::Rgb; +use cadcraft_doc::{Drawing, PlotStyleTable}; +use cadcraft_render::raster::RasterOptions; +use serde_json::Value; + +/// The background a render draws on without `background`: the dark canvas. +pub const DARK: Rgb = Rgb(33, 40, 48); +/// The background of `"white"` and `"paper"`. +pub const WHITE: Rgb = Rgb(255, 255, 255); + +/// What `background` accepts, for the error message and the docs. +pub const BACKGROUNDS: &str = "\"dark\" (the default), \"white\", \"paper\" or \"#rrggbb\""; + +/// Longest part of a refused value repeated in its error message. +const ECHO: usize = 40; + +/// The look of a render: what it draws on and with which plot style table. +#[derive(Clone, Debug)] +pub struct RenderLook { + pub background: Rgb, + /// `None` = draw with the objects' own properties (or, in a layout showing plot styles, its + /// page setup's table). + pub plot_style_table: Option>, +} + +impl Default for RenderLook { + fn default() -> Self { + RenderLook { background: DARK, plot_style_table: None } + } +} + +impl RenderLook { + /// `background` and `plot_style` of a request's params for drawing `d`; absent or `null` + /// keeps the default. `Err` says what is accepted. + pub fn from_params(d: &Drawing, p: &Value) -> Result { + let text = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) => Ok(Some(s.as_str())), + Some(_) => Err(format!("`{key}` must be a string")), + }; + let mut look = RenderLook::default(); + if let Some(b) = text("background")? { + look.background = background(b).ok_or_else(|| format!("unknown background `{}`: use {BACKGROUNDS}", echo(b)))?; + } + if let Some(name) = text("plot_style")? { + look.plot_style_table = plot_style(d, name)?.map(Arc::new); + } + Ok(look) + } + + /// The raster options of a render with this look. + pub fn raster(&self) -> RasterOptions { + RasterOptions { background: self.background, ..RasterOptions::default() } + } +} + +/// The colour of a `background` value (any case): `dark`, `white`, `paper` or `#rrggbb`. +pub fn background(v: &str) -> Option { + let v = v.trim(); + match v.to_ascii_lowercase().as_str() { + "dark" => Some(DARK), + "white" | "paper" => Some(WHITE), + hex if hex.starts_with('#') => Rgb::parse_hex(hex), + _ => None, + } +} + +/// The plot style table `name` names: one the drawing holds, or a built-in one (`.ctb` may be +/// left out); `none` or an empty name is no table. `Err` lists the tables there are. +fn plot_style(d: &Drawing, name: &str) -> Result, String> { + if cadcraft_doc::no_plot_style_table(name) { + return Ok(None); + } + match cadcraft_doc::plot_style_table(d, name.trim()) { + Some(t) => Ok(Some(t)), + None => Err(format!("unknown plot style table `{}`: use one of {}", echo(name), cadcraft_doc::plot_style_table_names(d).join(", "))), + } +} + +/// The start of a refused value, to repeat in its error message. +fn echo(v: &str) -> String { + v.chars().take(ECHO).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn backgrounds() { + assert_eq!(background("dark"), Some(DARK)); + assert_eq!(DARK, RasterOptions::default().background, "the default is the rasteriser's canvas"); + assert_eq!(background(" Paper "), Some(WHITE)); + assert_eq!(background("WHITE"), Some(WHITE)); + assert_eq!(background("#336699"), Some(Rgb(0x33, 0x66, 0x99))); + for bad in ["", "purple", "336699", "#12345", "#1234567", "##336699", "#33669g"] { + assert_eq!(background(bad), None, "{bad}"); + } + } + + #[test] + fn from_params() { + let d = Drawing::new_imperial(); + let look = RenderLook::from_params(&d, &json!({})).unwrap(); + assert_eq!(look.background, DARK); + assert!(look.plot_style_table.is_none()); + let look = RenderLook::from_params(&d, &json!({"background": null, "plot_style": "none"})).unwrap(); + assert_eq!(look.background, DARK); + assert!(look.plot_style_table.is_none()); + let look = RenderLook::from_params(&d, &json!({"background": "white", "plot_style": "Monochrome"})).unwrap(); + assert_eq!(look.raster().background, WHITE); + assert_eq!(look.plot_style_table.map(|t| t.name.clone()).as_deref(), Some("monochrome.ctb")); + let e = RenderLook::from_params(&d, &json!({"plot_style": "nope.ctb"})).unwrap_err(); + assert!(e.contains("nope.ctb") && e.contains("grayscale.ctb"), "{e}"); + let e = RenderLook::from_params(&d, &json!({"background": "x".repeat(10_000)})).unwrap_err(); + assert!(e.len() < 200 && e.contains("#rrggbb"), "{e}"); + assert!(RenderLook::from_params(&d, &json!({"background": 1})).is_err()); + assert!(RenderLook::from_params(&d, &json!({"plot_style": {}})).is_err()); + } +} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 1359fbdda..dc5d8ca2a 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -17,3 +17,7 @@ serde_json = { workspace = true } log = { workspace = true } # Secure randomness for the per-session control token (MIT OR Apache-2.0). getrandom = "0.4" + +[dev-dependencies] +# Reads the pixels of rendered PNGs in the tests. +tiny-skia = { workspace = true } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 913569e82..d1ac6727d 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -300,7 +300,7 @@ const HEADLESS_METHODS: &[(&str, &str, &str)] = &[ ("engine.execute", "{command, params}", "Run any command with JSON parameters. Never opens a dialog."), ("engine.commands", "", "Every command: id, label, menu path, shortcut, aliases, params doc, enabled."), ("drawing.inspect", "{entities?, limit?}", "Drawing summary and entities with handles and geometry."), - ("ui.render", "{path?, width?, height?, fit?}", "Render the drawing; replies pngBase64."), + ("ui.render", "{path?, width?, height?, fit?, window?, background?, plot_style?}", "Render the drawing; replies pngBase64."), ("app.open", "{path}", "Open a drawing."), ("app.save", "{path?}", "Save the drawing (Save As with a path)."), ("control.methods", "", "This list."), @@ -400,7 +400,14 @@ impl Backend for Headless { 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 opts = cadcraft_render::Options { view: window, transparency: s.settings.transparency_display, ..Default::default() }; + // `background` and `plot_style` (#803), read as the app reads them. + let look = cadcraft_engine::render_look::RenderLook::from_params(&st.doc, &p)?; + let opts = cadcraft_render::Options { + view: window, + transparency: s.settings.transparency_display, + plot_style_table: look.plot_style_table.clone(), + ..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); let side = |k: &str| p.get(k).and_then(Value::as_f64).map(|x| x as u32); @@ -413,8 +420,7 @@ impl Backend for Headless { cadcraft_render::raster::View { center: v.center, scale: f64::from(h) / v.height.max(1e-12), width: w, height: h } }; let (w, h) = (view.width, view.height); - let png = - cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()).ok_or("render failed")?; + let png = cadcraft_render::raster::render_png(&list, &view, &look.raster()).ok_or("render failed")?; 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") { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 9a437b076..aec224baf 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -259,3 +259,110 @@ fn a_lazy_bridge_starts_without_the_app_and_says_how_to_open_it() { assert_ne!(r["result"]["isError"], json!(true), "{r}"); app.join().unwrap(); } + +/// The pixels of a `render` tool result. +fn render_pixels(s: &mut Server, args: Value) -> tiny_skia::Pixmap { + let img = tool(s, "render", args); + assert_eq!(img["type"], "image", "{img}"); + let png = cadcraft_engine::cmd::file::base64_decode(img["data"].as_str().unwrap()).unwrap(); + tiny_skia::Pixmap::decode_png(&png).unwrap() +} + +/// The RGB of pixel (x, y). +fn rgb(pm: &tiny_skia::Pixmap, x: u32, y: u32) -> (u8, u8, u8) { + let c = pm.pixel(x, y).unwrap(); + (c.red(), c.green(), c.blue()) +} + +/// The pixel of the middle column that differs most from the corner: what the line along the +/// middle of the image is drawn with. +fn ink(pm: &tiny_skia::Pixmap) -> (u8, u8, u8) { + let bg = rgb(pm, 0, 0); + let far = |c: &(u8, u8, u8)| bg.0.abs_diff(c.0) as u32 + bg.1.abs_diff(c.1) as u32 + bg.2.abs_diff(c.2) as u32; + (0..pm.height()).map(|y| rgb(pm, pm.width() / 2, y)).max_by_key(far).unwrap() +} + +/// A drawing with one line along y = 0: colour 7 (layer 0's colour), or red on a red layer. +fn line_drawing(red: bool) -> Server { + let mut s = Server::new(Box::new(Headless::default())); + if red { + tool(&mut s, "execute", json!({"command": "layer.new", "params": {"name": "Red", "color": "red", "current": true}})); + } + tool(&mut s, "execute", json!({"command": "line", "params": {"points": [[0, 0], [10, 0]]}})); + s +} + +/// Around the line, which runs along the middle of pixel row 20 of a 120 x 40 image (not on a +/// pixel edge, so it isn't blended across two rows). +const WINDOW: [[f64; 2]; 2] = [[-1.0, -1.95], [11.0, 2.05]]; + +/// Guards #803: `render` draws on the background asked for (`white`, `paper`, `#rrggbb`) and a +/// colour-7 line follows it, as on a plot: dark on white, light on the dark canvas, which stays +/// the default. +#[test] +fn render_draws_on_the_background_asked_for() { + let mut s = line_drawing(false); + let dark = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40})); + assert_eq!(rgb(&dark, 0, 0), (33, 40, 48), "the default stays the dark canvas"); + let (r, g, b) = ink(&dark); + assert!(r > 200 && g > 200 && b > 200, "colour 7 is light on the dark canvas: {:?}", (r, g, b)); + for bg in ["white", "paper", "WHITE"] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": bg})); + let (w, h) = (pm.width(), pm.height()); + for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] { + assert_eq!(rgb(&pm, x, y), (255, 255, 255), "{bg}: corner ({x}, {y})"); + } + let (r, g, b) = ink(&pm); + assert!(r < 128 && g < 128 && b < 128, "{bg}: colour 7 is drawn dark on white: {:?}", (r, g, b)); + } + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "#336699"})); + assert_eq!(rgb(&pm, 0, 0), (0x33, 0x66, 0x99)); + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "dark"})); + assert_eq!(rgb(&pm, 0, 0), (33, 40, 48)); +} + +/// Guards #803: `plot_style` draws with a built-in plot style table: `monochrome.ctb` turns a red +/// line black, which without one stays red. +#[test] +fn render_draws_with_the_plot_style_asked_for() { + let mut s = line_drawing(true); + let plain = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "white"})); + let (r, g, b) = ink(&plain); + assert!(r > 200 && g < 100 && b < 100, "red without a plot style: {:?}", (r, g, b)); + for table in ["monochrome.ctb", "Monochrome", "monochrome.CTB"] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "white", "plot_style": table})); + let (r, g, b) = ink(&pm); + assert!(r < 100 && r == g && g == b, "{table}: red plots black: {:?}", (r, g, b)); + } + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "background": "white", "plot_style": "grayscale.ctb"})); + let (r, g, b) = ink(&pm); + assert!(r == g && g == b, "grayscale.ctb draws red grey: {:?}", (r, g, b)); +} + +/// Guards #803: an unknown `background` or `plot_style` is refused with what is accepted, not +/// drawn some other way; a value of the wrong type is invalid params. +#[test] +fn render_refuses_unknown_backgrounds_and_plot_styles() { + let mut s = line_drawing(false); + for (args, wants) in [ + (json!({"background": "purple"}), "#rrggbb"), + (json!({"background": "#12345"}), "#rrggbb"), + (json!({"background": "336699"}), "#rrggbb"), + (json!({"background": ""}), "#rrggbb"), + (json!({"plot_style": "nope.ctb"}), "monochrome.ctb"), + (json!({"plot_style": "default.ctx"}), "monochrome.ctb"), + ] { + let r = call(&mut s, 1, "tools/call", json!({"name": "render", "arguments": args.clone()})); + assert_eq!(r["result"]["isError"], json!(true), "{args} must be refused, not drawn"); + let msg = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(msg.contains(wants), "{args}: {msg}"); + } + for args in [json!({"background": 7}), json!({"plot_style": ["monochrome.ctb"]})] { + let r = call(&mut s, 2, "tools/call", json!({"name": "render", "arguments": args.clone()})); + assert_eq!(r["error"]["code"], -32602, "{args} must be invalid params"); + } + // The headless control method refuses them too. + let mut h = Headless::default(); + assert!(crate::Backend::call(&mut h, "ui.render", json!({"background": "purple"})).is_err()); + assert!(crate::Backend::call(&mut h, "ui.render", json!({"plot_style": 3})).is_err()); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 2c432d608..c6560218b 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -22,9 +22,11 @@ pub fn tool_definitions(has_ui: bool) -> Value { "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}, "layer": {"type": "string"}, "selected": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, "crossing": {"type": "boolean"}, "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), - json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image: fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape.", + json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image content block (content[0].type is \"image\", not text): fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape. `background`: \"dark\" (default, the canvas), \"white\", \"paper\" or \"#rrggbb\"; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. \"monochrome.ctb\" (every colour black, as most plots) or \"grayscale.ctb\"; with a white background it makes light colours readable. An unknown background or plot style is refused.", "inputSchema": {"type": "object", "properties": {"width": {"type": "integer", "minimum": 16}, "height": {"type": "integer", "minimum": 16}, "fit": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, + "background": {"type": "string", "description": "\"dark\" (default), \"white\", \"paper\" or \"#rrggbb\""}, + "plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds"}, "path": {"type": "string"}}}}), json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.", "inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"}, diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9c806a96f..ffa1b7d1a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -15,8 +15,10 @@ //! - `ui.click {x, y, shift?, ctrl?}`, `ui.move {x, y}`: real egui pointer input in screen points //! - `ui.key {key, cmd?, shift?, alt?}`, `ui.text {text}`: synthetic keyboard input //! - `ui.set {...UiState fields}`, `ui.resize {width, height}` -//! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, width?, height?, fit?}`: headless -//! render of the drawing (no window needed; fits the drawing unless `fit` is false; replies `pngBase64`) +//! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, width?, height?, fit?, window?, +//! background?, plot_style?}`: headless render of the drawing (no window needed; fits the drawing +//! unless `fit` is false or a `window` is given; on the dark canvas unless `background` is +//! `white`, `paper` or `#rrggbb`; `plot_style` names a plot style table; replies `pngBase64`) //! - `app.open {path}`, `app.save {path?}`, `app.quit` //! - `control.methods`: this list, with params and a description; `ping`: replies `"pong"` @@ -211,7 +213,7 @@ const METHODS: &[(&str, &str, &str)] = &[ ("ui.resize", "{width, height}", "Resize the window."), ("ui.focus", "", "Activate the native window."), ("ui.screenshot", "{path?}", "PNG of the window (needs a presented frame)."), - ("ui.render", "{path?, width?, height?, fit?}", "Headless render of the drawing; replies pngBase64."), + ("ui.render", "{path?, width?, height?, fit?, window?, background?, plot_style?}", "Headless render of the drawing; replies pngBase64."), ("app.open", "{path}", "Open a drawing."), ("app.save", "{path?}", "Save the drawing (Save As with a path)."), ("app.quit", "", "Quit without the unsaved-changes prompt."), @@ -475,7 +477,17 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou let Ok(st) = app.session.state() else { return err("no drawing") }; // `window`: just that area, at the size given or matching its shape. let window = render_window(p); - let opts = cadcraft_render::Options { view: window, transparency: app.session.settings.transparency_display, ..Default::default() }; + // `background` and `plot_style` (#803), read as the headless MCP backend reads them. + let look = match cadcraft_engine::render_look::RenderLook::from_params(&st.doc, p) { + Ok(look) => look, + Err(e) => return err(e), + }; + let opts = cadcraft_render::Options { + view: window, + transparency: app.session.settings.transparency_display, + plot_style_table: look.plot_style_table.clone(), + ..Default::default() + }; let list = cadcraft_render::build(&st.doc, &st.space, &opts); let v = st.view(); let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(true); @@ -484,7 +496,7 @@ pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Ou None => render_view(&list.bounds, v.center, v.height, fit, w, h), }; let (w, h) = (view.width, view.height); - let Some(png) = cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()) else { + let Some(png) = cadcraft_render::raster::render_png(&list, &view, &look.raster()) else { return err("render failed"); }; #[cfg(not(target_arch = "wasm32"))] @@ -834,4 +846,55 @@ mod tests { 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); } + + /// The reply to a `ui.render` request in an app showing one colour-7 line along y = 0. + fn render_line(params: Value) -> Value { + let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); + app.session.new_drawing(false); + app.session.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let (req, _rx) = ControlRequest::new("ui.render", params); + match handle(&mut app, &egui::Context::default(), &req) { + Outcome::Done(v) => v, + Outcome::Screenshot { .. } => panic!("ui.render must not take a screenshot"), + } + } + + /// The RGB of a reply's corner pixel and of its middle column's darkest pixel. + fn corner_and_darkest(reply: &Value) -> ([u8; 3], [u8; 3]) { + let png = cadcraft_engine::cmd::file::base64_decode(reply["result"]["pngBase64"].as_str().unwrap_or_default()).unwrap(); + let img = image::load_from_memory(&png).unwrap().to_rgb8(); + let corner = img.get_pixel(0, 0).0; + let darkest = (0..img.height()).map(|y| img.get_pixel(img.width() / 2, y).0).min_by_key(|p| p.iter().map(|&c| u32::from(c)).sum::()); + (corner, darkest.unwrap_or_default()) + } + + /// Guards #803 in the app: `ui.render` takes `background` and `plot_style` as the headless MCP + /// backend does (colour 7 drawn dark on white), keeps the dark canvas by default and refuses + /// unknown values. + #[test] + fn render_takes_a_background_and_a_plot_style() { + // The line runs along the middle of pixel row 20 of the 120 x 40 image. + let window = json!([[-1.0, -1.95], [11.0, 2.05]]); + let sized = |mut p: Value| { + p["window"] = window.clone(); + p["width"] = json!(120); + p["height"] = json!(40); + p + }; + let r = render_line(sized(json!({}))); + assert_eq!(r["ok"], true, "{}", r["error"]); + assert_eq!(corner_and_darkest(&r).0, [33, 40, 48], "the default stays the dark canvas"); + for p in [json!({"background": "white"}), json!({"background": "paper", "plot_style": "monochrome.ctb"})] { + let r = render_line(sized(p.clone())); + assert_eq!(r["ok"], true, "{p}: {}", r["error"]); + let (corner, ink) = corner_and_darkest(&r); + assert_eq!(corner, [255, 255, 255], "{p}"); + assert!(ink.iter().all(|&c| c < 128), "{p}: colour 7 is drawn dark on white: {ink:?}"); + } + for p in [json!({"background": "purple"}), json!({"background": 7}), json!({"plot_style": "nope.ctb"})] { + let r = render_line(p.clone()); + assert_eq!(r["ok"], false, "{p} must be refused"); + assert!(r.get("result").is_none(), "{p}"); + } + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d10d43abb..8b6927e62 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -61,7 +61,7 @@ field. `engine.commands` returns a separate command catalog, not a list of addit | `ui.resize` | `{width, height}` | Resize the window. | | `ui.focus` | | Activate the native window. Does not assign focus to a widget. | | `ui.screenshot` | `{path?}` | PNG of the window (needs a presented frame). Bounded: at most 4 queued/in-flight/completed requests, 64 MiB per image and 64 MiB total (completed but undrained images still count), an 8 s deadline, and cancellation when the document or keyboard focus changes while the request is outstanding. A queued request adopts the settled window size when issued. After issue, a change in window size, scale, OS window focus, minimization or occlusion cancels it. Every reply carries `request`; failures include `ok:false,error`. Files are written only after the deadline and identity checks pass. Without `path`, each request gets a unique PNG in a private owner-only per-process directory under the temp dir (created exclusively; an existing symlink is never followed), so concurrent app instances cannot collide; the caller owns those files and should remove them when done. | -| `ui.render` | `{path?, width?, height?, fit?}` | Headless render. `fit` (default true) frames the whole drawing; `false` uses the current view. Replies `{pngBase64, width, height, bytes, path?}`. | +| `ui.render` | `{path?, width?, height?, fit?, window?, background?, plot_style?}` | Headless render. `fit` (default true) frames the whole drawing; `false` uses the current view; `window` `[[x0, y0], [x1, y1]]` shows just that area (drawing units). `background`: `"dark"` (default, the canvas), `"white"`, `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, built-in (`monochrome.ctb` prints every colour black, `grayscale.ctb` grey; `default.ctb`, `default.stb`, `monochrome.stb`) or one the drawing holds. An unknown `background` or `plot_style` is refused. Replies `{pngBase64, width, height, bytes, path?}`. | | `app.open` / `app.save` / `app.quit` | `{path}` | File operations. | | `control.methods` | | Every method this server answers: `{method, params, description}`. Headless (`cadcraft-cli mcp`) lists only the methods it serves. | | `ping` | | Replies `"pong"`. A cheap health check. | diff --git a/docs/mcp.md b/docs/mcp.md index ecdc53d09..dcb63e7db 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -47,7 +47,7 @@ Example client configuration (Claude Code / Claude Desktop): | `execute {"command": "usage", "params": {type?, limit?, offset?}}` | Read-only cross-reference of the layers, blocks, text styles and linetypes: for each, the objects in model space and layouts that use it, the objects in block definitions that use it, whether it is used only inside block definitions, and whether it is empty or unused. `summary` counts each kind and `unused` lists what PURGE would offer, in table order. One scan reads at most 5,000,000 objects; a larger drawing sets `incomplete: true` with an `incompleteReason`, because counts, statuses and summaries then omit the objects past the limit. | | `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. | | `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). | -| `render {width?, height?, fit?, window?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). | +| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (default, the canvas), `"white"`, `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`. An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. | | `find_text {contains?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (any case), layer and a window around the insertion points. Read-only (the `texts` command). | | `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. | | `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. | From 04a279cff08e32406e8300ffde1c60174a9eb119 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Thu, 5 Nov 2026 12:09:31 +0600 Subject: [PATCH 144/185] fix(mcp): a render with a plot style plots on white; "none" turns plot styles off (#803) A plot style alone drew black lines on the dark canvas: the tables that change colours print colour 7 (and, in monochrome.ctb, every colour) black. With `plot_style` and no `background`, the render now draws on white, as a plot prints on paper; a given background still wins. `plot_style: "none"` (or "") draws every object with its own properties, also in a layout that shows its own plot styles. An unknown table's error lists the built-in tables and at most ten of the drawing's own. The app's ui.render test now draws a red line, so it fails if the plot style isn't passed on. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/render_look.rs | 91 +++++++++++++++++++++++++++----- crates/mcp/src/tests.rs | 25 +++++++++ crates/mcp/src/tools.rs | 6 +-- crates/ui-egui/src/control.rs | 47 +++++++++++------ docs/control-protocol.md | 2 +- docs/mcp.md | 2 +- 6 files changed, 139 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/render_look.rs b/crates/engine/src/render_look.rs index 531807953..ba4dbc8f4 100644 --- a/crates/engine/src/render_look.rs +++ b/crates/engine/src/render_look.rs @@ -3,6 +3,14 @@ //! //! Colour 7 (white/black) follows the background, as on a plot: the rasteriser draws it white on //! a dark background and black on a light one ([`cadcraft_color::display_rgb`]). +//! +//! A render with a plot style table draws on white unless `background` says otherwise, as a plot +//! prints on paper: the tables that change colours print colour 7 (and, in `monochrome.ctb`, +//! every colour) black, which can hardly be seen on the dark canvas. +//! +//! `plot_style: "none"` (or `""`) draws every object with its own properties, also in a layout +//! whose page setup has "Display plot styles" on; without `plot_style` such a layout draws with +//! its own table, as on screen. use std::sync::Arc; @@ -17,7 +25,11 @@ pub const DARK: Rgb = Rgb(33, 40, 48); pub const WHITE: Rgb = Rgb(255, 255, 255); /// What `background` accepts, for the error message and the docs. -pub const BACKGROUNDS: &str = "\"dark\" (the default), \"white\", \"paper\" or \"#rrggbb\""; +pub const BACKGROUNDS: &str = "\"dark\" (the default without a plot style), \"white\" (the default with one), \"paper\" or \"#rrggbb\""; + +/// Most table names an unknown `plot_style` error lists from the drawing's own tables (the +/// built-in ones are always listed). +const LISTED_TABLES: usize = 10; /// Longest part of a refused value repeated in its error message. const ECHO: usize = 40; @@ -27,7 +39,8 @@ const ECHO: usize = 40; pub struct RenderLook { pub background: Rgb, /// `None` = draw with the objects' own properties (or, in a layout showing plot styles, its - /// page setup's table). + /// page setup's table). `plot_style: "none"` is a table that keeps every property, so such a + /// layout's table doesn't apply either. pub plot_style_table: Option>, } @@ -47,12 +60,19 @@ impl RenderLook { Some(_) => Err(format!("`{key}` must be a string")), }; let mut look = RenderLook::default(); + if let Some(name) = text("plot_style")? { + look.plot_style_table = Some(Arc::new(match plot_style(d, name)? { + Some(t) => { + // Plotted on paper, unless `background` says otherwise. + look.background = WHITE; + t + } + None => object_properties(), + })); + } if let Some(b) = text("background")? { look.background = background(b).ok_or_else(|| format!("unknown background `{}`: use {BACKGROUNDS}", echo(b)))?; } - if let Some(name) = text("plot_style")? { - look.plot_style_table = plot_style(d, name)?.map(Arc::new); - } Ok(look) } @@ -79,10 +99,30 @@ fn plot_style(d: &Drawing, name: &str) -> Result, String> if cadcraft_doc::no_plot_style_table(name) { return Ok(None); } - match cadcraft_doc::plot_style_table(d, name.trim()) { - Some(t) => Ok(Some(t)), - None => Err(format!("unknown plot style table `{}`: use one of {}", echo(name), cadcraft_doc::plot_style_table_names(d).join(", "))), + cadcraft_doc::plot_style_table(d, name.trim()) + .map(Some) + .ok_or_else(|| format!("unknown plot style table `{}`: use none or one of {}", echo(name), table_list(d))) +} + +/// The tables a drawing can use, for an error message: the built-in ones, then at most +/// [`LISTED_TABLES`] of the drawing's own and how many more there are. +fn table_list(d: &Drawing) -> String { + let builtin = |n: &String| cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().any(|b| b.eq_ignore_ascii_case(n)); + let names = cadcraft_doc::plot_style_table_names(d); + let own: Vec = names.iter().filter(|n| !builtin(n)).map(|n| echo(n)).collect(); + let mut list: Vec = cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().map(|b| (*b).to_string()).collect(); + list.extend(own.iter().take(LISTED_TABLES).cloned()); + let mut text = list.join(", "); + if own.len() > LISTED_TABLES { + text.push_str(&format!(" and {} more of the drawing's", own.len() - LISTED_TABLES)); } + text +} + +/// A table that prints every object with its own properties: what `plot_style: "none"` draws +/// with, so a layout's own table doesn't apply either. +fn object_properties() -> PlotStyleTable { + PlotStyleTable::color_dependent("None", "Object properties", |_| None) } /// The start of a refused value, to repeat in its error message. @@ -113,17 +153,44 @@ mod tests { let look = RenderLook::from_params(&d, &json!({})).unwrap(); assert_eq!(look.background, DARK); assert!(look.plot_style_table.is_none()); - let look = RenderLook::from_params(&d, &json!({"background": null, "plot_style": "none"})).unwrap(); - assert_eq!(look.background, DARK); - assert!(look.plot_style_table.is_none()); + // "none" keeps the dark canvas and draws every object with its own properties, also in a + // layout that shows its own plot styles. + for none in ["none", "", " None "] { + let look = RenderLook::from_params(&d, &json!({"background": null, "plot_style": none})).unwrap(); + assert_eq!(look.background, DARK, "{none:?}"); + let t = look.plot_style_table.unwrap(); + assert!(t.is_color_dependent() && t.styles.iter().all(|s| s.keeps_color() && s.lineweight.is_none()), "{none:?}"); + } let look = RenderLook::from_params(&d, &json!({"background": "white", "plot_style": "Monochrome"})).unwrap(); assert_eq!(look.raster().background, WHITE); assert_eq!(look.plot_style_table.map(|t| t.name.clone()).as_deref(), Some("monochrome.ctb")); + // A plot style plots on paper unless `background` says otherwise. + for table in ["monochrome.ctb", "grayscale.ctb", "default.stb"] { + assert_eq!(RenderLook::from_params(&d, &json!({"plot_style": table})).unwrap().background, WHITE, "{table}"); + let look = RenderLook::from_params(&d, &json!({"plot_style": table, "background": "dark"})).unwrap(); + assert_eq!(look.background, DARK, "{table}"); + } let e = RenderLook::from_params(&d, &json!({"plot_style": "nope.ctb"})).unwrap_err(); - assert!(e.contains("nope.ctb") && e.contains("grayscale.ctb"), "{e}"); + assert!(e.contains("nope.ctb") && e.contains("grayscale.ctb") && e.contains("none"), "{e}"); let e = RenderLook::from_params(&d, &json!({"background": "x".repeat(10_000)})).unwrap_err(); assert!(e.len() < 200 && e.contains("#rrggbb"), "{e}"); assert!(RenderLook::from_params(&d, &json!({"background": 1})).is_err()); assert!(RenderLook::from_params(&d, &json!({"plot_style": {}})).is_err()); } + + /// An unknown plot style lists the built-in tables and only some of the drawing's own. + #[test] + fn unknown_plot_style_lists_a_few_tables() { + let mut d = Drawing::new_imperial(); + for i in 0..500 { + d.plot_style_tables.push(PlotStyleTable::color_dependent(&format!("{}{i}.ctb", "own".repeat(30)), "", |_| None)); + } + let e = RenderLook::from_params(&d, &json!({"plot_style": "nope.ctb"})).unwrap_err(); + for b in cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES { + assert!(e.contains(b), "{b}: {e}"); + } + assert!(e.contains("and 490 more"), "{e}"); + assert!(e.len() < 1000, "{} bytes: {e}", e.len()); + assert!(RenderLook::from_params(&d, &json!({"plot_style": d.plot_style_tables[7].name.clone()})).is_ok()); + } } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index aec224baf..b7eee854e 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -339,6 +339,31 @@ fn render_draws_with_the_plot_style_asked_for() { assert!(r == g && g == b, "grayscale.ctb draws red grey: {:?}", (r, g, b)); } +/// Guards #803: a plot style alone plots on white, as on paper, so `monochrome.ctb` doesn't draw +/// black on the dark canvas; `background` still wins, and `plot_style: "none"` keeps the canvas +/// and the objects' colours. +#[test] +fn render_with_a_plot_style_plots_on_white() { + for red in [false, true] { + let mut s = line_drawing(red); + for table in ["monochrome.ctb", "grayscale.ctb"] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "plot_style": table})); + assert_eq!(rgb(&pm, 0, 0), (255, 255, 255), "{table} without a background plots on white"); + let (r, g, b) = ink(&pm); + assert!(r == g && g == b && r < 128, "{table}, red {red}: drawn dark grey or black on white: {:?}", (r, g, b)); + } + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "plot_style": "monochrome.ctb", "background": "dark"})); + assert_eq!(rgb(&pm, 0, 0), (33, 40, 48), "an explicit background wins"); + for none in ["none", ""] { + let pm = render_pixels(&mut s, json!({"window": WINDOW, "width": 120, "height": 40, "plot_style": none})); + assert_eq!(rgb(&pm, 0, 0), (33, 40, 48), "{none:?} keeps the dark canvas"); + let (r, g, b) = ink(&pm); + let light = r > 200 && g > 200 && b > 200; + assert!(if red { r > 200 && g < 100 && b < 100 } else { light }, "{none:?}, red {red}: own colour {:?}", (r, g, b)); + } + } +} + /// Guards #803: an unknown `background` or `plot_style` is refused with what is accepted, not /// drawn some other way; a value of the wrong type is invalid params. #[test] diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index c6560218b..8518a9aff 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -22,11 +22,11 @@ pub fn tool_definitions(has_ui: bool) -> Value { "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}, "layer": {"type": "string"}, "selected": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, "crossing": {"type": "boolean"}, "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), - json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image content block (content[0].type is \"image\", not text): fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape. `background`: \"dark\" (default, the canvas), \"white\", \"paper\" or \"#rrggbb\"; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. \"monochrome.ctb\" (every colour black, as most plots) or \"grayscale.ctb\"; with a white background it makes light colours readable. An unknown background or plot style is refused.", + json!({"name": "render", "description": "Render the active drawing to a PNG and return it as an image content block (content[0].type is \"image\", not text): fitted to the extents by default, or just the area `window` [[x0,y0],[x1,y1]] (drawing units), e.g. one sheet or one room of a large drawing. With a window and no size the image is 1600 px wide with the window's shape. `background`: \"dark\" (the canvas; the default without a plot style), \"white\" (the default with one, as a plot prints on paper), \"paper\" or \"#rrggbb\"; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. \"monochrome.ctb\" (every colour black, as most plots) or \"grayscale.ctb\", which make light colours readable on white; \"none\" (or \"\") draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown background or plot style is refused.", "inputSchema": {"type": "object", "properties": {"width": {"type": "integer", "minimum": 16}, "height": {"type": "integer", "minimum": 16}, "fit": {"type": "boolean"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, - "background": {"type": "string", "description": "\"dark\" (default), \"white\", \"paper\" or \"#rrggbb\""}, - "plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds"}, + "background": {"type": "string", "description": "\"dark\" (default without plot_style), \"white\" (default with one), \"paper\" or \"#rrggbb\""}, + "plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds; \"none\" or \"\" for the objects' own properties"}, "path": {"type": "string"}}}}), json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.", "inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"}, diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index ffa1b7d1a..2637c26f8 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -18,7 +18,8 @@ //! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, width?, height?, fit?, window?, //! background?, plot_style?}`: headless render of the drawing (no window needed; fits the drawing //! unless `fit` is false or a `window` is given; on the dark canvas unless `background` is -//! `white`, `paper` or `#rrggbb`; `plot_style` names a plot style table; replies `pngBase64`) +//! `white`, `paper` or `#rrggbb`; `plot_style` names a plot style table, which plots on white +//! unless `background` is given, or is `none`; replies `pngBase64`) //! - `app.open {path}`, `app.save {path?}`, `app.quit` //! - `control.methods`: this list, with params and a description; `ping`: replies `"pong"` @@ -847,10 +848,14 @@ mod tests { assert_eq!(render_reply(b"abc", 7, 5, None, true)["truncated"], true); } - /// The reply to a `ui.render` request in an app showing one colour-7 line along y = 0. - fn render_line(params: Value) -> Value { + /// The reply to a `ui.render` request in an app showing one line along y = 0: colour 7, or + /// red on a red layer. + fn render_line(red: bool, params: Value) -> Value { let mut app = CadApp::new(cadcraft_engine::Session::empty(), crate::Services::default()); app.session.new_drawing(false); + if red { + app.session.execute("layer.new", &json!({"name": "Red", "color": "red", "current": true})).unwrap(); + } app.session.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); let (req, _rx) = ControlRequest::new("ui.render", params); match handle(&mut app, &egui::Context::default(), &req) { @@ -869,30 +874,38 @@ mod tests { } /// Guards #803 in the app: `ui.render` takes `background` and `plot_style` as the headless MCP - /// backend does (colour 7 drawn dark on white), keeps the dark canvas by default and refuses - /// unknown values. + /// backend does (colour 7 drawn dark on white, a red line black with `monochrome.ctb`, white + /// by default with a plot style), keeps the dark canvas by default and refuses unknown values. #[test] fn render_takes_a_background_and_a_plot_style() { // The line runs along the middle of pixel row 20 of the 120 x 40 image. let window = json!([[-1.0, -1.95], [11.0, 2.05]]); - let sized = |mut p: Value| { + let render = |red: bool, mut p: Value| { p["window"] = window.clone(); p["width"] = json!(120); p["height"] = json!(40); - p - }; - let r = render_line(sized(json!({}))); - assert_eq!(r["ok"], true, "{}", r["error"]); - assert_eq!(corner_and_darkest(&r).0, [33, 40, 48], "the default stays the dark canvas"); - for p in [json!({"background": "white"}), json!({"background": "paper", "plot_style": "monochrome.ctb"})] { - let r = render_line(sized(p.clone())); + let r = render_line(red, p.clone()); assert_eq!(r["ok"], true, "{p}: {}", r["error"]); - let (corner, ink) = corner_and_darkest(&r); - assert_eq!(corner, [255, 255, 255], "{p}"); - assert!(ink.iter().all(|&c| c < 128), "{p}: colour 7 is drawn dark on white: {ink:?}"); + corner_and_darkest(&r) + }; + assert_eq!(render(false, json!({})).0, [33, 40, 48], "the default stays the dark canvas"); + let (corner, ink) = render(false, json!({"background": "white"})); + assert_eq!(corner, [255, 255, 255]); + assert!(ink.iter().all(|&c| c < 128), "colour 7 is drawn dark on white: {ink:?}"); + // A red line stays red without a plot style and plots black with monochrome.ctb, on white + // unless `background` says otherwise. + let (_, [r, g, b]) = render(true, json!({"background": "paper"})); + assert!(r > 200 && g < 100 && b < 100, "red without a plot style: {:?}", [r, g, b]); + for (p, bg) in [ + (json!({"plot_style": "monochrome.ctb"}), [255, 255, 255]), + (json!({"plot_style": "monochrome.ctb", "background": "#336699"}), [0x33, 0x66, 0x99]), + ] { + let (corner, [r, g, b]) = render(true, p.clone()); + assert_eq!(corner, bg, "{p}"); + assert!(r < 100 && r == g && g == b, "{p}: red plots black: {:?}", [r, g, b]); } for p in [json!({"background": "purple"}), json!({"background": 7}), json!({"plot_style": "nope.ctb"})] { - let r = render_line(p.clone()); + let r = render_line(false, p.clone()); assert_eq!(r["ok"], false, "{p} must be refused"); assert!(r.get("result").is_none(), "{p}"); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8b6927e62..f85731e37 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -61,7 +61,7 @@ field. `engine.commands` returns a separate command catalog, not a list of addit | `ui.resize` | `{width, height}` | Resize the window. | | `ui.focus` | | Activate the native window. Does not assign focus to a widget. | | `ui.screenshot` | `{path?}` | PNG of the window (needs a presented frame). Bounded: at most 4 queued/in-flight/completed requests, 64 MiB per image and 64 MiB total (completed but undrained images still count), an 8 s deadline, and cancellation when the document or keyboard focus changes while the request is outstanding. A queued request adopts the settled window size when issued. After issue, a change in window size, scale, OS window focus, minimization or occlusion cancels it. Every reply carries `request`; failures include `ok:false,error`. Files are written only after the deadline and identity checks pass. Without `path`, each request gets a unique PNG in a private owner-only per-process directory under the temp dir (created exclusively; an existing symlink is never followed), so concurrent app instances cannot collide; the caller owns those files and should remove them when done. | -| `ui.render` | `{path?, width?, height?, fit?, window?, background?, plot_style?}` | Headless render. `fit` (default true) frames the whole drawing; `false` uses the current view; `window` `[[x0, y0], [x1, y1]]` shows just that area (drawing units). `background`: `"dark"` (default, the canvas), `"white"`, `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, built-in (`monochrome.ctb` prints every colour black, `grayscale.ctb` grey; `default.ctb`, `default.stb`, `monochrome.stb`) or one the drawing holds. An unknown `background` or `plot_style` is refused. Replies `{pngBase64, width, height, bytes, path?}`. | +| `ui.render` | `{path?, width?, height?, fit?, window?, background?, plot_style?}` | Headless render. `fit` (default true) frames the whole drawing; `false` uses the current view; `window` `[[x0, y0], [x1, y1]]` shows just that area (drawing units). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, built-in (`monochrome.ctb` prints every colour black, `grayscale.ctb` grey; `default.ctb`, `default.stb`, `monochrome.stb`) or one the drawing holds; `"none"` (or `""`) draws every object with its own properties, also in a layout whose page setup shows plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown `background` or `plot_style` is refused. Replies `{pngBase64, width, height, bytes, path?}`. | | `app.open` / `app.save` / `app.quit` | `{path}` | File operations. | | `control.methods` | | Every method this server answers: `{method, params, description}`. Headless (`cadcraft-cli mcp`) lists only the methods it serves. | | `ping` | | Replies `"pong"`. A cheap health check. | diff --git a/docs/mcp.md b/docs/mcp.md index dcb63e7db..504ca2c15 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -47,7 +47,7 @@ Example client configuration (Claude Code / Claude Desktop): | `execute {"command": "usage", "params": {type?, limit?, offset?}}` | Read-only cross-reference of the layers, blocks, text styles and linetypes: for each, the objects in model space and layouts that use it, the objects in block definitions that use it, whether it is used only inside block definitions, and whether it is empty or unused. `summary` counts each kind and `unused` lists what PURGE would offer, in table order. One scan reads at most 5,000,000 objects; a larger drawing sets `incomplete: true` with an `incompleteReason`, because counts, statuses and summaries then omit the objects past the limit. | | `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. | | `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). | -| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (default, the canvas), `"white"`, `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`. An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. | +| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. | | `find_text {contains?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (any case), layer and a window around the insertion points. Read-only (the `texts` command). | | `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. | | `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. | From 75175c807de864b0cb6ab3aa6edf810d8c668686 Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Thu, 5 Nov 2026 19:10:58 +0600 Subject: [PATCH 145/185] refactor(render): one constant for the dark canvas; the render error limits say they are limits (#803) render_look's DARK repeated the rasteriser's default background; both now read RasterOptions::DARK_BACKGROUND. ECHO and LISTED_TABLES are renamed MAX_ECHO_CHARS and MAX_LISTED_TABLES. No change in behaviour. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/render_look.rs | 18 +++++++++--------- crates/render/src/raster.rs | 7 ++++++- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/render_look.rs b/crates/engine/src/render_look.rs index ba4dbc8f4..524d288e9 100644 --- a/crates/engine/src/render_look.rs +++ b/crates/engine/src/render_look.rs @@ -20,7 +20,7 @@ use cadcraft_render::raster::RasterOptions; use serde_json::Value; /// The background a render draws on without `background`: the dark canvas. -pub const DARK: Rgb = Rgb(33, 40, 48); +pub const DARK: Rgb = RasterOptions::DARK_BACKGROUND; /// The background of `"white"` and `"paper"`. pub const WHITE: Rgb = Rgb(255, 255, 255); @@ -29,10 +29,10 @@ pub const BACKGROUNDS: &str = "\"dark\" (the default without a plot style), \"wh /// Most table names an unknown `plot_style` error lists from the drawing's own tables (the /// built-in ones are always listed). -const LISTED_TABLES: usize = 10; +const MAX_LISTED_TABLES: usize = 10; -/// Longest part of a refused value repeated in its error message. -const ECHO: usize = 40; +/// Longest part of a refused value repeated in its error message, in characters. +const MAX_ECHO_CHARS: usize = 40; /// The look of a render: what it draws on and with which plot style table. #[derive(Clone, Debug)] @@ -105,16 +105,16 @@ fn plot_style(d: &Drawing, name: &str) -> Result, String> } /// The tables a drawing can use, for an error message: the built-in ones, then at most -/// [`LISTED_TABLES`] of the drawing's own and how many more there are. +/// [`MAX_LISTED_TABLES`] of the drawing's own and how many more there are. fn table_list(d: &Drawing) -> String { let builtin = |n: &String| cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().any(|b| b.eq_ignore_ascii_case(n)); let names = cadcraft_doc::plot_style_table_names(d); let own: Vec = names.iter().filter(|n| !builtin(n)).map(|n| echo(n)).collect(); let mut list: Vec = cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().map(|b| (*b).to_string()).collect(); - list.extend(own.iter().take(LISTED_TABLES).cloned()); + list.extend(own.iter().take(MAX_LISTED_TABLES).cloned()); let mut text = list.join(", "); - if own.len() > LISTED_TABLES { - text.push_str(&format!(" and {} more of the drawing's", own.len() - LISTED_TABLES)); + if own.len() > MAX_LISTED_TABLES { + text.push_str(&format!(" and {} more of the drawing's", own.len() - MAX_LISTED_TABLES)); } text } @@ -127,7 +127,7 @@ fn object_properties() -> PlotStyleTable { /// The start of a refused value, to repeat in its error message. fn echo(v: &str) -> String { - v.chars().take(ECHO).collect() + v.chars().take(MAX_ECHO_CHARS).collect() } #[cfg(test)] diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index d802d2c1d..8c9205a14 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -64,9 +64,14 @@ pub struct RasterOptions { pub antialias: bool, } +impl RasterOptions { + /// The dark canvas a render draws on by default. + pub const DARK_BACKGROUND: Rgb = Rgb(33, 40, 48); +} + impl Default for RasterOptions { fn default() -> Self { - RasterOptions { background: Rgb(33, 40, 48), hairline: 1.0, px_per_mm: 0.0, antialias: true } + RasterOptions { background: Self::DARK_BACKGROUND, hairline: 1.0, px_per_mm: 0.0, antialias: true } } } From deb1468d085221c0719ec67ec538f43ffe6589f2 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 5 Nov 2026 16:10:30 -0700 Subject: [PATCH 146/185] build: drop three egui patches nothing uses egui_system_font_provider, egui_demo_lib and egui_inspection were patched to the egui fork with the rest of its family (#2119), but no crate here depends on them: Cargo.lock lists them as [[patch.unused]] and cargo warns on every build. A vendored offline build (Nix's importCargoLock) refuses an unused git patch, so the flakes in #794 and #1814 can't build main. Reported by @mbolling on #1814. --- Cargo.lock | 15 --------------- Cargo.toml | 3 --- 2 files changed, 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aef8a49c3..21cf7f054 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6292,18 +6292,3 @@ dependencies = [ "syn 3.0.9", "winnow", ] - -[[patch.unused]] -name = "egui_demo_lib" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - -[[patch.unused]] -name = "egui_inspection" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - -[[patch.unused]] -name = "egui_system_font_provider" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" diff --git a/Cargo.toml b/Cargo.toml index f2112a517..60d198514 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -118,8 +118,5 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968 egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } From 2b88b22949991b68905191a6717d80a3a39e51d8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 5 Nov 2026 18:34:43 -0700 Subject: [PATCH 147/185] Stage 1 stack: review fixes on #2584, #2471, #1626, #2028, #1026, #2658, #2612 - #2584: a tilted LWPOLYLINE/HATCH run is flattened to at most a million vertices, then its arcs stay chords (a hostile file of arcs asked for gigabytes; austin62jake). The file-format-parity.md hunk is dropped: maintainers update the parity docs. - #2471: another program's proxy objects are in the DWG loss report as its proxy entities are (left out before 2013, or when their class can't be named); they went silently. - #1626: a drawing saved at a view keeps it in the desktop app and when it has xrefs: the app's first frame and the xref pass both fitted the extents over it. OPEN's result says `saved_view`; one `view::saved_view` replaces the copy of `usable_view` in files.rs. A misplaced doc comment goes back to its test. - #2028: a plot rotation (73) outside 0-3 is written back as 0, not as read. - #1026: the binary code-page retry drops the first pass's tags before it runs (the peak doubled near the tag limit); a float spelling of an integer group clamps to what the width holds unsigned too, so 65535.0 reads as 65535 does, not 32767. - #2658: the reference names Undo by the last command ("Undo Group of commands"); Undo matched nothing and went to the end of Edit. Ordering and its test share one rule. - #2612: its test's Insert gets `clip: None` (XCLIP landed after it was written). --- crates/dxf/src/lib.rs | 18 +++++++----- crates/dxf/tests/hardening.rs | 17 +++++++++-- crates/engine/src/cmd/blocks/xref.rs | 4 +-- crates/engine/src/cmd/file.rs | 14 +++++++-- crates/engine/src/session/files.rs | 7 +---- crates/engine/src/tests.rs | 27 +++++++++++++++++ crates/engine/src/view.rs | 6 ++++ .../engine/tests/it/properties_set_locked.rs | 1 + crates/engine/tests/save_reports_not_saved.rs | 28 ++++++++++++++++++ crates/io/src/dxf_read/common.rs | 11 +++++-- crates/io/src/dxf_read/objects.rs | 4 ++- crates/io/src/tests.rs | 29 ++++++++++++++++--- crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/src/menus.rs | 24 +++++++++++++-- docs/file-format-parity.md | 5 ++-- 15 files changed, 164 insertions(+), 34 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 14b762516..94c652fd3 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -159,11 +159,12 @@ 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 => { - // A float spelling ("1e3", "12.0") is accepted when finite, clamped to the group's - // width; NaN, inf and text become 0. + // A float spelling ("1e3", "12.0") is accepted when finite, clamped to what the + // group's width holds, signed or unsigned (files write 16-bit flags up to 65535, as + // the integer spelling reads them); 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)), + Kind::Int16 => (i64::from(i16::MIN), i64::from(u16::MAX)), + Kind::Int32 => (i64::from(i32::MIN), i64::from(u32::MAX)), _ => (i64::MIN, i64::MAX), }; t.parse::() @@ -434,10 +435,13 @@ pub fn parse_binary(b: &[u8]) -> Result> { fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result> { 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()); + if !text.needs_code_page_pass() { + return Ok(tags); } - Ok(tags) + // The first pass's tags go before the second pass runs: both held at once would double + // the peak near the tag limit. + drop(tags); + parse_binary_pass(b, max_tags, &mut codepage::BinaryText::code_page_pass()) } fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText) -> Result> { diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs index 64b7340c6..1bff0d97f 100644 --- a/crates/dxf/tests/hardening.rs +++ b/crates/dxf/tests/hardening.rs @@ -109,15 +109,28 @@ 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))); + // Clamped to what the group's width holds, unsigned values included (the binary writer + // keeps up to 65535 and 4294967295 as their bit patterns). + assert_eq!(t[2], Tag::i(70, i64::from(u16::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[4], Tag::i(90, i64::from(u32::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); } +/// An unsigned value spelled as a float reads as the same spelled as an integer (#1026 review): +/// `65535.0` is 65535 like `65535`, not 32767. +#[test] +fn unsigned_values_read_the_same_in_either_spelling() { + let t = parse(b"70\n65535.0\n70\n65535\n90\n4294967295.0\n90\n4294967295\n0\nEOF\n").unwrap(); + assert_eq!(t[0], t[1]); + assert_eq!(t[0], Tag::i(70, 65535)); + assert_eq!(t[2], t[3]); + assert_eq!(t[2], Tag::i(90, 4_294_967_295)); +} + #[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(); diff --git a/crates/engine/src/cmd/blocks/xref.rs b/crates/engine/src/cmd/blocks/xref.rs index 18da7fa0f..3b91809e5 100644 --- a/crates/engine/src/cmd/blocks/xref.rs +++ b/crates/engine/src/cmd/blocks/xref.rs @@ -50,7 +50,7 @@ pub(super) fn specs() -> Vec { } /// Load the xrefs of drawing `i`, just opened (OPEN): the opened state counts as saved, and the -/// view frames the drawing with them. +/// view frames the drawing with them, unless the drawing opened on the view it was saved at. pub(crate) fn after_open(s: &mut Session, i: usize) { let px = s.viewport_px; let Some(st) = s.docs.get_mut(i) else { return }; @@ -61,7 +61,7 @@ pub(crate) fn after_open(s: &mut Session, i: usize) { let out = load::load_all(Arc::make_mut(&mut st.doc), path.as_deref()); st.saved = st.doc.clone(); let ext = st.doc.extents(&cadcraft_doc::Space::Model); - if !ext.is_empty() { + if !ext.is_empty() && crate::view::saved_view(&st.doc).is_none() { // 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); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 020317a91..378ddee4d 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -365,10 +365,12 @@ pub(crate) fn open_bytes(s: &mut Session, bytes: &[u8], name: &str, path: Option fn opened(s: &Session, i: usize, entities: bool) -> Value { let d = s.docs.get(i).map(|st| &st.doc); let warnings = d.map(|d| d.read_notes.clone()).unwrap_or_default(); + // Opened on the view it was saved at: a viewer keeps it instead of fitting the extents. + let saved_view = d.is_some_and(|d| crate::view::saved_view(d).is_some()); if entities { - json!({ "index": i, "entities": d.map(|d| d.entity_count()), "warnings": warnings }) + json!({ "index": i, "entities": d.map(|d| d.entity_count()), "warnings": warnings, "saved_view": saved_view }) } else { - json!({ "index": i, "warnings": warnings }) + json!({ "index": i, "warnings": warnings, "saved_view": saved_view }) } } @@ -804,6 +806,14 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap *n = n.saturating_add(1); } } + // Another program's proxy objects (in the OBJECTS section) follow the same rule as its proxy + // entities: the DWG writer leaves them out before 2013, or when their class can't be named. + for o in d.foreign.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACAD_PROXY_OBJECT")) { + if version < Version::R2013 || d.foreign.proxy_class(&o.tags).is_none() { + let n = out.entry("ACAD_PROXY_OBJECT".to_string()).or_insert(0); + *n = n.saturating_add(1); + } + } out } diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index e7e1639f9..9707086c4 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -1,10 +1,5 @@ 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 { @@ -26,7 +21,7 @@ impl Session { // 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, twist: 0.0 }).filter(usable_view); + let saved = crate::view::saved_view(&st.doc); let ext = st.doc.extents(&Space::Model); // The current tile (the first), or the lone untiled view, keeps its saved twist. 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)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 258222670..4d8081d7a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -213,6 +213,33 @@ fn a_drawing_opens_on_the_view_it_was_saved_at() { assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view()); } +/// Resolving a drawing's xrefs after OPEN refits the view only for a drawing that stores none: +/// one saved at a view keeps it, xref or not (#1626 review). +#[test] +fn a_drawing_with_an_xref_keeps_the_view_it_was_saved_at() { + let mut d = cadcraft_doc::Drawing::new_metric(); + let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(5e6, 5e6, 0.0) }; + d.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap(); + let mut xref = cadcraft_doc::Block::new("XR"); + xref.xref_path = Some("missing-xref.dxf".into()); + d.blocks.insert("XR".into(), std::sync::Arc::new(xref)); + let mut plain = d.clone(); + d.header.set_saved_view(Vec2::new(50.0, 50.0), 20.0); + + let mut s = Session::new(); + let i = s.open_drawing(d, "saved-view.dxf", None); + crate::cmd::blocks::xref::after_open(&mut s, i); + assert_eq!(s.state().unwrap().view(), View { center: Vec2::new(50.0, 50.0), height: 20.0, twist: 0.0 }); + + // With no stored view, the xrefs' pass still frames the drawing. + plain.header.vars.remove("VIEWCTR"); + plain.header.vars.remove("VIEWSIZE"); + let mut s = Session::new(); + let i = s.open_drawing(plain, "no-view.dxf", None); + crate::cmd::blocks::xref::after_open(&mut s, i); + 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/engine/src/view.rs b/crates/engine/src/view.rs index bbfc4f972..5514b968c 100644 --- a/crates/engine/src/view.rs +++ b/crates/engine/src/view.rs @@ -35,6 +35,12 @@ pub(crate) fn usable_view(v: &View) -> bool { v.center.is_finite() && v.height.is_finite() && v.height > 1e-12 && v.twist.is_finite() } +/// The view drawing `d` was saved at, when it records a usable one: OPEN opens on it, and nothing +/// after the open (resolving xrefs, the UI's first frame) fits the extents over it. +pub(crate) fn saved_view(d: &cadcraft_doc::Drawing) -> Option { + d.header.saved_view().map(|(center, height)| View { center, height, twist: 0.0 }).filter(usable_view) +} + /// Tiled model viewports (VPORTS): the session side of the drawing's `*Active` configuration. #[derive(Clone, Debug, Default, PartialEq)] pub struct ModelTiles { diff --git a/crates/engine/tests/it/properties_set_locked.rs b/crates/engine/tests/it/properties_set_locked.rs index 5277f48bd..d36ec72e9 100644 --- a/crates/engine/tests/it/properties_set_locked.rs +++ b/crates/engine/tests/it/properties_set_locked.rs @@ -127,6 +127,7 @@ fn during_refedit_objects_outside_the_working_set_are_left_out() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }); let a = s.doc_mut().unwrap().add(&Space::Model, Common::default(), kind).unwrap(); let other = line(&mut s, 20.0); diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index c8c33b2de..980f92676 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -148,6 +148,34 @@ fn proxy_entities_are_reported_only_before_2013() { assert_eq!(not_saved_as(&d, Version::R2018), [("ACAD_PROXY_ENTITY".to_string(), 2), ("MLINE".to_string(), 1)].into_iter().collect()); } +/// Another program's proxy objects are left out of a DWG the same way as its proxy entities, and +/// said so: before 2013 always, from 2013 when the file names no class for them (#2471 review). +#[test] +fn proxy_objects_are_reported_like_proxy_entities() { + use cadcraft_engine::cmd::file::{Version, not_saved_as}; + use cadcraft_engine::doc::Handle; + use cadcraft_engine::doc::foreign::{Foreign, ForeignObject}; + let object = |h: u64, class: i64| ForeignObject { + handle: Handle(h), + kind: "ACAD_PROXY_OBJECT".into(), + tags: vec![ + RawTag { code: 5, value: format!("{h:X}") }, + RawTag { code: 90, value: "499".into() }, + RawTag { code: 91, value: class.to_string() }, + ], + }; + let mut d = Drawing::new_imperial(); + d.foreign = std::sync::Arc::new(Foreign { + class_order: vec!["MYAPP_DATA".into()], + objects: vec![object(0x500, 500), object(0x501, 501)], + ..Foreign::default() + }); + let lost = |v| not_saved_as(&d, v).get("ACAD_PROXY_OBJECT").copied().unwrap_or(0); + assert_eq!(lost(Version::R2004), 2, "before 2013 every proxy object is left out"); + assert_eq!(lost(Version::R2010), 2); + assert_eq!(lost(Version::R2018), 1, "from 2013 only the one whose class the file doesn't name"); +} + /// 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] diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 47a51b903..59dcf7107 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -159,10 +159,15 @@ pub(super) fn run_points(vertices: &[PolyVertex], elevation: f64, closed: bool) pts.into_iter().map(|p| p.to3(elevation)).collect() } +/// The most vertices one tilted run is flattened to: past it, bulged edges are kept as their +/// chords, so a file full of arcs can't ask for gigabytes (one arc adds at most 4,096 more). +const MAX_TILTED_VERTICES: usize = 1_000_000; + /// 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 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. +/// of the edge's own size, up to [`MAX_TILTED_VERTICES`] in all), 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()); @@ -175,7 +180,7 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c None }; match next { - Some(w) if v.bulge != 0.0 => { + Some(w) if v.bulge != 0.0 && local.len() < MAX_TILTED_VERTICES => { 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(); diff --git a/crates/io/src/dxf_read/objects.rs b/crates/io/src/dxf_read/objects.rs index 17a00249c..98cdf7d52 100644 --- a/crates/io/src/dxf_read/objects.rs +++ b/crates/io/src/dxf_read/objects.rs @@ -252,7 +252,9 @@ 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))); + // Kept to be written back, so only a rotation the DXF Reference defines (0-3): any other + // value reads as not rotated and is written so. + p.file_paper = Some((w, h, t.i(73).filter(|r| (0..=3).contains(r)).unwrap_or(0))); } else if t.i(73).is_some() { p.landscape = rotated; } diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 829056b97..92c84a9f2 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -648,10 +648,6 @@ 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). /// 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). @@ -676,6 +672,10 @@ fn a_tiled_drawing_with_no_saved_view_keeps_its_first_tiles_view() { assert_eq!(back.header.saved_view(), Some((Vec2::new(1.0, 1.0), 10.0)), "read from the first tile"); } +/// 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(); @@ -832,6 +832,10 @@ fn a_files_own_paper_groups_are_written_back() { 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"); + // A plot rotation the DXF Reference doesn't define (0-3) reads as not rotated and is written + // back as 0, not as read (#2028 review). + let r = read_dxf(set(&write_dxf(&d), (210.0, 297.0, 99)).as_bytes()).unwrap(); + assert_eq!(plot_paper_groups(&write_dxf(&r), "Layout1").2, 0, "an undefined rotation is not written back"); } #[test] @@ -2683,6 +2687,23 @@ fn tilted_tapered_arc_spreads_its_width() { 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)); } +/// A tilted polyline made of a great many arcs is flattened within a budget: past a million +/// vertices its arcs stay chords, so a hostile file can't ask for gigabytes (#2584 review). +#[test] +fn a_tilted_polyline_of_many_arcs_is_flattened_within_a_budget() { + let n = 50_000; + let mut text = format!("0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n{n}\n70\n0\n210\n0\n220\n0.5\n230\n-0.8660254037844386\n"); + for i in 0..n { + text.push_str(&format!("10\n{i}\n20\n0\n42\n1\n")); + } + text.push_str("0\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 }); + // Every arc flattened would be millions; the budget, one last arc past it and the chords. + assert!(p.vertices.len() <= 1_000_000 + 4_096 + n, "{} vertices", p.vertices.len()); + assert!(p.vertices.len() > n, "the arcs before the budget are still curved"); +} + /// 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. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d27712da2..0f43acfbd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -640,7 +640,8 @@ impl CadApp { Err(e) => self.set_status(e), Ok(v) => { self.ui.start_tab = false; - self.canvas.zoom_pending = true; + // A drawing that opened on the view it was saved at keeps it (#1626). + self.canvas.zoom_pending = !v.get("saved_view").and_then(Value::as_bool).unwrap_or(false); let doc = v.get("index").and_then(Value::as_u64).and_then(|i| self.session.docs.get(usize::try_from(i).ok()?)); if let Some(path) = doc.and_then(|d| d.path.clone()) { self.remember_recent(path); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 0c92813c0..5d9f02151 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -45,10 +45,17 @@ fn reference() -> &'static [Reference] { }) } +/// Whether our item `ours` is the reference's `theirs`. The reference names Undo by what it shows +/// at the moment, the last command ("Undo Group of commands" when the tree was read), not by a +/// fixed label. +fn same_item(ours: &str, theirs: &str) -> bool { + ours == theirs || (ours == "Undo" && theirs.starts_with("Undo ")) +} + /// 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); + let position = |label: &str| reference.iter().position(|r| same_item(label, r.label)).unwrap_or(usize::MAX); entries.sort_by_key(|e| match e { Entry::Item { label, .. } | Entry::Sub { label, .. } => position(label), }); @@ -1079,8 +1086,10 @@ mod reference_order_tests { /// 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 theirs = |e: &Entry| reference.iter().find(|r| super::same_item(label(e), r.label)).map(|r| r.label); + let known = |e: &Entry| theirs(e).is_some(); + // Our items by the reference's names for them, to compare orders. + let listed: Vec<&str> = entries.iter().filter_map(theirs).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:?}")); @@ -1125,6 +1134,15 @@ mod reference_order_tests { 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)); } + + /// Edit starts with Undo and Redo, as the reference's does: its Undo is named by the last + /// command, so a plain label match sent Undo to the end of the menu (#2658 review). + #[test] + fn edit_starts_with_undo_and_redo() { + let app = CadApp::new(Session::new(), Services::default()); + let edit = tree(&app).into_iter().find(|(m, _)| m == "Edit").map(|(_, e)| e).unwrap_or_default(); + assert_eq!(edit.iter().take(2).map(label).collect::>(), ["Undo", "Redo"]); + } } #[cfg(test)] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 913cb2388..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,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), 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) | | @@ -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. | From 417f195cc31786c51c53a8543f62cae3e4ba4054 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 5 Nov 2026 18:57:19 -0700 Subject: [PATCH 148/185] Stage 1 stack: CodeRabbit on #2837 (CLASS places, the first *ACTIVE record) - #2471: an unnamed CLASS record keeps its place in the class list a DWG maps proxies by, so the classes after it keep theirs; a proxy of the unnamed class is left out instead of taking the next class's name (the ODA refuses such a DWG). - #1626: the first *ACTIVE VPORT record is the caller's to say. A first record with a usable view but an unusable tile kept no tile, so the next *ACTIVE record was taken for the first and its view replaced the saved one (also austin62jake on #1626). --- crates/dwg/src/lib.rs | 18 ++++++++++++++++-- crates/io/src/dxf_read/tables.rs | 13 ++++++++----- crates/io/src/tests.rs | 13 +++++++++++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index d41240488..0dcbd0667 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -816,9 +816,19 @@ mod native { 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"0", v) if in_classes => { + in_class = v == b"CLASS"; + // Every record keeps its place, named or not: a proxy numbers its class by + // place, so a record without a name must not move the ones after it. An empty + // name matches no class, and such a proxy is left out. + if in_class { + names.push(String::new()); + } + } (b"1", v) if in_class => { - names.push(String::from_utf8_lossy(v).into_owned()); + if let Some(last) = names.last_mut() { + *last = String::from_utf8_lossy(v).into_owned(); + } in_class = false; } _ => {} @@ -1622,6 +1632,10 @@ mod tests { 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).unwrap(), ["WIDGETA", "WIDGETB"]); + // A CLASS record without a name keeps its place, so the classes after it keep theirs + // (#2837 review). + let unnamed = b" 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 2\r\nAcDbNoName\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n"; + assert_eq!(native::dxf_class_names(unnamed).unwrap(), ["", "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/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index d55cbdfca..f18c44412 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -199,7 +199,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { // The first *ACTIVE viewport holds the current snap/grid settings. "VPORT" if !active_vport && t.s(2).is_some_and(|n| n.trim().eq_ignore_ascii_case("*ACTIVE")) => { active_vport = true; - vport_record(d, &t); + vport_record(d, &t, true); for (name, code) in [("SNAPUNIT", 14), ("GRIDUNIT", 15)] { if let (Some(x), Some(y)) = (t.f(code), t.f(code + 10)) { let p = Vec2::new(x, y); @@ -282,7 +282,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { None => d.dim_styles.push(st), } } - "VPORT" => vport_record(d, &t), + "VPORT" => vport_record(d, &t, false), _ => {} } } @@ -323,8 +323,9 @@ fn index_table_handles(recs: &[(String, Vec)], rx: &mut Rx) { const MAX_VPORT_TILES: usize = 64; /// A VPORT record: one tile of the configuration it names (`*ACTIVE` the one shown). Corners -/// are fractions of the drawing area; unusable tiles are skipped. -fn vport_record(d: &mut Drawing, t: &T) { +/// are fractions of the drawing area; unusable tiles are skipped. `first_active`: this is the +/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view. +fn vport_record(d: &mut Drawing, t: &T, first_active: bool) { let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default(); // View twist (group 51, degrees). let twist = t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians())); @@ -334,7 +335,9 @@ fn vport_record(d: &mut Drawing, t: &T) { // 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()); + // From the caller, which knows the record's place: whether a tile was kept for an earlier + // `*ACTIVE` record says nothing when that record's tile was unusable. + let first_active = first_active && name.eq_ignore_ascii_case(VportConfig::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); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 92c84a9f2..0a10424bc 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -648,6 +648,19 @@ 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"); } +/// The saved view is the first `*ACTIVE` record's even when that record's tile rectangle is +/// unusable: the next `*ACTIVE` record is a second tile, not the first again (#2837 review). +#[test] +fn the_first_active_record_gives_the_view_even_with_an_unusable_tile() { + const TWO: &str = "\ +0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n\ +0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n0.0\n21\n0.0\n12\n50.0\n22\n50.0\n40\n20.0\n\ +0\nVPORT\n2\n*ACTIVE\n70\n0\n10\n0.0\n20\n0.0\n11\n1.0\n21\n1.0\n12\n900.0\n22\n900.0\n40\n5.0\n\ +0\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(TWO.as_bytes()).unwrap(); + assert_eq!(d.header.saved_view(), Some((Vec2::new(50.0, 50.0), 20.0)), "the first record's view"); +} + /// 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). From 1f11d4f7014549f2872bd4a02b10c72cacde3b59 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Thu, 5 Nov 2026 20:16:44 -0700 Subject: [PATCH 149/185] Stage 1 stack 2: review fixes on #2587, #2585, #2608 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - #2587: a frame turned by anything but a quarter turn keeps its size about its turned centre; the box of its two mapped corners collapsed it (a 10 x 10 square turned 45° became 14.14 x 0, and the OLE header with it) for EXPLODE, REFEDIT, paste and array placement (austin62jake, CodeRabbit). Moves, scales, mirrors and quarter turns keep the exact corner mapping. `recase` reads only the rewritten digits and a few after them, not the whole 310 line (austin62jake). The PR's rotated-frame test expects the kept size. - #2585: an `output` that contradicts the path's extension is refused, as a device that does is; it lost silently to the extension. - #2608: the window's state is dropped when another dialog took its place (it missed a UI pass), so reopening reads the drawing instead of an old unsent edit (CodeRabbit); TEXT and ATTDEF get a one-line field (Enter commits), so a line break can't turn into a space on save; the module comment says the shortcut menu opens it. --- crates/doc/src/extents.rs | 99 ++++++++++++++++++++++++--- crates/engine/src/cmd/layout/tests.rs | 4 ++ crates/engine/src/cmd/plotters.rs | 7 ++ crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/textdlg.rs | 28 ++++++-- 5 files changed, 125 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 618da4aab..9f29c07b6 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -124,7 +124,10 @@ fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4 let (Some(t), Some(chunk)) = (tags.get_mut(i), bytes.get(pos..pos + n)) else { return }; // 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()); + // Only the rewritten digits and a few after them, for the case of the nearest letter: a + // hostile 310 line can be as long as the file (the value is checked to be ASCII above). + let end = start.saturating_add(2 * n + 64).min(t.value.len()); + let hex = recase(chunk, t.value.get(start..end).unwrap_or_default()); t.value.replace_range(start..start + 2 * n, &hex); pos += n; } @@ -189,14 +192,32 @@ const CORNER_EPS: f64 = 1e-6; /// 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 +/// its upper-left corner first. A matrix that keeps the axes or swaps them (a move, scale, mirror or +/// quarter turn) gives the box of the two mapped corners. Any other turn would collapse that box +/// (a square turned 45° maps its two corners level), so the frame's centre is mapped and its size +/// kept, scaled by `m`'s, its sides swapped when the turn is nearer a quarter turn. 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 }; let frame = [x1, y1, x2, y2]; - let (a, b) = (m.apply(Vec2::new(x1, y1)), m.apply(Vec2::new(x2, y2))); + let t = 1e-12 * (m.a.abs() + m.b.abs() + m.c.abs() + m.d.abs()); + let axes_kept = (m.b.abs() <= t && m.c.abs() <= t) || (m.a.abs() <= t && m.d.abs() <= t); + let (a, b) = if axes_kept { + (m.apply(Vec2::new(x1, y1)), m.apply(Vec2::new(x2, y2))) + } else { + let center = m.apply(Vec2::new((x1 + x2) / 2.0, (y1 + y2) / 2.0)); + // A plain turn keeps the size exactly; cos² + sin² can miss 1 by an ulp or two. + let s = (m.a * m.d - m.b * m.c).abs().sqrt(); + let scale = if (s - 1.0).abs() < 1e-12 { 1.0 } else { s }; + let (mut w, mut h) = ((x2 - x1).abs() * scale, (y2 - y1).abs() * scale); + // Where the frame's x axis goes: nearer to y than to x is nearer a quarter turn. + if m.b.abs() > m.a.abs() { + std::mem::swap(&mut w, &mut h); + } + (center - Vec2::new(w, h) / 2.0, center + Vec2::new(w, h) / 2.0) + }; if !(a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) { return; } @@ -909,16 +930,23 @@ mod tests { } /// 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). + /// It stays axis aligned: groups 10/20 are the upper-left of its box, 11/21 the lower-right, + /// and the OLE data holds the same box (review on #2587). A mirror keeps the axes, so the box + /// is that of the mapped corners; a 30° turn keeps the frame's own 5 x 3 about its turned + /// centre, where the corners' box would flatten it. #[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] { + for (m, turned) in [(rotate, true), (mirror, false)] { let mut tags = small_frame(); - let mapped = [m.apply(Vec2::new(30.0, -19.0)), m.apply(Vec2::new(35.0, -22.0))]; + let mapped = if turned { + let c = m.apply(Vec2::new(32.5, -20.5)); + [c - Vec2::new(2.5, 1.5), c + Vec2::new(2.5, 1.5)] + } else { + [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); @@ -1034,4 +1062,57 @@ mod tests { assert!(same > 40, "most of the header is unchanged: {same}"); assert_eq!(header_corners(&tags)[0], (40.0, -14.0)); } + + /// A frame from `(x1, y1)` (upper left) to `(x2, y2)` (lower right), its OLE header holding the + /// same corners. + fn frame_at(x1: f64, y1: f64, x2: f64, y2: f64) -> Vec { + let mut blob = vec![1u8, 0]; + for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] { + for v in [x, y, 0.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()), + ] + } + + fn size(tags: &[crate::RawTag]) -> (f64, f64, Vec2) { + let o = ole_frame(tags).unwrap(); + let b = Bounds2::from_points(o); + (b.width(), b.height(), b.center()) + } + + /// A frame turned by an angle that isn't a quarter turn keeps its size about its turned + /// centre instead of collapsing to the box of its two corners (a 10 x 10 square turned 45° + /// became 14.14 x 0), and the OLE header follows (#2587 review). + #[test] + fn a_frame_turned_off_the_axes_keeps_its_size() { + use cadcraft_geom::Mat3; + let close = |a: f64, b: f64| (a - b).abs() < 1e-9; + let mut tags = frame_at(0.0, 10.0, 10.0, 0.0); + ole_frame_transform(&mut tags, &Mat3::rotate(std::f64::consts::FRAC_PI_4)); + let (w, h, c) = size(&tags); + assert!(close(w, 10.0) && close(h, 10.0), "{w} x {h}"); + assert!(close(c.x, 0.0) && close(c.y, 50f64.sqrt()), "{c:?}"); + let (ul, lr) = (header_corners(&tags)[0], header_corners(&tags)[2]); + assert!(close(ul.0, -5.0) && close(lr.1, 50f64.sqrt() - 5.0), "the header follows: {ul:?} {lr:?}"); + // Nearer a quarter turn, the sides swap: a 10 wide, 4 tall frame turned 100° is 4 x 10. + let mut tags = frame_at(0.0, 4.0, 10.0, 0.0); + ole_frame_transform(&mut tags, &Mat3::rotate(100f64.to_radians())); + let (w, h, _) = size(&tags); + assert!(close(w, 4.0) && close(h, 10.0), "{w} x {h}"); + // A turn and its inverse bring the frame back. + let mut tags = frame_at(2.0, 9.0, 7.0, 3.0); + let m = Mat3::rotate(0.3); + ole_frame_transform(&mut tags, &m); + ole_frame_transform(&mut tags, &m.inverse().unwrap()); + let (w, h, c) = size(&tags); + assert!(close(w, 5.0) && close(h, 6.0) && close(c.x, 4.5) && close(c.y, 6.0), "{w} x {h} at {c:?}"); + } } diff --git a/crates/engine/src/cmd/layout/tests.rs b/crates/engine/src/cmd/layout/tests.rs index 63af8ebe1..57d52a7ef 100644 --- a/crates/engine/src/cmd/layout/tests.rs +++ b/crates/engine/src/cmd/layout/tests.rs @@ -366,5 +366,9 @@ fn plot_path_extension_picks_the_format_like_export() { } // An explicit output still decides for an odd name. assert_eq!(s.execute("plot", &json!({"path": path("z.txt"), "output": "pdf"})).unwrap()["format"], "pdf"); + // But one that contradicts the extension is refused, as a device that does is (#2585 review). + let e = s.execute("plot", &json!({"path": path("w.png"), "output": "svg"})).unwrap_err().to_string(); + assert!(e.contains("svg") && e.contains("png"), "{e}"); + assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree"); std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index 9701940a7..457a098b4 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -312,6 +312,13 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { { return Err(bad(cmd, format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str()))); } + // An `output` that says another format than the path's extension is refused too, as a device + // that does is: either way the file would not hold what its name says. + if let (Some(want), Some(asked)) = (by_path, p.get("output").and_then(Value::as_str).and_then(PlotOutput::parse)) + && asked != want + { + return Err(bad(cmd, format!("`output` is {}, but the path asks for {}", asked.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())); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b2e3af0f9..1b68264d9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -40,7 +40,7 @@ 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. +// The Edit Text window, opened from the shortcut menu's Edit Text entry. 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 index b0c56e4ef..4c79d0993 100644 --- a/crates/ui-egui/src/textdlg.rs +++ b/crates/ui-egui/src/textdlg.rs @@ -38,6 +38,12 @@ struct State { /// active, and committing to it would edit an object the user never saw. uid: u64, message: String, + /// Multiline text (MTEXT): plain Enter breaks the line. TEXT and ATTDEF are one line, and a + /// line break typed there would be a space once saved. + multiline: bool, + /// The UI pass the window last showed in. A window that missed a pass was closed some other + /// way (another dialog took its place), and its edit is not the user's any more. + pass: u64, } /// Read the object the window is for. A handle that no longer exists, or an object that is not @@ -49,6 +55,7 @@ fn initial(app: &CadApp, hex: &str) -> State { 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.multiline = matches!(e.kind, EntityKind::MText(_)); st.text = text_of(&e.kind).unwrap_or_default(); st.original = st.text.clone(); st @@ -61,10 +68,19 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, spec: &str, open: &mut bool 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 pass = ctx.cumulative_pass_nr(); let mut st = match cached { - Some(s) => s, + // Shown in the last pass: the same window, still open. + Some(s) if s.pass.saturating_add(1) >= pass => s, + // Closed without passing through here: start from the drawing again, with a fresh field. + Some(s) => { + let field = egui::Id::unique("textedit_field").with(s.uid).with(&s.handle); + ctx.data_mut(|d| d.remove::(field)); + initial(app, &hex) + } None => initial(app, &hex), }; + st.pass = pass; // 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; @@ -82,10 +98,12 @@ 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).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.ctrl && i.key_pressed(egui::Key::Enter)) { + let edit = if st.multiline { egui::TextEdit::multiline(&mut st.text).desired_rows(3) } else { egui::TextEdit::singleline(&mut st.text) }; + let r = ui.add(edit.id(field).desired_width(f32::INFINITY).hint_text(crate::tl!("Text"))); + // Ctrl+Enter commits from inside the field, so a multiline text can keep plain Enter; + // a one-line field commits on Enter too. + let enter = ui.input(|i| i.key_pressed(egui::Key::Enter)); + if (r.has_focus() && enter && ui.input(|i| i.modifiers.ctrl)) || (!st.multiline && r.lost_focus() && enter) { commit = true; } ui.horizontal(|ui| { From aa1c896ef254389fd1d86d51da2fe186dd737529 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:50:01 +0100 Subject: [PATCH 150/185] Copy the shared house rules into AGENTS.md. The blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. CLAUDE.md imports AGENTS.md. The house-rules workflow checks the copy. --- .github/workflows/house-rules.yml | 28 ++++++++++++++ AGENTS.md | 62 +++++++++++++++++++++++++++---- CLAUDE.md | 53 +------------------------- 3 files changed, 84 insertions(+), 59 deletions(-) create mode 100644 .github/workflows/house-rules.yml diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 000000000..de64ad3ee --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 309f3f0ce..8d040f598 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,13 +1,62 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # CADCraft — instructions for agents 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). ## 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). -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §6). Don't stop to ask unless it lists the decision as the owner's. - -`plan/` is gitignored (local only). +Read [`ROADMAP.md`](ROADMAP.md) and [`docs/gaps.md`](docs/gaps.md). `plan/` is an optional gitignored notebook (status, execution notes, `plan/autocad/*`). Do not ask for it and do not stop when it is absent. Licence choices stay inside the house-rules allowlist. ## Never crash People trust CADCraft with their drawings; a crash loses their work. **This outranks feature work.** @@ -28,9 +77,8 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr - **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence. - **Layering** is enforced by `cargo xtask layers`: L0 `geom`, `dxf` → L1 `color`, `doc` → L2 `fonts`, `render`, `constraints` → L3 `io` → L4 `engine` → L5 `ui-egui`, `mcp` → apps. Nothing below L5 depends on egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.** - **The UI is thin**: panels read engine state and act through `app.run(id, params)` / `app.start(id)` / `app.cmdline(text)`. Colours come from `theme::Tokens`. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds, and push to `main`. +- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds. ## Running and looking at the app - `cargo run --release -p cadcraft -- --sample --control PORT` (sample drawing + control channel). Pick a free port; other crafting apps use control ports too. diff --git a/CLAUDE.md b/CLAUDE.md index 659cc8c2b..43c994c2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,52 +1 @@ -# CADCraft — instructions for agents - -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). - -## 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). -3. Follow the autonomous operation protocol (`plan/execution-plan.md` §6). Don't stop to ask unless it lists the decision as the owner's. - -`plan/` is gitignored (local only). - -## Never crash -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. -- **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`, `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 -- **Clean-room.** AutoCAD is installed on the dev machine and may be *observed* black-box: run it, use its UI with synthetic drawings, take screenshots (by window id) stored only under `plan/autocad/screenshots/` (never committed). **Never** read, disassemble or copy anything inside the AutoCAD bundle (names/listings only); never copy Autodesk fonts (SHX), hatch patterns (`.pat`), linetypes (`.lin`), templates, CUI/PGP files, icons, artwork or help text; never commit files produced by AutoCAD. File formats come from public specifications (Autodesk's published DXF Reference, the Open Design Alliance's public DWG specification) and our own synthetic tests. Never copy or link GPL/LGPL/AGPL code (LibreDWG, LibreCAD, QCAD, FreeCAD's planegcs, SolveSpace, OpenCASCADE) — don't even read their sources. -- **Assets — absolutely essential.** CADCraft contains **no Autodesk, Adobe or Avid iconography, images, fonts, patterns or artwork — ever.** Every icon is drawn in code (`crates/ui-egui/src/icons.rs`), every hatch pattern and linetype is our own definition (`crates/doc/src/library.rs`), the drafting font is our own (`crates/fonts/src/stroke.rs`). Any file asset must be original, public domain/CC0, OSI-licensed, or redistributable Creative Commons (or licensed open source by a contributor who made it), and **must have a row in `ATTRIBUTION.md`** with author, source and licence (`cargo xtask assets` enforces it). The only exception is the ArtCraft brand in `docs/brand/` (trademarks, `docs/brand/LICENSE-brand.txt`). Screenshots of Autodesk software are never committed. Breaking this rule is the most serious mistake you can make in this repo. -- **Fonts live in [`storytold/craft-fonts`](https://github.com/storytold/craft-fonts)**, never in this repo. It is an optional build input (`CRAFT_FONTS_DIR`, embedded by `crates/fonts/build.rs`), never a `Cargo.toml` dependency. Code and tests must work without it. -- **Shared test corpora** live in separate repos (`storytold/-corpus`); never commit large binary fixtures here. -- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (`CommandSpec`: id = AutoCAD's command name in lower case, label, menu path, shortcut, aliases, params doc, `enabled`, JSON `run`, optional `interactive` prompt machine) + tests. UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The command line, menus, toolbar, Tool Sets, scripts, CLI, control channel and MCP all reach the same commands. -- **Programmatic calls never open dialogs.** `engine.execute` runs the JSON form with defaults; only menu/toolbar invocation starts the interactive prompt sequence. -- **Layering** is enforced by `cargo xtask layers`: L0 `geom`, `dxf` → L1 `color`, `doc` → L2 `fonts`, `render`, `constraints` → L3 `io` → L4 `engine` → L5 `ui-egui`, `mcp` → apps. Nothing below L5 depends on egui/eframe/winit/wgpu/rfd. **The UI crate is swappable.** -- **The UI is thin**: panels read engine state and act through `app.run(id, params)` / `app.start(id)` / `app.cmdline(text)`. Colours come from `theme::Tokens`. -- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`). -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, assets, layers, wasm). Commit after every feature arc that builds, and push to `main`. - -## Running and looking at the app -- `cargo run --release -p cadcraft -- --sample --control PORT` (sample drawing + control channel). Pick a free port; other crafting apps use control ports too. -- Drive it with JSON lines on `127.0.0.1:PORT`: - - `{"id":1,"method":"cmdline.input","params":{"text":"circle 0,0 5"}}` — type at the command line exactly like a user (prompts, keywords, `@dx,dy`, `@d Date: Fri, 6 Nov 2026 13:35:40 -0700 Subject: [PATCH 151/185] Stage 1 stack 3: review fixes on #1105, #1002, #1908, #1907, #2134, #2371 --- crates/engine/src/cmd/file/pgp.rs | 28 ++++++++-- crates/engine/src/cmd/modify2/textedit.rs | 9 ++- crates/engine/src/mtext_edit.rs | 23 +++++++- crates/engine/src/prompt.rs | 5 +- crates/engine/tests/aliases.rs | 9 +++ crates/engine/tests/it/mleader_text_edit.rs | 61 ++++++++++++++++++++- crates/ui-egui/src/aliasdlg.rs | 48 +++++++++++++++- crates/ui-egui/src/context_menu.rs | 12 ++-- crates/ui-egui/src/keys.rs | 9 +++ crates/ui-egui/src/menus.rs | 4 ++ crates/ui-egui/src/mtext_editor.rs | 46 ++++++++++++---- crates/ui-egui/src/options/dialog.rs | 2 +- 12 files changed, 223 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/file/pgp.rs b/crates/engine/src/cmd/file/pgp.rs index 71dfee5c1..3269abc9f 100644 --- a/crates/engine/src/cmd/file/pgp.rs +++ b/crates/engine/src/cmd/file/pgp.rs @@ -1,8 +1,8 @@ //! The user's command alias file (the publicly documented `.pgp` format: `ALIAS, *COMMAND` lines, //! `;` comments): ALIASEDIT and REINIT. //! -//! A loaded file adds aliases or overrides the built-in ones for the rest of the session, for -//! every drawing; command names themselves always win. Lines that define external commands +//! A loaded file replaces the user aliases, which add to or override the built-in ones for every +//! drawing; command names themselves always win. Lines that define external commands //! (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. @@ -63,7 +63,13 @@ pub(crate) fn user_alias(name: &str) -> Option { /// `{"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 }) + // A path [`restore_aliases`] would refuse is left out, so it can't grow the profile either. + json!({ "aliases": st.map, "file": st.file.as_deref().filter(|f| keepable_path(f)) }) +} + +/// Whether the profile keeps an alias file path: short enough, and no control characters. +fn keepable_path(f: &str) -> bool { + f.chars().count() <= MAX_ALIAS_FILE_CHARS && !f.chars().any(char::is_control) } /// Restore aliases saved by [`alias_profile`], replacing the user aliases and the file. @@ -75,14 +81,18 @@ 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(f)) if keepable_path(f) => 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) { + // Entries that are skipped don't use up the cap. + for (alias, target) in map { + if aliases.len() >= MAX_ALIASES { + break; + } let Ok(name) = alias_name(alias) else { continue }; let Some(id) = target.as_str().and_then(command_id) else { continue }; aliases.insert(name, id); @@ -263,4 +273,12 @@ mod tests { assert!(spec.id.chars().count() <= MAX_COMMAND_ID_CHARS, "`{}` exceeds the alias profile bound", spec.id); } } + + /// An alias file path the profile couldn't restore isn't saved in it. + #[test] + fn only_paths_the_profile_restores_are_saved() { + assert!(super::keepable_path("C:\\support\\mine.pgp")); + assert!(!super::keepable_path(&"x".repeat(super::MAX_ALIAS_FILE_CHARS + 1))); + assert!(!super::keepable_path("mine\n.pgp")); + } } diff --git a/crates/engine/src/cmd/modify2/textedit.rs b/crates/engine/src/cmd/modify2/textedit.rs index a0daa7d40..081737a7b 100644 --- a/crates/engine/src/cmd/modify2/textedit.rs +++ b/crates/engine/src/cmd/modify2/textedit.rs @@ -96,6 +96,10 @@ 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*"))?; + // Refused when picked, not after the new text has been typed. + if curves::is_locked(s, h) { + return Err(other("The object is on a locked layer.")); + } let kind = curves::entity(s, h)?.kind; let old = text_of(&kind).ok_or_else(|| other("Select a text, mtext, multileader, attribute definition or dimension."))?; self.mtext = match kind { @@ -104,10 +108,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. + // The editor would drop part of a text this long, and saving would lose it: the + // command line asks for it instead. if self.mtext.as_ref().is_some_and(|m| !crate::mtext_edit::Formatted::fits(&m.contents)) { self.mtext = None; - return Err(other("This text is too long to edit; it is left as it is.")); + s.echo("This text is too long for the editor; enter the new text at the command line."); } 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 334ff5ed7..c6d06f46a 100644 --- a/crates/engine/src/mtext_edit.rs +++ b/crates/engine/src/mtext_edit.rs @@ -111,8 +111,8 @@ impl 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. + /// Whether the editor holds all of `contents`: past [`MAX_CHARS`] characters, [`MAX_PARAS`] + /// paragraphs or [`MAX_ATOMS`] kept codes the rest would be dropped, and saving would lose it. pub fn fits(contents: &str) -> bool { Self::parse(contents, None).1 } @@ -125,6 +125,8 @@ impl Formatted { let mut cur = CharFmt::default(); let mut props = ParaProps::default(); f.paras = vec![props.clone()]; + // Cleared when a paragraph or a kept code doesn't fit. + let mut whole = true; let mut i = 0; while let Some(&c) = chars.get(i) { if f.fmt.len() >= MAX_CHARS { @@ -148,6 +150,8 @@ impl Formatted { if f.paras.len() < MAX_PARAS { f.push_char('\n', &cur); f.paras.push(props.clone()); + } else { + whole = false; } i += 1; } @@ -160,6 +164,7 @@ impl Formatted { f.push_char('\n', &cur); f.paras.push(props.clone()); } + Some('P') => whole = false, Some(c @ ('\\' | '{' | '}')) => f.push_char(c, &cur), Some('L') => cur.underline = true, Some('l') => cur.underline = false, @@ -197,6 +202,7 @@ impl Formatted { code.extend(chars.get(i..=end.min(chars.len().saturating_sub(1))).unwrap_or_default().iter()); i = end + 1; } + whole &= f.atoms.len() < MAX_ATOMS; f.push_atom(code, &cur); } } @@ -207,7 +213,7 @@ impl Formatted { } } } - (f, true) + (f, whole) } fn push_char(&mut self, c: char, fmt: &CharFmt) { @@ -621,4 +627,15 @@ mod tests { let _ = f.fmt_at(usize::MAX); let _ = Formatted::from_contents(&"{".repeat(100_000)); } + + /// A text with more paragraphs or kept codes than the editor holds doesn't fit, so TEXTEDIT + /// leaves it to the command line instead of dropping the rest on save. + #[test] + fn too_many_paragraphs_or_codes_do_not_fit() { + assert!(Formatted::fits("one\\Ptwo\\A1;three")); + assert!(!Formatted::fits(&"a\\P".repeat(MAX_PARAS))); + assert!(!Formatted::fits(&"a\n".repeat(MAX_PARAS))); + assert!(!Formatted::fits(&"\\A1;".repeat(MAX_ATOMS + 1))); + assert!(Formatted::fits(&"\\A1;".repeat(MAX_ATOMS))); + } } diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index 8bf4b28d8..884237bb0 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -286,8 +286,9 @@ pub trait Interactive: Send { fn drag(&self, _s: &Session, _cursor: Vec2) -> Option { None } - /// The multiline text being typed (MTEXT, once its box is known) with empty contents: where - /// the UI places its in-place editor and with which height, width and justification. + /// The multiline text being typed (MTEXT, once its box is known, with empty contents) or edited + /// (TEXTEDIT on an MTEXT or a multileader's text, with its contents): where the UI places its + /// in-place editor and with which height, width, justification and starting text. fn editing_mtext(&self) -> Option { None } diff --git a/crates/engine/tests/aliases.rs b/crates/engine/tests/aliases.rs index 625354f60..dba5b1791 100644 --- a/crates/engine/tests/aliases.rs +++ b/crates/engine/tests/aliases.rs @@ -110,6 +110,15 @@ fn a_saved_alias_profile_restores_without_overriding_commands() { assert!(restored > 9_000, "the valid entries restore, not just {restored}"); assert_eq!(listing["file"], json!("mine.pgp")); + // Skipped entries don't use up the cap: invalid ones sorted first leave a full valid set. + let mut first_bad = serde_json::Map::new(); + for i in 0..cadcraft_engine::cmd::file::MAX_ALIASES { + first_bad.insert(format!("A{i:05}"), json!("nosuchcommand")); + first_bad.insert(format!("B{i:05}"), json!("line")); + } + cadcraft_engine::cmd::file::restore_aliases(&json!({ "aliases": first_bad, "file": null })); + let listing = s.execute("aliasedit", &json!({})).unwrap(); + assert_eq!(listing["aliases"].as_object().map_or(0, serde_json::Map::len), cadcraft_engine::cmd::file::MAX_ALIASES); // 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"); diff --git a/crates/engine/tests/it/mleader_text_edit.rs b/crates/engine/tests/it/mleader_text_edit.rs index bff071cf1..2f2f17814 100644 --- a/crates/engine/tests/it/mleader_text_edit.rs +++ b/crates/engine/tests/it/mleader_text_edit.rs @@ -44,8 +44,57 @@ fn textedit_and_properties_change_a_multileaders_text() { assert_eq!(text_of(&s), "from properties"); } +/// An edited multileader text is undone in one step and is what a DXF save keeps. #[test] -fn a_text_too_long_for_the_editor_is_left_as_it_is() { +fn an_edited_multileader_text_undoes_and_survives_a_dxf_save() { + let mut s = Session::new(); + s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); + let at = s + .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(); + s.cmdline("TEXTEDIT").unwrap(); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + s.input(Input::Text("edited\nsecond line".into())).unwrap(); + s.cancel(); + let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let saved = + reopened.model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| t.contents.clone()) } else { None }); + assert_eq!(saved.as_deref(), Some("edited\\Psecond line")); + s.undo().unwrap(); + assert_eq!(text_of(&s), "example text"); +} + +/// A multileader on a locked layer is refused when it is picked, before the editor opens, and +/// Properties leaves it alone. +#[test] +fn a_multileader_on_a_locked_layer_is_refused_when_picked() { + 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(); + s.execute("layer.set", &json!({"name": "0", "locked": true})).unwrap(); + 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("The object is on a locked layer.")); + assert!(s.editing_mtext().is_none(), "the editor doesn't open"); + assert_eq!(s.current_prompt().unwrap().message, "Select an annotation object"); + s.cancel(); + let r = s.execute("properties.set", &json!({"handles": [h.hex()], "text": "from properties"})).unwrap(); + assert_eq!((r["changed"].as_u64(), r["locked"].as_u64()), (Some(0), Some(1)), "{r}"); + assert_eq!(text_of(&s), "example text"); +} + +#[test] +fn a_text_too_long_for_the_editor_is_asked_for_at_the_command_line() { let mut s = Session::new(); s.execute("mleader", &json!({"points": [[0, 0], [20, 20]], "text": "example text"})).unwrap(); let (h, at) = s @@ -60,8 +109,14 @@ fn a_text_too_long_for_the_editor_is_left_as_it_is() { 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_eq!(s.log.last().map(String::as_str), Some("This text is too long for the editor; enter the new text at the command line.")); assert!(s.editing_mtext().is_none(), "the editor doesn't open"); - s.cancel(); + assert_eq!(s.current_prompt().unwrap().message, "Enter new text"); + // Enter keeps it whole; a typed answer still replaces it, as for any other text. + s.input(Input::Enter).unwrap(); assert_eq!(text_of(&s), long, "the text is not shortened"); + s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); + s.input(Input::Text("short".into())).unwrap(); + assert_eq!(text_of(&s), "short"); + s.cancel(); } diff --git a/crates/ui-egui/src/aliasdlg.rs b/crates/ui-egui/src/aliasdlg.rs index d6fa49d3c..93110a5a7 100644 --- a/crates/ui-egui/src/aliasdlg.rs +++ b/crates/ui-egui/src/aliasdlg.rs @@ -38,6 +38,13 @@ pub struct AliasDlgState { pub warnings: Vec, /// ALIASEDIT typed again while open: bring the window to the front on the next frame. pub raise: bool, + /// Import… was clicked over aliases of the user's own: the dialog asks before a file replaces them. + pub confirm_import: bool, +} + +/// Whether Import… asks first: the file would replace the user's aliases or the edits not applied yet. +pub fn import_replaces_something(st: &AliasDlgState) -> bool { + !st.user.is_empty() || !st.applied.is_empty() } /// The user aliases and alias file ALIASEDIT holds now. @@ -230,6 +237,8 @@ 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, mut import_clicked) = (false, false, false, false); + // Without a native file picker (the web) Import… can't open one; ALIASEDIT's `text` form loads a file there. + let can_pick = app.services.pick_pgp.is_some(); let Some(st) = app.alias_dlg.as_mut() else { return }; let id = egui::Id::unique("aliasedit_dialog"); if std::mem::take(&mut st.raise) { @@ -301,10 +310,31 @@ 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 import = ui + .add_enabled(can_pick, egui::Button::new(crate::tl!("Import…"))) + .on_disabled_hover_text(crate::tl!("Run ALIASEDIT with the file's contents using its text parameter.")); + if import.clicked() { + if import_replaces_something(st) { + st.confirm_import = true; + } else { + import_clicked = true; + } } }); + if st.confirm_import { + ui.group(|ui| { + ui.label(crate::tf!("Importing a file replaces your {n} aliases, and any changes not applied yet.", n = st.user.len())); + ui.horizontal(|ui| { + if ui.button(crate::tl!("Import and replace")).clicked() { + st.confirm_import = false; + import_clicked = true; + } + if ui.button(crate::tl!("Keep my aliases")).clicked() { + st.confirm_import = false; + } + }); + }); + } let mut save = false; let mut discard = false; if let Some(form) = st.form.as_mut() { @@ -453,6 +483,20 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Import… asks first when a file would replace aliases of the user's own or unapplied edits; + /// with neither it opens the picker at once. + #[test] + fn import_asks_before_replacing_the_users_aliases() { + let mut st = super::AliasDlgState::default(); + assert!(!super::import_replaces_something(&st)); + st.user.insert("xxl".into(), "line".into()); + assert!(super::import_replaces_something(&st), "an edit not applied yet"); + st.applied = st.user.clone(); + assert!(super::import_replaces_something(&st), "an applied user alias"); + st.user.clear(); + assert!(super::import_replaces_something(&st), "a removal not applied yet"); + } + #[test] fn a_cancelled_picker_changes_nothing() { let _guard = alone(); diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index c6890a3bb..d9af319c2 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -319,14 +319,16 @@ 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. + // a right-click may repeat the last command instead of opening the menu. With no last command + // yet, it opens 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() - { + if !snap + && mode == crate::options::IdleClick::Repeat + && let Some(last) = app.session.last_command.clone() + { + if resp.secondary_clicked() { app.start(&last); } return; diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rs index 2fd7419bd..f0757c141 100644 --- a/crates/ui-egui/src/keys.rs +++ b/crates/ui-egui/src/keys.rs @@ -638,6 +638,15 @@ mod tests { assert_eq!(c.ui.shortcuts, UserKeys::from([("arc".to_string(), "Cmd+K".to_string()), ("circle".to_string(), "Cmd+J".to_string())])); } + /// Window ▸ Reset Palettes puts the palettes back, not the user's shortcuts. + #[test] + fn reset_palettes_keeps_the_users_shortcuts() { + let mut app = app(); + let _ = app.run("ui.shortcuts", json!({"set": {"line": "Cmd+L"}})); + app.run("ui.resetpalettes", json!({})).unwrap(); + assert_eq!(app.ui.shortcuts, UserKeys::from([("line".to_string(), "Cmd+L".to_string())])); + } + #[test] fn the_menus_show_the_shortcut_in_force() { let mut app = app(); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 591c96293..8df574eea 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -494,6 +494,8 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option Option(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") { + // keeps it for an empty answer, and for one left unchanged (no undo step). + let textedit = app.session.running.as_ref().is_some_and(|r| r.id == "textedit"); + let contents = st.fmt.to_contents(); + if !st.fmt.is_empty() && !(textedit && contents == mt.contents) { + let _ = app.session.input(cadcraft_engine::Input::Text(contents)); + } else if textedit { let _ = app.session.input(cadcraft_engine::Input::Enter); } if app.session.running.as_ref().is_some_and(|r| r.id == "mtext") { @@ -626,8 +628,16 @@ mod tests { /// Clicking Diameter inserts U+2300 into both the formatted text and `to_contents()`, selects it, and leaves no unnamed widget. #[test] fn diameter_insertion_keeps_real_text_and_renders_without_optional_fonts() { - let state = - State { fmt: Formatted::default(), typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None, focused: false, target: None }; + let state = State { + fmt: Formatted::default(), + typing: CharFmt::default(), + typing_at: 0, + top: 70.0, + sel: (0, 0), + caret: None, + focused: false, + target: None, + }; let mut harness = Harness::builder().with_size(vec2(1100.0, 300.0)).with_context_setup(install_diameter_glyph).build_ui_state( |ui, state| { toolbar(ui, state, 2.5); @@ -648,8 +658,16 @@ mod tests { /// 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, target: None }; + let state = State { + fmt: Formatted::default(), + typing: CharFmt::default(), + typing_at: 0, + top: 70.0, + sel: (0, 0), + caret: None, + focused: false, + target: None, + }; let mut harness = Harness::builder().with_size(vec2(1100.0, 300.0)).build_ui_state( |ui, state| { toolbar(ui, state, 2.5); @@ -668,8 +686,16 @@ mod tests { /// The ten toolbar controls listed in the test are found by semantic name under the harness's default bundled fonts, and no toolbar widget is unnamed. #[test] fn the_whole_toolbar_uses_bundled_glyphs_and_names_its_controls() { - let mut state = - State { fmt: Formatted::default(), typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None, focused: false, target: None }; + let mut state = State { + fmt: Formatted::default(), + typing: CharFmt::default(), + typing_at: 0, + top: 70.0, + sel: (0, 0), + caret: None, + focused: false, + target: None, + }; let mut harness = Harness::builder().with_size(vec2(1100.0, 120.0)).build_ui(move |ui| toolbar(ui, &mut state, 2.5)); harness.run(); for name in ["Left", "Center", "Right", "Justify", "Bulleted list", "Numbered list", "Insert tab", "Diameter", "Text color", "Font"] { diff --git a/crates/ui-egui/src/options/dialog.rs b/crates/ui-egui/src/options/dialog.rs index e1a9fa966..951ca78d8 100644 --- a/crates/ui-egui/src/options/dialog.rs +++ b/crates/ui-egui/src/options/dialog.rs @@ -571,7 +571,7 @@ fn preferences(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map if ui.checkbox(&mut timed, crate::tl!("Time-sensitive right-click: a quick click is Enter, holding opens the menu")).changed() { changes.insert("timeSensitiveRightClick".into(), json!(timed)); } - hint(ui, crate::tl!("Turned off, a right-click while a command runs always opens the shortcut menu.")); + hint(ui, crate::tl!("Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode.")); if ui.button(crate::tl!("Right-Click Customization...")).clicked() { right_click = true; } From 098fa7fd8020c27ec3e4444ac9075deaa025aa7f Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 6 Nov 2026 13:44:57 -0700 Subject: [PATCH 152/185] Stack 3: #1105's multileader height field takes #2403's ids as they are --- 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 554ea4f9b..684768e67 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1170,7 +1170,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { set = Some(json!({ "handles": ids, "text": s })); } }); - num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, &ids); + num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, ids); } } EntityKind::LwPolyline(pl) => { From 0140e275f3646df372e9eefe45a25c9e13433e79 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 6 Nov 2026 14:33:18 -0700 Subject: [PATCH 153/185] Stack 3: the multileader save test saves as 2007 DXF, where a multileader stays one --- crates/engine/tests/it/mleader_text_edit.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/it/mleader_text_edit.rs b/crates/engine/tests/it/mleader_text_edit.rs index 2f2f17814..605b3247c 100644 --- a/crates/engine/tests/it/mleader_text_edit.rs +++ b/crates/engine/tests/it/mleader_text_edit.rs @@ -60,7 +60,9 @@ fn an_edited_multileader_text_undoes_and_survives_a_dxf_save() { s.input(Input::Point(at + Vec2::new(1.0, -0.05))).unwrap(); s.input(Input::Text("edited\nsecond line".into())).unwrap(); s.cancel(); - let reopened = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + // 2007 DXF: older versions keep a multileader as a LEADER and an MTEXT. + let opts = cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2007), binary: false }; + let reopened = cadcraft_io::read_dxf(&cadcraft_io::write_with(s.doc().unwrap(), "x.dxf", &opts).unwrap()).unwrap(); let saved = reopened.model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.as_ref().map(|t| t.contents.clone()) } else { None }); assert_eq!(saved.as_deref(), Some("edited\\Psecond line")); From 1452ab6f9fd681096b00b6107096ccd4d9e98fbe Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 6 Nov 2026 14:58:21 -0700 Subject: [PATCH 154/185] Stack 3: CodeRabbit on #2874: editor limits for braces and deep nesting, OK on a rewritten but unedited text, round-off next to zero in the palette, test folder cleanup --- crates/engine/src/mtext_edit.rs | 32 ++++++++++++++++++++--- crates/ui-egui/src/mtext_editor.rs | 3 ++- crates/ui-egui/src/palettes.rs | 12 ++++++++- crates/ui-egui/tests/alias_persistence.rs | 1 + 4 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/mtext_edit.rs b/crates/engine/src/mtext_edit.rs index c6d06f46a..103178472 100644 --- a/crates/engine/src/mtext_edit.rs +++ b/crates/engine/src/mtext_edit.rs @@ -117,6 +117,13 @@ impl Formatted { Self::parse(contents, None).1 } + /// Whether `edited`, what the editor gives back for `original` (a text `height` high), is the + /// text as it was: the same, or what opening it and pressing OK without an edit gives (a + /// non-canonical `{\fArial|b1;first}` comes back written another way). + pub fn leaves_unchanged(original: &str, height: Option, edited: &str) -> bool { + edited == original || edited == Self::from_contents_with_height(original, height).to_contents() + } + /// The parse, and whether it took in all of `contents`. fn parse(contents: &str, height: Option) -> (Formatted, bool) { let mut f = Formatted::default(); @@ -125,22 +132,30 @@ impl Formatted { let mut cur = CharFmt::default(); let mut props = ParaProps::default(); f.paras = vec![props.clone()]; - // Cleared when a paragraph or a kept code doesn't fit. + // Cleared when a paragraph, a kept code or a nesting level doesn't fit. let mut whole = true; + // Groups opened past the 64 levels kept: their closing braces pop nothing. + let mut unkept = 0usize; let mut i = 0; while let Some(&c) = chars.get(i) { - if f.fmt.len() >= MAX_CHARS { + // Braces after the last character the editor holds add no text. + if f.fmt.len() >= MAX_CHARS && !matches!(c, '{' | '}' | '\r') { return (f, false); } match c { '{' => { if stack.len() < 64 { stack.push(cur.clone()); + } else { + unkept = unkept.saturating_add(1); + whole = false; } i += 1; } '}' => { - if let Some(p) = stack.pop() { + if unkept > 0 { + unkept -= 1; + } else if let Some(p) = stack.pop() { cur = p; } i += 1; @@ -637,5 +652,16 @@ mod tests { assert!(!Formatted::fits(&"a\n".repeat(MAX_PARAS))); assert!(!Formatted::fits(&"\\A1;".repeat(MAX_ATOMS + 1))); assert!(Formatted::fits(&"\\A1;".repeat(MAX_ATOMS))); + // A full formatted run's closing brace adds no text: it still fits. + assert!(Formatted::fits(&format!("{{\\L{}}}", "x".repeat(MAX_CHARS)))); + assert!(!Formatted::fits(&format!("{{\\L{}}}y", "x".repeat(MAX_CHARS)))); + // OK without an edit leaves a text alone, also one the editor writes another way. + let odd = "{\\fArial|b1;first}"; + assert!(Formatted::leaves_unchanged(odd, Some(2.5), &Formatted::from_contents_with_height(odd, Some(2.5)).to_contents())); + assert!(Formatted::leaves_unchanged(odd, Some(2.5), odd)); + assert!(!Formatted::leaves_unchanged(odd, Some(2.5), "second")); + // Nesting past the 64 levels the editor keeps doesn't fit. + assert!(Formatted::fits(&format!("{}a{}", "{".repeat(64), "}".repeat(64)))); + assert!(!Formatted::fits(&format!("{}a{}", "{".repeat(65), "}".repeat(65)))); } } diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index fa9daac51..941940e1b 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -175,7 +175,8 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { // keeps it for an empty answer, and for one left unchanged (no undo step). let textedit = app.session.running.as_ref().is_some_and(|r| r.id == "textedit"); let contents = st.fmt.to_contents(); - if !st.fmt.is_empty() && !(textedit && contents == mt.contents) { + let unchanged = textedit && Formatted::leaves_unchanged(&mt.contents, Some(mt.height), &contents); + if !st.fmt.is_empty() && !unchanged { let _ = app.session.input(cadcraft_engine::Input::Text(contents)); } else if textedit { let _ = app.session.input(cadcraft_engine::Input::Enter); diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 684768e67..678ec93e7 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -768,8 +768,10 @@ fn selection_memo(ui: &egui::Ui, app: &CadApp, sel: &[cadcraft_engine::doc::Hand /// 5.000000000000001) from reading as a difference. const EXACT_SEP: char = '\u{1f}'; -/// `shown`, tagged with the number `v` it was formatted from. +/// `shown`, tagged with the number `v` it was formatted from. Round-off next to zero (a Delta Y +/// of 1.2e-16 on a level line) is tagged as zero, since 12 significant digits of it are noise. fn exact(shown: String, v: f64) -> String { + let v = if v.abs() < 1e-12 { 0.0 } else { v }; format!("{shown}{EXACT_SEP}{:.11e}", v + 0.0) } @@ -1588,6 +1590,14 @@ mod tests { /// 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 round_off_next_to_zero_is_no_difference() { + let tag = |v: f64| super::exact("0.0000".into(), v); + assert_eq!(tag(0.0), tag(1.2e-16)); + assert_eq!(tag(0.0), tag(-3e-15)); + assert_ne!(tag(0.0), tag(1e-6), "a real difference below the display precision still shows"); + } + #[test] fn values_that_differ_below_the_display_precision_still_vary() { let mut app = CadApp::new(Session::default(), Services::default()); diff --git a/crates/ui-egui/tests/alias_persistence.rs b/crates/ui-egui/tests/alias_persistence.rs index 5080905ed..2601552c5 100644 --- a/crates/ui-egui/tests/alias_persistence.rs +++ b/crates/ui-egui/tests/alias_persistence.rs @@ -173,4 +173,5 @@ fn a_loaded_alias_file_survives_with_its_path_and_reinit_rereads_it() { b.run("reinit", json!({})).unwrap(); assert_eq!(resolve_alias("zzprofile"), "circle", "REINIT re-reads the restored file"); a.run("aliasedit", json!({ "clear": true })).unwrap(); + let _ = std::fs::remove_dir_all(&dir); } From 85b35fc5b9ed5c66416f2a1c0d5e4c82b09bdb4b Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:48:26 +0800 Subject: [PATCH 155/185] cadcraft-web: window.cadcraft, the page command API from craft-web-api The web shell queues the page's calls as control requests (the channel the desktop control server uses) and answers them on the next frame. PendingReply gains try_reply, so a transport that cannot block can poll it, and cancels a request the app has not started when it is dropped, as a timed-out wait does: the page was told the call failed, so the app skips it. The API is installed in every mode; opening, saving, the file name and the unsaved flag stay with the host messages. --- Cargo.lock | 13 +++++++- apps/cadcraft-web/Cargo.toml | 5 ++- apps/cadcraft-web/src/api.rs | 61 +++++++++++++++++++++++++++++++++++ apps/cadcraft-web/src/main.rs | 5 ++- crates/ui-egui/src/control.rs | 48 ++++++++++++++++++++++++++- packaging/web/README.md | 12 +++++++ 6 files changed, 140 insertions(+), 4 deletions(-) create mode 100644 apps/cadcraft-web/src/api.rs diff --git a/Cargo.lock b/Cargo.lock index 21cf7f054..4a9206bcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -828,6 +828,7 @@ dependencies = [ "cadcraft-fonts", "cadcraft-io", "cadcraft-ui-egui", + "craft-web-api", "craft-web-host", "eframe", "egui", @@ -1232,10 +1233,20 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-web-api" +version = "0.1.0" +dependencies = [ + "js-sys", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", +] + [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6" +source = "git+https://github.com/storytold/craft-libs?rev=a231e517c3b371e1bf0ee8af71ed807424a9a05d#a231e517c3b371e1bf0ee8af71ed807424a9a05d" dependencies = [ "wasm-bindgen", "web-sys", diff --git a/apps/cadcraft-web/Cargo.toml b/apps/cadcraft-web/Cargo.toml index b1225faf7..b96ec0d9c 100644 --- a/apps/cadcraft-web/Cargo.toml +++ b/apps/cadcraft-web/Cargo.toml @@ -20,7 +20,9 @@ cadcraft-ui-egui = { workspace = true } cadcraft-io = { workspace = true } cadcraft-fonts = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" } +# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel. +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } @@ -33,4 +35,5 @@ web-sys = { version = "0.3", features = ["HtmlInputElement", "FileList", "File"] eframe = { workspace = true, features = ["persistence", "wgpu", "accesskit"] } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" +js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] } diff --git a/apps/cadcraft-web/src/api.rs b/apps/cadcraft-web/src/api.rs new file mode 100644 index 000000000..574130f7e --- /dev/null +++ b/apps/cadcraft-web/src/api.rs @@ -0,0 +1,61 @@ +//! `window.cadcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the app's +//! own control channel, the one the desktop control server drives (`docs/control-protocol.md`). +//! +//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`, +//! `screenshot`, as promises with a timeout). This module is CADCraft's part: a [`Request`] that +//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the +//! reply. A call the page gave up on drops its [`PendingReply`], which cancels a request the app has +//! not started, so the app skips it instead of running it late. + +use std::rc::Rc; +use std::sync::mpsc::{Receiver, channel}; + +use cadcraft_ui_egui::{ControlRequest, PendingReply}; +use craft_web_api::methods::Methods; +use craft_web_api::page::{PageApi, Request}; +use serde_json::{Value, json}; +use wasm_bindgen_futures::JsFuture; + +/// The app id in `window.`. +const APP: &str = "cadcraft"; + +/// How often a waiting call looks for the app's reply, in milliseconds (about a frame). +const POLL_MS: i32 = 16; + +/// Put `window.cadcraft` on the page and return the queue the app drains each frame (hand it to +/// `CadApp::with_control`). An existing `window.cadcraft` keeps the functions it already has. +pub fn install(ctx: egui::Context) -> Receiver { + let (queue, requests) = channel::(); + let request: Request = Rc::new(move |method, params| { + let (control, reply) = ControlRequest::new(method, params); + if queue.send(control).is_err() { + return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) }); + } + ctx.request_repaint(); + Box::pin(wait(reply)) + }); + if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() { + log::warn!("couldn't install window.{APP}: {e:?}"); + } + requests +} + +/// The app's reply, polled about once a frame. Dropping this future (the page's timeout) drops +/// `reply`, which cancels the request if the app has not started it. +async fn wait(reply: PendingReply) -> Value { + loop { + if let Some(reply) = reply.try_reply() { + return reply; + } + sleep(POLL_MS).await; + } +} + +async fn sleep(ms: i32) { + let promise = js_sys::Promise::new(&mut |resolve, _| { + if let Some(window) = web_sys::window() { + let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); + } + }); + let _ = JsFuture::from(promise).await; +} diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index 7a867b78a..3d1c00d4c 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -10,6 +10,8 @@ //! `data-host="page"` on the canvas, talking over DOM `CustomEvent`s on it (`host.rs`). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(target_arch = "wasm32")] +mod api; #[cfg(target_arch = "wasm32")] pub mod download; #[cfg(target_arch = "wasm32")] @@ -160,7 +162,8 @@ mod web { Box::new(move |cc| { // Embedded, the host sends the drawing: start on the Start tab, not Drawing1. let session = if app_bridge.is_some() { Session::empty() } else { Session::new() }; - let mut app = CadApp::new(session, services()); + let control = crate::api::install(cc.egui_ctx.clone()); + let mut app = CadApp::new(session, services()).with_control(control); app.system_languages = web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default(); if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6ed1d22b5..093f1e8d5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -25,7 +25,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU8, Ordering}; -use std::sync::mpsc::{Receiver, Sender}; +use std::sync::mpsc::{Receiver, Sender, TryRecvError}; use std::time::Duration; use cadcraft_engine::Input; @@ -87,6 +87,25 @@ impl PendingReply { // Started: a reply that arrived just now still counts. self.rx.try_recv().unwrap_or_else(|_| json!({"ok": false, "error": "timeout", "state": "may-have-run"})) } + + /// The reply if the app has answered, without waiting: a transport that cannot block (the web + /// shell) polls this once a frame. A request the app dropped without answering reports that. + pub fn try_reply(&self) -> Option { + match self.rx.try_recv() { + Ok(reply) => Some(reply), + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => Some(json!({"ok": false, "error": "the app dropped the request"})), + } + } +} + +impl Drop for PendingReply { + /// A reply nobody waits for any more cancels a request the app has not started, as a timed-out + /// [`PendingReply::wait`] does: the client was told it failed, so the app must not run it late. + /// A request the app already started, or answered, is unaffected. + fn drop(&mut self) { + let _ = self.state.compare_exchange(QUEUED, CANCELLED, Ordering::AcqRel, Ordering::Acquire); + } } pub enum Outcome { @@ -742,6 +761,33 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) mod tests { use super::*; + #[test] + fn dropping_a_pending_reply_cancels_a_request_the_app_has_not_started() { + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + drop(pending); + assert!(!request.begin(), "the app must skip a request nobody waits for"); + } + + #[test] + fn dropping_a_pending_reply_leaves_a_started_request_alone() { + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + assert!(request.begin()); + drop(pending); + assert_eq!(request.state.load(Ordering::Acquire), STARTED, "a started request is not cancelled"); + } + + #[test] + fn try_reply_polls_without_blocking() { + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + assert_eq!(pending.try_reply(), None, "no answer yet"); + assert!(request.begin()); + request.reply.send(json!({"ok": true, "result": 1})).unwrap_or_default(); + assert_eq!(pending.try_reply(), Some(json!({"ok": true, "result": 1}))); + let (request, pending) = ControlRequest::new("ui.inspect", json!({})); + drop(request); + assert_eq!(pending.try_reply().and_then(|r| r["ok"].as_bool()), Some(false), "the app went away"); + } + #[test] fn render_view_fit_finds_offscreen_drawing() { let far = cadcraft_geom::Bounds2::new(Vec2::new(9000.0, 9000.0), Vec2::new(9100.0, 9050.0)); diff --git a/packaging/web/README.md b/packaging/web/README.md index 90b7d54f9..6a1c2c959 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -159,6 +159,18 @@ The messages and both transports are the shared contract of [`craft-web-host`](h - **Files from the host are untrusted input.** An opened file goes through the same reading as one picked with File ▸ Open or dropped on the window, with the same format limits; before it is copied into the app's memory, its size is checked against the app's open size limit and a larger drawing is refused, and a name is cut to 255 characters. - **The event and message names are the interface.** `cadcraft:ready`, `cadcraft:open`, `cadcraft:save`, `cadcraft:dirty` and `cadcraft:failed`, and the fields they carry (the same as the `?host=parent` messages), stay stable; changing one is a breaking change. +### Driving it from the page (`window.cadcraft`) + +Every CADCraft web build puts `window.cadcraft` on the page, from [`craft-web-api`](https://github.com/storytold/craft-libs/tree/main/crates/web-api) (storytold/craft-libs#413), the same shape in every Craft app. `cadcraft.request(method, params)` calls any method of the control channel the desktop app serves (`docs/control-protocol.md`), and `execute(command, params)`, `commands()`, `docInspect(params)`, `uiInspect(params)` and `screenshot(params)` are shortcuts for the common ones. Each returns a Promise that resolves with the method's result and rejects with an `Error`; a call the app does not answer within 30 seconds rejects, and the app drops it unrun if it had not started it. + +```js +const drawing = await cadcraft.docInspect(); // counts, extents, layers, styles, selection +await cadcraft.execute("ui.theme", { theme: "dark" }); +const { data } = await cadcraft.screenshot(); // the canvas as PNG (base64) +``` + +The API is there in every mode, with or without a host. Opening a drawing, handing a saved or exported file to the page, the file name and the unsaved flag stay with the host messages above. + ## Renderer selection and fallback flags CADCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls back to From 14a6cc3cdcb09cb1483952e4356add65e3f6e3a6 Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Fri, 6 Nov 2026 09:13:11 +0800 Subject: [PATCH 156/185] cadcraft-ui-egui: ui.screenshot returns the PNG inline on wasm Without a path the screenshot was written into a private temp directory, and std::env::temp_dir panics on wasm32 (no file system), which stopped the whole web app: the page's call never got a reply and nothing after it ran. On wasm the PNG now comes back inline (pngBase64, width, height, bytes), as ui.render's does. Native builds are unchanged. --- Cargo.lock | 4 +++- apps/cadcraft-web/Cargo.toml | 4 ++-- crates/ui-egui/src/control.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4a9206bcc..a62aa7337 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -832,6 +832,7 @@ dependencies = [ "craft-web-host", "eframe", "egui", + "js-sys", "log", "serde_json", "wasm-bindgen", @@ -1236,6 +1237,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" dependencies = [ "js-sys", "serde_json", @@ -1246,7 +1248,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a231e517c3b371e1bf0ee8af71ed807424a9a05d#a231e517c3b371e1bf0ee8af71ed807424a9a05d" +source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" dependencies = [ "wasm-bindgen", "web-sys", diff --git a/apps/cadcraft-web/Cargo.toml b/apps/cadcraft-web/Cargo.toml index b96ec0d9c..b73444064 100644 --- a/apps/cadcraft-web/Cargo.toml +++ b/apps/cadcraft-web/Cargo.toml @@ -21,8 +21,8 @@ cadcraft-io = { workspace = true } cadcraft-fonts = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.cadcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "a231e517c3b371e1bf0ee8af71ed807424a9a05d", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 093f1e8d5..55e2da3f6 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -747,6 +747,10 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) let Some(img) = image::RgbaImage::from_raw(w as u32, h as u32, buf) else { return json!({"ok": false, "error": "bad image", "request": token}); }; + // No file system to write to (the web build): the PNG comes back inline, as `ui.render`'s does. + if cfg!(target_arch = "wasm32") { + return inline_screenshot(&img, token); + } let saved = match path { Some(path) => img.save(path).map(|()| path.to_string()).map_err(std::io::Error::other), None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()), @@ -757,10 +761,33 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64) } } +/// A screenshot as an inline PNG reply (`pngBase64`, `width`, `height`, `bytes`, like `ui.render`), for a +/// build that has no file system to write it to: the web build, where `std::env::temp_dir` panics. +fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value { + let (w, h) = img.dimensions(); + let mut png = Vec::new(); + if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) { + return json!({"ok": false, "error": e.to_string(), "request": token}); + } + json!({"ok": true, "request": token, "result": {"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "bytes": png.len()}}) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn an_inline_screenshot_carries_the_png_and_its_size() { + let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255])); + let reply = inline_screenshot(&img, 7); + assert_eq!(reply["ok"], true); + assert_eq!(reply["request"], 7); + assert_eq!((reply["result"]["width"].as_u64(), reply["result"]["height"].as_u64()), (Some(3), Some(2))); + let b64 = reply["result"]["pngBase64"].as_str().unwrap_or_default(); + assert!(b64.starts_with("iVBORw0KGgo"), "a PNG signature in base64: {b64:.20}"); + assert!(reply["result"]["bytes"].as_u64().is_some_and(|n| n > 30), "the PNG byte count is reported"); + } + #[test] fn dropping_a_pending_reply_cancels_a_request_the_app_has_not_started() { let (request, pending) = ControlRequest::new("ui.inspect", json!({})); From 07b6b8c53a3c48d43d97f0591dafce38c40766e7 Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:28:05 +0800 Subject: [PATCH 157/185] cadcraft: document that ui.screenshot ignores path in the web build --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 326bc4fe4..05927226c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -60,7 +60,7 @@ field. `engine.commands` returns a separate command catalog, not a list of addit | `ui.set` | UiState fields | Show/hide palettes, toolbars, command line, ViewCube…; `theme: "system"\|"light"\|"dark"` (also `engine.execute` with `ui.theme {theme}`); `ui.inspect` reports the theme shown (`theme`: light/dark). `animations: "system"\|"on"\|"off"` (also `ui.animations {animations}`) shows or hides animation effects (dialog and menu fades, smoothed scrolling), `system` following the operating system's setting; `ui.inspect` reports whether they show (`animations`: true/false). `saveFormat: "dxf"\|"dwg"` (also `ui.saveformat {format}`) is the format Save As suggests for new drawings; `saveVersion: "2000"`…`"2018"` (also `ui.saveversion {version}`) the version it saves them in (SAVEAS also takes `version` and `binary` directly). | | `ui.resize` | `{width, height}` | Resize the window. | | `ui.focus` | | Activate the native window. Does not assign focus to a widget. | -| `ui.screenshot` | `{path?}` | PNG of the window (needs a presented frame). Bounded: at most 4 queued/in-flight/completed requests, 64 MiB per image and 64 MiB total (completed but undrained images still count), an 8 s deadline, and cancellation when the document or keyboard focus changes while the request is outstanding. A queued request adopts the settled window size when issued. After issue, a change in window size, scale, OS window focus, minimization or occlusion cancels it. Every reply carries `request`; failures include `ok:false,error`. Files are written only after the deadline and identity checks pass. Without `path`, each request gets a unique PNG in a private owner-only per-process directory under the temp dir (created exclusively; an existing symlink is never followed), so concurrent app instances cannot collide; the caller owns those files and should remove them when done. | +| `ui.screenshot` | `{path?}` | PNG of the window (needs a presented frame). Bounded: at most 4 queued/in-flight/completed requests, 64 MiB per image and 64 MiB total (completed but undrained images still count), an 8 s deadline, and cancellation when the document or keyboard focus changes while the request is outstanding. A queued request adopts the settled window size when issued. After issue, a change in window size, scale, OS window focus, minimization or occlusion cancels it. Every reply carries `request`; failures include `ok:false,error`. Files are written only after the deadline and identity checks pass. Without `path`, each request gets a unique PNG in a private owner-only per-process directory under the temp dir (created exclusively; an existing symlink is never followed), so concurrent app instances cannot collide; the caller owns those files and should remove them when done. | In the web build there is no file system: `path` is ignored and the PNG comes back inline (`pngBase64`, `width`, `height`, `bytes`). | `ui.render` | `{path?, width?, height?, fit?, window?, background?, plot_style?}` | Headless render. `fit` (default true) frames the whole drawing; `false` uses the current view; `window` `[[x0, y0], [x1, y1]]` shows just that area (drawing units). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, built-in (`monochrome.ctb` prints every colour black, `grayscale.ctb` grey; `default.ctb`, `default.stb`, `monochrome.stb`) or one the drawing holds; `"none"` (or `""`) draws every object with its own properties, also in a layout whose page setup shows plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown `background` or `plot_style` is refused. Replies `{pngBase64, width, height, bytes, path?}`. | | `app.open` / `app.save` / `app.quit` | `{path}` | File operations. | | `control.methods` | | Every method this server answers: `{method, params, description}`. Headless (`cadcraft-cli mcp`) lists only the methods it serves. | From 6304abd8f0082b1f8950a27aeb9c3e3208a5dc88 Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:29:59 +0800 Subject: [PATCH 158/185] cadcraft: keep the ui.screenshot web note inside the table row --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 05927226c..b620230bc 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -60,7 +60,7 @@ field. `engine.commands` returns a separate command catalog, not a list of addit | `ui.set` | UiState fields | Show/hide palettes, toolbars, command line, ViewCube…; `theme: "system"\|"light"\|"dark"` (also `engine.execute` with `ui.theme {theme}`); `ui.inspect` reports the theme shown (`theme`: light/dark). `animations: "system"\|"on"\|"off"` (also `ui.animations {animations}`) shows or hides animation effects (dialog and menu fades, smoothed scrolling), `system` following the operating system's setting; `ui.inspect` reports whether they show (`animations`: true/false). `saveFormat: "dxf"\|"dwg"` (also `ui.saveformat {format}`) is the format Save As suggests for new drawings; `saveVersion: "2000"`…`"2018"` (also `ui.saveversion {version}`) the version it saves them in (SAVEAS also takes `version` and `binary` directly). | | `ui.resize` | `{width, height}` | Resize the window. | | `ui.focus` | | Activate the native window. Does not assign focus to a widget. | -| `ui.screenshot` | `{path?}` | PNG of the window (needs a presented frame). Bounded: at most 4 queued/in-flight/completed requests, 64 MiB per image and 64 MiB total (completed but undrained images still count), an 8 s deadline, and cancellation when the document or keyboard focus changes while the request is outstanding. A queued request adopts the settled window size when issued. After issue, a change in window size, scale, OS window focus, minimization or occlusion cancels it. Every reply carries `request`; failures include `ok:false,error`. Files are written only after the deadline and identity checks pass. Without `path`, each request gets a unique PNG in a private owner-only per-process directory under the temp dir (created exclusively; an existing symlink is never followed), so concurrent app instances cannot collide; the caller owns those files and should remove them when done. | In the web build there is no file system: `path` is ignored and the PNG comes back inline (`pngBase64`, `width`, `height`, `bytes`). +| `ui.screenshot` | `{path?}` | PNG of the window (needs a presented frame). Bounded: at most 4 queued/in-flight/completed requests, 64 MiB per image and 64 MiB total (completed but undrained images still count), an 8 s deadline, and cancellation when the document or keyboard focus changes while the request is outstanding. A queued request adopts the settled window size when issued. After issue, a change in window size, scale, OS window focus, minimization or occlusion cancels it. Every reply carries `request`; failures include `ok:false,error`. Files are written only after the deadline and identity checks pass. Without `path`, each request gets a unique PNG in a private owner-only per-process directory under the temp dir (created exclusively; an existing symlink is never followed), so concurrent app instances cannot collide; the caller owns those files and should remove them when done. In the web build there is no file system: `path` is ignored and the PNG comes back inline (`pngBase64`, `width`, `height`, `bytes`). | | `ui.render` | `{path?, width?, height?, fit?, window?, background?, plot_style?}` | Headless render. `fit` (default true) frames the whole drawing; `false` uses the current view; `window` `[[x0, y0], [x1, y1]]` shows just that area (drawing units). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, built-in (`monochrome.ctb` prints every colour black, `grayscale.ctb` grey; `default.ctb`, `default.stb`, `monochrome.stb`) or one the drawing holds; `"none"` (or `""`) draws every object with its own properties, also in a layout whose page setup shows plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown `background` or `plot_style` is refused. Replies `{pngBase64, width, height, bytes, path?}`. | | `app.open` / `app.save` / `app.quit` | `{path}` | File operations. | | `control.methods` | | Every method this server answers: `{method, params, description}`. Headless (`cadcraft-cli mcp`) lists only the methods it serves. | From 62caaa30d9e7bf9ad55727e1c61928e923dc89ea Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:33:15 +0100 Subject: [PATCH 159/185] docs: alpha-gate drafting gap, POLARMODE bit, DWG failsafe boundary, ACIS wording, breadth metric label Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- docs/file-format-parity.md | 4 ++-- docs/roadmap.md | 2 +- docs/ui-parity.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ad6f8f85e..54c36e231 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -21,7 +21,7 @@ is ≈ 600–930 h away. | Number | Value | Kind | |---|---|---| -| Feature breadth (AutoCAD for Mac menu items with a live command) | **50%** (245 / 491; 2D menus only ≈ 65%) | measured ([parity-checklist.md](docs/parity-checklist.md) + UI-only commands) | +| Feature breadth (AutoCAD for Mac menu items with a live command) | **50%** (245 / 491 at the 2026-10-10 re-measure, including UI-only commands; not re-measured since; the generated checklist counts engine commands only and now reads 298 / 491; 2D menus only ≈ 65%) | measured ([parity-checklist.md](docs/parity-checklist.md) + UI-only commands) | | Ready for real work | **≈ 38%** | estimated ([target-app-parity.md](docs/target-app-parity.md)) | | Mainstream practitioner (2D drafter) | **≈ 28%** (lower than the full number: file exchange, stability and interaction discounts multiply) | estimated ([target-app-parity.md](docs/target-app-parity.md#mainstream-practitioner)) | | Essentials user | **≈ 46%** | estimated ([target-app-parity.md](docs/target-app-parity.md#essentials-user)) | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 05c815294..70cfb3e17 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -31,7 +31,7 @@ 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.5 crate (failsafe mode since 0.6.4: 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 +with the `acadrust` 0.6.6 crate (failsafe mode since 0.6.4: an object record it can't decode is left out and a note says so, #859; if the file's header or section map can't be read, or it isn't a DWG, the file is rejected) 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 gaps in 2010+ DWG (measured with 0.6.3): merged table cells and table-style @@ -51,7 +51,7 @@ title/header suppression. | Web build | — | — | **no** (error: "save as DXF") | no | — | Everything lost in the DXF read/write paths below is also lost through DWG, plus whatever -`acadrust`'s own DXF output omits (proxy objects, ACIS data, custom objects: not measured). User +`acadrust`'s own DXF output omits (proxy objects and custom objects: not measured; ACIS data of solids is kept, #781). User report #57: a 10 MB DWG failed after about two minutes; limits now stop runaway conversions early (#175), but the throughput problem remains. DGN line style components that no line style definition uses (leftovers of DGN imports, hundreds of thousands in some drawings) are left out diff --git a/docs/roadmap.md b/docs/roadmap.md index f54d34398..23b23cac7 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -20,7 +20,7 @@ Opus 5.5 agent-hours. 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. + with a plot dialog and preview (F14)~~ landed (#824, #818, #525, #410, #160, #186); left: the precise-drafting gaps (approximate ellipse and spline intersections, prompt options that still print "not available yet"; U4, F1), dynamic-block authoring, XCLIP, editing an xref in place (F2, F3), and printing beyond files (F14, H3). ≈ 50–80 h. Items 2 and 7 are the open [alpha gate](#alpha-gate) rows. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 56962dbf2..24c0aafd5 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -87,7 +87,7 @@ percentages below are from 2026-10-11 and were not re-measured. Remaining: **≈ |---|---|---| | Ortho (F8) | yes, Shift overrides it while held | yes; holding Shift turns it on or off while held (`Session::snap_cursor`, `snap/tracking.rs`) | | Polar tracking increment | yes | yes, measured from ANGBASE; 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); relative to the last segment with POLARMODE bit 4 (`snap/tracking.rs`, #450) | +| Additional polar angles, relative to last segment | yes | additional angles yes (POLARADDANG); relative to the last segment with POLARMODE bit 1 (`snap/tracking.rs`, #450) | | Polar distance snap (PolarSnap) | yes | yes: SNAPTYPE 1 steps along the tracking paths by POLARDIST (#450; also over the isometric snap, #633) (`snap/tracking.rs` `polar_snap`) | | **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 | From 5ece42054341ed8d443177ca1b2a54ab79b763b2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 18:18:39 +0100 Subject: [PATCH 160/185] docs: XCLIP, existing-MTEXT editing and Vietnamese are shipped; date the 245/491 and 233/491 references Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 10 +++++----- docs/gaps.md | 4 ++-- docs/localization-parity.md | 12 +++++++----- docs/localization.md | 4 ++-- docs/roadmap.md | 10 +++++----- docs/target-app-parity.md | 8 ++++---- docs/ui-parity.md | 2 +- 7 files changed, 26 insertions(+), 24 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 54c36e231..8be3de33d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -11,7 +11,7 @@ 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 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); +authored and xrefs can't be edited in place (the Block Editor, REFEDIT, dynamic block editing and XCLIP 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 @@ -82,8 +82,8 @@ 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 fifteen catalogs -(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian and Turkish). Detail: [localization-parity.md](docs/localization-parity.md). +AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus eighteen catalogs +(Ukrainian, Brazilian Portuguese, German, Spanish, Czech, Russian, French, Simplified Chinese, Italian, Korean, Swedish, Arabic, Greek, Hungarian, Turkish, Bosnian, Georgian and Vietnamese). Detail: [localization-parity.md](docs/localization-parity.md). | Language | Status | UI translated | |---|---|---:| @@ -99,7 +99,7 @@ AutoCAD 2027 for Mac ships 8 interface languages; CADCraft ships English plus fi | Greek | partial | 1,330 catalog rows; independent proofreading pending | | German | partial | 1,031 catalog rows | | Korean | partial | 1,235 catalog rows | -| Vietnamese | none | 0% | +| Vietnamese | partial | 1,460 catalog rows (2026-11-07); native review pending | Other languages shipped: Ukrainian (1,357 rows, the reference catalog, #36), Czech (1,215), Russian (1,005), Italian (1,352), Swedish (1,382), Hungarian (1,326) and Turkish (1,330), counted 2026-10-24; engine messages stay English. Every catalog but Ukrainian's has strings added since it landed that still fall back to English: 6 (Italian, Swedish) to 296 (French) per `cargo xtask i18n` ([localization-parity.md](docs/localization-parity.md)). @@ -115,7 +115,7 @@ Ranked; detail and the full beta checklist in [docs/roadmap.md](docs/roadmap.md) 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): 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. +8. Xrefs, block editor, groups, then dynamic blocks (80–120 h): xrefs (#525), groups (#417), the Block Editor (#824, #833, #885), REFEDIT (#818), XCLIP and XCLIPFRAME (#2354) and dynamic block references (#838–#883) landed; left: dynamic-block authoring, editing an xref in place. ## Progress log diff --git a/docs/gaps.md b/docs/gaps.md index 2b9493400..289f0b4be 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -32,7 +32,7 @@ do them first. | 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 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 | +| 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 is edited as plain text on the command line with TEXTEDIT (alias DDEDIT; a double-click starts it, #868), while an existing MTEXT opens in the in-place editor with its contents (#1002, merged 2026-11-06); 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; 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 | @@ -107,7 +107,7 @@ Detail: [localization-parity.md](localization-parity.md). | # | Gap | Est. | |---|---|---| | L1 | Catalog covers the UI (Ukrainian reference catalog: 1,368 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, el, es, fr, hu, it, ko, tr, zh-Hans, pt-BR, ar, bs, cs, ru, sv, uk landed: 16 catalogs in `crates/ui-egui/src/i18n/`); the landed catalogs still need native review | 13–21 + native review | +| L2 | Japanese from AutoCAD for Mac's list, plus hi and id from the standard's list (18 non-English catalogs have landed in `crates/ui-egui/src/i18n/`, counted 2026-11-07: ar, bs, cs, de, el, es, fr, hu, it, ka, ko, pt-BR, ru, sv, tr, uk, vi, zh-Hans; Vietnamese and Georgian are shipped but their English-fallback counts are not measured here); the landed catalogs still need native review and a fresh `cargo xtask i18n` fallback count | 10–16 + 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 | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index f15acaeb6..2cf9508c9 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -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 fifteen catalogs have between 1,004 - (French) and 1,382 rows (Swedish; Ukrainian, the reference, has 1,357), counted 2026-10-24, + and plurals ([localization.md](localization.md)). The eighteen non-English catalogs have between 1,026 + (Russian) and 1,471 rows (Swedish; Ukrainian, the reference, has 1,414), counted 2026-11-07 on main 486d558a7 (rows without comment lines, `@plural` rows included), 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 @@ -68,7 +68,8 @@ plus native review by a human; extending the catalog to the remaining English-on | German | de | 1,031 catalog rows; 284 strings fall back to 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 | | Greek | el | 1,330 catalog rows; 34 strings fall back to English | Menus, dialogs, tooltips, drawing prompts, command labels and contextual headings; English fallback for uncatalogued UI | Greek script; bundled egui glyph check added | Original AI-assisted translation by @Camthalion77, independent native review pending | complete when it landed; 34 strings added since fall back to English | native proofreading and platform layout review | | Korean | ko | 1,235 catalog rows; 124 strings fall back to English | 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; 124 strings 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 | +| Vietnamese | vi | 1,460 catalog rows (2026-11-07); English-fallback count not measured | catalog shipped; dialog and tooltip coverage not audited | Latin with stacked diacritics: renders per code point, untested | original translations by @2ez4gcx (AI-assisted); no native review recorded | partial | 1–2 h + native review | +| Georgian | ka | 1,458 catalog rows (2026-11-07); written to cover the union of the existing catalogs | menus, dialogs and tooltips | Georgian script: drawn with the craft-fonts `Geor` face, none in a build without craft-fonts | original clean-room translation by the CADCraft contributors; no native review recorded | partial | native review | | 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 | @@ -77,14 +78,14 @@ plus native review by a human; extending the catalog to the remaining English-on | 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, Turkish and Bosnian. +Other languages shipped: Ukrainian, Brazilian Portuguese, German, Czech, Russian, French, Italian, Korean, Swedish, Hungarian, Turkish, Bosnian, Georgian and Vietnamese. The per-language cells above keep the counts of the dated audit that wrote them (2026-10-24 or earlier, as stated); only the row totals in "What CADCraft has" and the Vietnamese and Georgian rows are from 2026-11-07, and the English-fallback counts have not been re-measured since 2026-10-24. 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. **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 gaps of the fourteen lagging catalogs 15–30 h, +three languages not started (hi, id, ja) 10–16 h, closing the gaps of the 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. @@ -92,6 +93,7 @@ each language, which needs humans. Translations parallelise fully once the catal | Date | Change | Summary | |---|---|---| +| 2026-11-07 | minor | Inventory reconciled with main 486d558a7: 18 non-English catalogs (Georgian and Vietnamese rows added; Vietnamese no longer listed as not started), row totals re-counted; per-language cells and fallback counts keep their earlier dates | | 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-24 | minor | Re-audit against main 41d9b5e95: catalog row counts and English-fallback counts re-measured for all fifteen catalogs (main 41d9b5e95) | | 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) | diff --git a/docs/localization.md b/docs/localization.md index 5f7489d2d..10af9e7fd 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), **Bosanski** (Bosnian), 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), **ქართული** (Georgian), or **Tiếng Việt** (Vietnamese). 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 @@ -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`, `bs`, `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`, `ka`, and `vi`; invalid values are rejected without changing the current selection. Resetting palettes keeps the language choice. ## Translation coverage diff --git a/docs/roadmap.md b/docs/roadmap.md index 23b23cac7..518d142d0 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -20,7 +20,7 @@ Opus 5.5 agent-hours. 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: the precise-drafting gaps (approximate ellipse and spline intersections, prompt options that still print "not available yet"; U4, F1), dynamic-block authoring, XCLIP, editing an xref in place (F2, F3), and printing beyond files (F14, H3). ≈ 50–80 h. + with a plot dialog and preview (F14)~~ landed (#824, #818, #525, #410, #160, #186); left: the precise-drafting gaps (approximate ellipse and spline intersections, prompt options that still print "not available yet"; U4, F1), dynamic-block authoring, editing an xref in place (F2, F3), and printing beyond files (F14, H3). ≈ 50–80 h. Items 2 and 7 are the open [alpha gate](#alpha-gate) rows. @@ -33,7 +33,7 @@ the alpha checklist. Main platform: macOS. |---|---|---|---| | 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 | +| 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), XCLIP and XCLIPFRAME (#2354) and dynamic block references (visibility, distances, stretch and move actions, lookups, grips; #838–#883) work; 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 (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** | @@ -53,11 +53,11 @@ remaining gaps are known bugs and edge features (≈ 75% ready for real work). | 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 | partial (xrefs, Block Editor, REFEDIT, groups, attribute tools and dynamic block references landed; authoring, XCLIP and in-place xref editing 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, XCLIP included; authoring 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 | partial (fifteen catalogs shipped, six of AutoCAD for Mac's seven other languages; Japanese and the catalog extension not started) | 30–45 | +| Catalog plus AutoCAD for Mac's languages | partial (eighteen 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** | @@ -85,7 +85,7 @@ agents that built each milestone, are in the progress log of [ROADMAP.md](../ROA | 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% (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 fifteen languages, live language switching, #36; percentage from 2026-10-10 and not re-scored) | 110–170 | +| M13 | 1.0 polish: preferences, workspaces, localisation, accessibility, signed packages, docs | ≈ 15% (signed packages for every platform exist; themes done; string catalog with eighteen 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** | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 25201fd6d..c13bb0a2f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -12,7 +12,7 @@ and the deep checklists are [geometry-parity.md](geometry-parity.md), | Number | Value | Kind | |---|---|---| -| **Feature breadth** (AutoCAD for Mac menu items with a live command) | **245 / 491 = 50%** (233 = 47% counted by `cargo xtask parity`, which sees engine commands only; +12 UI-only items) | measured ([parity-checklist.md](parity-checklist.md), source scan) | +| **Feature breadth** (AutoCAD for Mac menu items with a live command) | **245 / 491 = 50%** at the 2026-10-10 re-measure, not re-measured since (the generated checklist now reads 298 / 491, engine commands only; 233 = 47% counted by `cargo xtask parity`, which sees engine commands only; +12 UI-only items) | measured ([parity-checklist.md](parity-checklist.md), source scan) | | Feature breadth, 2D menus only (excluding 150 3D items) | **≈ 65%** (222 / 341 by `cargo xtask parity`'s rule) | measured (source scan, 2026-10-10) | | Feature depth, weighted by use (features dimension) | **≈ 41%** | estimated (table below) | | **Ready for real work** | **≈ 38%** | estimated (dimension table below; weighted 37.7%) | @@ -59,7 +59,7 @@ mainstream and essentials numbers use multiplicative discounts. geometry kernel, DXF/DWG paths, interaction code. Plus the 88 GitHub issues and 47 open PRs. Disk was nearly full, so nothing was built or run: `cargo xtask parity` was reproduced by a Python scan of `CommandSpec` menus with the xtask's matching rule, which gives exactly the same - uncovered list as the last generated report (233 / 491). Re-run `cargo xtask parity` to + uncovered list as the last generated report (233 / 491 at the 2026-10-10 scan, a historical figure). Re-run `cargo xtask parity` to confirm. ## Mainstream practitioner @@ -150,7 +150,7 @@ presence: an option that prints "not available yet" doesn't count. | 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); 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) | +| 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 on the command line with TEXTEDIT; an existing MTEXT opens in the in-place editor with its contents, #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, REFSET and REFCLOSE (#818); XCLIP and XCLIPFRAME (#2354); dynamic block references read and edited, with grips (#838–#883); no dynamic-block authoring, DesignCenter | [gaps](gaps.md#features) | @@ -173,7 +173,7 @@ presence: an option that prints "not available yet" doesn't count. | 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'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 fifteen languages (Ukrainian 1,357 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) | +| Localization | 3% | 5% | 60–100 | string catalog with eighteen languages (Ukrainian 1,414 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** | | | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 24c0aafd5..1c3bdd3be 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -160,7 +160,7 @@ dimensions are edited). | Feature | AutoCAD for Mac | CADCraft | |---|---|---| -| Menu bar | 11 menus, 491 leaf items | same 11 menus; 245/491 items covered (233 by `cargo xtask parity`, which counts engine commands only, plus 12 UI-only items: see [parity-checklist.md](parity-checklist.md)); once a menu is open, pointing at another title opens that menu (#1567) | +| Menu bar | 11 menus, 491 leaf items | same 11 menus; 245/491 items covered at the 2026-10-10 re-measure, not re-measured since (the generated checklist now reads 298/491, engine commands only; 233 by `cargo xtask parity`, which counts engine commands only, plus 12 UI-only items: see [parity-checklist.md](parity-checklist.md)); once a menu is open, pointing at another title opens that menu (#1567) | | Tool Bar, File tabs, Start tab, layout tabs | yes | yes | | Tool Sets palette (Drafting, Modeling, … with flyouts) | yes | yes for 2D groups | | Properties Inspector, Quick Properties | yes | yes (every control acts or is visibly unavailable, #182); block references show read-only Position X/Y/Z from their stored insertion point; coordinate editing is still missing; numeric fields take feet and inches and show lengths in the drawing's units (#870) | From 3f9e45f7262b2998ec541524fc165e84e2da8589 Mon Sep 17 00:00:00 2001 From: mkzung <103102868+mkzung@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:32:34 +0000 Subject: [PATCH 161/185] DWG: another application's objects are kept as proxy objects of their class An object of another application's class that acadrust has no model for is read only as its DWG record (ObjectType::Unknown), which its DXF writer leaves out. The DWG to DXF bridge lost every such object with no note, and the references to it went too (an extension dictionary entry naming the object, say). Each one is now carried as a proxy object of its class (ACAD_PROXY_OBJECT): the record is split into its common object data (owner, reactors, extension dictionary) and the streams after it (data bits, R2007+ strings, object references), as the Open Design Specification for .dwg describes them. The references are read to the end of the handle stream (to its exact length from R2010 on), null ones too: a null reference is an empty field, and the references after it belong to the next fields. Objects of the drawing database's own classes, and records that don't split, stay as they were and are named in a note. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H43qQA41CJLauqXnPgBQ7r --- crates/dwg/src/lib.rs | 331 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 331 insertions(+) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 0dcbd0667..5a7eabbac 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -107,6 +107,9 @@ mod native { } let mut notes = read_notes(&outcome.stats); let mut doc = outcome.document; + notes.extend( + guarded(AssertUnwindSafe(|| application_objects(&mut doc))).map_err(|_| "the DWG application object 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") }; @@ -390,6 +393,214 @@ mod native { std::panic::catch_unwind(f).map_err(|_| ()) } + /// The version a proxy record of a DWG of `version` names its format by (Open Design + /// Specification for .dwg, proxy objects): 19 for R13, 21 for R14, 23 for 2000, 25 for 2004, + /// 27 for 2007, 29 for 2010, 31 for 2013 and 33 for 2018; `None` for any other version. + fn proxy_dwg_version(version: acadrust::DxfVersion) -> Option { + Some(match version.version_code() { + 1012 => 19, + 1014 => 21, + 1015 => 23, + 1018 => 25, + 1021 => 27, + 1024 => 29, + 1027 => 31, + 1032 => 33, + _ => return None, + }) + } + + /// Objects of another application's class that acadrust keeps only as their DWG record + /// (`ObjectType::Unknown`, which has no DXF form): its DXF writer left them out, and the + /// references to them went with them (a dimension's extension dictionary entry naming its + /// application data, say), with no note. Each is carried as a proxy object of its class instead + /// (DXF Reference, ACAD_PROXY_OBJECT), so the DXF keeps it and a DWG written from that DXF has it + /// again: its common object data (owner, reactors, extension dictionary) and the streams after + /// it (data bits, R2007+ strings, object references), as the Open Design Specification for .dwg + /// splits an object record. Objects of the drawing database's own classes are not turned into + /// another application's proxies. What is still without a DXF form is named in the notes, so a + /// save over the original is not mistaken for a complete one. + fn application_objects(doc: &mut acadrust::CadDocument) -> Vec { + use acadrust::objects::{ObjectType, ProxyObject}; + let classes: Vec = doc.classes.iter().cloned().collect(); + let source = doc.dwg_source_version.unwrap_or(doc.version); + if let Some(dwg_version) = proxy_dwg_version(source) { + let maintenance = i32::from(doc.maintenance_version); + for object in doc.objects.values_mut() { + let ObjectType::Unknown { handle, raw_dwg_data: Some(data), raw_dwg_handle_bits, raw_dwg_version: Some(version), type_name, .. } = + &*object + else { + continue; + }; + if !application_class(&classes, type_name) { + continue; + } + let raw = acadrust::entities::RawRecord { data: data.clone(), handle_bits: *raw_dwg_handle_bits, version: *version }; + let handle = *handle; + // A record that doesn't split stays as it was, and is named below. + let Ok(Ok(record)) = std::panic::catch_unwind(AssertUnwindSafe(|| object_record(&raw, handle.value()))) else { continue }; + let Some(class) = classes.iter().find(|c| c.class_number == record.kind && !c.is_an_entity) else { continue }; + *object = ObjectType::ProxyObject(ProxyObject { + handle, + owner: record.owner, + reactors: record.reactors, + xdictionary_handle: record.xdictionary, + proxy_id: 499, + class_id: i32::from(class.class_number), + dwg_version, + maintenance_version: maintenance, + version: (maintenance << 16) | dwg_version, + payload: record.payload, + text_payload: record.text_payload, + object_ids: record.object_ids, + ..Default::default() + }); + } + } + let mut left: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + for object in doc.objects.values() { + if let ObjectType::Unknown { type_name, raw_dxf_codes: None, .. } = object { + let n = left.entry(type_name.as_str()).or_insert(0); + *n = n.saturating_add(1); + } + } + if left.is_empty() { + return Vec::new(); + } + let total = left.values().fold(0usize, |a, n| a.saturating_add(*n)); + let mut list: Vec = left.iter().take(NOTE_TYPES).map(|(t, n)| format!("{t:.60} × {n}")).collect(); + if left.len() > NOTE_TYPES { + list.push(format!("{} more types", left.len() - NOTE_TYPES)); + } + vec![format!( + "DWG: {total} objects of types CADCraft doesn't keep were left out ({}); saving over the original file would lose them", + list.join(", ") + )] + } + + /// Whether `name` is an object class of another application, which only that application + /// rebuilds: not one of the drawing database's own classes (`AcDb…`/`ACDB…`/`ACAD_…`), whose + /// leftovers the database regenerates itself. + fn application_class(classes: &[acadrust::classes::DxfClass], name: &str) -> bool { + classes.iter().any(|c| { + !c.is_an_entity + && c.dxf_name.eq_ignore_ascii_case(name) + && !c.cpp_class_name.starts_with("AcDb") + && !["ACDB", "ACAD_", "ACAD"].iter().any(|p| c.dxf_name.to_ascii_uppercase().starts_with(p)) + }) + } + + /// An application object acadrust kept only as its record: the parts a proxy object carries. + struct ObjectRecord { + kind: i16, + owner: acadrust::types::Handle, + reactors: Vec, + xdictionary: Option, + payload: acadrust::objects::ProxyPayload, + text_payload: acadrust::objects::ProxyPayload, + object_ids: Vec, + } + + /// Split an object record into its common object data and the uninterpreted streams after it + /// (data bits, R2007+ strings and object references), as an application object's proxy holds + /// them (Open Design Specification for .dwg, common object data and proxy objects). The record + /// is hostile: sizes are checked against it, and acadrust's checked stream reader does the rest. + fn object_record(raw: &acadrust::entities::RawRecord, handle: u64) -> Result { + use acadrust::io::dwg::{ + DwgVersion, dwg_reference_type::DwgReferenceType, dwg_stream_readers::object_reader::DwgObjectReader, + dwg_stream_writers::bit_writer::DwgBitWriter, + }; + use acadrust::objects::{ProxyObjectReference, ProxyPayload, ProxyReferenceKind}; + use acadrust::types::{DxfVersion, Handle}; + if raw.data.len() > 32 << 20 { + return Err("object record exceeds the transport limit".into()); + } + let handle_bits = usize::try_from(raw.handle_bits).map_err(|_| "object has a negative handle stream size")?; + let total_bits = raw.data.len().checked_mul(8).ok_or("object record is too large")?; + if handle_bits > total_bits { + return Err("object handle stream exceeds its record".into()); + } + let version = DwgVersion::from_dxf_version(raw.version).map_err(|e| e.to_string())?; + 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, std::collections::HashMap::new()).map_err(|e| e.to_string())?; + let (kind, mut streams) = reader.read_record_at(0).map_err(|e| e.to_string())?; + if kind < 500 { + return Err("object has no application class".into()); + } + let common = reader.read_common_non_entity_data(&mut streams, kind); + streams.check_error().map_err(|e| e.to_string())?; + if common.common.handle != handle { + return Err("object record names another handle".into()); + } + let read_bits = |count: usize, bit: &mut dyn FnMut() -> bool| -> Result { + if count > total_bits { + return Err("object stream exceeds its record".into()); + } + let n = u32::try_from(count).map_err(|_| "object stream is too large")?; + let mut bytes = vec![0u8; count.div_ceil(8)]; + for index in 0..count { + if bit() + && let Some(b) = bytes.get_mut(index / 8) + { + *b |= 0x80 >> (index % 8); + } + } + Ok(ProxyPayload::from_bits(&bytes, n)) + }; + let main = usize::try_from(streams.main_remaining_bits()).map_err(|_| "object body has an invalid size")?; + let payload = read_bits(main, &mut || streams.read_bit())?; + let text_payload = if raw.version >= DxfVersion::AC1021 { + let bits = usize::try_from(streams.text_remaining_bits()).map_err(|_| "object has a negative string stream size")?; + read_bits(bits, &mut || streams.read_text_bit())? + } else { + ProxyPayload::default() + }; + // Every reference to the end of the handle stream, null ones too: an object keeps a null pointer in its + // field's place, and the references after it are the next fields' (as acadrust reads a proxy's own). R2010+ + // records give the stream's exact length; the bits of its last byte past it are padding. + let mut object_ids = Vec::new(); + let mut left = if raw.version >= DxfVersion::AC1024 { + streams.get_handle_bits().max(0).min(streams.handle_remaining_bits()) + } else { + streams.handle_remaining_bits() + }; + while left >= 8 { + if object_ids.len() >= 100_000 { + return Err("object has too many references".into()); + } + let before = streams.handle_remaining_bits(); + let (target, reference) = streams.read_handle_reference(handle); + let used = before.saturating_sub(streams.handle_remaining_bits()); + if used <= 0 || used > left { + break; + } + left -= used; + let kind = match reference { + DwgReferenceType::SoftOwnership => ProxyReferenceKind::SoftOwnership, + DwgReferenceType::HardOwnership => ProxyReferenceKind::HardOwnership, + DwgReferenceType::SoftPointer => ProxyReferenceKind::SoftPointer, + DwgReferenceType::HardPointer => ProxyReferenceKind::HardPointer, + DwgReferenceType::Undefined => ProxyReferenceKind::Undefined, + }; + object_ids.push(ProxyObjectReference { handle: Handle::from(target), kind }); + } + streams.check_error().map_err(|e| e.to_string())?; + Ok(ObjectRecord { + kind, + owner: Handle::from(common.owner_handle), + reactors: common.reactors.into_iter().map(Handle::from).collect(), + xdictionary: common.xdictionary_handle.map(Handle::from), + payload, + text_payload, + object_ids, + }) + } + /// [`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 { @@ -1159,6 +1370,126 @@ mod native { assert_eq!(guarded(|| 3), Ok(3)); } } + + #[cfg(test)] + mod application_object_tests { + use super::*; + use acadrust::CadDocument; + use acadrust::classes::DxfClass; + use acadrust::objects::{ObjectType, ProxyObjectReference, ProxyPayload, ProxyReferenceKind, RegisteredClassObject}; + use acadrust::types::{DxfVersion, Handle}; + + /// An object of another application's class that acadrust keeps only as its record (a + /// vertical product's dimension data, say) is carried as that class's proxy object, with its + /// data bits, references, owner and extension dictionary, through DXF and back to DWG, twice. + #[test] + fn undecoded_application_object_is_kept_as_its_proxy() { + for version in [DxfVersion::AC1027, DxfVersion::AC1032] { + let mut source = CadDocument::new(); + source.version = version; + source.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); + let handle = Handle::from(0x2Bu64); + let target = Handle::from(0x2Cu64); + let payload = ProxyPayload::from_bits(&[0x5A, 0x3C, 0xC0], 18); + // A null pointer between two references: it keeps its place, the one after it is not lost. + let references = vec![ + ProxyObjectReference { handle: target, kind: ProxyReferenceKind::HardPointer }, + ProxyObjectReference { handle: Handle::from(0u64), kind: ProxyReferenceKind::SoftPointer }, + ProxyObjectReference { handle: Handle::from(0x0Cu64), kind: ProxyReferenceKind::HardPointer }, + ]; + source.objects.insert( + handle, + ObjectType::RegisteredClass(RegisteredClassObject { + handle, + owner: Handle::from(0x0Cu64), + dxf_name: "TESTCONTAINER".into(), + cpp_class_name: "xyzDbTestContainer".into(), + payload: payload.clone(), + object_ids: references.clone(), + ..Default::default() + }), + ); + let mut dwg = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + // acadrust has no model of it: read back, it is only its record. + let decoded = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); + assert!(matches!(decoded.objects.get(&handle), Some(ObjectType::Unknown { .. })), "{:?}", decoded.objects.get(&handle)); + for generation in 0..2 { + let (dxf, notes) = dwg_to_dxf_noted(&dwg, Limits::DEFAULT).unwrap(); + assert!(notes.is_empty(), "{version:?} {generation}: {notes:?}"); + // The DXF has the object, by its handle, as a proxy record. + let text = String::from_utf8_lossy(&dxf); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let record = lines.windows(4).any(|w| w == ["0", "ACAD_PROXY_OBJECT", "5", "2B"]); + assert!(record, "{version:?} {generation}: no proxy record for the object"); + dwg = dxf_to_dwg_as(&dxf, "AC1032").unwrap(); + let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.clone())).read().unwrap(); + let Some(ObjectType::ProxyObject(proxy)) = doc.objects.get(&handle) else { panic!("{version:?} {generation}: proxy object") }; + assert_eq!(proxy.payload.bit_count, payload.bit_count); + assert_eq!(proxy.payload.data(), payload.data()); + assert_eq!(proxy.object_ids, references); + let class = doc.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap(); + assert_eq!(class.dxf_name, "TESTCONTAINER"); + assert!(!class.is_an_entity); + } + } + } + + /// The database's own classes are not turned into another application's proxies; what is + /// left without a DXF form is said, not dropped silently. + #[test] + fn database_objects_without_a_form_are_reported() { + let mut doc = CadDocument::new(); + doc.classes.add_or_update(DxfClass::new("BLOCKPROPERTIESTABLE", "AcDbBlockPropertiesTable")); + let handle = Handle::from(0x40u64); + doc.objects.insert( + handle, + ObjectType::Unknown { + type_name: "BLOCKPROPERTIESTABLE".into(), + handle, + owner: Handle::from(0x0Cu64), + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0; 8]), + raw_dwg_handle_bits: 0, + raw_dwg_version: Some(DxfVersion::AC1032), + }, + ); + let notes = application_objects(&mut doc); + assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); + assert_eq!( + notes, + [ + "DWG: 1 objects of types CADCraft doesn't keep were left out (BLOCKPROPERTIESTABLE × 1); saving over the original file would lose them" + ] + ); + } + + /// A record that doesn't split stays as it was and is named, never guessed at. + #[test] + fn invalid_object_records_are_rejected() { + for handle_bits in [-1, 1000] { + let raw = acadrust::entities::RawRecord { data: vec![0; 8], handle_bits, version: DxfVersion::AC1032 }; + assert!(object_record(&raw, 42).is_err()); + } + let mut doc = CadDocument::new(); + doc.classes.add_or_update(DxfClass::new("TESTCONTAINER", "xyzDbTestContainer")); + let handle = Handle::from(0x41u64); + doc.objects.insert( + handle, + ObjectType::Unknown { + type_name: "TESTCONTAINER".into(), + handle, + owner: Handle::from(0x0Cu64), + raw_dxf_codes: None, + raw_dwg_data: Some(vec![0xFF; 4]), + raw_dwg_handle_bits: 1000, + raw_dwg_version: Some(DxfVersion::AC1032), + }, + ); + let notes = application_objects(&mut doc); + assert!(matches!(doc.objects.get(&handle), Some(ObjectType::Unknown { .. }))); + assert!(notes.iter().any(|n| n.contains("(TESTCONTAINER × 1)")), "{notes:?}"); + } + } } #[cfg(not(no_dwg_bridge))] From 1363afb883f8c647e901892dbdf5564f9f483847 Mon Sep 17 00:00:00 2001 From: mkzung <103102868+mkzung@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:32:34 +0000 Subject: [PATCH 162/185] DXF/DWG: an object a kept object holds by a hard owner reference is kept An object whose owner (group 330) is null but which another kept object holds by a hard owner reference (group 360), as one application's proxy object held by another, broke the owner chain the reader and writer follow to decide what to keep: it was dropped, and the holder kept a reference to nothing. Such an object's owner is now the object that hard-owns it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H43qQA41CJLauqXnPgBQ7r --- crates/io/src/dxf_raw.rs | 32 +++++++- crates/io/tests/hard_owned_objects_kept.rs | 94 ++++++++++++++++++++++ 2 files changed, 124 insertions(+), 2 deletions(-) create mode 100644 crates/io/tests/hard_owned_objects_kept.rs diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 3be39aa5b..c68f74e65 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -517,6 +517,7 @@ fn retained_objects( // 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 hard_owners = hard_owners(objects.iter().map(|(_, _, t)| *t)); let mut retained = HashMap::new(); for index in 0..objects.len() { let mut path = Vec::new(); @@ -531,7 +532,8 @@ fn retained_objects( path.push(current); let Some((_, _, tags)) = objects.get(current) else { break false }; let header = head(tags); - let (Some(handle), Some(owner)) = (header.handle, header.owner) else { break false }; + let Some(handle) = header.handle else { break false }; + let Some(owner) = owner_of(header.owner, &handle, &hard_owners) else { break false }; if by_handle.get(&handle) != Some(¤t) { break false; } @@ -557,6 +559,25 @@ fn retained_objects( retained } +/// The object that owns each object by a hard owner reference (group 360), the first one +/// to name it: `child handle → owner handle`. +fn hard_owners<'a>(objects: impl Iterator) -> HashMap { + let mut out = HashMap::new(); + for t in objects { + let Some(h) = head(t).handle else { continue }; + for c in t.iter().take_while(|g| g.code < 1000).filter(|g| g.code == 360) { + out.entry(norm(&c.str())).or_insert_with(|| h.clone()); + } + } + out +} + +/// An object's owner: its group 330, or for one whose owner is null (another application's +/// proxy that another proxy holds) the object that hard-owns it ([`hard_owners`]). +fn owner_of(owner: Option, handle: &str, hard: &HashMap) -> Option { + owner.filter(|o| o != "0").or_else(|| hard.get(handle).cloned()) +} + /// Proxy records (DXF Reference, ACAD_PROXY_OBJECT and ACAD_PROXY_ENTITY): another application's /// objects and entities, whose class is named by number in group 91. fn is_proxy(kind: &str) -> bool { @@ -901,10 +922,17 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap = f.objects.iter().map(|o| (o.handle.hex(), o)).collect(); let dict_entries: HashMap = f.dictionary.iter().map(|(k, h)| (h.hex(), k.as_str())).collect(); let nod = f.targets.iter().filter(|(_, k)| k.0 == "NOD" && k.1.is_empty()).map(|(h, _)| h.hex()).collect::>(); + let kept_tags: Vec> = f.objects.iter().map(|o| o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect()).collect(); + let hard = hard_owners(kept_tags.iter().map(Vec::as_slice)); let owners: HashMap = f .objects .iter() - .filter_map(|o| Some((o.handle.hex(), head(&o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect::>()).owner?))) + .zip(&kept_tags) + .filter_map(|(o, t)| { + let h = o.handle.hex(); + let owner = owner_of(head(t).owner, &h, &hard)?; + Some((h, owner)) + }) .collect(); let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { diff --git a/crates/io/tests/hard_owned_objects_kept.rs b/crates/io/tests/hard_owned_objects_kept.rs new file mode 100644 index 000000000..727a6fb3d --- /dev/null +++ b/crates/io/tests/hard_owned_objects_kept.rs @@ -0,0 +1,94 @@ +//! An object of another application whose owner is null, but which another kept object holds by a +//! hard owner reference (360), is kept with it, as one application's proxy object held by another. +//! In DXF and in DWG, save after save. + +use cadcraft_io::{read, read_dxf, write, write_dxf}; + +/// A named object dictionary entry `OTHER_APP` (a dictionary) with an XRECORD that holds a second +/// XRECORD by a 360 reference; the second one's owner is null. +fn source() -> String { + let groups: &[(i32, &str)] = &[ + (0, "SECTION"), + (2, "ENTITIES"), + (0, "LINE"), + (5, "30"), + (8, "0"), + (10, "0"), + (20, "0"), + (11, "10"), + (21, "0"), + (0, "ENDSEC"), + (0, "SECTION"), + (2, "OBJECTS"), + (0, "DICTIONARY"), + (5, "C"), + (330, "0"), + (100, "AcDbDictionary"), + (3, "OTHER_APP"), + (350, "50"), + (0, "DICTIONARY"), + (5, "50"), + (330, "C"), + (100, "AcDbDictionary"), + (281, "1"), + (3, "HOLDER"), + (360, "51"), + (0, "XRECORD"), + (5, "51"), + (102, "{ACAD_REACTORS"), + (330, "50"), + (102, "}"), + (330, "50"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "holder"), + (360, "52"), + (0, "XRECORD"), + (5, "52"), + (102, "{ACAD_REACTORS"), + (330, "51"), + (102, "}"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "held"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + groups.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +fn check(text: &str, label: &str) { + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + let pairs: Vec<(&str, &str)> = lines.chunks(2).filter_map(|c| Some((*c.first()?, *c.get(1)?))).collect(); + // Each record from its `0` group on, as (code, value) pairs. + let records: Vec<&[(&str, &str)]> = pairs + .iter() + .enumerate() + .filter(|(_, (c, _))| *c == "0") + .map(|(i, _)| { + let n = pairs[i + 1..].iter().position(|(c, _)| *c == "0").map_or(pairs.len(), |n| i + 1 + n); + &pairs[i..n] + }) + .collect(); + let with = |text: &str| records.iter().find(|r| r.contains(&("1", text))).copied().unwrap_or_else(|| panic!("{label}: no record {text}")); + let holder = with("holder"); + let Some((_, held_handle)) = holder.iter().find(|(c, _)| *c == "360") else { panic!("{label}: the holder holds nothing: {holder:?}") }; + let held = with("held"); + assert!(held.contains(&("5", *held_handle)), "{label}: the holder's 360 names the held record: {holder:?} {held:?}"); +} + +#[test] +fn an_object_held_by_a_kept_one_is_kept() { + let mut d = read_dxf(source().as_bytes()).expect("read"); + for generation in 1..=2 { + let text = write_dxf(&d); + check(&text, &format!("DXF {generation}")); + d = read_dxf(text.as_bytes()).expect("reread"); + } + for generation in 1..=2 { + let dwg = write(&d, "held.dwg").expect("DWG"); + d = read(&dwg, "held.dwg").expect("DWG read"); + check(&write_dxf(&d), &format!("DWG {generation}")); + } +} From 7a9ec9bae323bdb548ff4b647a971f5c448e59c2 Mon Sep 17 00:00:00 2001 From: Luis <43929895+Luis-0508@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:44:24 +0100 Subject: [PATCH 163/185] Release: refresh contributor credits for each release (#2880) (#2881) About > Contributors still showed an old snapshot, because nothing regenerated contributors/contributors.json before a release. Opt in to the shared refresh from craft-common-actions: a read-only credits job regenerates the snapshot for the release commit, and the shared release workflow installs it before every source build. The snapshot is not committed back. --- .github/workflows/release.yml | 9 ++++++++- docs/contributors.md | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c2cf475e8..a0ae76e01 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,6 +18,12 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main git-sources: name: Git dependencies come from storytold runs-on: ubuntu-latest @@ -58,7 +64,7 @@ jobs: PY release: - needs: git-sources + needs: [git-sources, credits] permissions: # The reusable release workflow tags and uploads the draft release. contents: write @@ -70,6 +76,7 @@ jobs: app-title: CADCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} diff --git a/docs/contributors.md b/docs/contributors.md index 13f693149..9459809af 100644 --- a/docs/contributors.md +++ b/docs/contributors.md @@ -8,7 +8,8 @@ the AI models named in `Co-Authored-By` trailers. - 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. + username. Release builds regenerate it for the release commit + (`.github/workflows/release.yml`, `credits` job); the copy in the repository is not updated. - [`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 From adf02f9f0469da480f5d8b5380b49f1e3eaebdf8 Mon Sep 17 00:00:00 2001 From: mkzung <103102868+mkzung@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:15:03 +0000 Subject: [PATCH 164/185] DXF/DWG: a null-owner object goes with a hard owner that is kept hard_owners took the first object naming a null-owner object in a 360 as its owner, kept or not. When an object that is left out named it first, the reader dropped the object, though a kept one held it too, and the save wrote the kept holder's 360 as 0. hard_owners now lists every object naming it, in file order, and owner_of takes the first of them that is kept, else the first. The read (retained_objects) and the write liveness pass in finish run until what they keep settles; a file where no object has two hard owners takes one pass, as before. The write pass no longer keeps a converted copy of every object's groups. The test adds an object nothing keeps that names the held record before its holder does: the held record stays with the holder and the stray object is dropped, DXF and DWG, twice. It fails before this change ("DXF 1: no record held"). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01H43qQA41CJLauqXnPgBQ7r --- crates/io/src/dxf_raw.rs | 216 +++++++++++++-------- crates/io/tests/hard_owned_objects_kept.rs | 13 +- 2 files changed, 142 insertions(+), 87 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index c68f74e65..4009389b9 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -517,65 +517,104 @@ fn retained_objects( // 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 hard_owners = hard_owners(objects.iter().map(|(_, _, t)| *t)); - let mut retained = HashMap::new(); - for index in 0..objects.len() { - let mut path = Vec::new(); - let mut current = index; - let keep = loop { - if let Some(&known) = retained.get(¤t) { - break known; - } - if path.contains(¤t) || path.len() >= MAX_DEPTH { - break false; - } - path.push(current); - let Some((_, _, tags)) = objects.get(current) else { break false }; - let header = head(tags); - let Some(handle) = header.handle else { break false }; - let Some(owner) = owner_of(header.owner, &handle, &hard_owners) else { break false }; - if by_handle.get(&handle) != Some(¤t) { - break false; - } - if root == Some(owner.as_str()) { - break root_key(&handle).is_some_and(|key| !modelled_key(key)); - } - if let Some(&parent) = by_handle.get(&owner) { - if is_xdict(parent) && objects.get(parent).is_some_and(|object| modelled_entry(object.2, &handle)) { + let hard = hard_owners(objects.iter().filter_map(|(_, _, t)| Some((head(t).handle?, held(t))))); + // One pass with `kept` the objects an earlier pass kept: a null-owner object goes with the + // first of its hard owners that is kept. + let mut pass = |kept: &HashMap| { + let kept = |h: &str| by_handle.get(h).and_then(|i| kept.get(i)) == Some(&true); + let mut retained = HashMap::new(); + for index in 0..objects.len() { + let mut path = Vec::new(); + let mut current = index; + let keep = loop { + if let Some(&known) = retained.get(¤t) { + break known; + } + if path.contains(¤t) || path.len() >= MAX_DEPTH { break false; } - current = parent; - continue; + path.push(current); + let Some((_, _, tags)) = objects.get(current) else { break false }; + let header = head(tags); + let Some(handle) = header.handle else { break false }; + let Some(owner) = owner_of(header.owner, &handle, &hard, kept) else { break false }; + if by_handle.get(&handle) != Some(¤t) { + break false; + } + if root == Some(owner.as_str()) { + break root_key(&handle).is_some_and(|key| !modelled_key(key)); + } + if let Some(&parent) = by_handle.get(&owner) { + if is_xdict(parent) && objects.get(parent).is_some_and(|object| modelled_entry(object.2, &handle)) { + break false; + } + current = parent; + continue; + } + if is_xdict(current) { + break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); + } + break entities.get(&owner) == Some(&true); + }; + for visited in path { + retained.insert(visited, keep); } - if is_xdict(current) { - break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str())); - } - break entities.get(&owner) == Some(&true); - }; - for visited in path { - retained.insert(visited, keep); } - } - retained + retained + }; + settle(&hard, |kept| pass(kept)) } -/// The object that owns each object by a hard owner reference (group 360), the first one -/// to name it: `child handle → owner handle`. -fn hard_owners<'a>(objects: impl Iterator) -> HashMap { - let mut out = HashMap::new(); - for t in objects { - let Some(h) = head(t).handle else { continue }; - for c in t.iter().take_while(|g| g.code < 1000).filter(|g| g.code == 360) { - out.entry(norm(&c.str())).or_insert_with(|| h.clone()); +/// Run `pass` until what it keeps settles. The first pass sees nothing kept, so a null-owner +/// object goes with its first hard owner; while one of its other hard owners is kept and that +/// one is not, the next pass moves it there. A file where no object has two hard owners takes +/// one pass; otherwise it stops when a pass changes nothing, after at most [`MAX_DEPTH`] more. +fn settle( + hard: &HashMap>, + mut pass: impl FnMut(&HashMap) -> HashMap, +) -> HashMap { + let mut kept = pass(&HashMap::new()); + if hard.values().all(|owners| owners.len() < 2) { + return kept; + } + for _ in 0..MAX_DEPTH { + let next = pass(&kept); + if next == kept { + break; + } + kept = next; + } + kept +} + +/// The handles an object names by a hard owner reference (group 360). +fn held(tags: &[Tag]) -> impl Iterator + '_ { + tags.iter().take_while(|g| g.code < 1000).filter(|g| g.code == 360).map(|g| g.str()) +} + +/// The objects that own each object by a hard owner reference (group 360), in file order: +/// `child handle → owner handles`. +fn hard_owners>(objects: impl Iterator)>) -> HashMap> { + let mut out: HashMap> = HashMap::new(); + for (h, children) in objects { + for c in children { + let owners = out.entry(norm(c.as_ref())).or_default(); + if !owners.contains(&h) { + owners.push(h.clone()); + } } } out } /// An object's owner: its group 330, or for one whose owner is null (another application's -/// proxy that another proxy holds) the object that hard-owns it ([`hard_owners`]). -fn owner_of(owner: Option, handle: &str, hard: &HashMap) -> Option { - owner.filter(|o| o != "0").or_else(|| hard.get(handle).cloned()) +/// proxy that another proxy holds) the object that hard-owns it ([`hard_owners`]): the first +/// one that is `kept`, or else the first one. +fn owner_of(owner: Option, handle: &str, hard: &HashMap>, kept: impl Fn(&str) -> bool) -> Option { + owner.filter(|o| o != "0").or_else(|| { + let owners = hard.get(handle)?; + owners.iter().find(|o| kept(o)).or_else(|| owners.first()).cloned() + }) } /// Proxy records (DXF Reference, ACAD_PROXY_OBJECT and ACAD_PROXY_ENTITY): another application's @@ -922,50 +961,55 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap = f.objects.iter().map(|o| (o.handle.hex(), o)).collect(); let dict_entries: HashMap = f.dictionary.iter().map(|(k, h)| (h.hex(), k.as_str())).collect(); let nod = f.targets.iter().filter(|(_, k)| k.0 == "NOD" && k.1.is_empty()).map(|(h, _)| h.hex()).collect::>(); - let kept_tags: Vec> = f.objects.iter().map(|o| o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect()).collect(); - let hard = hard_owners(kept_tags.iter().map(Vec::as_slice)); - let owners: HashMap = f + let hard = hard_owners( + f.objects.iter().map(|o| (o.handle.hex(), o.tags.iter().take_while(|t| t.code < 1000).filter(|t| t.code == 360).map(|t| t.value.trim()))), + ); + // Each kept object's own owner (group 330), read one record at a time. + let own: HashMap> = f .objects .iter() - .zip(&kept_tags) - .filter_map(|(o, t)| { - let h = o.handle.hex(); - let owner = owner_of(head(t).owner, &h, &hard)?; - Some((h, owner)) + .map(|o| { + let t: Vec = o.tags.iter().take_while(|t| t.code < 1000).map(tag).collect(); + (o.handle.hex(), head(&t).owner) }) .collect(); - let mut alive_memo: HashMap = HashMap::new(); - for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { - alive_memo.insert(o.handle.hex(), false); - } - for o in &f.objects { - let mut path: Vec = Vec::new(); - let mut cur = o.handle.hex(); - let verdict = loop { - if let Some(&v) = alive_memo.get(&cur) { - break v; - } - if path.contains(&cur) || path.len() >= MAX_DEPTH { - break false; - } - path.push(cur.clone()); - let Some(owner) = owners.get(&cur).cloned() else { break false }; - if objs.contains_key(&owner) { - cur = owner; - continue; - } - if nod.contains(&owner) { - break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some(); - } - if attached.contains(&cur) { - break true; - } - break unknown.contains(&owner) && written.contains(&owner); - }; - for p in path { - alive_memo.insert(p, verdict); + let alive_memo = settle(&hard, |kept: &HashMap| { + let kept = |h: &str| kept.get(h) == Some(&true); + let mut alive_memo: HashMap = HashMap::new(); + for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) + { + alive_memo.insert(o.handle.hex(), false); } - } + for o in &f.objects { + let mut path: Vec = Vec::new(); + let mut cur = o.handle.hex(); + let verdict = loop { + if let Some(&v) = alive_memo.get(&cur) { + break v; + } + if path.contains(&cur) || path.len() >= MAX_DEPTH { + break false; + } + path.push(cur.clone()); + let Some(owner) = owner_of(own.get(&cur).cloned().flatten(), &cur, &hard, kept) else { break false }; + if objs.contains_key(&owner) { + cur = owner; + continue; + } + if nod.contains(&owner) { + break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some(); + } + if attached.contains(&cur) { + break true; + } + break unknown.contains(&owner) && written.contains(&owner); + }; + for p in path { + alive_memo.insert(p, verdict); + } + } + alive_memo + }); // New handles for the written kept objects, above every written handle and the seed. let mut next = seed(tags).max(max_handle(tags).saturating_add(1)); let mut alive: HashMap = HashMap::new(); diff --git a/crates/io/tests/hard_owned_objects_kept.rs b/crates/io/tests/hard_owned_objects_kept.rs index 727a6fb3d..a8ccb6ae0 100644 --- a/crates/io/tests/hard_owned_objects_kept.rs +++ b/crates/io/tests/hard_owned_objects_kept.rs @@ -5,7 +5,8 @@ use cadcraft_io::{read, read_dxf, write, write_dxf}; /// A named object dictionary entry `OTHER_APP` (a dictionary) with an XRECORD that holds a second -/// XRECORD by a 360 reference; the second one's owner is null. +/// XRECORD by a 360 reference; the second one's owner is null. An object nothing keeps names the +/// second XRECORD by a 360 first. fn source() -> String { let groups: &[(i32, &str)] = &[ (0, "SECTION"), @@ -26,6 +27,15 @@ fn source() -> String { (100, "AcDbDictionary"), (3, "OTHER_APP"), (350, "50"), + // An object nothing keeps (null owner, no holder) that also names the held record by a + // 360, before the holder does: it is dropped, and the held record stays with the holder. + (0, "XRECORD"), + (5, "60"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "stray"), + (360, "52"), (0, "DICTIONARY"), (5, "50"), (330, "C"), @@ -76,6 +86,7 @@ fn check(text: &str, label: &str) { let Some((_, held_handle)) = holder.iter().find(|(c, _)| *c == "360") else { panic!("{label}: the holder holds nothing: {holder:?}") }; let held = with("held"); assert!(held.contains(&("5", *held_handle)), "{label}: the holder's 360 names the held record: {holder:?} {held:?}"); + assert!(!records.iter().any(|r| r.contains(&("1", "stray"))), "{label}: the object nothing keeps is dropped"); } #[test] From 9ec57281591d34dcb39e7e3916fc18375880b340 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:11:26 +0100 Subject: [PATCH 165/185] Fix FreeBSD ARM64 test dependency gating --- crates/io/Cargo.toml | 7 ++++-- crates/io/src/tests.rs | 6 ++--- crates/io/tests/dwg_active_layout.rs | 2 ++ crates/io/tests/dwg_kept_object_versions.rs | 2 +- crates/io/tests/dwg_polyline_vertex_order.rs | 2 +- crates/io/tests/dwg_required_dictionaries.rs | 2 +- crates/io/tests/dwg_table_cell_height.rs | 2 +- crates/io/tests/dwg_unavailable.rs | 21 ++++++++++++++++ crates/io/tests/it/dim_block_text.rs | 2 +- crates/io/tests/it/dwg_layout_owner.rs | 2 ++ crates/io/tests/it/dynblock_read.rs | 2 ++ crates/io/tests/it/mtext_caret_spaces.rs | 4 ++-- crates/io/tests/it/roundtrip/mod.rs | 2 +- xtask/tests/dwg_dependency_targets.rs | 25 ++++++++++++++++++++ 14 files changed, 68 insertions(+), 13 deletions(-) create mode 100644 crates/io/tests/dwg_unavailable.rs create mode 100644 xtask/tests/dwg_dependency_targets.rs diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 21ba5d5cc..f39a630f1 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -25,8 +25,11 @@ 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). -acadrust = "0.6.6" tiny-skia = { workspace = true } # Reads plotted PDFs back. craft-pdf = { workspace = true, features = ["read"] } + +# Inspect DWG output only where cadcraft-dwg builds its native bridge. An unconditional +# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526). +[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies] +acadrust = "0.6.6" diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 0a10424bc..040e71927 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -3511,7 +3511,7 @@ fn proxies_keep_their_class_when_classes_are_rewritten() { /// 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"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn proxies_keep_their_class_in_dwg() { use acadrust::entities::{EntityType, ExtendedEntityData}; @@ -3553,7 +3553,7 @@ fn proxies_keep_their_class_in_dwg() { /// 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"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_proxy_whose_class_is_unknown_is_left_out_of_the_dwg() { use acadrust::entities::{EntityType, ExtendedEntityData}; @@ -3602,7 +3602,7 @@ fn a_proxy_left_out_of_the_dwg_is_counted_as_unwritten() { /// 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"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_binary_dxf_leaves_its_proxies_out_of_the_dwg() { use acadrust::entities::{EntityType, ExtendedEntityData}; diff --git a/crates/io/tests/dwg_active_layout.rs b/crates/io/tests/dwg_active_layout.rs index 5093b2f5f..fd7d594ed 100644 --- a/crates/io/tests/dwg_active_layout.rs +++ b/crates/io/tests/dwg_active_layout.rs @@ -2,6 +2,8 @@ //! the one written as `*Paper_Space` (the DWG header's paper space block), the others //! `*Paper_SpaceN`. Saving used to make the first tab the active one again. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + use std::io::Cursor; use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, Space}; diff --git a/crates/io/tests/dwg_kept_object_versions.rs b/crates/io/tests/dwg_kept_object_versions.rs index 787470705..5cb39919f 100644 --- a/crates/io/tests/dwg_kept_object_versions.rs +++ b/crates/io/tests/dwg_kept_object_versions.rs @@ -11,7 +11,7 @@ //! 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"))] +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use std::fmt::Write as _; use std::io::Cursor; diff --git a/crates/io/tests/dwg_polyline_vertex_order.rs b/crates/io/tests/dwg_polyline_vertex_order.rs index 5cb63d2f6..b9606ded5 100644 --- a/crates/io/tests/dwg_polyline_vertex_order.rs +++ b/crates/io/tests/dwg_polyline_vertex_order.rs @@ -4,7 +4,7 @@ //! //! The DWG is written here with acadrust, giving the second 3D-polyline vertex the highest //! handle: exactly what an editing program produces when it inserts a vertex. -#![cfg(not(target_arch = "wasm32"))] +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use acadrust::entities::{EntityType, Polyline3D, Vertex3DPolyline}; use acadrust::types::{DxfVersion, Handle, Vector3}; diff --git a/crates/io/tests/dwg_required_dictionaries.rs b/crates/io/tests/dwg_required_dictionaries.rs index 3feb0d7dd..f28be9618 100644 --- a/crates/io/tests/dwg_required_dictionaries.rs +++ b/crates/io/tests/dwg_required_dictionaries.rs @@ -3,7 +3,7 @@ //! it as empty ("No data was imported..."), though it reads the same drawing as DXF (and as an //! AC1032 DWG) fine. The DWG bridge adds the dictionary AutoCAD writes, with its usual variables, //! when the DXF has none. -#![cfg(not(target_arch = "wasm32"))] +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use std::io::Cursor; diff --git a/crates/io/tests/dwg_table_cell_height.rs b/crates/io/tests/dwg_table_cell_height.rs index 11ee98c9d..6e077b870 100644 --- a/crates/io/tests/dwg_table_cell_height.rs +++ b/crates/io/tests/dwg_table_cell_height.rs @@ -1,5 +1,5 @@ //! TABLE heights inherit from the table style unless the file records a cell override. -#![cfg(not(target_arch = "wasm32"))] +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use cadcraft_doc::{Common, Drawing, EntityKind, Space, Table, TableCell, TableStyle}; diff --git a/crates/io/tests/dwg_unavailable.rs b/crates/io/tests/dwg_unavailable.rs new file mode 100644 index 000000000..421aded7c --- /dev/null +++ b/crates/io/tests/dwg_unavailable.rs @@ -0,0 +1,21 @@ +//! The targets without the native DWG bridge still handle DXF and report an actionable error +//! for DWG instead of pretending that opening or saving succeeded. + +#![cfg(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))] + +use cadcraft_doc::Drawing; +use cadcraft_io::{read, write}; + +#[test] +fn no_dwg_bridge_preserves_dxf_and_reports_dwg_unavailable() { + let drawing = Drawing::new_metric(); + let dxf = write(&drawing, "drawing.dxf").expect("DXF remains available"); + assert!(read(&dxf, "drawing.dxf").is_ok()); + + let read_error = read(b"AC1032unavailable", "drawing.dwg").unwrap_err().to_string(); + let write_error = write(&drawing, "drawing.dwg").unwrap_err().to_string(); + for error in [read_error, write_error] { + assert!(error.contains("DWG"), "{error}"); + assert!(error.contains("DXF"), "{error}"); + } +} diff --git a/crates/io/tests/it/dim_block_text.rs b/crates/io/tests/it/dim_block_text.rs index 244e9401c..8a6225a93 100644 --- a/crates/io/tests/it/dim_block_text.rs +++ b/crates/io/tests/it/dim_block_text.rs @@ -103,7 +103,7 @@ fn dxf_angular_block_text_keeps_the_decimal_separator() { } } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn dwg_angular_block_text_keeps_the_decimal_separator() { use std::io::Cursor; diff --git a/crates/io/tests/it/dwg_layout_owner.rs b/crates/io/tests/it/dwg_layout_owner.rs index 45de12cb8..20dfa72c3 100644 --- a/crates/io/tests/it/dwg_layout_owner.rs +++ b/crates/io/tests/it/dwg_layout_owner.rs @@ -2,6 +2,8 @@ //! by their own block (entity mode 0 and its handle). Written as "paper space" (mode 1), AutoCAD //! put them on the first layout and left theirs empty. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + use std::io::Cursor; use cadcraft_doc::{Circle, Common, Drawing, EntityKind, Layout, Line, Space}; diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index 01e67069f..fbcc74e35 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -87,6 +87,7 @@ fn a_saved_drawing_keeps_the_dynamic_block_as_read() { } /// The Door fixture with a scale action on the Width parameter: graph node 6, object 68. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] 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\ @@ -105,6 +106,7 @@ fn with_scale_action() -> String { /// 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). +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn a_scale_action_survives_a_dwg_save() { use acadrust::objects::{DynamicBlockData, DynamicBlockObject, ObjectType}; diff --git a/crates/io/tests/it/mtext_caret_spaces.rs b/crates/io/tests/it/mtext_caret_spaces.rs index 8bb1ed071..92b6ffd9a 100644 --- a/crates/io/tests/it/mtext_caret_spaces.rs +++ b/crates/io/tests/it/mtext_caret_spaces.rs @@ -74,7 +74,7 @@ fn dxf_mtext_caret_spaces_round_trip() -> TestResult { Ok(()) } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn dwg_mtext_caret_spaces_round_trip() -> TestResult { let (original, expected) = drawing()?; @@ -103,7 +103,7 @@ fn dwg_mtext_caret_spaces_round_trip() -> TestResult { Ok(()) } -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] #[test] fn bridge_caret_space_is_escaped_once_in_each_direction() -> TestResult { let (d, _) = drawing()?; diff --git a/crates/io/tests/it/roundtrip/mod.rs b/crates/io/tests/it/roundtrip/mod.rs index d38f84eb1..02a35c808 100644 --- a/crates/io/tests/it/roundtrip/mod.rs +++ b/crates/io/tests/it/roundtrip/mod.rs @@ -4,7 +4,7 @@ mod cases; mod collections; mod compare; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] mod dwg; mod dxf; mod handle_limits; diff --git a/xtask/tests/dwg_dependency_targets.rs b/xtask/tests/dwg_dependency_targets.rs new file mode 100644 index 000000000..a25b80bb5 --- /dev/null +++ b/xtask/tests/dwg_dependency_targets.rs @@ -0,0 +1,25 @@ +//! Test builds must not reintroduce the DWG decoder on targets where the bridge excludes it. + +use serde_json::Value; +use std::process::Command; + +#[test] +fn dwg_test_dependency_matches_the_bridge_targets() { + let output = Command::new(env!("CARGO")) + .args(["metadata", "--format-version", "1", "--no-deps", "--locked"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .output() + .expect("read workspace dependency metadata"); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + let metadata: Value = serde_json::from_slice(&output.stdout).expect("Cargo returns JSON"); + let packages = metadata["packages"].as_array().expect("workspace packages"); + let dependency = |name: &str| { + let package = packages.iter().find(|p| p["name"] == name).expect("workspace crate"); + package["dependencies"].as_array().expect("crate dependencies").iter().find(|d| d["name"] == "acadrust").expect("DWG decoder dependency") + }; + let bridge = dependency("cadcraft-dwg"); + let tests = dependency("cadcraft-io"); + assert_eq!(tests["kind"], "dev", "the IO crate only inspects acadrust output in tests"); + assert_eq!(tests["target"], bridge["target"], "--all-targets must not add acadrust where the native DWG bridge is unavailable"); + assert_eq!(tests["req"], bridge["req"], "tests must inspect the same decoder version as the bridge"); +} From a0dfe07f5a96743364512947bc10233164973c7b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:25:00 +0100 Subject: [PATCH 166/185] Preserve decoded proxy class identities through the DWG bridge --- crates/dwg/src/lib.rs | 49 +++++++++++++---------- crates/dwg/src/proxy_transport.rs | 49 +++++++++++++++++++---- crates/io/tests/registered_proxy.rs | 61 ++++++++++++++++++++++++++++- 3 files changed, 130 insertions(+), 29 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index af18fe1f3..534765457 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -963,7 +963,7 @@ mod native { /// 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])> { + pub(super) fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> { let mut offset = 0usize; let mut lines = dxf.split(|b| *b == b'\n').map(|line| { let at = offset.saturating_add(line.len() - line.trim_ascii_start().len()); @@ -1023,32 +1023,32 @@ mod native { /// 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> { + use acadrust::io::dxf::reader::DxfStreamReader; + let mut reader = super::proxy_transport::text_reader(dxf)?; let mut names = Vec::new(); - if dxf.starts_with(b"AutoCAD Binary DXF") { - 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); - 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"; - // Every record keeps its place, named or not: a proxy numbers its class by - // place, so a record without a name must not move the ones after it. An empty - // name matches no class, and such a proxy is left out. + let (mut section, mut in_classes, mut in_class) = (false, false, false); + while let Some(pair) = reader.read_pair().ok()? { + match (pair.code, pair.value_string.as_str()) { + (0, "ENDSEC") if in_classes => break, + (0, "SECTION") => section = true, + (2, name) if section => { + in_classes = name == "CLASSES"; + section = false; + } + (0, kind) if in_classes => { + in_class = kind == "CLASS"; + // Even an unnamed record keeps its place in the source class table. if in_class { names.push(String::new()); } } - (b"1", v) if in_class => { + (1, value) if in_class => { if let Some(last) = names.last_mut() { - *last = String::from_utf8_lossy(v).into_owned(); + *last = value.to_string(); } in_class = false; } - _ => {} + _ => section = false, } } Some(names) @@ -1094,8 +1094,17 @@ mod native { return left_out(objects.len(), entities.len()); } }; + // Name matching cannot choose between different source classes with the same name. + // Count those proxies as unwritten rather than silently changing their class identity. + let mut unique = std::collections::HashMap::new(); + for name in classes { + unique.entry(name.to_uppercase()).and_modify(|value| *value = false).or_insert(true); + } let number = |id: i32| -> Option { let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?; + if unique.get(&name.to_uppercase()) != Some(&true) { + return None; + } doc.classes.get_by_name(name).map(|c| i32::from(c.class_number)) }; let objects: Vec<(acadrust::Handle, Option)> = doc @@ -1188,8 +1197,8 @@ mod native { Some(d) => d, None => dxf.to_vec(), }; - let classes = dxf_class_names(&data); - let source = super::proxy_transport::source_classes(&data); + let (classes, source) = guarded(AssertUnwindSafe(|| (dxf_class_names(&data), super::proxy_transport::source_classes(&data)))) + .map_err(|_| "the DXF proxy class conversion failed".to_string())?; 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}"))?; diff --git a/crates/dwg/src/proxy_transport.rs b/crates/dwg/src/proxy_transport.rs index 620a20dcb..4bd63de33 100644 --- a/crates/dwg/src/proxy_transport.rs +++ b/crates/dwg/src/proxy_transport.rs @@ -3,10 +3,12 @@ //! one, the DWG gets the source DXF's classes in their places, so every proxy names its own class. use std::collections::{HashMap, HashSet}; +use std::io::{BufReader, Cursor}; use acadrust::CadDocument; use acadrust::classes::{DxfClass, ProxyFlags}; use acadrust::entities::{EntityType, ExtendedEntityData, ProxyEntityData}; +use acadrust::io::dxf::reader::{DxfStreamReader, DxfTextReader}; use acadrust::objects::{ObjectType, ProxyPayload}; fn class_number(index: usize) -> Result { @@ -188,22 +190,36 @@ fn registered_text(raw: &acadrust::entities::RawRecord) -> Result Option>> { + if dxf.starts_with(b"AutoCAD Binary DXF") { + return None; + } + // Use the same text decoder as the bridge reader. Raw DXF strings may contain CIF/MIF + // escapes, including an escaped literal backslash, or bytes in a declared legacy code page. + let mut reader = DxfTextReader::new(BufReader::new(Cursor::new(dxf))).ok()?; + let version = + super::native::header_value(dxf, b"$ACADVER").and_then(|(_, v)| std::str::from_utf8(v).ok()).map(acadrust::DxfVersion::from_version_string); + if version.is_some_and(|v| v < acadrust::DxfVersion::AC1021) + && let Some((_, page)) = super::native::header_value(dxf, b"$DWGCODEPAGE") + && let Some(encoding) = std::str::from_utf8(page).ok().and_then(acadrust::io::dxf::code_page::encoding_from_code_page) + { + reader.set_encoding(encoding); + } + Some(reader) +} + /// The CLASS records of an ASCII DXF, in CLASSES order and numbered by place from 500 (DXF /// Reference, CLASSES; a proxy's group 91 is that number). `None` for a binary DXF (CADCraft's own /// bridge DXF is ASCII), and for one with a record that can't be written back as it is: no names, /// flags or instance count out of range, more classes than the numbers allow. Then /// `proxy_classes` matches the classes by name instead. pub(super) fn source_classes(dxf: &[u8]) -> Option> { - if dxf.starts_with(b"AutoCAD Binary DXF") { - return None; - } - let mut lines = dxf.split(|b| *b == b'\n').map(<[u8]>::trim_ascii); + let mut reader = text_reader(dxf)?; let mut records: Vec> = Vec::new(); let (mut section, mut in_classes) = (false, false); - while let (Some(code), Some(value)) = (lines.next(), lines.next()) { - let code: i32 = std::str::from_utf8(code).ok()?.parse().ok()?; - let value = String::from_utf8_lossy(value); - match (code, value.as_ref()) { + while let Some(pair) = reader.read_pair().ok()? { + match (pair.code, pair.value_string.as_str()) { (0, "ENDSEC") if in_classes => break, (0, "SECTION") => section = true, (2, name) if section => { @@ -377,6 +393,23 @@ mod tests { } } + #[test] + fn source_classes_decode_escapes_once_and_respect_legacy_code_pages() { + let body = "0\nCLASS\n1\n\\U+041E\\U+0431\\U+044A\\U+0435\\U+043A\\U+0442\n2\nClass\n3\nCaf\\U+00E9\\U+D83D\\U+DE42\\U+005CU+0041\n281\n1\n0\nENDSEC\n0\nEOF\n"; + let text = format!("0\nSECTION\n2\nCLASSES\n{body}"); + let classes = source_classes(text.as_bytes()).unwrap(); + assert_eq!(classes[0].dxf_name, "Объект"); + assert_eq!(classes[0].application_name, "Café🙂\\U+0041"); + + let prefix = + b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n9\n$DWGCODEPAGE\n3\nANSI_1251\n0\nENDSEC\n0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\n"; + let encoded = [prefix.as_slice(), b"\xCF\xF0\xE8\xEC\xE5\xF0", b"\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n"].concat(); + assert_eq!(source_classes(&encoded).unwrap()[0].dxf_name, "Пример"); + // R2007+ text is UTF-8 even with a legacy code-page declaration. + let modern = String::from_utf8_lossy(prefix).replace("AC1015", "AC1032") + "Пример\n2\nClass\n3\nApp\n281\n1\n0\nENDSEC\n0\nEOF\n"; + assert_eq!(source_classes(modern.as_bytes()).unwrap()[0].dxf_name, "Пример"); + } + #[test] fn proxies_of_missing_classes_are_left_out() { for id in [-1, 499, 501, i32::MAX] { diff --git a/crates/io/tests/registered_proxy.rs b/crates/io/tests/registered_proxy.rs index dd614f57d..20ccffea1 100644 --- a/crates/io/tests/registered_proxy.rs +++ b/crates/io/tests/registered_proxy.rs @@ -1,5 +1,5 @@ //! Synthetic application data must keep its identity as well as its bytes. -#![cfg(not(target_arch = "wasm32"))] +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use acadrust::classes::DxfClass; use acadrust::entities::{EntityCommon, EntityType, ExtendedEntity, ExtendedEntityData, Line, RegisteredClassEntityData}; use acadrust::objects::{ProxyObjectReference, ProxyPayload, ProxyReferenceKind}; @@ -235,3 +235,62 @@ fn proxy_spelling_is_preserved_in_dxf_and_normalized_only_for_dwg() { assert_eq!(recovered.entity_count(), 3); } } + +/// Exercise the actual ASCII bridge, which writes Unicode as CIF escapes. +#[test] +fn unicode_class_identity_survives_the_ascii_bridge() { + let mut tags = cadcraft_dxf::parse(&duplicate_class_dxf()).unwrap(); + for tag in &mut tags { + let text = tag.str(); + let replacement = match (tag.code, text.as_str()) { + (1, "CUSTOM") => Some("Объект"), + (2, "First") => Some("Первый"), + (2, "Second") => Some("Второй"), + (2, "Object") => Some("ОбъектКласс"), + (3, "Synthetic") => Some("Café🙂"), + _ => None, + }; + if let Some(text) = replacement { + *tag = cadcraft_dxf::Tag::s(tag.code, text); + } + } + let text = cadcraft_dxf::write_ascii(&tags); + assert!(text.contains("\\U+")); + let mut drawing = cadcraft_io::read(text.as_bytes(), "unicode.dxf").unwrap(); + for _ in 0..2 { + let bytes = cadcraft_io::write_with(&drawing, "copy.dwg", &SaveOptions { version: Some(Version::R2018), ..Default::default() }).unwrap(); + let decoded = acadrust::DwgReader::from_stream(std::io::Cursor::new(&bytes)).read().unwrap(); + let classes: Vec<_> = decoded.classes.iter().filter(|c| c.dxf_name == "Объект").collect(); + assert_eq!(classes.len(), 3); + for (class, cpp) in classes.iter().zip(["Первый", "Второй", "ОбъектКласс"]) { + assert_eq!(class.cpp_class_name, cpp); + assert_eq!(class.application_name, "Café🙂"); + } + drawing = cadcraft_io::read(&bytes, "copy.dwg").unwrap(); + assert_eq!(drawing.entity_count(), 3); + } +} + +/// A malformed unused class must not silently collapse two otherwise valid class identities. +#[test] +fn ambiguous_fallback_classes_are_reported_without_losing_plain_geometry() { + for escaped in [false, true] { + let mut source = String::from_utf8(duplicate_class_dxf()).unwrap().replacen( + "0\nENDSEC\n0\nSECTION\n2\nENTITIES", + "0\nCLASS\n1\nUNUSED\n2\nUnused\n90\n65536\n0\nENDSEC\n0\nSECTION\n2\nENTITIES", + 1, + ); + if escaped { + // Different DXF spellings decode to the same name. The unrelated object class + // remains unambiguous and must still be written. + source = source.replace("1\nCUSTOM\n2\nSecond", "1\n\\U+0043USTOM\n2\nSecond"); + source = source.replace("1\nCUSTOM\n2\nObject", "1\nOTHER\n2\nObject"); + } + let (bytes, unwritten) = cadcraft_dwg::dxf_to_dwg_noted(source.as_bytes(), "AC1032").unwrap(); + assert_eq!(unwritten.get("ACAD_PROXY_ENTITY"), Some(&2)); + assert_eq!(unwritten.get("ACAD_PROXY_OBJECT"), if escaped { None } else { Some(&1) }); + let drawing = cadcraft_io::read(&bytes, "copy.dwg").unwrap(); + assert_eq!(drawing.entity_count(), 1); + assert!(drawing.model.iter().all(|e| matches!(e.kind, EntityKind::Line(_)))); + } +} From ec09c87c43cafbc2628da004cc3c201aea021555 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:26:26 +0100 Subject: [PATCH 167/185] Keep DXF regressions enabled without the DWG bridge --- crates/io/tests/dwg_active_layout.rs | 13 ++++++++++--- crates/io/tests/dwg_table_cell_height.rs | 14 +++++++++++++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/io/tests/dwg_active_layout.rs b/crates/io/tests/dwg_active_layout.rs index fd7d594ed..f2da61dcc 100644 --- a/crates/io/tests/dwg_active_layout.rs +++ b/crates/io/tests/dwg_active_layout.rs @@ -2,13 +2,15 @@ //! the one written as `*Paper_Space` (the DWG header's paper space block), the others //! `*Paper_SpaceN`. Saving used to make the first tab the active one again. -#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] - +// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] use std::io::Cursor; use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, Space}; use cadcraft_geom::Vec3; -use cadcraft_io::{SaveOptions, Version, read, write_with}; +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +use cadcraft_io::Version; +use cadcraft_io::{SaveOptions, read, write_with}; fn three_sheets() -> Drawing { let mut d = Drawing::new_metric(); @@ -21,6 +23,7 @@ fn three_sheets() -> Drawing { } /// The layout the DWG marks active: the one whose block the header names as paper space. +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn dwg_active_layout(dwg: &[u8]) -> String { let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap(); let ps = doc.header.paper_space_block_handle; @@ -33,11 +36,13 @@ fn dwg_active_layout(dwg: &[u8]) -> String { .unwrap() } +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn dwg(d: &Drawing) -> Vec { write_with(d, "case.dwg", &SaveOptions { version: Some(Version::R2018), binary: false }).unwrap() } #[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn the_active_layout_stays_active_through_dwg_saves() { let mut d = three_sheets(); d.active_layout = Some("S2".into()); @@ -70,6 +75,7 @@ fn the_active_layout_survives_dxf_too() { } #[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn without_an_active_layout_the_first_tab_is_active() { let mut d = three_sheets(); d.active_layout = Some("gone".into()); @@ -77,6 +83,7 @@ fn without_an_active_layout_the_first_tab_is_active() { } #[test] +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] fn the_active_layout_name_is_matched_ignoring_case() { let mut d = three_sheets(); d.active_layout = Some("s2".into()); diff --git a/crates/io/tests/dwg_table_cell_height.rs b/crates/io/tests/dwg_table_cell_height.rs index 6e077b870..e7f7ca79a 100644 --- a/crates/io/tests/dwg_table_cell_height.rs +++ b/crates/io/tests/dwg_table_cell_height.rs @@ -1,5 +1,7 @@ //! TABLE heights inherit from the table style unless the file records a cell override. -#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#![cfg(not(target_arch = "wasm32"))] + +// FreeBSD ARM64 has no native DWG bridge (#2526), but the DXF regression still applies. use cadcraft_doc::{Common, Drawing, EntityKind, Space, Table, TableCell, TableStyle}; @@ -42,6 +44,7 @@ fn check(d: &Drawing) { } #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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. @@ -68,11 +71,13 @@ fn table_cell_heights_keep_inheritance_through_dxf() { // ---- cells with their own style record (review on #2588) ---- +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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. +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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(); @@ -100,6 +105,7 @@ fn first_cell_height(as_dxf: bool, edit: impl FnOnce(&mut acadrust::entities::ta .unwrap() } +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] fn styled(height: f64, flags: CellStylePropertyFlags) -> CellStyle { let mut s = CellStyle::new(); s.text_height = height; @@ -108,12 +114,14 @@ fn styled(height: f64, flags: CellStylePropertyFlags) -> CellStyle { } #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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. @@ -131,6 +139,7 @@ fn content_with_format_override_bit_128_keeps_its_own_height() { /// 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] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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)); @@ -147,6 +156,7 @@ fn a_later_contents_height_does_not_replace_the_first_contents() { /// Bit 128 with an unusable content height copies nothing, so the writer's default style height /// is still cleared (review on #2588). #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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| { @@ -162,12 +172,14 @@ fn bit_128_with_an_invalid_height_still_clears_the_default() { } #[test] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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] +#[cfg(not(all(target_os = "freebsd", target_arch = "aarch64")))] 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); } From baf2424164df618741b0a86436c5fdf8948fc39c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:31:08 +0100 Subject: [PATCH 168/185] Keep hard-owner liveness monotonic and deduplicate holders in linear time --- crates/io/src/dxf_raw.rs | 42 +++++++-- crates/io/tests/hard_owned_objects_kept.rs | 99 ++++++++++++++++++++++ 2 files changed, 135 insertions(+), 6 deletions(-) diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 4009389b9..11a38f4d6 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -521,8 +521,10 @@ fn retained_objects( // One pass with `kept` the objects an earlier pass kept: a null-owner object goes with the // first of its hard owners that is kept. let mut pass = |kept: &HashMap| { + // Previously live objects already have a proved path to a retained owner. Seed that + // proof before traversal, so mutual hard owners cannot hide it from their children. + let mut retained: HashMap = kept.iter().filter(|(_, live)| **live).map(|(&i, &live)| (i, live)).collect(); let kept = |h: &str| by_handle.get(h).and_then(|i| kept.get(i)) == Some(&true); - let mut retained = HashMap::new(); for index in 0..objects.len() { let mut path = Vec::new(); let mut current = index; @@ -595,16 +597,18 @@ fn held(tags: &[Tag]) -> impl Iterator + '_ { /// The objects that own each object by a hard owner reference (group 360), in file order: /// `child handle → owner handles`. fn hard_owners>(objects: impl Iterator)>) -> HashMap> { - let mut out: HashMap> = HashMap::new(); + // Membership is hashed, while the vector keeps file order. A long list of distinct + // holders for one child must not scan all earlier holders once per reference. + let mut out: HashMap, HashSet)> = HashMap::new(); for (h, children) in objects { for c in children { - let owners = out.entry(norm(c.as_ref())).or_default(); - if !owners.contains(&h) { + let (owners, seen) = out.entry(norm(c.as_ref())).or_default(); + if seen.insert(h.clone()) { owners.push(h.clone()); } } } - out + out.into_iter().map(|(child, (owners, _))| (child, owners)).collect() } /// An object's owner: its group 330, or for one whose owner is null (another application's @@ -974,8 +978,9 @@ pub(crate) fn finish(tags: &mut Vec, d: &Drawing, reactors: &HashMap| { + // Keep established live paths available to descendants during this pass as well. + let mut alive_memo: HashMap = kept.iter().filter(|(_, live)| **live).map(|(h, &live)| (h.clone(), live)).collect(); let kept = |h: &str| kept.get(h) == Some(&true); - let mut alive_memo: HashMap = HashMap::new(); for o in f.objects.iter().filter(|o| is_proxy(&o.kind) && renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str())))).is_none()) { alive_memo.insert(o.handle.hex(), false); @@ -1332,3 +1337,28 @@ fn seed(tags: &[Tag]) -> u64 { fn max_handle(tags: &[Tag]) -> u64 { tags.iter().filter(|t| t.code == 5 || t.code == 105).filter_map(|t| Handle::parse_hex(&t.str())).map(|h| h.0).max().unwrap_or(0) } + +#[cfg(test)] +mod hard_owner_tests { + use super::hard_owners; + + #[test] + fn holders_are_unique_in_first_seen_order() { + let objects = + [("10".to_string(), ["00a", "A"].into_iter()), ("20".to_string(), ["A", "00A"].into_iter()), ("10".to_string(), ["A", "A"].into_iter())]; + let owners = hard_owners(objects.into_iter()); + assert_eq!(owners.get("A").unwrap(), &["10", "20"]); + assert_eq!(owners.len(), 1); + } + + #[test] + fn many_distinct_holders_keep_file_order() { + let count = 10_000; + let owners = hard_owners((0..count).map(|i| (format!("{i:X}"), ["FFFF", "FFFF"].into_iter()))); + let holders = owners.get("FFFF").unwrap(); + assert_eq!(holders.len(), count); + for (i, holder) in holders.iter().enumerate() { + assert_eq!(holder, &format!("{i:X}")); + } + } +} diff --git a/crates/io/tests/hard_owned_objects_kept.rs b/crates/io/tests/hard_owned_objects_kept.rs index a8ccb6ae0..93aba5cc4 100644 --- a/crates/io/tests/hard_owned_objects_kept.rs +++ b/crates/io/tests/hard_owned_objects_kept.rs @@ -97,9 +97,108 @@ fn an_object_held_by_a_kept_one_is_kept() { check(&text, &format!("DXF {generation}")); d = read_dxf(text.as_bytes()).expect("reread"); } + #[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] for generation in 1..=2 { let dwg = write(&d, "held.dwg").expect("DWG"); d = read(&dwg, "held.dwg").expect("DWG read"); check(&write_dxf(&d), &format!("DWG {generation}")); } } + +/// Mutual hard owners must not erase the live path through a retained dictionary entry. +#[test] +fn cyclic_hard_owners_with_a_live_holder_stay_kept() { + let groups = [ + (0, "SECTION"), + (2, "OBJECTS"), + (0, "DICTIONARY"), + (5, "C"), + (330, "0"), + (100, "AcDbDictionary"), + (3, "OTHER_APP"), + (350, "50"), + (0, "XRECORD"), + (5, "60"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "stray"), + (360, "54"), + (0, "XRECORD"), + (5, "52"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "first"), + (360, "53"), + (360, "54"), + (0, "XRECORD"), + (5, "53"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "second"), + (360, "52"), + (0, "XRECORD"), + (5, "54"), + (330, "0"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "child"), + (0, "DICTIONARY"), + (5, "50"), + (330, "C"), + (100, "AcDbDictionary"), + (281, "1"), + (3, "HOLDER"), + (360, "51"), + (0, "XRECORD"), + (5, "51"), + (330, "50"), + (100, "AcDbXrecord"), + (280, "1"), + (1, "holder"), + (360, "52"), + (360, "53"), + (0, "ENDSEC"), + (0, "EOF"), + ]; + let text = groups.iter().map(|(code, value)| format!("{code}\n{value}\n")).collect::(); + let mut drawing = read_dxf(text.as_bytes()).unwrap(); + let mut names = vec!["copy.dxf", "again.dxf"]; + if cfg!(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64")))) { + names.extend(["copy.dwg", "again.dwg"]); + } + for name in names { + let bytes = write(&drawing, name).unwrap(); + drawing = read(&bytes, name).unwrap(); + let text = write_dxf(&drawing); + let tags = cadcraft_dxf::parse(text.as_bytes()).unwrap(); + let objects = cadcraft_dxf::sections(&tags).into_iter().find(|s| s.name == "OBJECTS").unwrap(); + let records = cadcraft_dxf::records(&objects.tags); + let record = |label: &str| records.iter().find(|(_, tags)| tags.iter().any(|t| t.code == 1 && t.str() == label)).unwrap().1.clone(); + let first = record("first"); + let second = record("second"); + let holder = record("holder"); + let child = record("child"); + assert!(!records.iter().any(|(_, tags)| tags.iter().any(|t| t.code == 1 && t.str() == "stray")), "{name}"); + let handle = |tags: &[cadcraft_dxf::Tag]| tags.iter().find(|t| t.code == 5).unwrap().str(); + assert!(first.iter().any(|t| t.code == 360 && t.str() == handle(&second)), "{name}"); + assert!(second.iter().any(|t| t.code == 360 && t.str() == handle(&first)), "{name}"); + assert!(first.iter().any(|t| t.code == 360 && t.str() == handle(&child)), "{name}"); + for object in [&first, &second] { + assert!(holder.iter().any(|t| t.code == 360 && t.str() == handle(object)), "{name}"); + } + } +} + +/// A real 330 owner takes precedence, even when a retained object also names the record by 360. +#[test] +fn a_real_owner_is_not_replaced_by_a_hard_owner() { + let text = source().replace("330\n0\n100\nAcDbXrecord\n280\n1\n1\nheld", "330\nDEAD\n100\nAcDbXrecord\n280\n1\n1\nheld"); + assert!(text.contains("330\nDEAD")); + let drawing = read_dxf(text.as_bytes()).unwrap(); + let output = write_dxf(&drawing); + assert!(output.lines().any(|line| line.trim() == "holder")); + assert!(!output.lines().any(|line| line.trim() == "held")); +} From 1434d1017b92954268418028affc2c9315a3c544 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:31:40 +0100 Subject: [PATCH 169/185] Use public DXF codecs in the streaming class scanner --- crates/dwg/src/lib.rs | 8 ++--- crates/dwg/src/proxy_transport.rs | 53 +++++++++++++++++++++---------- 2 files changed, 40 insertions(+), 21 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 534765457..4cbd552e2 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -1023,12 +1023,12 @@ mod native { /// 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> { - use acadrust::io::dxf::reader::DxfStreamReader; - let mut reader = super::proxy_transport::text_reader(dxf)?; + let pairs = super::proxy_transport::text_pairs(dxf)?; let mut names = Vec::new(); let (mut section, mut in_classes, mut in_class) = (false, false, false); - while let Some(pair) = reader.read_pair().ok()? { - match (pair.code, pair.value_string.as_str()) { + for pair in pairs { + let (code, value) = pair?; + match (code, value.as_str()) { (0, "ENDSEC") if in_classes => break, (0, "SECTION") => section = true, (2, name) if section => { diff --git a/crates/dwg/src/proxy_transport.rs b/crates/dwg/src/proxy_transport.rs index 4bd63de33..a8a5647e9 100644 --- a/crates/dwg/src/proxy_transport.rs +++ b/crates/dwg/src/proxy_transport.rs @@ -3,12 +3,10 @@ //! one, the DWG gets the source DXF's classes in their places, so every proxy names its own class. use std::collections::{HashMap, HashSet}; -use std::io::{BufReader, Cursor}; use acadrust::CadDocument; use acadrust::classes::{DxfClass, ProxyFlags}; use acadrust::entities::{EntityType, ExtendedEntityData, ProxyEntityData}; -use acadrust::io::dxf::reader::{DxfStreamReader, DxfTextReader}; use acadrust::objects::{ObjectType, ProxyPayload}; fn class_number(index: usize) -> Result { @@ -190,23 +188,43 @@ fn registered_text(raw: &acadrust::entities::RawRecord) -> Result Option>> { +/// ASCII DXF pairs decoded with the bridge's public code-page and escape codecs. A malformed +/// pair yields `None`, so both class scans fall back rather than guessing its identity. +pub(super) fn text_pairs(dxf: &[u8]) -> Option> + '_> { + use acadrust::io::dxf::code_page::{decode_legacy_escapes, encoding_from_code_page}; + if dxf.starts_with(b"AutoCAD Binary DXF") { return None; } - // Use the same text decoder as the bridge reader. Raw DXF strings may contain CIF/MIF - // escapes, including an escaped literal backslash, or bytes in a declared legacy code page. - let mut reader = DxfTextReader::new(BufReader::new(Cursor::new(dxf))).ok()?; let version = super::native::header_value(dxf, b"$ACADVER").and_then(|(_, v)| std::str::from_utf8(v).ok()).map(acadrust::DxfVersion::from_version_string); - if version.is_some_and(|v| v < acadrust::DxfVersion::AC1021) - && let Some((_, page)) = super::native::header_value(dxf, b"$DWGCODEPAGE") - && let Some(encoding) = std::str::from_utf8(page).ok().and_then(acadrust::io::dxf::code_page::encoding_from_code_page) - { - reader.set_encoding(encoding); - } - Some(reader) + let unicode = version.is_some_and(|v| v >= acadrust::DxfVersion::AC1021); + let encoding = if version.is_some_and(|v| v < acadrust::DxfVersion::AC1021) { + super::native::header_value(dxf, b"$DWGCODEPAGE").and_then(|(_, page)| std::str::from_utf8(page).ok()).and_then(encoding_from_code_page) + } else { + None + }; + let mut lines = dxf.split(|b| *b == b'\n').map(|line| line.strip_suffix(b"\r").unwrap_or(line)); + Some(std::iter::from_fn(move || { + let code = lines.next()?; + let Some(value) = lines.next() else { return (!code.trim_ascii().is_empty()).then_some(None) }; + let pair = || { + let code = std::str::from_utf8(code).ok()?.trim().parse().ok()?; + let text = if let Some(encoding) = encoding { + encoding.decode(value).0.into_owned() + } else if unicode { + String::from_utf8_lossy(value).into_owned() + } else { + // The decoder uses UTF-8 with Latin-1 fallback when no encoding was declared. + std::str::from_utf8(value).map_or_else(|_| value.iter().map(|&b| char::from(b)).collect(), str::to_string) + }; + let text = decode_legacy_escapes(&text); + // DXF's escaped control characters are decoded after CIF/MIF, as in the bridge. + let text = text.replace("^J", "\n").replace("^M", "\r").replace("^I", "\t").replace("^ ", "^"); + Some((code, text)) + }; + Some(pair()) + })) } /// The CLASS records of an ASCII DXF, in CLASSES order and numbered by place from 500 (DXF @@ -215,11 +233,12 @@ pub(super) fn text_reader(dxf: &[u8]) -> Option>> { /// flags or instance count out of range, more classes than the numbers allow. Then /// `proxy_classes` matches the classes by name instead. pub(super) fn source_classes(dxf: &[u8]) -> Option> { - let mut reader = text_reader(dxf)?; + let pairs = text_pairs(dxf)?; let mut records: Vec> = Vec::new(); let (mut section, mut in_classes) = (false, false); - while let Some(pair) = reader.read_pair().ok()? { - match (pair.code, pair.value_string.as_str()) { + for pair in pairs { + let (code, value) = pair?; + match (code, value.as_str()) { (0, "ENDSEC") if in_classes => break, (0, "SECTION") => section = true, (2, name) if section => { From 3a9aebc210edeec2cff847dfb23672c52f5e046d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 12:45:18 -0800 Subject: [PATCH 170/185] Updates: the updater reports installing, ready, installed and failed, and installs at exit craft-update moves from craft-libs c5a1cbfb to c7c84230, a branch that is craft-libs main at 0a9d1f48 with storytold/craft-libs#687 and #696 merged in. Cargo.lock changes the craft-update entry and drops zopfli from zip. The check result window now shows whenever the updater's status is not idle, not only after Help > Check for Updates, and never over the startup prompt. At the first start after an update it reports that the update installed or why it failed. Restart to Update calls Updater::restart_to_update. The install helper starts when the app exits and drops the updater, so a canceled close keeps the update ready. --- Cargo.lock | 15 +------- Cargo.toml | 2 +- crates/ui-egui/src/updates_ui.rs | 66 +++++++++++++++++++++----------- 3 files changed, 46 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a62aa7337..194793cb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1211,7 +1211,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "chrono", "dunce", @@ -6223,7 +6223,6 @@ dependencies = [ "nix 0.31.3", "typed-path", "windows-sys 0.61.2", - "zopfli", ] [[package]] @@ -6238,18 +6237,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zopfli" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index 60d198514..64ff8456e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,7 +71,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 = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +craft-update = { git = "https://github.com/dotCooCoo/craft-libs", version = "=0.1.0", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", 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 ce8f53a3f..ccd9733b4 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -17,15 +17,13 @@ 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, result_open: false, result_echoed: false } + Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false, result_echoed: false } } } @@ -39,7 +37,6 @@ impl CadApp { /// 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; } @@ -55,45 +52,70 @@ pub fn tick(app: &mut CadApp, ctx: &egui::Context) { let outcome = match rt.updater.status() { Status::UpToDate => Some(crate::tl!("CADCraft is up to date.")), Status::Failed(_) => Some(crate::tl!("Could not check for updates.")), - Status::Idle | Status::Checking => None, - }; - 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; + Status::Idle | Status::Checking | Status::Installing | Status::Ready | Status::Managed | Status::Updated(_) | Status::InstallFailed(_) => { + None } - return; }; - if !rt.result_open { - rt.updater.dismiss_status(); - } else if !std::mem::replace(&mut rt.result_echoed, true) { + if let Some(message) = outcome + && !std::mem::replace(&mut rt.result_echoed, true) + { app.session.echo(message); } } +/// Whether the check result window shows: for every status but idle (a requested check, and the +/// first start after an update, which reports that it installed or why it failed), and never +/// over the startup prompt. +fn result_window_shows(status: &Status, prompt_open: bool) -> bool { + !prompt_open && !matches!(status, Status::Idle) +} + /// Draw the prompt while there is one and act on its answer. 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. + // The close for a ready update waits until no drawing holds unsaved changes. let clean = !app.session.docs.iter().any(|d| d.is_dirty()); let rt = &mut app.updates_rt; - if rt.result_open { + if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) { match CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status()) { - CheckResultResponse::Close => { - rt.result_open = false; - rt.updater.dismiss_status(); - } + CheckResultResponse::Close => rt.updater.dismiss_status(), CheckResultResponse::CheckAgain => { rt.result_echoed = false; rt.check_requested = true; } + // The next `show_if` asks the window to close once nothing is unsaved. + CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), 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 - // process has exited. + // The guarded close path asks about unsaved changes. The install helper starts when the + // app exits and drops the updater. Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Action::None => {} } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn result_window_shows_every_status_but_idle() { + let shown = [ + Status::Checking, + Status::UpToDate, + Status::Failed("no network".into()), + Status::Installing, + Status::Ready, + Status::Managed, + Status::Updated("0.2.0".into()), + Status::InstallFailed("disk full".into()), + ]; + for status in &shown { + assert!(result_window_shows(status, false), "{status:?}"); + assert!(!result_window_shows(status, true), "{status:?} over the prompt"); + } + assert!(!result_window_shows(&Status::Idle, false)); + } +} From 3074f189604224fc98b5ff6b330d627d55fd16a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 19:45:36 -0800 Subject: [PATCH 171/185] Updates: take craft-update from craft-libs main at 1b34eba41 --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fb408a3af..334acd517 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1212,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "chrono", "dunce", diff --git a/Cargo.toml b/Cargo.toml index 64ff8456e..78309ded4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,7 +71,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/dotCooCoo/craft-libs", version = "=0.1.0", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } rfd = "0.17" arboard = { version = "3.6", default-features = false } From 6f0f1fefa81d08031bde56a8b3d5b1556810f397 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Tue, 10 Nov 2026 03:01:17 -0800 Subject: [PATCH 172/185] Fonts: the MTEXT strip test expects a short \U+ escape to keep its digits (#2954) strips_formatting expected `\U+12` to strip to nothing. plain_mtext dropped every unknown code up to the next `;` when that assertion was written. #1036 limits this to the codes in takes_arg, and `\U` is not one of them, so plain_mtext returns `+12`. The layout and paragraph paths give the same text, and unicode_escapes_are_decoded_in_every_parser already expects it. The test has failed on main since both changes merged, and the failure stops the gate at its test step. The test module now also checks the short escape in both layout paths. --- crates/fonts/src/mtext.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/fonts/src/mtext.rs b/crates/fonts/src/mtext.rs index e2ff9a3f9..9fe7aa47e 100644 --- a/crates/fonts/src/mtext.rs +++ b/crates/fonts/src/mtext.rs @@ -904,7 +904,7 @@ mod tests { 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"); + assert_eq!(plain_mtext("\\U+12"), "+12", "a short escape loses only the backslash and the code"); } #[test] @@ -928,6 +928,8 @@ mod tests { 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!(lay("a\\U+12 b", 0.0).lines, vec!["a+12 b"]); + assert_eq!(lay("\\pxql;a\\U+12 b", 0.0).lines, vec!["a+12 b"]); assert_eq!(plain_mtext("a\\M+ b"), "a+ b"); } From 2f8f1861886412f529900b37e3f80f8d1e2af119 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:20:25 -0500 Subject: [PATCH 173/185] macOS: file dialogs no longer run inside the window's event handler (#1534) On macOS the Open and Save panels ran modally inside winit's event handler, and resizing one aborted the app (#1527). Every file dialog now goes through CadApp::pick_then / pick_then_open. On macOS, Services::start_pick shows the dialog as a sheet on the window and the answer is acted on in a later frame. The answer is bound to the drawing that asked for it. Windows and Linux are unchanged. Fixes #1527 Co-authored-by: mocenigo <4894657+mocenigo@users.noreply.github.com> --- Cargo.lock | 1 + apps/cadcraft/Cargo.toml | 6 +- apps/cadcraft/src/main.rs | 67 ++++++----- apps/cadcraft/src/sheet.rs | 51 +++++++++ crates/ui-egui/src/aliasdlg.rs | 42 ++++++- crates/ui-egui/src/closing.rs | 106 +++++++++++++++--- crates/ui-egui/src/exchange.rs | 199 +++++++++++++++++++++++++++++---- crates/ui-egui/src/lib.rs | 169 ++++++++++++++++++++++++++++ crates/ui-egui/src/managers.rs | 64 +++++++---- crates/ui-egui/src/menus.rs | 74 ++++++------ crates/ui-egui/src/xrefs.rs | 27 +++-- 11 files changed, 655 insertions(+), 151 deletions(-) create mode 100644 apps/cadcraft/src/sheet.rs diff --git a/Cargo.lock b/Cargo.lock index 334acd517..9b3467cfb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -631,6 +631,7 @@ dependencies = [ "log", "muda", "objc2-app-kit 0.3.2", + "pollster 1.0.1", "rfd", "ron", "serde_json", diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index ee1b8b9c8..cf9809c97 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -55,7 +55,11 @@ muda = { version = "0.21", default-features = false } 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 } +# `rwh_06`: the window handle a file dialog shown as a sheet attaches to (src/sheet.rs). +winit = { version = "0.30", default-features = false, features = ["rwh_06"] } +# Waits for the answer of a file dialog shown as a sheet (src/sheet.rs). MIT OR Apache-2.0, already +# in Cargo.lock through eframe. +pollster = "1" # 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 75653c6a3..7d33cec19 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -23,13 +23,15 @@ mod launch_args; mod logging; #[cfg(target_os = "macos")] mod native_menu; +#[cfg(target_os = "macos")] +mod sheet; mod spacemouse; mod system_animations; mod workspace; use cadcraft_engine::Session; use cadcraft_ui_egui::switch::Switch; -use cadcraft_ui_egui::{CadApp, Services, i18n}; +use cadcraft_ui_egui::{CadApp, Pick, Services, i18n}; struct App { cad: CadApp, @@ -159,39 +161,44 @@ pub fn install_io() { fn services() -> Services { Services { - pick_open: Some(Box::new(|| { - rfd::FileDialog::new() - .add_filter(i18n::t("Drawings (DWG, DXF)"), &["dwg", "dxf", "dwt"]) - .add_filter(i18n::t("SVG drawings (SVG, SVGZ)"), &["svg", "svgz"]) - .add_filter(i18n::t("All files"), &["*"]) - .pick_file() - .map(|p| p.to_string_lossy().to_string()) - })), - pick_save: Some(Box::new(|name: &str| { - filters_for_save(name) - .iter() - .fold(rfd::FileDialog::new().set_file_name(name), |d, (label, ext)| d.add_filter(i18n::t(label), &[*ext])) - .save_file() - .map(|p| p.to_string_lossy().to_string()) - })), + pick_open: Some(Box::new(|| file_dialog(&Pick::Open).pick_file().map(|p| p.to_string_lossy().to_string()))), + pick_save: Some(Box::new(|name: &str| file_dialog(&Pick::Save(name.into())).save_file().map(|p| p.to_string_lossy().to_string()))), + // macOS shows the dialogs as sheets (`sheet::start_pick`), set once the window exists. + start_pick: None, // APPLOAD: AutoLISP routines only, starting where the last one was loaded from. - pick_lisp: Some(Box::new(|dir: &str| { - let dialog = rfd::FileDialog::new().add_filter(i18n::t("AutoLISP (LSP)"), &["lsp"]).add_filter(i18n::t("All files"), &["*"]); - let dialog = if dir.is_empty() { dialog } else { dialog.set_directory(dir) }; - dialog.pick_file().map(|p| p.to_string_lossy().to_string()) - })), + pick_lisp: Some(Box::new(|dir: &str| file_dialog(&Pick::Lisp(dir.into())).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()) + file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string()) })), } } +/// The file types `pick` offers: (label, extensions). Shared by the blocking dialogs and the +/// macOS sheets. +fn filters(pick: &Pick) -> Vec<(&'static str, Vec<&'static str>)> { + match pick { + Pick::Open => vec![ + (i18n::t("Drawings (DWG, DXF)"), vec!["dwg", "dxf", "dwt"]), + (i18n::t("SVG drawings (SVG, SVGZ)"), vec!["svg", "svgz"]), + (i18n::t("All files"), vec!["*"]), + ], + Pick::Save(name) => filters_for_save(name).iter().map(|(label, ext)| (i18n::t(label), vec![*ext])).collect(), + Pick::Lisp(_) => vec![(i18n::t("AutoLISP (LSP)"), vec!["lsp"]), (i18n::t("All files"), vec!["*"])], + Pick::Pgp(_) => vec![(i18n::t("Alias files (PGP)"), vec!["pgp"])], + } +} + +/// The blocking dialog for `pick` (Windows, Linux, FreeBSD). +fn file_dialog(pick: &Pick) -> rfd::FileDialog { + let dialog = filters(pick).iter().fold(rfd::FileDialog::new(), |d, (label, exts)| d.add_filter(*label, exts)); + match pick { + Pick::Save(name) => dialog.set_file_name(name), + Pick::Lisp(dir) | Pick::Pgp(dir) if !dir.is_empty() => dialog.set_directory(dir), + _ => dialog, + } +} + /// File types for the Save dialog, the suggested name's type first: Windows adds the first /// filter's extension, and macOS accepts only listed extensions, replacing any other with the /// first one. DWG must be listed for a `.dwg` name to survive, and a drawing opened from DWG @@ -361,6 +368,12 @@ fn main() -> eframe::Result { options, Box::new(move |cc| { let mut app = CadApp::new(Session::empty(), services()); + // File dialogs are sheets on macOS: a modal loop inside the event handler crashes the + // app when the dialog is resized (#1527). + #[cfg(target_os = "macos")] + if let Some(window) = cc.winit_window().cloned() { + app.services.start_pick = Some(sheet::start_pick(window, cc.egui_ctx.clone())); + } let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref()); if let Some(ui) = restored { app.ui = ui; diff --git a/apps/cadcraft/src/sheet.rs b/apps/cadcraft/src/sheet.rs new file mode 100644 index 000000000..f18da9d45 --- /dev/null +++ b/apps/cadcraft/src/sheet.rs @@ -0,0 +1,51 @@ +//! macOS file dialogs as sheets. Shown in line, or from a helper thread that rfd hands to the main +//! thread's modal loop, a panel runs AppKit's modal event loop; resizing it sends window events +//! back into winit's event handler and winit aborts the app (#1527). A sheet returns at once and +//! the window keeps running; a thread of its own waits for the answer. + +use std::sync::Arc; + +use cadcraft_ui_egui::{Pick, StartPick}; + +type Answer = std::pin::Pin> + Send>>; + +/// `Services::start_pick`: shows `pick` as a sheet on `window`; `ui` is woken when it answers. +pub fn start_pick(window: Arc, ui: egui::Context) -> StartPick { + Box::new(move |pick, done| { + let (sheet_tx, sheet_rx) = std::sync::mpsc::channel::(); + let ui = ui.clone(); + // The thread first, so the answer of a sheet once shown always has somewhere to go. If it + // cannot start, `done` is dropped unanswered and the app says the dialog could not be + // shown. + let spawned = std::thread::Builder::new().name("file-dialog".into()).spawn(move || { + if let Ok(answer) = sheet_rx.recv() { + done(pollster::block_on(answer)); + ui.request_repaint(); + } + }); + if let Err(e) = spawned { + log::warn!("file dialog: {e}"); + return; + } + // rfd builds the panel and begins the sheet here, on the main thread (as it must). + let dialog = + crate::filters(&pick).iter().fold(rfd::AsyncFileDialog::new().set_parent(&*window), |d, (label, exts)| d.add_filter(*label, exts)); + let path = |f: rfd::FileHandle| f.path().to_string_lossy().to_string(); + let answer: Answer = match pick { + Pick::Save(name) => { + let picked = dialog.set_file_name(name).save_file(); + Box::pin(async move { picked.await.map(path) }) + } + Pick::Lisp(dir) | Pick::Pgp(dir) => { + let dialog = if dir.is_empty() { dialog } else { dialog.set_directory(dir) }; + let picked = dialog.pick_file(); + Box::pin(async move { picked.await.map(path) }) + } + Pick::Open => { + let picked = dialog.pick_file(); + Box::pin(async move { picked.await.map(path) }) + } + }; + let _ = sheet_tx.send(answer); + }) +} diff --git a/crates/ui-egui/src/aliasdlg.rs b/crates/ui-egui/src/aliasdlg.rs index 93110a5a7..16e46e8dc 100644 --- a/crates/ui-egui/src/aliasdlg.rs +++ b/crates/ui-egui/src/aliasdlg.rs @@ -217,15 +217,14 @@ pub fn import(app: &mut CadApp, path: &str) -> Result<(), String> { /// then load it. A cancelled picker is a no-op; without a native picker (the web) the error names /// 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 { + let dir = app.ui.last_pgp_dir.clone().unwrap_or_default(); + // Through `pick_for`, so macOS shows it as a sheet (#1527); aliases belong to no drawing. + match app.pick_for(crate::Pick::Pgp(dir), false, Box::new(|app, path| import(app, &path).map(|()| serde_json::Value::Null))) { 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), + Some(r) => r.map(|_| ()), } } @@ -450,6 +449,39 @@ mod tests { let _ = app.run("aliasedit", json!({ "clear": true })); } + /// Where the host shows dialogs without waiting (macOS sheets, #1527), Import… does not run + /// the blocking picker; the file loads once the sheet answers. + #[test] + fn import_waits_for_a_sheet_instead_of_blocking() { + type Done = Box) + Send>; + let _guard = alone(); + let dir = temp_dir("sheet"); + let path = dir.join("aliases.pgp"); + std::fs::write(&path, "XXS, *LINE\n").unwrap_or_default(); + let asked = Rc::new(RefCell::new(Vec::new())); + let answer: Rc>> = Rc::default(); + let (log, slot) = (Rc::clone(&asked), Rc::clone(&answer)); + let services = Services { + pick_pgp: Some(Box::new(|_: Option<&str>| panic!("the blocking picker ran"))), + start_pick: Some(Box::new(move |pick, done| { + log.borrow_mut().push(pick); + *slot.borrow_mut() = Some(done); + })), + ..Services::default() + }; + let mut app = CadApp::new(Session::new(), services); + open(&mut app); + + pick_and_import(&mut app).expect("the sheet starts"); + assert!(matches!(asked.borrow().as_slice(), [crate::Pick::Pgp(_)])); + answer.borrow_mut().take().expect("a sheet was started")(Some(path.to_string_lossy().to_string())); + app.finish_pick(&egui::Context::default()); + + let st = app.alias_dlg.as_ref().expect("the dialog stays open"); + assert_eq!(st.user.get("xxs").map(String::as_str), Some("line")); + clear(&mut app); + } + #[test] fn import_loads_the_aliases_shows_the_path_and_warnings() { let _guard = alone(); diff --git a/crates/ui-egui/src/closing.rs b/crates/ui-egui/src/closing.rs index 04d526fa2..435917642 100644 --- a/crates/ui-egui/src/closing.rs +++ b/crates/ui-egui/src/closing.rs @@ -88,6 +88,11 @@ impl CadApp { /// Answer the open close prompt (no-op without one). pub fn answer_close(&mut self, choice: Choice) { let Some(uid) = self.closing.as_ref().and_then(|c| c.asking) else { return }; + // Its Save dialog is open (macOS): Save again or Don't Save would race it. + if choice != Choice::Cancel && self.pending_pick.as_ref().is_some_and(|p| p.for_close) { + self.set_status("Answer the Save dialog first."); + return; + } let i = match (choice, self.doc_index(uid)) { (Choice::Cancel, _) => { self.closing = None; @@ -114,26 +119,53 @@ impl CadApp { // The Block Editor's unsaved changes go into the block first (BSAVE), then the // drawing is saved with them. let r = if self.session.state().is_ok_and(|st| st.block_unsaved()) { self.run("bsave", json!({})) } else { Ok(Value::Null) }; + let waiting = self.pending_pick.is_some(); let r = r.and_then(|_| self.run("qsave", Value::Null)); - let saved = r.is_ok() && self.doc_index(uid).and_then(|i| self.session.docs.get(i)).is_some_and(|d| !d.is_dirty()); - match (saved, self.doc_index(uid)) { - (true, Some(i)) => { - self.close_front(i); - self.advance_close(); - } - _ => { - // Not saved (picker cancelled, save failed or unavailable): keep the - // drawing and its edits, and stop closing. - self.closing = None; - let title = self.doc_index(uid).and_then(|i| self.session.docs.get(i)).map(|d| d.title.clone()).unwrap_or_default(); - let msg = match r { - Err(e) => format!("{title} was not saved ({e}); it stays open."), - Ok(_) => format!("{title} was not saved; it stays open."), - }; - self.session.echo(msg.clone()); - self.set_status(msg); - } + // The Save dialog opened without waiting (macOS): closing goes on once it has + // saved; cancelling it leaves the prompt up. + // The dialog is bound to this drawing: if it is closed meanwhile, nothing is + // saved and the prompt goes on with the next drawing. + if !waiting && let Some(mut pending) = self.pending_pick.take() { + let then = pending.then; + pending.for_close = true; + pending.then = Box::new(move |app: &mut CadApp, path| { + let r = then(app, path); + // Unless the prompt was answered otherwise meanwhile. + if app.closing.as_ref().and_then(|c| c.asking) == Some(uid) { + // It reports the outcome itself; an error returned here would + // replace its message in the status bar. + app.close_after_save(uid, r); + return Ok(Value::Null); + } + r + }); + self.pending_pick = Some(pending); + return; } + self.close_after_save(uid, r); + } + } + } + + /// Go on closing after the drawing `uid` was asked to save with result `r`. + fn close_after_save(&mut self, uid: u64, r: Result) { + let saved = r.is_ok() && self.doc_index(uid).and_then(|i| self.session.docs.get(i)).is_some_and(|d| !d.is_dirty()); + match (saved, self.doc_index(uid)) { + (true, Some(i)) => { + self.close_front(i); + self.advance_close(); + } + _ => { + // Not saved (picker cancelled, save failed or unavailable): keep the + // drawing and its edits, and stop closing. + self.closing = None; + let title = self.doc_index(uid).and_then(|i| self.session.docs.get(i)).map(|d| d.title.clone()).unwrap_or_default(); + let msg = match r { + Err(e) => format!("{title} was not saved ({e}); it stays open."), + Ok(_) => format!("{title} was not saved; it stays open."), + }; + self.session.echo(msg.clone()); + self.set_status(msg); } } } @@ -264,6 +296,44 @@ mod tests { app.session.docs.iter().map(|d| d.title.clone()).collect() } + type Done = Box) + Send>; + + /// The host shows its Save dialog without waiting (macOS): the callback that answers it. + fn deferred_save(app: &mut CadApp) -> std::rc::Rc>> { + let slot: std::rc::Rc>> = std::rc::Rc::default(); + let s = slot.clone(); + app.services = Services { + pick_save: Some(Box::new(|_: &str| None)), + start_pick: Some(Box::new(move |_, done| *s.borrow_mut() = Some(done))), + ..Services::default() + }; + slot + } + + /// While the prompt's Save dialog is open, Don't Save (or Save again) does not race it; when + /// the save then fails, the prompt's own "was not saved" message is what the status bar shows. + #[test] + fn the_close_prompt_waits_for_its_save_dialog() { + let mut app = app_with(&["A", "B"]); + let answer = deferred_save(&mut app); + dirty(&mut app, 0); + app.request_close(Some(0)); + app.answer_close(Choice::Save); + assert!(answer.borrow().is_some(), "the Save dialog is open"); + app.answer_close(Choice::Discard); + app.answer_close(Choice::Save); + assert_eq!(titles(&app), ["A", "B"], "Don't Save waits for the Save dialog"); + assert_eq!(app.close_prompt(), Some("A")); + + let nowhere = std::env::temp_dir().join(format!("cadcraft-no-such-dir-{}", std::process::id())).join("A.dxf"); + answer.borrow_mut().take().unwrap()(Some(nowhere.to_string_lossy().to_string())); + app.finish_pick(&egui::Context::default()); + assert_eq!(titles(&app), ["A", "B"], "not saved, so not closed"); + assert!(app.session.docs[0].is_dirty()); + let status = app.status.as_ref().map(|(s, _)| s.as_str()).unwrap_or_default(); + assert!(status.starts_with("A was not saved") && status.ends_with("it stays open."), "{status}"); + } + #[test] fn clean_drawing_closes_without_prompt() { let mut app = app_with(&["A", "B"]); diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index 48a615003..b7a0246c6 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -7,7 +7,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use egui::TextureHandle; use serde_json::{Value, json}; -use crate::CadApp; +use crate::{CadApp, Pick}; /// Bumped each time PREVIEW is started, so the window renders the drawing as it is now. static PREVIEW_GEN: AtomicU32 = AtomicU32::new(0); @@ -23,27 +23,15 @@ pub fn route(app: &mut CadApp, id: &str) -> Result { app.ui.dialog = Some("preview".into()); Ok(Value::Null) } - "import" | "imp" => { - let Some(pick) = app.services.pick_open.as_ref() else { return no_picker(app, "IMPORT", r#"import {"path": "parts.dxf"}"#) }; - match pick() { - Some(path) => app.run("import", json!({ "path": path })), - None => Ok(Value::Null), - } - } - "publish" => { - let Some(pick) = app.services.pick_save.as_ref() else { return no_picker(app, "PUBLISH", "publish {}") }; - match pick(&format!("{stem}.pdf")) { - Some(path) => app.run("publish", json!({ "path": path })), - None => Ok(Value::Null), - } - } - _ => { - let Some(pick) = app.services.pick_save.as_ref() else { return no_picker(app, "EXPORT", r#"export {"format": "svg"}"#) }; - match pick(&format!("{stem}.svg")) { - Some(path) => app.run("export", json!({ "path": path })), - None => Ok(Value::Null), - } - } + "import" | "imp" => app + .pick_then(Pick::Open, |app, path| app.run("import", json!({ "path": path }))) + .unwrap_or_else(|| no_picker(app, "IMPORT", r#"import {"path": "parts.dxf"}"#)), + "publish" => app + .pick_then(Pick::Save(format!("{stem}.pdf")), |app, path| app.run("publish", json!({ "path": path }))) + .unwrap_or_else(|| no_picker(app, "PUBLISH", "publish {}")), + _ => app + .pick_then(Pick::Save(format!("{stem}.svg")), |app, path| app.run("export", json!({ "path": path }))) + .unwrap_or_else(|| no_picker(app, "EXPORT", r#"export {"format": "svg"}"#)), } } @@ -161,7 +149,7 @@ mod tests { use cadcraft_engine::Session; use serde_json::json; - use crate::{CadApp, Services}; + use crate::{CadApp, Pick, Services}; /// An app whose file dialogs record what they were asked and cancel. fn app() -> (CadApp, Rc>>) { @@ -207,4 +195,169 @@ mod tests { let e = app.run("share", json!({})).unwrap_err(); assert!(e.contains("not available yet"), "{e}"); } + + type Done = Box) + Send>; + + /// An app whose host shows its dialogs without waiting (macOS, #1527): the dialogs asked + /// for, and the callback that answers the open one. + fn deferred_app() -> (CadApp, Rc>>, Rc>>) { + let asked = Rc::new(RefCell::new(Vec::new())); + let answer: Rc>> = Rc::default(); + let (log, slot) = (asked.clone(), answer.clone()); + let services = Services { + pick_open: Some(Box::new(|| None)), + pick_save: Some(Box::new(|_: &str| None)), + pick_lisp: Some(Box::new(|_: &str| None)), + start_pick: Some(Box::new(move |pick, done| { + log.borrow_mut().push(pick); + *slot.borrow_mut() = Some(done); + })), + ..Services::default() + }; + (CadApp::new(Session::new(), services), asked, answer) + } + + fn status(app: &CadApp) -> &str { + app.status.as_ref().map(|(s, _)| s.as_str()).unwrap_or_default() + } + + fn uid(app: &CadApp) -> u64 { + app.session.state().unwrap().uid + } + + /// Where the host shows its dialogs without waiting (macOS, #1527), the command acts on the + /// path in a later frame, and no second dialog opens while one is up. + #[test] + fn a_deferred_dialog_acts_when_its_answer_arrives() { + let (mut app, asked, answer) = deferred_app(); + let ctx = egui::Context::default(); + + // Cancelled: nothing happens, and the next command may ask again. + app.start("export"); + assert_eq!(*asked.borrow(), [Pick::Save("Drawing1.svg".into())]); + answer.borrow_mut().take().unwrap()(None); + app.finish_pick(&ctx); + assert!(app.pending_pick.is_none()); + + app.start("imp"); + app.finish_pick(&ctx); + assert!(app.pending_pick.is_some() && app.status.is_none(), "nothing runs before the answer"); + // A second dialog is refused, and says so: in the status bar for a typed or menu + // command, and as an error for a programmatic call. + app.start("publish"); + assert!(status(&app).contains("already open"), "{:?}", app.status); + let e = app.run("ui.open", json!(null)).unwrap_err(); + assert!(e.contains("already open"), "{e}"); + assert_eq!(asked.borrow().len(), 2, "no second dialog while one is open"); + app.status = None; + let missing = std::env::temp_dir().join(format!("cadcraft-missing-{}.dxf", std::process::id())); + answer.borrow_mut().take().unwrap()(Some(missing.to_string_lossy().to_string())); + app.finish_pick(&ctx); + assert!(app.pending_pick.is_none()); + assert!(app.status.is_some(), "IMPORT ran with the picked file and reported its error"); + } + + /// A dialog's answer acts on the drawing that asked for it, even when another drawing was + /// made active before it arrived (a control-channel `document.switch` runs before the answer + /// in the same frame): Save As must not write the other drawing to the chosen file. + #[test] + fn a_deferred_dialog_acts_on_the_drawing_that_asked() { + let (mut app, _, answer) = deferred_app(); + let ctx = egui::Context::default(); + app.run("new", json!({})).unwrap(); + app.run("document.switch", json!({ "index": 0 })).unwrap(); + let first = uid(&app); + let acted_on = Rc::new(RefCell::new(None)); + let seen = acted_on.clone(); + let r = app.pick_then(Pick::Save("Drawing1.dxf".into()), move |app, path| { + *seen.borrow_mut() = Some((uid(app), path)); + Ok(json!(null)) + }); + assert_eq!(r, Some(Ok(json!(null)))); + + app.run("document.switch", json!({ "index": 1 })).unwrap(); + assert_ne!(uid(&app), first); + answer.borrow_mut().take().unwrap()(Some("a.dxf".into())); + app.finish_pick(&ctx); + assert_eq!(*acted_on.borrow(), Some((first, "a.dxf".to_string()))); + assert_eq!(app.session.active, 0, "the drawing that asked is shown again"); + } + + /// The drawing that asked was closed before the answer: nothing is done, and the status bar + /// says so. A dialog that opens a drawing (OPEN, NEW from a template) still acts. + #[test] + fn a_deferred_dialog_for_a_closed_drawing_does_nothing() { + let (mut app, _, answer) = deferred_app(); + let ctx = egui::Context::default(); + app.run("new", json!({})).unwrap(); + let ran = Rc::new(RefCell::new(0)); + let r1 = ran.clone(); + let _ = app.pick_then(Pick::Save("Drawing2.svg".into()), move |_, _| { + *r1.borrow_mut() += 1; + Ok(json!(null)) + }); + app.run("close", json!({ "index": 1 })).unwrap(); + answer.borrow_mut().take().unwrap()(Some("b.svg".into())); + app.finish_pick(&ctx); + assert_eq!(*ran.borrow(), 0, "the closed drawing's export did not run on another drawing"); + assert!(app.pending_pick.is_none()); + assert!(app.status.as_ref().is_some_and(|(s, _)| s.contains("closed") && s.contains("b.svg")), "{:?}", app.status); + + app.run("new", json!({})).unwrap(); + let r2 = ran.clone(); + let _ = app.pick_then_open(Pick::Open, move |_, _| { + *r2.borrow_mut() += 1; + Ok(json!(null)) + }); + app.run("close", json!({ "index": 1 })).unwrap(); + answer.borrow_mut().take().unwrap()(Some("c.dxf".into())); + app.finish_pick(&ctx); + assert_eq!(*ran.borrow(), 1, "OPEN goes on whichever drawing closed meanwhile"); + } + + /// The host dropped the answer (its dialog thread could not start): the status bar says + /// the dialog could not be shown, unlike a cancelled dialog, and the next one may open. + #[test] + fn a_dialog_that_never_answers_is_reported() { + let services = + Services { pick_save: Some(Box::new(|_: &str| None)), start_pick: Some(Box::new(|_, done| drop(done))), ..Services::default() }; + let mut app = CadApp::new(Session::new(), services); + app.start("export"); + app.finish_pick(&egui::Context::default()); + assert!(app.pending_pick.is_none()); + assert!(status(&app).contains("could not be shown"), "{:?}", app.status); + } + + /// With no drawing open, a dialog bound to the active drawing is not shown: its answer could + /// otherwise save or export a drawing opened while it was up. + #[test] + fn a_bound_dialog_needs_an_open_drawing() { + let (mut app, asked, _) = deferred_app(); + app.run("close", json!({ "index": 0 })).unwrap(); + assert!(app.session.state().is_err()); + app.start("ui.saveas"); + let r = app.run("ui.saveas", json!(null)); + assert!(asked.borrow().is_empty(), "no dialog"); + assert!(app.pending_pick.is_none()); + assert!(r.is_err() && app.status.is_some(), "{r:?} {:?}", app.status); + // OPEN needs no drawing. + app.start("ui.open"); + assert_eq!(*asked.borrow(), [Pick::Open]); + } + + /// A command started while APPLOAD's dialog was open (a control request, say) keeps + /// running; APPLOAD is refused and says to run it again. + #[test] + fn appload_does_not_cancel_a_command_started_meanwhile() { + let (mut app, asked, answer) = deferred_app(); + let ctx = egui::Context::default(); + app.start("appload"); + assert!(matches!(asked.borrow().as_slice(), [Pick::Lisp(_)])); + app.start("line"); + assert!(app.session.prompting()); + answer.borrow_mut().take().unwrap()(Some("routine.lsp".into())); + app.finish_pick(&ctx); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("line"), "LINE was not cancelled"); + assert!(status(&app).starts_with("APPLOAD: another command started"), "{:?}", app.status); + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3eb2196d2..41787b002 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -227,6 +227,12 @@ impl Default for UiState { pub struct Services { pub pick_open: Option Option>>, pub pick_save: Option Option>>, + /// Where set, the file dialogs are shown with this instead of calling `pick_open` / + /// `pick_save` / `pick_lisp` (which must still be set, to say which dialogs there are), and + /// the answer is acted on in a later frame ([`CadApp::pick_then`]). macOS needs it: a panel run modally + /// inside the window's event handler gets the window events of its own resizing sent back + /// into that handler, and winit aborts the app (#1527). + pub start_pick: Option, /// Pick a `.lsp` file for APPLOAD, starting in the given folder (empty for the default one). /// `None` where there is no native file dialog: the desktop without one asks for the name, /// and the web (no file system) says to drop the file (`no_file_system`). @@ -238,6 +244,36 @@ pub struct Services { pub pick_pgp: Option) -> Option>>, } +/// The file dialog to show: Open, Save with the suggested file name, APPLOAD's `.lsp` picker or +/// ALIASEDIT's `.pgp` picker, starting in the given folder (empty for the default one). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Pick { + Open, + Save(String), + Lisp(String), + Pgp(String), +} + +/// Shows a file dialog without waiting for it and calls the callback (from any thread) with the +/// chosen path, or `None` when the dialog is cancelled ([`Services::start_pick`]). +pub type StartPick = Box) + Send>)>; + +/// What to do with the path a file dialog chose ([`CadApp::pick_then`]). +type PickDone = Box Result>; + +/// A file dialog shown with [`Services::start_pick`] that has not answered yet. +struct PendingPick { + answer: Receiver>, + /// The drawing (its `uid`) the answer is for: Save As writes that drawing, export and plot + /// read it, and so on, whichever drawing is active when the answer arrives. `None` for the + /// dialogs that open a drawing (Open, New from Template, Recover). + doc: Option, + /// The close prompt's Save is waiting for this dialog: its other answers wait too + /// ([`closing`]). + for_close: bool, + then: PickDone, +} + pub struct CadApp { pub system_languages: Vec, /// Whether the operating system shows animations, as the host reads it; `None` when the OS @@ -329,6 +365,8 @@ pub struct CadApp { pub hatch_dlg: Option, /// The Edit Block Definition dialog ([`bedit`]). pub bedit: bedit::State, + /// A file dialog shown with [`Services::start_pick`]: its answer, and what to do with it. + pending_pick: Option, /// The startup update check and its prompt (desktop; [`updates_ui`]). #[cfg(not(target_arch = "wasm32"))] pub updates_rt: updates_ui::Runtime, @@ -389,9 +427,139 @@ impl CadApp { bedit: bedit::State::default(), #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), + pending_pick: None, } } + /// Ask for a file with the host's dialog (`pick`) and run `then` with the chosen path, on the + /// drawing that is active now. `None` when the host has no dialog of that kind. Cancelling + /// gives `Ok(Null)`. With a synchronous picker the result is `then`'s; with + /// [`Services::start_pick`] the dialog opens and this returns `Ok(Null)` at once: `then` runs + /// in a later frame ([`Self::logic`]) with that drawing made active again (if something else + /// was switched to meanwhile, such as a control-channel `document.switch`), and not at all if + /// the drawing was closed. Its error, if any, shows in the status bar. With no drawing open + /// it refuses without showing a dialog. While one dialog is open, no other is shown: the + /// request is refused with an error, also shown in the status bar. + pub fn pick_then( + &mut self, + pick: Pick, + then: impl FnOnce(&mut CadApp, String) -> Result + 'static, + ) -> Option> { + self.pick_for(pick, true, Box::new(then)) + } + + /// [`Self::pick_then`] for a dialog that opens a drawing (Open, New from Template, Recover): + /// `then` does not act on the drawing that was active, so it runs whatever was switched to + /// or closed meanwhile. + pub fn pick_then_open( + &mut self, + pick: Pick, + then: impl FnOnce(&mut CadApp, String) -> Result + 'static, + ) -> Option> { + self.pick_for(pick, false, Box::new(then)) + } + + /// Show the dialog `pick` for `then`, bound to the active drawing when `bound`. + fn pick_for(&mut self, pick: Pick, bound: bool, then: PickDone) -> Option> { + let available = match pick { + Pick::Open => self.services.pick_open.is_some(), + Pick::Save(_) => self.services.pick_save.is_some(), + Pick::Lisp(_) => self.services.pick_lisp.is_some(), + Pick::Pgp(_) => self.services.pick_pgp.is_some(), + }; + if !available { + return None; + } + if self.pending_pick.is_some() { + return Some(Err(self.refuse_pick("A file dialog is already open; answer it first.".into()))); + } + // A bound answer must not land on a drawing created or opened while the dialog is up. + let doc = match (bound, self.session.state()) { + (false, _) => None, + (true, Ok(st)) => Some(st.uid), + (true, Err(e)) => { + let why = e.to_string(); + return Some(Err(self.refuse_pick(why))); + } + }; + if let Some(start) = &self.services.start_pick { + let (tx, answer) = std::sync::mpsc::channel(); + start( + pick, + Box::new(move |path| { + let _ = tx.send(path); + }), + ); + self.pending_pick = Some(PendingPick { answer, doc, for_close: false, then }); + return Some(Ok(Value::Null)); + } + let path = match &pick { + Pick::Open => self.services.pick_open.as_ref().and_then(|f| f()), + Pick::Save(name) => self.services.pick_save.as_ref().and_then(|f| f(name)), + Pick::Lisp(dir) => self.services.pick_lisp.as_ref().and_then(|f| f(dir)), + Pick::Pgp(dir) => self.services.pick_pgp.as_ref().and_then(|f| f(Some(dir.as_str()).filter(|d| !d.is_empty()))), + }; + Some(match path { + Some(path) => then(self, path), + None => Ok(Value::Null), + }) + } + + /// A file dialog that is not shown: the reason goes to the status bar too, since a typed or + /// menu command's result is not shown ([`Self::start`]). + fn refuse_pick(&mut self, why: String) -> String { + self.set_status(why.clone()); + why + } + + /// Start the interactive command `id` with a dialog's answer. `was_prompting`: whether a + /// command was running when the dialog was asked for. Starting cancels the running command, + /// so a command started while the dialog was open (a control request, say) is kept and this + /// one refused instead; one that was already running is cancelled as when the dialog answers + /// at once. + pub fn start_after_pick(&mut self, id: &str, was_prompting: bool) -> Result<(), String> { + if !was_prompting && self.session.prompting() { + return Err(format!("{}: another command started while the file dialog was open; run it again.", id.to_ascii_uppercase())); + } + self.session.start(id).map_err(|e| e.to_string()) + } + + /// Act on the answer of a dialog started with [`Services::start_pick`], once it arrives. + fn finish_pick(&mut self, ctx: &egui::Context) { + let Some(pending) = &self.pending_pick else { return }; + match pending.answer.try_recv() { + Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(100)), + Ok(None) => self.pending_pick = None, + // The host dropped the answer without giving one: the dialog never opened (its + // thread could not start) or failed. + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.pending_pick = None; + self.set_status("The file dialog could not be shown."); + } + Ok(Some(path)) => { + if let Some(PendingPick { doc, then, .. }) = self.pending_pick.take() + && let Err(e) = self.make_active(doc, &path).and_then(|()| then(self, path)) + { + self.set_status(e); + } + ctx.request_repaint(); + } + } + } + + /// Make the drawing `uid` active again for the answer `path` of a dialog it asked for, or + /// refuse when it was closed meanwhile. + fn make_active(&mut self, uid: Option, path: &str) -> Result<(), String> { + let Some(uid) = uid else { return Ok(()) }; + let Some(i) = self.session.docs.iter().position(|d| d.uid == uid) else { + return Err(format!("The drawing was closed before the file dialog answered; nothing was done with {path}.")); + }; + if self.session.active != i { + self.run("document.switch", json!({ "index": i }))?; + } + Ok(()) + } + /// The interface language shown: the chosen one, or English when this computer has no font /// for it (Chinese or Korean without a suitable font would be boxes). pub fn language(&self) -> &'static str { @@ -702,6 +870,7 @@ impl CadApp { // Consume-based queues: each item is handled once, whichever callback delivers it. A // reply arriving during a later pass is never starved until the next frame. self.drain_control(ctx); + self.finish_pick(ctx); self.finish_opening(); // Finishing an open switches to the new drawing. capture::note_identity(self, ctx); diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index 42266d3b6..8942741e0 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -11,9 +11,9 @@ use std::sync::atomic::{AtomicU32, Ordering}; use egui::{RichText, Sense, Stroke, vec2}; use serde_json::{Value, json}; -use crate::CadApp; use crate::parametric::expr_field; use crate::theme::Tokens; +use crate::{CadApp, Pick}; /// The Block Attribute Manager (BATTMAN). mod battman; @@ -121,6 +121,7 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { let library: Vec = cadcraft_doc::library::standard_linetypes().into_iter().map(|l| l.name).filter(|n| d.linetype(n).is_none()).collect(); let mut sel = temp::(ctx, "ltmgr_sel").filter(|s| rows.iter().any(|r| r.0.eq_ignore_ascii_case(s))).unwrap_or_else(|| current.clone()); let mut action = None; + let mut pick_lin = false; egui::Window::new("Linetype Manager").open(open).default_size(vec2(520.0, 360.0)).resizable(true).show(ctx, |ui| { ui.horizontal(|ui| { craft_ui::ComboBox::from_id_salt("ltmgr_load").selected_text("Load...").width(110.0).show_ui(ui, |ui| { @@ -135,12 +136,10 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { } } // The user's own .lin file (where the host has a file picker). - if let Some(pick) = app.services.pick_open.as_ref() { + if app.services.pick_open.is_some() { ui.separator(); - if ui.selectable_label(false, "From File...").clicked() - && let Some(path) = pick() - { - action = Some(("linetype", json!({ "load": "*", "file": path }))); + if ui.selectable_label(false, "From File...").clicked() { + pick_lin = true; } } }); @@ -187,6 +186,10 @@ fn linetype(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { }); }); set_temp(ctx, "ltmgr_sel", sel); + // The user's .lin file, asked for once the window is drawn. Errors are echoed by `run`. + if pick_lin { + let _ = app.pick_then(Pick::Open, |app, path| app.run("linetype", json!({ "load": "*", "file": path }))); + } action } @@ -1038,33 +1041,46 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { return action; } if ok { - let mut params = plot_params(&st, None); - if let Some(pick) = app.services.pick_save.as_ref() { + let params = plot_params(&st, None); + let target = st.target.clone(); + if app.services.pick_save.is_some() { let title = app.session.state().map(|s| s.title.clone()).unwrap_or_default(); let stem = std::path::Path::new(&title).file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.is_empty()); let suggested = format!("{}-{}.{ext}", stem.unwrap_or_else(|| "Drawing".into()), st.target); // Cancelling the file dialog keeps the Plot dialog open with its settings. - let Some(path) = pick(&suggested) else { return action }; - if let Some(o) = params.as_object_mut() { - o.insert("path".into(), json!(path)); - } - } - *open = false; - match app.run("plot", params) { - Ok(r) => { - let msg = match r.get("path").and_then(Value::as_str) { - Some(path) => format!("Plotted {} to {path}", st.target), - None => format!("Plotted {} ({} bytes of PDF; there is no file dialog here)", st.target, r["bytes"]), - }; - app.session.echo(msg); - } - // `run` already echoed the error; keep the dialog open to fix the settings. - Err(_) => *open = true, + let _ = app.pick_then(Pick::Save(suggested), move |app, path| { + let mut params = params; + if let Some(o) = params.as_object_mut() { + o.insert("path".into(), json!(path)); + } + run_plot(app, params, &target); + Ok(Value::Null) + }); + } else { + run_plot(app, params, &target); } } action } +/// Plot with the Plot dialog's settings: it closes, and opens again when the plot fails. +fn run_plot(app: &mut CadApp, params: Value, target: &str) { + if app.ui.dialog.as_deref() == Some("plot") { + app.ui.dialog = None; + } + match app.run("plot", params) { + Ok(r) => { + let msg = match r.get("path").and_then(Value::as_str) { + Some(path) => format!("Plotted {target} to {path}"), + None => format!("Plotted {target} ({} bytes of PDF; there is no file dialog here)", r["bytes"]), + }; + app.session.echo(msg); + } + // `run` already echoed the error; keep the dialog open to fix the settings. + Err(_) => app.ui.dialog = Some("plot".into()), + } +} + /// The sheet in the chosen orientation with its printable area, and its size. fn sheet_sketch(ui: &mut egui::Ui, page: &cadcraft_doc::PageSetup, t: &Tokens) { let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 8df574eea..e0b3c50df 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; -use crate::CadApp; +use crate::{CadApp, Pick}; /// The top-level menus, in order. pub const MENUS: &[&str] = &["File", "Edit", "View", "Insert", "Format", "Tools", "Draw", "Dimension", "Modify", "Window", "Help"]; @@ -405,13 +405,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()); - if let Some(p) = picked { + "ui.open" | "open" if no_path => app + .pick_then_open(Pick::Open, |app, p| { app.open_path(std::path::Path::new(&p)); - } - Ok(Value::Null) - } + Ok(Value::Null) + }) + .unwrap_or(Ok(Value::Null)), // APPLOAD typed or chosen from a menu: the `.lsp` file picker, starting where the last // one came from. JSON calls carry `path` and never open one. A picked file is loaded as a // typed name is, through the interactive command, so a routine it starts that asks for a @@ -423,57 +422,54 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { - if let Some(p) = app.services.pick_open.as_ref().and_then(|f| f()) { - return Some(app.session.execute("new", &json!({ "template": p })).map_err(|e| e.to_string())); - } - Ok(Value::Null) - } + "ui.newtemplate" => app + .pick_then_open(Pick::Open, |app, p| app.session.execute("new", &json!({ "template": p })).map_err(|e| e.to_string())) + .unwrap_or(Ok(Value::Null)), // RECOVER from the menu or typed: pick the file. Without a picker the engine asks for the // file name on the command line. - "recover" if no_path && app.services.pick_open.is_some() => { - if let Some(p) = app.services.pick_open.as_ref().and_then(|f| f()) { + "recover" if no_path && app.services.pick_open.is_some() => app + .pick_then_open(Pick::Open, |app, p| { let r = app.run("recover", json!({ "path": p })); app.opened(r); - } - Ok(Value::Null) - } + Ok(Value::Null) + }) + .unwrap_or(Ok(Value::Null)), "ui.saveas" | "saveas" if no_path => { let title = app.session.state().map(|s| s.title.clone()).ok(); let name = app.ui.save_format.suggested_name(title.as_deref()); - if let Some(p) = app.services.pick_save.as_ref().and_then(|f| f(&name)) { - return Some(app.session.execute("saveas", &saveas_params(&app.ui, &app.session, &p)).map_err(|e| e.to_string())); - } - Ok(Value::Null) + // Bound to this drawing: the answer saves it, not whichever drawing is active then. + app.pick_then(Pick::Save(name), |app, p| { + app.session.execute("saveas", &saveas_params(&app.ui, &app.session, &p)).map_err(|e| e.to_string()) + }) + .unwrap_or(Ok(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. "exportpdf" if params.is_null() && app.session.state().is_ok() => { - let pick = app.services.pick_save.as_ref()?; let title = app.session.state().map(|s| s.title.clone()).unwrap_or_default(); let stem = std::path::Path::new(&title).file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.is_empty()); - let Some(path) = pick(&format!("{}.pdf", stem.unwrap_or_else(|| "Drawing".into()))) else { return Some(Ok(Value::Null)) }; - let r = app.session.execute("exportpdf", &json!({ "path": path })).map_err(|e| e.to_string()); - app.session.echo(match &r { - Ok(_) => format!("Plotted to {path}"), - Err(e) => e.clone(), + return app.pick_then(Pick::Save(format!("{}.pdf", stem.unwrap_or_else(|| "Drawing".into()))), |app, path| { + let r = app.session.execute("exportpdf", &json!({ "path": path })).map_err(|e| e.to_string()); + app.session.echo(match &r { + Ok(_) => format!("Plotted to {path}"), + Err(e) => e.clone(), + }); + r }); - r } "ui.sample" => { let d = cadcraft_engine::sample::default_sample(); diff --git a/crates/ui-egui/src/xrefs.rs b/crates/ui-egui/src/xrefs.rs index 51a21834f..ee5aa385b 100644 --- a/crates/ui-egui/src/xrefs.rs +++ b/crates/ui-egui/src/xrefs.rs @@ -6,8 +6,8 @@ use egui::RichText; use serde_json::{Value, json}; -use crate::CadApp; use crate::docking::Panel; +use crate::{CadApp, Pick}; /// XREF typed or chosen from a menu opens this palette; XATTACH there asks for the file first /// (with the host's file picker, where there is one). JSON calls (with parameters) run the @@ -19,19 +19,18 @@ pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option Some(open_palette(app)), "xattach" => { - let picked = app.services.pick_open.as_ref().and_then(|f| f())?; - let path = relative_to_host(app, &picked); - if let Err(e) = app.session.start("xattach") { - return Some(Err(e.to_string())); - } - // Submit the picked filename as literal text, not through the command line: a path is - // attacker-controlled (the file picker returns whatever the user selected), and - // `cmdline` interprets command syntax, so a name like `'closeall` would run an engine - // command instead of naming the file (CWE-74). - if let Err(e) = app.session.input(cadcraft_engine::Input::Text(path)) { - return Some(Err(e.to_string())); - } - Some(Ok(Value::Null)) + app.services.pick_open.as_ref()?; + let was_prompting = app.session.prompting(); + app.pick_then(Pick::Open, move |app, picked| { + let path = relative_to_host(app, &picked); + app.start_after_pick("xattach", was_prompting)?; + // Submit the picked filename as literal text, not through the command line: a + // path is attacker-controlled (the file picker returns whatever the user + // selected), and `cmdline` interprets command syntax, so a name like `'closeall` + // would run an engine command instead of naming the file (CWE-74). + app.session.input(cadcraft_engine::Input::Text(path)).map_err(|e| e.to_string())?; + Ok(Value::Null) + }) } _ => None, } From bc9ad6b059271b1c86ee2fa9bfbf2aacf6a0d6bf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 21:29:35 -0500 Subject: [PATCH 174/185] fix: index or bound four small lookups (DOF selection, xref palette, QSELECT colours, log lines) (#2728) * fix: index or bound four small lookups (DOF selection, xref palette, QSELECT colours, log lines) DOF scanned the selection list per slot; the xref palette scanned the xref list per INSERT; QSELECT parsed a possibly long layer name as a colour for every entity; and a log message could carry CR/LF or other control characters that started apparent extra records. Each now uses a set or map, a length bound, or escaping, with the same results for ordinary input. * address review: trim colour text before length limit --- apps/cadcraft/src/logging.rs | 25 +++++++++++++++++++++--- crates/constraints/src/dof.rs | 4 +++- crates/engine/src/cmd/qselect.rs | 33 ++++++++++++++++++++++++++++++-- crates/ui-egui/src/xrefs.rs | 8 +++++++- 4 files changed, 63 insertions(+), 7 deletions(-) diff --git a/apps/cadcraft/src/logging.rs b/apps/cadcraft/src/logging.rs index 724d09c1a..e4e86c982 100644 --- a/apps/cadcraft/src/logging.rs +++ b/apps/cadcraft/src/logging.rs @@ -148,7 +148,20 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { /// One formatted log line: ` [] : \n`. pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String { let message = message.strip_suffix('\n').unwrap_or(message); - format!("{ts} {level:<5} [{thread}] {target}: {message}\n") + // A message can carry text from a file (a code page name, a path), so it must not be able to + // start what looks like another record: control characters other than tab and line feed are + // shown escaped, and every continuation line is indented, so only this function's own + // timestamp is ever at the start of a line. + let mut safe = String::with_capacity(message.len()); + for c in message.chars() { + match c { + '\n' => safe.push_str("\n "), + '\t' => safe.push('\t'), + c if c.is_control() => safe.extend(c.escape_default()), + c => safe.push(c), + } + } + format!("{ts} {level:<5} [{thread}] {target}: {safe}\n") } /// Where formatted lines go besides standard error: kept in memory until a file is attached, @@ -441,8 +454,14 @@ mod tests { format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "cadcraft", "app icon: invalid PNG signature"), "2026-10-08T07:59:17.728Z WARN [main] cadcraft: app icon: invalid PNG signature\n" ); - // A multi-line message keeps its lines; the record still ends in exactly one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); + // A multi-line message keeps its lines, indented so they can't pass for records; the + // record still ends in exactly one newline. + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n")); + // Control characters in a message (from a file) can't forge a record. + let forged = format_line("t", log::Level::Warn, "w", "x", "page\r\n2026-01-01T00:00:00Z ERROR [main] x: fake\u{1b}[0m"); + assert_eq!(forged.lines().count(), 2); + assert!(forged.lines().skip(1).all(|l| l.starts_with(" "))); + assert!(!forged.contains('\r') && !forged.contains('\u{1b}')); } #[test] diff --git a/crates/constraints/src/dof.rs b/crates/constraints/src/dof.rs index e6128665c..7ac58e112 100644 --- a/crates/constraints/src/dof.rs +++ b/crates/constraints/src/dof.rs @@ -138,7 +138,9 @@ pub fn dof(d: &Drawing, handles: &[Handle]) -> Result { let cons: Vec<&Constraint> = d.constraints.iter().take(MAX_CONSTRAINTS).collect(); 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); + // The selection as a set, built once: a scan of the list per slot multiplied the two sizes. + let selected: HashSet = handles.iter().copied().collect(); + let want = |h: Handle| handles.is_empty() || selected.contains(&h); let mut objects = Vec::new(); let mut seen = HashSet::new(); let mut total = Some(0usize); diff --git a/crates/engine/src/cmd/qselect.rs b/crates/engine/src/cmd/qselect.rs index 2c5330371..469a0895f 100644 --- a/crates/engine/src/cmd/qselect.rs +++ b/crates/engine/src/cmd/qselect.rs @@ -175,8 +175,14 @@ pub fn compare(prop: &Value, op: Op, value: &Value) -> bool { if ptxt.eq_ignore_ascii_case(vtxt.trim()) { return true; } - // Colours: `red` = `1` = `Red`; `bylayer` = `ByLayer`. - match (Color::parse(&ptxt), Color::parse(vtxt.trim())) { + // Colours: `red` = `1` = `Red`; `bylayer` = `ByLayer`. No colour spelling is long, so a + // long text (a layer name from a file) isn't parsed, copied and split per entity. + const MAX_COLOR_TEXT: usize = 64; + let (pc, vc) = (ptxt.trim(), vtxt.trim()); + if pc.len() > MAX_COLOR_TEXT || vc.len() > MAX_COLOR_TEXT { + return false; + } + match (Color::parse(pc), Color::parse(vc)) { (Some(a), Some(b)) => a == b, _ => false, } @@ -400,3 +406,26 @@ mod tests { assert!(!wildcard(&"*a".repeat(500), &"b".repeat(4000))); } } + +#[cfg(test)] +mod long_text_tests { + use super::*; + + /// A long string property is compared as text only, and a colour name still equals its index. + #[test] + fn long_values_skip_colour_parsing() { + let long = Value::String("x".repeat(100_000)); + assert!(compare(&long, Op::Eq, &long)); + assert!(!compare(&long, Op::Eq, &Value::String("red".into()))); + assert!(compare(&Value::String("red".into()), Op::Eq, &Value::String("1".into()))); + } + + /// Padding is trimmed before the length limit, so a padded colour still matches. + #[test] + fn padded_colours_still_match() { + let padded = |c: &str| Value::String(format!("{}{c}{}", " ".repeat(100), " ".repeat(100))); + assert!(compare(&padded("red"), Op::Eq, &Value::String("1".into()))); + assert!(compare(&Value::String("red".into()), Op::Eq, &padded("1"))); + assert!(!compare(&padded("red"), Op::Ne, &padded("1"))); + } +} diff --git a/crates/ui-egui/src/xrefs.rs b/crates/ui-egui/src/xrefs.rs index ee5aa385b..ed1f43d79 100644 --- a/crates/ui-egui/src/xrefs.rs +++ b/crates/ui-egui/src/xrefs.rs @@ -77,10 +77,16 @@ fn rows(app: &CadApp, ui: &egui::Ui) -> Vec { let xrefs: Vec<_> = d.blocks.values().filter(|b| b.xref_path.is_some() && !b.name.contains('|')).collect(); let mut counts = vec![0usize; xrefs.len()]; if !xrefs.is_empty() { + // Xref name (ASCII-upper-cased) → its row, the first of names that differ only in case, so + // each INSERT is one lookup instead of a scan of the xref list. + let mut index: std::collections::HashMap = std::collections::HashMap::new(); + for (k, b) in xrefs.iter().enumerate() { + index.entry(b.name.to_ascii_uppercase()).or_insert(k); + } let mut count = |store: &cadcraft_engine::doc::EntityStore| { for e in store.iter() { if let cadcraft_engine::doc::EntityKind::Insert(i) = &e.kind - && let Some(k) = xrefs.iter().position(|b| b.name.eq_ignore_ascii_case(&i.block)) + && let Some(&k) = index.get(&i.block.to_ascii_uppercase()) && let Some(c) = counts.get_mut(k) { *c += 1; From 7804e94ee0a5772d2ae08beea4d2b9c6dc401b61 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 21:29:40 -0500 Subject: [PATCH 175/185] fix(geom): bound the points one polyline tessellation samples (#2723) * fix(geom): bound the points one polyline tessellation samples Polyline::tessellate sampled every arc segment (up to 4096 points each) with no total limit, and hatch boundary preparation did this for every loop, so compact curved vertices expanded into gigabytes. tessellate_within takes a point budget; once spent, remaining arcs are drawn as chords. Hatch loops share one budget. * address review: correct tessellate_within doc --- crates/geom/src/curve.rs | 19 ++++++++++++++++++- crates/geom/src/lib.rs | 3 ++- crates/geom/src/tests.rs | 12 ++++++++++++ crates/render/src/hatch.rs | 5 ++++- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index 04f665f88..5d0e53f17 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -484,6 +484,9 @@ pub struct Polyline { pub closed: bool, } +/// Sampled points one [`Polyline::tessellate`] call produces before arcs become chords. +pub const MAX_TESSELLATED_POINTS: usize = 4_000_000; + impl Polyline { pub fn from_points(pts: &[Vec2], closed: bool) -> Self { Polyline { vertices: pts.iter().map(|p| PolyVertex::new(*p)).collect(), closed } @@ -516,10 +519,24 @@ impl Polyline { b } pub fn tessellate(&self, tol: f64) -> Vec { + let mut budget = MAX_TESSELLATED_POINTS; + self.tessellate_within(tol, &mut budget) + } + /// [`Polyline::tessellate`] spending about `budget` sampled points (shared by the caller + /// across many polylines). The budget is checked before each segment, so the last segment + /// started may overshoot it by that one segment's samples. Once it is spent, the remaining arcs are drawn as chords, so the + /// output stays proportional to the input vertices. Each arc can sample thousands of points, + /// so a compact polyline could otherwise expand into gigabytes (CWE-400). + pub fn tessellate_within(&self, tol: f64, budget: &mut usize) -> Vec { let mut out: Vec = Vec::new(); for s in self.segments() { let mut pts = Vec::new(); - s.tessellate(tol, &mut pts); + if *budget > 0 { + s.tessellate(tol, &mut pts); + *budget = budget.saturating_sub(pts.len()); + } else { + pts.extend([s.start(), s.end()]); + } let skip = usize::from(out.last().is_some_and(|l| pts.first().is_some_and(|f| l.near(*f, 1e-9)))); out.extend(pts.into_iter().skip(skip)); } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index e62f478fb..d482141fd 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -20,7 +20,8 @@ mod vec; pub use bounds::Bounds2; pub use curve::{ - Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Segment, arc_to_bulge, bulge_to_arc, point_in_polygon, polygon_centroid, shoelace, + Arc, Circle, Ellipse, Line, MAX_TESSELLATED_POINTS, PolyVertex, Polyline, Segment, arc_to_bulge, bulge_to_arc, point_in_polygon, + polygon_centroid, shoelace, }; pub use fillet::{CornerFit, TanCurve, tangent_circles}; pub use intersect::{circle_circle, intersect_ext, intersect_segments, line_circle, line_line, line_line_infinite}; diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rs index 915a1071e..57ffcd663 100644 --- a/crates/geom/src/tests.rs +++ b/crates/geom/src/tests.rs @@ -221,6 +221,18 @@ fn segment_offset() { assert!(s.offset(6.0).is_none()); } +/// A polyline of many fine arcs samples at most the point budget, then draws chords. +#[test] +fn polyline_tessellation_is_bounded() { + let vertices: Vec = (0..3000).map(|i| PolyVertex { bulge: 1.0, ..PolyVertex::new(Vec2::new(f64::from(i) * 1e6, 0.0)) }).collect(); + let pl = Polyline { vertices, closed: false }; + let pts = pl.tessellate(1e-9); + assert!(pts.len() <= MAX_TESSELLATED_POINTS + 2 * 3000 + 4096, "{}", pts.len()); + assert!(pts.len() > 3000); + let mut budget = 10; + assert!(pl.tessellate_within(1e-9, &mut budget).len() <= 4096 + 2 * 3000); +} + #[test] fn arc_segments_bounded() { assert_eq!(arc_segments(0.0, 1.0, 0.1), 1); diff --git a/crates/render/src/hatch.rs b/crates/render/src/hatch.rs index 1bfeb1b6c..ecd78fdfe 100644 --- a/crates/render/src/hatch.rs +++ b/crates/render/src/hatch.rs @@ -128,7 +128,10 @@ const MAX_DEDUP_COMPARISONS: u64 = 50_000_000; /// within islands alternate), 1 outer keeps the outermost loops and their first islands, 2 /// ignore keeps only the outermost loops. Nesting depth = how many other loops enclose a loop. pub fn fill_loops(h: &Hatch, tol: f64) -> Vec> { - let mut loops: Vec> = h.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(tol)).collect(); + // One point budget for all the loops: many short arcs across loops must not add up unbounded. + let mut budget = cadcraft_geom::MAX_TESSELLATED_POINTS; + let mut loops: Vec> = + h.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate_within(tol, &mut budget)).collect(); dedup_polygons(&mut loops); let max_depth = match h.style { 1 => 1, From 36f5ad64f9ad46ebda91718e4bdc216990ed2792 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 21:29:48 -0500 Subject: [PATCH 176/185] fix(engine): move LISP output to the command history in one pass (#2714) lisp_flush drained each line from the front of the output buffer, shifting everything after it every time, so newline-dense PRINC output cost quadratic time outside the interpreter's step budget. It now walks the buffer once and drops the printed prefix once. --- crates/engine/src/lisp.rs | 10 +++++++--- crates/engine/src/lisp/tests.rs | 10 ++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lisp.rs b/crates/engine/src/lisp.rs index 977d4f551..b1ab4c384 100644 --- a/crates/engine/src/lisp.rs +++ b/crates/engine/src/lisp.rs @@ -415,9 +415,12 @@ impl Session { /// Move printed text to the command history: complete lines, and with `all` the rest too. fn lisp_flush(&mut self, env: &mut Env, all: bool) { - while let Some(i) = env.out.find('\n') { - let line: String = env.out.drain(..=i).collect(); - let line = line.trim_end_matches(['\n', '\r']).to_string(); + // One pass over the buffer, dropping the printed lines once at the end: draining each line + // from the front shifted the rest every time, quadratic in newline-dense output. + let mut done = 0; + while let Some(i) = env.out.get(done..).and_then(|rest| rest.find('\n')) { + let line = env.out.get(done..done + i).unwrap_or_default().trim_end_matches('\r').to_string(); + done += i + 1; // `(princ "\nText")` after a prompt or a command's echo ends that line instead of // leaving an empty one; after LISP's own line it does print an empty line. if line.is_empty() && env.printed_at != Some(self.log.len()) { @@ -427,6 +430,7 @@ impl Session { self.echo(line); env.printed_at = Some(self.log.len()); } + env.out.drain(..done); if all && !env.out.is_empty() { let line = std::mem::take(&mut env.out); self.echo(line); diff --git a/crates/engine/src/lisp/tests.rs b/crates/engine/src/lisp/tests.rs index 0ed4b22fd..0feba7534 100644 --- a/crates/engine/src/lisp/tests.rs +++ b/crates/engine/src/lisp/tests.rs @@ -307,6 +307,16 @@ fn printing() { assert_eq!(ok(&mut s, "(rtos 12.5 2 2)"), "\"12.50\""); } +/// Output with many lines moves to the history in one pass, not one buffer shift per line. +#[test] +fn printing_many_lines_is_linear() { + let mut s = session(); + let started = std::time::Instant::now(); + ok(&mut s, "(setq x \"a\\r\\n\") (repeat 17 (setq x (strcat x x))) (princ x) (princ)"); + assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed()); + assert_eq!(s.log.last().map(String::as_str), Some("a")); +} + #[test] fn command_draws_and_one_routine_is_one_undo_step() { let mut s = session(); From 0843770389a861f7dd35c54ffbb19a9daa54df55 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 21:29:52 -0500 Subject: [PATCH 177/185] fix(engine): read local files for RECOVER, INSERT, IMPORT, COMPARE, NEW, DATALINK and STYLESMANAGER through the capped reader (#2687) A path naming an endless device or a FIFO was buffered to EOF before any size check ran, so one short command could exhaust memory or block. These paths now go through capped_read::read_capped, which refuses non-regular files and enforces the byte limit while reading. --- crates/engine/src/cmd/audit.rs | 2 +- crates/engine/src/cmd/blocks/insert_file.rs | 3 ++- crates/engine/src/cmd/exchange.rs | 3 ++- crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/file/compare.rs | 2 +- crates/engine/src/cmd/file/template.rs | 2 +- crates/engine/src/cmd/layout/plotstyle.rs | 8 +++----- crates/engine/src/cmd/table/breaks.rs | 20 ++++++++++++++------ 8 files changed, 25 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/audit.rs b/crates/engine/src/cmd/audit.rs index fa3cc2f98..6bd068c11 100644 --- a/crates/engine/src/cmd/audit.rs +++ b/crates/engine/src/cmd/audit.rs @@ -157,7 +157,7 @@ fn write_audit_log(_: &Session, _: &crate::audit::Report) {} #[cfg(not(target_arch = "wasm32"))] fn read_path(cmd: &str, path: &str) -> Result> { - std::fs::read(path).map_err(|e| bad(cmd, format!("{path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(path), file::MAX_DRAWING_BYTES).map_err(|e| bad(cmd, 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..e39dc06bb 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -85,7 +85,8 @@ fn read_drawing(path: &str) -> Result { fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { - std::fs::read(_path).map_err(|e| bad("insert", format!("{_path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(_path), crate::cmd::file::MAX_DRAWING_BYTES) + .map_err(|e| bad("insert", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("insert", "paths are not available on the web")) diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 6148a0446..1b8d7c72e 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -204,7 +204,8 @@ 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"))] { - std::fs::read(_path).map_err(|e| bad("import", format!("{_path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(_path), crate::cmd::file::MAX_DRAWING_BYTES) + .map_err(|e| bad("import", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("import", "paths are not available on the web; pass `data`")) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 1ec3b315a..b2a677e11 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -24,7 +24,7 @@ pub use template::{qnew_template, set_qnew_template}; /// endless device must be rejected before it exhausts memory (CWE-400), so native opens read /// through [`crate::capped_read`] rather than buffering to EOF. #[cfg(not(target_arch = "wasm32"))] -const MAX_DRAWING_BYTES: usize = 512 << 20; +pub(crate) const MAX_DRAWING_BYTES: usize = 512 << 20; /// Largest `.scr` script accepted from a local path. #[cfg(not(target_arch = "wasm32"))] const MAX_SCRIPT_BYTES: usize = 64 << 20; diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 295b472b1..273ec1ac7 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -110,7 +110,7 @@ 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::capped_read::read_capped(std::path::Path::new(_path), super::MAX_DRAWING_BYTES).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..908e320a0 100644 --- a/crates/engine/src/cmd/file/template.rs +++ b/crates/engine/src/cmd/file/template.rs @@ -74,7 +74,7 @@ fn read_template(path: &str) -> Result { #[cfg(not(target_arch = "wasm32"))] fn read_bytes(path: &str) -> Result> { - std::fs::read(path).map_err(|e| bad("new", format!("template {path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(path), super::MAX_DRAWING_BYTES).map_err(|e| bad("new", format!("template {path}: {e}"))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index d432343c2..d5d4f3b1c 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -303,11 +303,9 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { (None, Some(_path)) => { #[cfg(not(target_arch = "wasm32"))] { - 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"))); - } - std::fs::read_to_string(_path).map_err(|e| bad(cmd, format!("{_path}: {e}")))? + let bytes = crate::capped_read::read_capped(std::path::Path::new(_path), cadcraft_doc::MAX_TABLE_FILE) + .map_err(|e| bad(cmd, format!("{_path}: {e}")))?; + String::from_utf8(bytes).map_err(|e| bad(cmd, format!("{_path}: {e}")))? } #[cfg(target_arch = "wasm32")] return Err(bad(cmd, "files can't be read here: pass `text`")); diff --git a/crates/engine/src/cmd/table/breaks.rs b/crates/engine/src/cmd/table/breaks.rs index 6f207ec50..206ac1ef0 100644 --- a/crates/engine/src/cmd/table/breaks.rs +++ b/crates/engine/src/cmd/table/breaks.rs @@ -12,7 +12,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; /// Largest linked file read (bytes). #[cfg(not(target_arch = "wasm32"))] -const MAX_LINK_BYTES: u64 = 8 << 20; +const MAX_LINK_BYTES: usize = 8 << 20; pub fn specs() -> Vec { vec![ @@ -238,11 +238,9 @@ fn read_link(id: &str, file: &std::path::Path) -> Result { let path = file.display(); #[cfg(not(target_arch = "wasm32"))] { - 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))); - } - let bytes = std::fs::read(file).map_err(|e| bad(id, format!("{path}: {e}")))?; + // The limit is enforced on the bytes read, not on reported metadata, so a device or FIFO + // that misreports its length can't be buffered to EOF. + let bytes = crate::capped_read::read_capped(file, MAX_LINK_BYTES).map_err(|e| bad(id, format!("{path}: {e}")))?; let text = String::from_utf8_lossy(&bytes); Ok(text.strip_prefix('\u{feff}').unwrap_or(&text).to_owned()) } @@ -370,6 +368,16 @@ fn run_update(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + /// A linked path naming an endless device is refused instead of buffered to EOF. + #[cfg(all(unix, not(target_arch = "wasm32")))] + #[test] + fn link_to_endless_device_is_rejected() { + let dev = std::path::Path::new("/dev/zero"); + if dev.exists() { + assert!(read_link("datalink", dev).is_err()); + } + } + #[test] fn csv_parsing() { assert_eq!(parse_csv("a,b\r\n\"c,d\",\"e\"\"f\"\n", ','), vec![vec!["a", "b"], vec!["c,d", "e\"f"]]); From 95fdf8d11ae83b215fae4658ec6a8d75d8ee0019 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 21:33:39 -0500 Subject: [PATCH 178/185] fix: bound region grid registrations, island containment tests, snap_ends visits, inference duplicate searches and font name decoding (#2742) * fix: bound region grid registrations, island containment tests, snap_ends visits, inference duplicate searches and font name decoding * address review: charge empty curves only in snap_ends search * fix(geom): report a spent containment budget instead of partial islands * address review: count pending point candidates in the perpendicular cap --- crates/constraints/src/auto.rs | 18 ++++++++++++------ crates/fonts/src/ttf.rs | 10 +++++++++- crates/geom/src/region.rs | 29 +++++++++++++++++++++++------ 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/crates/constraints/src/auto.rs b/crates/constraints/src/auto.rs index 211be6b93..b24d3e736 100644 --- a/crates/constraints/src/auto.rs +++ b/crates/constraints/src/auto.rs @@ -232,6 +232,10 @@ pub fn infer_placed(d: &Drawing, placed: &[Handle], others: &[Handle], o: &Infer let mut extra = Vec::new(); let mut on = Vec::new(); for (rp, p) in g.points.iter().filter(|(r, _)| placed.contains(&r.handle)) { + // Nothing is added once the candidates are full, so the points left need no search. + if extra.len() + on.len() + out.len() >= MAX_CANDIDATES { + break; + } if out.iter().any(|c| c.kind == ConstraintKind::Coincident && c.refs.contains(rp)) { continue; } @@ -267,20 +271,22 @@ pub fn infer_placed(d: &Drawing, placed: &[Handle], others: &[Handle], o: &Infer // Perpendicular lines meeting in a T (a perpendicular snap onto the middle of a line). let atol = if o.angle_tolerance.is_finite() { o.angle_tolerance.clamp(0.0, 45.0).to_radians() } else { 0.0 }; let allow_per = o.types.is_empty() || o.types.iter().any(|t| t.eq_ignore_ascii_case(ConstraintKind::Perpendicular.name())); - for (r1, a1, b1) in g.lines.iter().filter(|(r, _, _)| placed.contains(&r.handle)) { + 'per: for (r1, a1, b1) in g.lines.iter().filter(|(r, _, _)| allow_per && placed.contains(&r.handle)) { for (r2, a2, b2) in g.lines.iter().filter(|(r, _, _)| r.handle != r1.handle) { + // Full: nothing more can be added, so the pairs left need no geometry or duplicate search. + if out.len() + extra.len() + on.len() >= MAX_CANDIDATES { + break 'per; + } let (l1, l2) = (Line::new(*a1, *b1), Line::new(*a2, *b2)); let touches = |l: &Line, p: Vec2| l.dist(p) <= tol && (0.0..=1.0).contains(&l.param_of(p)); let tee = [*a1, *b1].iter().any(|p| touches(&l2, *p)) || [*a2, *b2].iter().any(|p| touches(&l1, *p)); let ang = ang_between(*b1 - *a1, *b2 - *a2); - let dup = out.iter().any(|c| c.kind == ConstraintKind::Perpendicular && c.refs.contains(r1) && c.refs.contains(r2)); - if allow_per - && tee - && !dup + // The duplicate search scans every candidate, so it comes after the cheap tests. + if tee && (std::f64::consts::FRAC_PI_2 - ang).abs() <= atol && l1.len() > tol && l2.len() > tol - && out.len() < MAX_CANDIDATES + && !out.iter().any(|c| c.kind == ConstraintKind::Perpendicular && c.refs.contains(r1) && c.refs.contains(r2)) { out.push(Constraint { id: 0, kind: ConstraintKind::Perpendicular, refs: vec![*r1, *r2], name: String::new(), expr: String::new() }); } diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 2f4ffab24..2edefe7b4 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -103,7 +103,11 @@ impl Face { 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] .into_iter() - .flat_map(|id| f.localized_strings(id).map(|s| norm(&s.to_string())).collect::>()) + // A name table can hold many records that point at one big string: at most + // MAX_NAME_RECORDS per name id, each decoded only up to MAX_NAME_CHARS characters. + .flat_map(|id| { + f.localized_strings(id).take(MAX_NAME_RECORDS).map(|s| norm(&s.chars().take(MAX_NAME_CHARS).collect::())).collect::>() + }) .collect() } } @@ -118,6 +122,10 @@ pub fn faces(bytes: &Arc>) -> Vec { } const MAX_FACES_PER_FILE: u32 = 32; +/// Name records read per name id of a face, and characters read of each: real fonts have a few +/// dozen short ones. +const MAX_NAME_RECORDS: usize = 64; +const MAX_NAME_CHARS: usize = 256; /// Bounds of the missing-glyph search: files loaded, bytes loaded, faces checked per character. const MAX_FALLBACK_FILES: usize = 24; const MAX_FALLBACK_BYTES: usize = 160 << 20; diff --git a/crates/geom/src/region.rs b/crates/geom/src/region.rs index 0c7ddd326..a132c699b 100644 --- a/crates/geom/src/region.rs +++ b/crates/geom/src/region.rs @@ -431,10 +431,10 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option> { } /// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`). -fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Vec { +fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option> { let comp = components(g); let outer_comp: std::collections::HashSet = outer.iter().filter_map(|&i| comp.get(i).copied()).collect(); - let Some(outer_pts) = points(g, outer) else { return Vec::new() }; + let outer_pts = points(g, outer)?; let ob = Bounds2::from_points(outer_pts.iter().copied()); let core = prune(g); // Leftmost (then lowest) vertex still on a cycle, per component. @@ -464,19 +464,32 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Vec { let mut starts: Vec<(usize, usize)> = start.into_iter().collect(); starts.sort_unstable(); let mut out = Vec::new(); + // Each containment test scans a whole polygon, accepted or not: they share one allowance of + // polygon edges, and the search ends when it is spent. + let mut edges_left: usize = 100_000_000; for (c, u) in starts { if out.len() >= MAX_ISLANDS { break; } let Some(&pu) = core.pts.get(u) else { continue }; - if !ob.contains(pu) || !point_in_polygon(&outer_pts, pu) { + if !ob.contains(pu) { + continue; + } + let left = edges_left.checked_sub(outer_pts.len())?; + edges_left = left; + if !point_in_polygon(&outer_pts, pu) { continue; } let steps = edges.get(&c).copied().unwrap_or(0).saturating_add(4); let Some(lp) = outside(&core, u, steps) else { continue }; let area = shoelace(&lp); let ib = Bounds2::from_points(lp.iter().copied()); - if lp.len() < 3 || !area.is_finite() || area <= 0.0 || !ob.contains_box(&ib) || point_in_polygon(&lp, p) { + if lp.len() < 3 || !area.is_finite() || area <= 0.0 || !ob.contains_box(&ib) { + continue; + } + let left = edges_left.checked_sub(lp.len())?; + edges_left = left; + if point_in_polygon(&lp, p) { continue; } let mut src = sources.remove(&c).unwrap_or_default(); @@ -484,7 +497,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Vec { src.dedup(); out.push(Island { outline: lp, sources: src }); } - out + Some(out) } /// The point of the nearest other curve within `snap` of the end `e` of curve `i`, as (curve, @@ -497,6 +510,10 @@ fn nearest_curve(polys: &[Vec], i: usize, e: Vec2, snap: f64, tol: f64, bu if j == i { continue; } + // A curve with no segment costs a visit too, so many of them can't multiply the searches. + if other.len() < 2 { + *budget = budget.checked_sub(1).ok_or(())?; + } for (k, w) in other.windows(2).enumerate() { if *budget == 0 { return Err(()); @@ -598,7 +615,7 @@ pub fn boundary_at_gap(polys: &[Vec], p: Vec2, tol: f64, gap: f64) -> Opti let g = build_gap(polys, tol, gap)?; let ids = outer_face(&g, p)?; let outer = points(&g, &ids)?; - let islands = islands(&g, &ids, p); + let islands = islands(&g, &ids, p)?; let mut outer_sources: Vec = ids.iter().zip(ids.iter().cycle().skip(1)).filter_map(|(&u, &v)| g.edge_src.get(&(u.min(v), u.max(v))).copied()).collect(); outer_sources.sort_unstable(); From 2c25c2d70043d76ed63c70d6cebdf5e76ae61c1f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 21:33:42 -0500 Subject: [PATCH 179/185] fix: index or bound array replacements, DIM field spellings, path samples, hatch refills and broken tables (#2734) * fix: index or bound array replacements, DIM field spellings, path samples, hatch refills and broken tables * address review: index placeable array replacements, search past zero-length DIVIDE runs, per-part broken-table outlines --- crates/doc/src/array.rs | 32 ++++++++++- crates/doc/src/dynblock/apply.rs | 6 +++ crates/doc/src/tables.rs | 7 +++ crates/doc/src/tests.rs | 11 ++++ crates/engine/src/cmd/array/edit.rs | 3 +- crates/engine/src/cmd/curves.rs | 62 +++++++++++++++++++--- crates/engine/src/cmd/draw2/divide.rs | 6 ++- crates/engine/src/cmd/draw2/revcloud.rs | 3 +- crates/engine/src/cmd/modify2/patharray.rs | 6 ++- crates/render/src/table.rs | 58 +++++++++++++++----- crates/render/src/tests.rs | 22 ++++++++ 11 files changed, 188 insertions(+), 28 deletions(-) diff --git a/crates/doc/src/array.rs b/crates/doc/src/array.rs index 1514bc055..e71b28739 100644 --- a/crates/doc/src/array.rs +++ b/crates/doc/src/array.rs @@ -204,6 +204,23 @@ impl ArrayParams { self.replaced.iter().rev().find(|r| (r.i, r.j, r.level) == (i, j, level)).map_or(self.source.as_str(), |r| r.block.as_str()) } + /// [`block_for`](Self::block_for) for many items: the replacements are indexed once (the last + /// entry for a place wins, as there), so each lookup is O(1) instead of a scan of `replaced`. + pub fn block_lookup<'a>(&'a self) -> impl Fn(u32, u32, u32) -> &'a str + 'a { + // Only places `items()` generates are indexed, so stray out-of-range records cost nothing. + let (cols, rows) = match &self.kind { + ArrayKind::Rect(r) => (r.cols, r.rows), + ArrayKind::Polar(p) => (p.items, p.rows), + }; + let index: std::collections::HashMap<(u32, u32, u32), &str> = self + .replaced + .iter() + .filter(|r| r.i < cols && r.j < rows && r.level < self.levels) + .map(|r| ((r.i, r.j, r.level), r.block.as_str())) + .collect(); + move |i, j, level| index.get(&(i, j, level)).copied().unwrap_or(self.source.as_str()) + } + /// The block references that make up the array block: one per item, on layer 0 with ByBlock /// properties so they take the array's. Handles are allocated from `d`. `None` when the /// parameters are not [valid](Self::is_valid). @@ -217,9 +234,10 @@ impl ArrayParams { ..Common::default() }; let mut out = Vec::with_capacity(items.len()); + let block_for = self.block_lookup(); for it in items { let ins = Insert { - block: self.block_for(it.i, it.j, it.level).to_string(), + block: block_for(it.i, it.j, it.level).to_string(), insert: it.insert, scale: Vec3::new(1.0, 1.0, 1.0), rotation: it.rotation, @@ -301,6 +319,18 @@ mod tests { } } + #[test] + fn block_lookup_agrees_with_block_for_and_the_last_replacement_wins() { + let mut p = rect(3, 2); + let r = |i, j, level, b: &str| ReplacedItem { i, j, level, block: b.into() }; + p.replaced = vec![r(1, 0, 0, "A"), r(1, 0, 0, "B"), r(2, 1, 1, "C")]; + let look = p.block_lookup(); + for (i, j, level) in [(0, 0, 0), (1, 0, 0), (2, 1, 1), (2, 1, 0)] { + assert_eq!(look(i, j, level), p.block_for(i, j, level)); + } + assert_eq!((look(1, 0, 0), look(0, 0, 0)), ("B", "*U1")); + } + #[test] fn rect_items_go_column_row_level() { let items = rect(3, 2).items().unwrap_or_default(); diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index c22a6df86..ded8271c5 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -674,6 +674,10 @@ fn apply( /// Associative hatches of block `b` whose loop is one closed polyline of the block take its /// outline again (it may have been stretched). fn refill_hatches(b: &mut Block) { + // Each loop gets its own copy of the outline, so many small loops on one big outline multiply it; + // past this many vertices in all, the remaining loops keep the outline they have. + const MAX_REFILLED_VERTICES: usize = 4_000_000; + let mut budget = MAX_REFILLED_VERTICES; let outlines: HashMap> = b .entities .iter() @@ -689,7 +693,9 @@ fn refill_hatches(b: &mut Block) { for l in &mut hh.loops { if let [s] = l.sources.as_slice() && let Some(vs) = outlines.get(s) + && let Some(left) = budget.checked_sub(vs.len()) { + budget = left; l.vertices.clone_from(vs); } } diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index 0b416b836..cb070e6b5 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -491,11 +491,18 @@ impl DimStyle { use serde_json::Value; let mut rejected = Vec::new(); let Ok(mut cur) = serde_json::to_value(&*self) else { return src.keys().cloned().collect() }; + // Spellings of one field (`DIMPOST`, `dimpost`, `textPrefix`…): only the last is applied, so + // the style is checked once per field, not once per spelling (each check copies its strings). + let last_spelling: std::collections::HashMap<&str, &String> = + src.keys().filter_map(|k| DimStyle::field_name(k).filter(|f| *f != "name").map(|f| (f, k))).collect(); for (k, v) in src { let Some(field) = DimStyle::field_name(k).filter(|f| *f != "name") else { rejected.push(k.clone()); continue; }; + if last_spelling.get(field) != Some(&k) { + continue; + } let Some(obj) = cur.as_object_mut() else { break }; let Some(old) = obj.get(field).cloned() else { rejected.push(k.clone()); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index ec3f38ebb..1f11ba494 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -714,3 +714,14 @@ fn space_names_its_tab() { assert_eq!(p.layout(), Some("Sheet A")); assert_eq!(p.tab_name(), "Sheet A"); } + +/// Several spellings of one DIM field apply once, the last in the map's order, and none is rejected. +#[test] +fn dim_style_spellings_of_one_field_apply_once() { + let mut st = DimStyle::default(); + let m = serde_json::json!({ "textHeight": 2.5, "TEXTHEIGHT": 3.5, "DIMTXT": 4.5 }); + let m = m.as_object().unwrap(); + let want = m.values().next_back().and_then(serde_json::Value::as_f64).unwrap(); + assert!(st.apply_fields(m).is_empty()); + assert_eq!(st.text_height, want); +} diff --git a/crates/engine/src/cmd/array/edit.rs b/crates/engine/src/cmd/array/edit.rs index 21bf6b132..93b515b4a 100644 --- a/crates/engine/src/cmd/array/edit.rs +++ b/crates/engine/src/cmd/array/edit.rs @@ -188,8 +188,9 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32) let mut best: Option<((u32, u32, u32), f64)> = None; // Each block's own extents, measured once. let mut extents: HashMap = HashMap::new(); + let block_for = p.block_lookup(); for it in p.items()? { - let name = p.block_for(it.i, it.j, it.level); + let name = block_for(it.i, it.j, it.level); let (base, local) = match extents.get(name) { Some(x) => *x, None => { diff --git a/crates/engine/src/cmd/curves.rs b/crates/engine/src/cmd/curves.rs index ca918834a..218a512ed 100644 --- a/crates/engine/src/cmd/curves.rs +++ b/crates/engine/src/cmd/curves.rs @@ -453,14 +453,32 @@ impl Chain { } /// Point and unit tangent at arc length `d` from the start (clamped). pub fn at_length(&self, d: f64) -> Option<(Vec2, Vec2)> { - let mut acc = 0.0; - for s in &self.segs { - let l = s.len(); - if d <= acc + l + 1e-12 && l > 0.0 { - let t = ((d - acc) / l).clamp(0.0, 1.0); - return Some((s.at(t), s.tangent(t))); - } - acc += l; + self.at_length_in(&self.end_lengths(), d) + } + /// The arc length from the chain's start to the end of each segment, for [`Self::at_length_in`]. + pub fn end_lengths(&self) -> Vec { + self.segs + .iter() + .scan(0.0, |acc, s| { + *acc += s.len(); + Some(*acc) + }) + .collect() + } + /// [`Self::at_length`] with the segment end lengths computed once (`ends` from + /// [`Self::end_lengths`]), so many samples along one chain each cost a binary search. + pub fn at_length_in(&self, ends: &[f64], d: f64) -> Option<(Vec2, Vec2)> { + let first = ends.partition_point(|e| d > e + 1e-12); + // A segment of no length can't hold the point; the next one that has length does. + // `ends` never decreases, so the first segment past `first` with length is found by search + // (a run of zero-length segments can be long) instead of a scan. + let base = first.checked_sub(1).and_then(|p| ends.get(p)).copied().unwrap_or(0.0); + let i = first + ends.get(first..).unwrap_or_default().partition_point(|e| *e <= base); + let i = (i < self.segs.len()).then_some(i); + if let Some(s) = i.and_then(|i| self.segs.get(i)) { + let start = i.and_then(|i| i.checked_sub(1)).and_then(|p| ends.get(p)).copied().unwrap_or(0.0); + let t = ((d - start) / s.len()).clamp(0.0, 1.0); + return Some((s.at(t), s.tangent(t))); } self.segs.last().map(|s| (s.end(), s.tangent(1.0))) } @@ -640,6 +658,34 @@ pub fn reverse_vertices(vs: &[PolyVertex], closed: bool) -> Vec { mod tests { use super::*; + /// The indexed lookup gives the point and tangent a scan from the start gives, also past the + /// ends and over a segment of no length. + #[test] + fn at_length_in_matches_a_scan() { + let l = |a: (f64, f64), b: (f64, f64)| Segment::Line(Line::new(Vec2::new(a.0, a.1), Vec2::new(b.0, b.1))); + let c = Chain { + segs: vec![l((0.0, 0.0), (0.0, 0.0)), l((0.0, 0.0), (4.0, 0.0)), l((4.0, 0.0), (4.0, 0.0)), l((4.0, 0.0), (4.0, 3.0))], + closed: false, + }; + let ends = c.end_lengths(); + for d in [-1.0, 0.0, 1.5, 4.0, 4.0 + 1e-13, 5.0, 7.0, 9.0] { + // The scan this replaced. + let mut acc = 0.0; + let mut want = c.segs.last().map(|s| (s.end(), s.tangent(1.0))); + for s in &c.segs { + let len = s.len(); + if d <= acc + len + 1e-12 && len > 0.0 { + let t = ((d - acc) / len).clamp(0.0, 1.0); + want = Some((s.at(t), s.tangent(t))); + break; + } + acc += len; + } + assert_eq!(c.at_length_in(&ends, d), want, "d = {d}"); + assert_eq!(c.at_length(d), want); + } + } + #[test] fn arc_builders() { let a = arc_sca(Vec2::new(1.0, 0.0), Vec2::ZERO, std::f64::consts::FRAC_PI_2).unwrap(); diff --git a/crates/engine/src/cmd/draw2/divide.rs b/crates/engine/src/cmd/draw2/divide.rs index 4e92f561f..d6c3dd612 100644 --- a/crates/engine/src/cmd/draw2/divide.rs +++ b/crates/engine/src/cmd/draw2/divide.rs @@ -36,16 +36,18 @@ fn check_block(s: &Session, b: Option<&str>) -> Result<()> { pub(crate) fn divide_points(c: &Chain, n: usize) -> Vec<(Vec2, Vec2)> { let l = c.len(); let range = if c.closed { 0..n } else { 1..n }; - range.filter_map(|i| c.at_length(l * i as f64 / n as f64)).collect() + let ends = c.end_lengths(); + range.filter_map(|i| c.at_length_in(&ends, l * i as f64 / n as f64)).collect() } pub(crate) fn measure_points(c: &Chain, step: f64) -> Vec<(Vec2, Vec2)> { let l = c.len(); + let ends = c.end_lengths(); let mut out = Vec::new(); let mut k = 1usize; while (k as f64) * step < l - 1e-9 && out.len() < MAX_GEN { let d = k as f64 * step; - out.extend(c.at_length(d)); + out.extend(c.at_length_in(&ends, d)); k += 1; } out diff --git a/crates/engine/src/cmd/draw2/revcloud.rs b/crates/engine/src/cmd/draw2/revcloud.rs index 634456b05..9baaee917 100644 --- a/crates/engine/src/cmd/draw2/revcloud.rs +++ b/crates/engine/src/cmd/draw2/revcloud.rs @@ -58,8 +58,9 @@ pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, re closed: true, }; let k = ((perim / arc_len).round() as usize).clamp(3, MAX_GEN); + let ends = chain.end_lengths(); for j in 0..k { - out.extend(chain.at_length(perim * j as f64 / k as f64).map(|x| x.0)); + out.extend(chain.at_length_in(&ends, perim * j as f64 / k as f64).map(|x| x.0)); } } let b = if reverse { -0.5 } else { 0.5 }; diff --git a/crates/engine/src/cmd/modify2/patharray.rs b/crates/engine/src/cmd/modify2/patharray.rs index dd9597177..f06c85701 100644 --- a/crates/engine/src/cmd/modify2/patharray.rs +++ b/crates/engine/src/cmd/modify2/patharray.rs @@ -34,10 +34,12 @@ pub(crate) fn arraypath( _ => (6, if c.closed { l / 6.0 } else { l / 5.0 }), }; 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()) }; + // Segment end lengths once: each sample is then a binary search, not a scan from the start. + let ends = c.end_lengths(); + let Some((p0, t0)) = c.at_length_in(&ends, 0.0) else { return Ok(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 Some((p, t)) = c.at_length_in(&ends, 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); diff --git a/crates/render/src/table.rs b/crates/render/src/table.rs index 741ffd410..146918d04 100644 --- a/crates/render/src/table.rs +++ b/crates/render/src/table.rs @@ -133,6 +133,20 @@ pub fn table_geometry(d: &Drawing, t: &Table) -> TableGeom { if parts.len() <= 1 { return layout(d, t); } + // Every part is laid out and kept, so the cells of all of them count together (a header repeated + // on each part adds to each); past the limit only the table's outline is drawn. + let cols = t.col_widths.len().min(10_000); + let total: usize = parts.iter().map(|p| p.rows.len().min(10_000).saturating_mul(cols)).fold(0, usize::saturating_add); + if total > MAX_LAYOUT_CELLS { + // One outline per part, at the part's origin and as tall as its displayed rows. + let w = edges(&t.col_widths, cols).last().copied().unwrap_or(0.0); + let mut g = TableGeom::default(); + for p in parts { + let h: f64 = p.rows.iter().take(10_000).map(|r| t.row_heights.get(*r).copied().filter(|v| v.is_finite()).unwrap_or(0.0)).sum(); + outline_box(&mut g, p.origin, w, h); + } + return g; + } let mut g = TableGeom::default(); for p in parts { let mut pg = layout(d, &part_table(t, &p.rows, p.origin)); @@ -156,16 +170,20 @@ fn part_table(t: &Table, rows: &[usize], origin: Vec2) -> Table { // Otherwise `layout` renders an outline, so materialising millions of empty cells here would be // wasted work an attacker can trigger with a compact dimension array (CWE-789). if rows.len().min(10_000).saturating_mul(cols) <= MAX_LAYOUT_CELLS { + // `run[i]`: how many rows from part row `i` follow one another in the table, found once so a + // merge is cut by a lookup, not by walking the rows it spans. + let mut run = vec![1u32; rows.len()]; + for i in (0..rows.len().saturating_sub(1)).rev() { + if rows.get(i + 1).zip(rows.get(i)).is_some_and(|(next, this)| *next == this + 1) { + run[i] = run.get(i + 1).copied().unwrap_or(0).saturating_add(1); + } + } for (i, row) in cells.iter_mut().enumerate() { row.resize_with(cols, Default::default); for cell in row.iter_mut() { if let Some((rs, cs)) = cell.merged { // Rows of the merge that follow in this part. - let start = rows.get(i).copied().unwrap_or(0); - let mut n = 1u32; - while n < rs && rows.get(i + n as usize).is_some_and(|r| *r == start + n as usize) { - n += 1; - } + let n = rs.max(1).min(run.get(i).copied().unwrap_or(1)); cell.merged = (n > 1 || cs > 1).then_some((n, cs)); } } @@ -186,6 +204,27 @@ fn part_table(t: &Table, rows: &[usize], origin: Vec2) -> Table { } } +/// The table's outline alone, for a table too large to lay out. +fn outline(t: &Table) -> TableGeom { + let rows = t.row_heights.len().min(10_000); + let cols = t.col_widths.len().min(10_000); + let (w, h) = (edges(&t.col_widths, cols).last().copied().unwrap_or(0.0), edges(&t.row_heights, rows).last().copied().unwrap_or(0.0)); + let mut g = TableGeom::default(); + outline_box(&mut g, t.insert.xy(), w, h); + g +} + +/// The four sides of a `w` by `h` box hanging down from `o`. +fn outline_box(g: &mut TableGeom, o: Vec2, w: f64, h: f64) { + let p = |x: f64, y: f64| o + Vec2::new(x, -y); + let corners = [p(0.0, 0.0), p(w, 0.0), p(w, h), p(0.0, h), p(0.0, 0.0)]; + for s in corners.windows(2) { + if let [a, b] = s { + g.lines.push(TableLine { a: *a, b: *b, color: Color::ByBlock, lineweight: Lineweight::ByBlock }); + } + } +} + /// Lay out one part. fn layout(d: &Drawing, t: &Table) -> TableGeom { let st = table_style_of(d, t); @@ -203,14 +242,7 @@ fn layout(d: &Drawing, t: &Table) -> TableGeom { } let cov = coverage(t); if rows.saturating_mul(cols) > MAX_LAYOUT_CELLS || cov.is_err() { - let (w, h) = (x_at(cols), y_at(rows)); - let corners = [p(0.0, 0.0), p(w, 0.0), p(w, h), p(0.0, h), p(0.0, 0.0)]; - for s in corners.windows(2) { - if let [a, b] = s { - g.lines.push(TableLine { a: *a, b: *b, color: Color::ByBlock, lineweight: Lineweight::ByBlock }); - } - } - return g; + return outline(t); } let k = style_scale(&st, t); // Cell styles by name, scaled to the table. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index cbbc83ca9..f35e7132a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1165,3 +1165,25 @@ fn without_linetypes_every_line_is_drawn_whole() { 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()); } + +/// A broken table whose parts, with their repeated labels, together hold more cells than a table may +/// lay out is drawn as its outline, though the table's own cells are within the limit. +#[test] +fn broken_table_cells_count_across_its_parts() { + let d = Drawing::new_imperial(); + let t = cadcraft_doc::Table { + col_widths: vec![1.0; 600], + row_heights: vec![1.0; 1000], + title: true, + header: true, + breaks: Some(cadcraft_doc::TableBreak { enabled: true, height: 3.0, ..Default::default() }), + ..Default::default() + }; + assert!(t.parts().len() > 500 && 1000 * 600 <= crate::MAX_LAYOUT_CELLS); + let g = crate::table_geometry(&d, &t); + let parts = t.parts(); + assert_eq!((g.lines.len(), g.texts.len(), g.fills.len()), (4 * parts.len(), 0, 0)); + // Each part's box starts at its own origin. + let top = |i: usize| g.lines[4 * i].a; + assert!((0..parts.len()).all(|i| top(i) == parts[i].origin)); +} From 6d744887f445bb98ac8c81bfdf79db67b1e23757 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 21:33:51 -0500 Subject: [PATCH 180/185] fix(mcp): send the control token only to 127.0.0.1:PORT and read it only from a private file (#2718) The bridge picked the token by port alone and sent it to whatever the address resolved to, so a listener another account opened on ::1 with the same port received the desktop's credential. The token is now attached only when the connected peer is exactly 127.0.0.1:PORT, where the app listens. Reading the token refuses a symlink, a non-plain file and a file others can read, and the shared temporary directory is no longer a fallback location for it. --- Cargo.lock | 1 + crates/mcp/Cargo.toml | 3 +++ crates/mcp/src/backend.rs | 45 ++++++++++++++++++++++++++----- crates/mcp/src/control_token.rs | 48 +++++++++++++++++++++++++++++++-- 4 files changed, 88 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9b3467cfb..f36c9607c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -776,6 +776,7 @@ dependencies = [ "cadcraft-render", "clap", "getrandom 0.4.3", + "libc", "log", "serde_json", "tiny-skia", diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index dc5d8ca2a..cb597504f 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -21,3 +21,6 @@ getrandom = "0.4" [dev-dependencies] # Reads the pixels of rendered PNGs in the tests. tiny-skia = { workspace = true } +[target.'cfg(unix)'.dependencies] +# O_NOFOLLOW when reading the token file (MIT OR Apache-2.0). +libc = "0.2" diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index d1ac6727d..efdb9c9ea 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -1,7 +1,7 @@ //! Where MCP tool calls end up: a control-channel method call. use std::io::{BufRead, BufReader, Read, Write}; -use std::net::{TcpStream, ToSocketAddrs}; +use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs}; use std::time::Duration; use cadcraft_engine::Session; @@ -76,9 +76,17 @@ impl Remote { /// The per-session token for this port, read (and cached) from the owner-only token file. A /// missing file is not fatal here: the request is sent without a token and the server replies /// with an authentication error the user can act on. + /// + /// The desktop app listens only on `127.0.0.1:PORT`, so the token goes only to that exact + /// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account + /// may listen on the same port) must not be handed the desktop's credential (CWE-522). fn token(&mut self) -> Option<&str> { + let port = port_of(&self.addr)?; + let peer = self.conn.as_ref().and_then(|(_, s)| s.peer_addr().ok()); + if peer != Some(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) { + return None; + } if self.token.is_none() - && let Some(port) = port_of(&self.addr) && let Ok(t) = crate::control_token::read(port) { self.token = Some(t); @@ -207,6 +215,14 @@ fn is_read_only(method: &str) -> bool { impl Remote { /// Put the current token (if any) on `req`, replacing the one it carries. + /// Connect if needed, put the token for the peer actually connected to on `req`, and send it. + fn sign_and_send(&mut self, req: &mut Value) -> Result { + if self.conn.is_none() { + self.reach().map_err(|e| (e, false))?; + } + self.set_token(req); + self.roundtrip(&req.to_string()) + } fn set_token(&mut self, req: &mut Value) { let token = self.token().map(str::to_string); if let Some(obj) = req.as_object_mut() { @@ -219,7 +235,7 @@ impl Remote { /// Send `req` and parse the reply, refreshing the token before a safe retry after a transport /// error. A mutation that may have reached the server is never resent automatically. fn exchange(&mut self, method: &str, req: &mut Value) -> Result { - let reply = match self.roundtrip(&req.to_string()) { + let reply = match self.sign_and_send(req) { Ok(r) => r, Err((e, sent)) => { self.token = None; @@ -232,8 +248,7 @@ impl Remote { )); } // A restarted server may have rotated its token before dropping the old socket. - self.set_token(req); - self.roundtrip(&req.to_string()).map_err(|(e, _)| { + self.sign_and_send(req).map_err(|(e, _)| { self.token = None; self.conn = None; format!("CADCraft at {}: {e}", self.addr) @@ -256,14 +271,12 @@ impl Backend for Remote { let id = self.next_id; self.next_id += 1; let mut req = json!({"id": id, "method": method, "params": params}); - self.set_token(&mut req); let mut v = self.exchange(method, &mut req)?; // The token is read before `--launch` opens the app, which then writes a new one (#2087); the // file can also be left over from an earlier session. Once, so a wrong token can't loop. if unauthorized(&v) && v.get("state").and_then(Value::as_str) == Some("not-run") { self.token = None; self.conn = None; - self.set_token(&mut req); v = self.exchange(method, &mut req)?; } if v.get("ok").and_then(Value::as_bool) == Some(true) { @@ -595,6 +608,24 @@ mod tests { }) } + /// A listener on another loopback address with the desktop's port (here `::1`) never receives + /// the desktop's token. + #[test] + fn token_is_not_sent_to_another_loopback_listener() { + let Ok(listener) = TcpListener::bind("[::1]:0") else { return }; + let addr = listener.local_addr().unwrap(); + crate::control_token::issue(addr.port()).unwrap(); + let server = fake_app(listener, move |req, _| { + assert!(req.get("token").is_none(), "token leaked to {addr}"); + json!({"ok": true, "result": "x"}) + }); + let mut remote = Remote::lazy(&addr.to_string(), false); + let got = remote.call("ping", json!({})); + crate::control_token::revoke(addr.port()); + assert_eq!(got, Ok(json!("x"))); + assert_eq!(server.join().unwrap(), 1); + } + /// `--launch` reads the token before it opens the app, so the first request carries the token /// of an earlier session (or none); the app refuses it without running it, and the call is /// resent once with the token the app has just written (#2087). diff --git a/crates/mcp/src/control_token.rs b/crates/mcp/src/control_token.rs index 084f8b455..97052be60 100644 --- a/crates/mcp/src/control_token.rs +++ b/crates/mcp/src/control_token.rs @@ -32,7 +32,9 @@ fn private_dir() -> io::Result { if let Some(h) = std::env::var_os("HOME").filter(|v| !v.is_empty()) { return Ok(PathBuf::from(h).join(".cache")); } - Ok(std::env::temp_dir()) + // The shared temporary directory would put the credential at a path any local account can + // predict and plant a link at: refuse instead. + Err(io::Error::new(io::ErrorKind::NotFound, "XDG_RUNTIME_DIR or HOME is required for a private control token")) } /// Require the Windows per-user local app-data directory for session token storage. @@ -75,7 +77,31 @@ fn issue_at(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> { /// Read the token for `port`, trimming trailing whitespace. Used by clients (the MCP bridge). pub fn read(port: u16) -> io::Result { - let raw = std::fs::read_to_string(token_path(port)?)?; + read_at(&token_path(port)?) +} + +/// Read a token file the issuer wrote: not through a link, a plain file, and (Unix) readable by +/// its owner only, so a file another account planted or left open is not taken as the credential. +fn read_at(path: &std::path::Path) -> io::Result { + use std::io::Read; + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = options.open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(io::Error::new(io::ErrorKind::InvalidData, "the control token is not a plain file")); + } + #[cfg(unix)] + if std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o077 != 0 { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "the control token file is readable by other users")); + } + let mut raw = String::new(); + file.take(1024).read_to_string(&mut raw)?; let token = raw.trim().to_string(); if token.is_empty() { return Err(io::Error::new(io::ErrorKind::InvalidData, "empty control token")); @@ -181,6 +207,24 @@ mod tests { assert_eq!(windows_private_dir(Some("private-app-data".into())).unwrap(), PathBuf::from("private-app-data")); } + /// A link, or a file other users can read, is not accepted as the token. + #[cfg(unix)] + #[test] + fn read_refuses_links_and_shared_files() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("cadcraft-token-read-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let secret = dir.join("secret"); + issue_at(&secret, b"abc").unwrap(); + assert_eq!(read_at(&secret).unwrap(), "abc"); + let link = dir.join("link"); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + assert!(read_at(&link).is_err()); + std::fs::set_permissions(&secret, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!(read_at(&secret).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + /// Token issuance creates its missing directory hierarchy before writing the credential. #[test] fn issuance_creates_missing_parent() { From 7e780548beed32b0ed997e0b4ef3eb3e47a35217 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 03:16:11 -0500 Subject: [PATCH 181/185] fix: bound MOCORO copies, array EXPLODE, COMPARE bounds, attribute extraction, PDF links and control-server parsing (#2738) * fix: bound MOCORO copies, array EXPLODE, COMPARE bounds, attribute extraction, PDF links and control-server parsing * address review: key extract cache by exact block, count live MOCORO objects, PDF link budget * review: select extraction columns before copying values, count live objects for MOCORO copies * address review: count exploded array objects before cloning; scan each block's constants once --- apps/cadcraft/src/control_server.rs | 13 ++-- crates/engine/src/cmd/array.rs | 26 ++++++- crates/engine/src/cmd/blocks/extract.rs | 90 ++++++++++++++++++++----- crates/engine/src/cmd/file/compare.rs | 20 +++--- crates/engine/src/cmd/modify2/mocoro.rs | 12 ++++ crates/engine/tests/it/mocoro.rs | 14 ++++ crates/io/src/pdf.rs | 20 +++++- crates/ui-egui/src/managers.rs | 9 +-- 8 files changed, 166 insertions(+), 38 deletions(-) diff --git a/apps/cadcraft/src/control_server.rs b/apps/cadcraft/src/control_server.rs index d502e1408..88007b889 100644 --- a/apps/cadcraft/src/control_server.rs +++ b/apps/cadcraft/src/control_server.rs @@ -250,17 +250,18 @@ fn parse_line(bytes: &[u8]) -> Line { Ok(v) => v, Err(e) => return Line::Reject(format!("bad JSON ({e}); expected one JSON request object per line; closing the connection")), }; - let Some(obj) = msg.as_object() else { + let Value::Object(mut obj) = msg else { return Line::Reject("not a control request (expected a JSON object); closing the connection".into()); }; - let Some(method) = obj.get("method").and_then(Value::as_str) else { + let Some(Value::String(method)) = obj.remove("method") else { return Line::Reject("not a control request (missing string `method`); closing the connection".into()); }; + // Moved out of the parsed object, not cloned: `params` can be most of the line. Line::Request { - id: obj.get("id").cloned().unwrap_or(Value::Null), - method: method.to_string(), - params: obj.get("params").cloned().unwrap_or(json!({})), - token: obj.get("token").and_then(Value::as_str).map(str::to_string), + id: obj.remove("id").unwrap_or(Value::Null), + method, + params: obj.remove("params").unwrap_or(json!({})), + token: obj.remove("token").and_then(|t| if let Value::String(t) = t { Some(t) } else { None }), } } diff --git a/crates/engine/src/cmd/array.rs b/crates/engine/src/cmd/array.rs index a443e03f8..1cc97a496 100644 --- a/crates/engine/src/cmd/array.rs +++ b/crates/engine/src/cmd/array.rs @@ -178,14 +178,34 @@ fn create(s: &mut Session, objs: &[Handle], base: Vec2, p: ArrayParams, assoc: b Ok(json!({ "created": n })) } +/// The most objects EXPLODE of one associative array makes from its source objects (ten times the +/// default MAXARRAY). +const MAX_EXPLODED_OBJECTS: usize = 1_000_000; + /// EXPLODE of an associative array: every item becomes the objects of its block (the source /// objects, or a replacement block's reference), in world coordinates. `None` for other objects. +/// +/// An array that would explode into more than [`MAX_EXPLODED_OBJECTS`] objects (items times the +/// objects of the source block, which a file sets freely) is not expanded here: `None`, so EXPLODE +/// takes the array block's own items. pub(crate) fn explode_array(d: &Drawing, e: &Entity) -> Option> { let EntityKind::Insert(ins) = &e.kind else { return None }; let p = d.array_params(e)?; let blk = d.block(&ins.block)?; let m = ins.transform(blk.base.xy()); - let mut out = Vec::new(); + // Count first: a hostile array must be refused before any entity is cloned. + let total = blk + .entities + .iter() + .map(|it| match &it.kind { + EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(&p.source) => d.block(&i.block).map_or(1, |b| b.entities.len()), + _ => 1, + }) + .fold(0usize, usize::saturating_add); + if total > MAX_EXPLODED_OBJECTS { + return None; + } + let mut out = Vec::with_capacity(total); for item in blk.entities.iter() { let item = placed(e, item, &m); let source = match &item.kind { @@ -193,7 +213,9 @@ pub(crate) fn explode_array(d: &Drawing, e: &Entity) -> Option> { _ => None, }; match source { - Some((im, b)) => out.extend(b.entities.iter().map(|se| placed(&item, se, &im))), + Some((im, b)) => { + out.extend(b.entities.iter().map(|se| placed(&item, se, &im))); + } None => out.push(item), } } diff --git a/crates/engine/src/cmd/blocks/extract.rs b/crates/engine/src/cmd/blocks/extract.rs index 10785f08f..de85956c7 100644 --- a/crates/engine/src/cmd/blocks/extract.rs +++ b/crates/engine/src/cmd/blocks/extract.rs @@ -2,9 +2,9 @@ //! block name and values, or one row per reference with its handle, layer, position and //! rotation — returned, written to a CSV file and/or inserted as a table. Tags match in any case. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; -use cadcraft_doc::{EntityKind, Insert}; +use cadcraft_doc::{Drawing, EntityKind, Insert}; use cadcraft_geom::Vec2; use serde_json::{Value, json}; @@ -88,22 +88,75 @@ fn matches(spec: &str, text: &str) -> bool { spec.split(',').any(|p| wildcard(p.trim(), text)) } -/// The attribute values of `ins`: its own, then the constant ones of its block. -fn values(d: &cadcraft_doc::Drawing, ins: &Insert) -> Vec<(String, String)> { - let mut v: Vec<(String, String)> = ins.attribs.iter().map(|a| (a.tag.to_ascii_uppercase(), a.text.value.clone())).collect(); - if let Some(b) = d.block(&ins.block) { - for e in b.entities.iter() { - if let EntityKind::AttDef(a) = &e.kind - && a.constant - && !v.iter().any(|(t, _)| t.eq_ignore_ascii_case(&a.tag)) - { - v.push((a.tag.to_ascii_uppercase(), a.text.value.clone())); - } +/// The constant attribute values of a block definition whose tags are selected for output. +fn constants(b: &cadcraft_doc::Block, selected: &[String]) -> Vec<(String, String)> { + let mut v: Vec<(String, String)> = Vec::new(); + for e in b.entities.iter() { + if let EntityKind::AttDef(a) = &e.kind + && a.constant + && selected.iter().any(|tag| tag == &a.tag.to_ascii_uppercase()) + && !v.iter().any(|(t, _)| t.eq_ignore_ascii_case(&a.tag)) + { + v.push((a.tag.to_ascii_uppercase(), a.text.value.clone())); } } v } +/// The attribute values of `ins` that `o.tags` selects: its own, then the constant ones of its +/// block (`consts`, read once per block). Values no column shows are not copied. +fn values(ins: &Insert, consts: &[(String, String)], selected: &[String]) -> Vec<(String, String)> { + let mut v: Vec<(String, String)> = ins + .attribs + .iter() + .map(|a| (a.tag.to_ascii_uppercase(), a)) + .filter(|(t, _)| selected.contains(t)) + .map(|(t, a)| (t, a.text.value.clone())) + .collect(); + for (t, val) in consts { + if !v.iter().any(|(k, _)| k.eq_ignore_ascii_case(t)) { + v.push((t.clone(), val.clone())); + } + } + v +} + +/// Select the output columns before copying any attribute text. A block definition can contain +/// many large constants that do not survive the table's 190-column limit. +fn selected_tags(ents: &[std::sync::Arc], d: &Drawing, o: &Options) -> Vec { + let mut selected = Vec::new(); + let mut add = |tag: &str| { + let tag = tag.to_ascii_uppercase(); + if selected.len() < MAX_TAGS && matches(&o.tags, &tag) && !selected.contains(&tag) { + selected.push(tag); + } + }; + let mut scanned = std::collections::HashSet::new(); + for entity in ents { + let EntityKind::Insert(ins) = &entity.kind else { continue }; + let anonymous = ins.block.starts_with('*') || d.block(&ins.block).is_some_and(|b| b.anonymous); + if anonymous || !matches(&o.blocks, &ins.block) { + continue; + } + for attribute in &ins.attribs { + add(&attribute.tag); + } + // A block's constants are read once, however many inserts reference it. + if scanned.insert(ins.block.as_str()) + && let Some(block) = d.block(&ins.block) + { + for entity in block.entities.iter() { + if let EntityKind::AttDef(attribute) = &entity.kind + && attribute.constant + { + add(&attribute.tag); + } + } + } + } + selected +} + /// The block references to extract from: `handles` when given, else model space and the layouts. fn found(s: &Session, p: &Value, o: &Options) -> Result> { let d = s.doc()?; @@ -112,7 +165,9 @@ fn found(s: &Session, p: &Value, o: &Options) -> Result> { } else { d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).cloned().collect() }; + let selected = selected_tags(&ents, d, o); let mut out = Vec::new(); + let mut consts: HashMap> = HashMap::new(); for e in &ents { let EntityKind::Insert(ins) = &e.kind else { continue }; let anonymous = ins.block.starts_with('*') || d.block(&ins.block).is_some_and(|b| b.anonymous); @@ -121,12 +176,17 @@ fn found(s: &Session, p: &Value, o: &Options) -> Result> { } let block = d.block(&ins.block).map(|b| b.name.clone()).unwrap_or_else(|| ins.block.clone()); out.push(Found { - block, handle: e.handle.hex(), layer: e.common.layer.clone(), at: ins.insert.xy(), rotation: ins.rotation.to_degrees(), - values: values(d, ins), + block: block.clone(), + values: values( + ins, + // Keyed by the resolved definition's exact name: `Part` and `PART` can both exist. + consts.entry(block.clone()).or_insert_with(|| d.block(&ins.block).map(|b| constants(b, &selected)).unwrap_or_default()), + &selected, + ), }); } Ok(out) diff --git a/crates/engine/src/cmd/file/compare.rs b/crates/engine/src/cmd/file/compare.rs index 273ec1ac7..5de5d8387 100644 --- a/crates/engine/src/cmd/file/compare.rs +++ b/crates/engine/src/cmd/file/compare.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, MAX_BLOCK_DEPTH, Space, entity_bounds}; +use cadcraft_doc::{BlockBoundsCache, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_DEPTH, Space, entity_bounds_cached}; use cadcraft_geom::{Bounds2, Vec2}; use serde_json::{Value, json}; @@ -375,16 +375,20 @@ fn run_compare(s: &mut Session, p: &Value) -> Result { } let Diff { added, removed, changed, common, truncated } = diff(&cur, &other, &space); let mut boxes = Vec::new(); - let mut bound = |d: &Drawing, h: Handle| { - if let Some(b) = d.entity(h).map(|e| entity_bounds(d, e, 0)).filter(|b| !b.is_empty() && b.min.is_finite() && b.max.is_finite()) { + // One block-bounds cache for each drawing, so a block many differing entities refer to is + // measured once, not once per entity. + let (mut cur_cache, mut other_cache) = (BlockBoundsCache::default(), BlockBoundsCache::default()); + fn bound<'a>(boxes: &mut Vec, d: &'a Drawing, h: Handle, cache: &mut BlockBoundsCache<'a>) { + if let Some(b) = d.entity(h).map(|e| entity_bounds_cached(d, e, 0, cache)).filter(|b| !b.is_empty() && b.min.is_finite() && b.max.is_finite()) + { boxes.push(b); } - }; - added.iter().for_each(|h| bound(&cur, *h)); - removed.iter().for_each(|h| bound(&other, *h)); + } + added.iter().for_each(|h| bound(&mut boxes, &cur, *h, &mut cur_cache)); + removed.iter().for_each(|h| bound(&mut boxes, &other, *h, &mut other_cache)); for (a, b, _, _) in &changed { - bound(&cur, *a); - bound(&other, *b); + bound(&mut boxes, &cur, *a, &mut cur_cache); + bound(&mut boxes, &other, *b, &mut other_cache); } let regions = regions(&boxes); let ch: Vec = changed diff --git a/crates/engine/src/cmd/modify2/mocoro.rs b/crates/engine/src/cmd/modify2/mocoro.rs index 47d6833fb..6954919bf 100644 --- a/crates/engine/src/cmd/modify2/mocoro.rs +++ b/crates/engine/src/cmd/modify2/mocoro.rs @@ -117,6 +117,12 @@ pub(super) fn run_mocoro(s: &mut Session, p: &Value) -> Result { _ => {} } } + // Each Copy clones every selected object: the copies together stay within MAXARRAY, as an array's do. + // Erased handles are skipped by `apply`, so only live objects count (none: nothing is copied). + let live = counts(s, &objs)?.0; + if live > 0 { + crate::cmd::array::check_size(s, ops.iter().filter(|o| matches!(o, Op::Copy(_))).count() as u64, live)?; + } let mut copies = Vec::new(); for op in ops { copies.extend(apply(s, &objs, &mut base, op)?); @@ -150,6 +156,12 @@ pub(super) struct MocoroM { impl MocoroM { fn run(&mut self, s: &mut Session, op: Op) -> Result { + if matches!(op, Op::Copy(_)) { + let live = counts(s, &self.objs)?.0; + if live > 0 { + crate::cmd::array::check_size(s, 1, live)?; + } + } let before = s.state()?.doc.clone(); let base = self.base; apply(s, &self.objs, &mut self.base, op)?; diff --git a/crates/engine/tests/it/mocoro.rs b/crates/engine/tests/it/mocoro.rs index 88fb8c4ee..8d1ff521c 100644 --- a/crates/engine/tests/it/mocoro.rs +++ b/crates/engine/tests/it/mocoro.rs @@ -233,3 +233,17 @@ fn options_on_objects_that_are_gone_record_nothing() { assert!(lines(&s).is_empty()); assert_eq!(undo_len(&s), undo, "no empty undo step"); } + +#[test] +fn json_form_copies_stay_within_maxarray() { + let mut s = Session::new(); + let l = line(&mut s, [0.0, 0.0], [10.0, 0.0]); + // 5,000 Copy options of 30 objects would be 150,000 copies, over the default MAXARRAY of 100,000. + let others: Vec = (0..29).map(|i| line(&mut s, [0.0, f64::from(i + 1)], [10.0, f64::from(i + 1)])).collect(); + let mut hs = vec![l]; + hs.extend(others); + let ops: Vec = (0..5_000).map(|i| json!({"copy": [0, i]})).collect(); + let e = s.execute("mocoro", &json!({"handles": hs, "base": [0, 0], "ops": ops})).unwrap_err(); + assert!(e.to_string().contains("MAXARRAY"), "{e}"); + assert_eq!(lines(&s).len(), 30, "nothing was copied"); +} diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 6d9a69bf1..c27a7b5dc 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -50,6 +50,8 @@ const MAX_LAYER_NAME: usize = 1000; /// Most link annotations in one file, and the longest link target (bytes). const MAX_LINKS: usize = 10_000; const MAX_URL: usize = 2048; +/// The most link annotations in one PDF, over all pages (a page holds at most [`MAX_LINKS`]). +const MAX_FILE_ANNOTATIONS: usize = 100_000; /// Longest title and page label written (characters). const MAX_TEXT: usize = 1000; @@ -357,7 +359,10 @@ fn sheet_name(space: &Space) -> String { /// Write a vector PDF with one page per space (at most [`MAX_PAGES`]), each labelled with its /// layout name. The options apply to every sheet; layouts use their own page setups. pub fn pdf_sheets(d: &Drawing, spaces: &[Space], o: &PdfOptions) -> Result> { - let items: Vec<(Space, PdfOptions)> = spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), o.clone())).collect(); + // Links are file-wide (`pdf_items` reads them from `o`), so a sheet's own options carry none: + // a copy of the list per sheet multiplied it by the sheet count. + let sheet = PdfOptions { links: Vec::new(), ..o.clone() }; + let items: Vec<(Space, PdfOptions)> = spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect(); pdf_items(d, &items, o) } @@ -453,8 +458,16 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as let mut writer = Writer::new(settings, metadata); let mut fonts = fonts::Fonts::new(!text_as_geometry); let mut groups = Groups::default(); + // Link annotations of the whole file: each page keeps its own copy of the targets, so the + // pages times the links must not multiply without a bound. + let mut annotations_left = MAX_FILE_ANNOTATIONS; for (s, po) in items { - let page = sheet(drawn, s, po, &links)?; + // Once the budget is spent no link is built (scanned and cloned) for later pages. + let mut page = sheet(drawn, s, po, if annotations_left == 0 { &links[..0] } else { &links })?; + // Only targets `write_page` accepts count against the budget. + page.links.retain(|(_, url)| uri(url).is_some()); + page.links.truncate(annotations_left); + annotations_left -= page.links.len(); let doc = writer.document_mut(); // Groups are added to the document, so they must exist before the page starts. groups.add(doc, d, &page.layers); @@ -625,7 +638,8 @@ pub(crate) fn placement(space: &Space, bounds: &Bounds2, fit: bool, sheet: &Shee /// The hyperlinks to plot: the options' own, then (with [`PdfOptions::hyperlinks`]) those the /// drawing file gave its entities as `PE_URL` extended data, at most [`MAX_LINKS`] in all. fn all_links(d: &Drawing, o: &PdfOptions) -> Vec<(Handle, String)> { - let mut out: Vec<(Handle, String)> = o.links.iter().take(MAX_LINKS).cloned().collect(); + // A target past MAX_URL is refused at the annotation anyway; it is left out before it is copied. + let mut out: Vec<(Handle, String)> = o.links.iter().filter(|(_, u)| u.len() <= MAX_URL).take(MAX_LINKS).cloned().collect(); if !o.hyperlinks { return out; } diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index 8942741e0..e1bafb0d8 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -309,7 +309,7 @@ fn point_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action enum Field { Num(&'static str, &'static str, f64), Bool(&'static str, &'static str, bool), - Choice(&'static str, &'static str, String, Vec), + Choice(&'static str, &'static str, String, std::sync::Arc<[String]>), } struct Style { @@ -374,7 +374,8 @@ fn mleader_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Acti no_drawing(ctx, "Multileader Style", open); return None; }; - let text_styles: Vec = d.text_styles.iter().map(|s| s.name.clone()).collect(); + // One list shared by every row: a copy per style multiplied the two counts. + let text_styles: std::sync::Arc<[String]> = d.text_styles.iter().map(|s| s.name.clone()).collect(); let mut styles: Vec