From bfadb1a94edfc4e8bab5f515a93a03d30654a07b Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:09:54 -0300 Subject: [PATCH 001/187] Pin the macOS Apple-event bridge dependency Part of the tested fix for #158, adapted from #683. Full local cargo xtask ci and packaged macOS opening checks passed. --- Cargo.lock | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index c054dcfd0..614d0f039 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -554,6 +554,7 @@ dependencies = [ "cadcraft-ui-egui", "eframe", "egui", + "fmv-macos-events", "hidapi", "log", "muda", @@ -1412,6 +1413,17 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" +[[package]] +name = "fmv-macos-events" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90642cf66dde7f205dc8b42dfe57b47d0f3a29f571b832742883ef512e23fe55" +dependencies = [ + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "foldhash" version = "0.2.0" From 2a9c14e96e3bd94b5df484e3d42c95de9a17c624 Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:18:47 -0300 Subject: [PATCH 002/187] Enable the Apple-event bridge only on macOS --- apps/cadcraft/Cargo.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/cadcraft/Cargo.toml b/apps/cadcraft/Cargo.toml index ec527437d..50fd7056e 100644 --- a/apps/cadcraft/Cargo.toml +++ b/apps/cadcraft/Cargo.toml @@ -38,6 +38,11 @@ muda = { version = "0.21", default-features = false } # View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion # (system_animations.rs). Already in Cargo.lock through muda. objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] } +# Finder double-click, Open With, Dock drops and `open -a CADCraft plan.dxf` arrive as a +# kAEOpenDocuments Apple event, which winit 0.30 doesn't handle (#158). Keep the Objective-C +# handler behind a safe API, without relaxing the workspace's unsafe-code lint. +# Pinned exactly: review the implementation before bumping. +fmv-macos-events = "=0.1.0" # Rust HID backends: no proprietary SDK or C HID library. [target.'cfg(target_os = "windows")'.dependencies] From 54d0e034e4f5a3eda73d1032e6af08c5519193e2 Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:21:11 -0300 Subject: [PATCH 003/187] Connect Finder document events to the desktop application Adapted from PR #683 to current main, retaining the existing accessibility dependency and async opening behavior. Validated together with the Apple-event module and regression tests. Co-authored-by: Isaac Levine --- apps/cadcraft/src/main.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 157294ac5..e90e6f658 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -14,6 +14,8 @@ #![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(target_os = "macos")] +mod apple_events; mod control_server; mod desktop_theme; #[cfg(any(target_os = "windows", test))] @@ -39,6 +41,9 @@ struct App { workspace_error: Option, #[cfg(target_os = "macos")] native_menu: Option, + /// Drawings and quit requests from Finder, the Dock and `open -a` (see `apple_events`). + #[cfg(target_os = "macos")] + apple_events: fmv_macos_events::Inbox, } impl App { @@ -74,6 +79,7 @@ impl eframe::App for App { if let Some(m) = &mut self.native_menu { m.poll(&mut self.cad, ctx); } + apple_events::poll(&self.apple_events, &mut self.cad, ctx); } self.cad.system_animations = self.system_animations.current(); self.cad.logic(ctx); @@ -304,6 +310,12 @@ fn main() -> eframe::Result { b.with_x11(); })); } + // Registered before the event loop starts, so it catches the Finder event that launched us as + // well as later ones. Lives until the event loop returns; the app creator only borrows it. + #[cfg(target_os = "macos")] + let apple_events = apple_events::AppleEvents::install(); + #[cfg(target_os = "macos")] + let apple_events = &apple_events; eframe::run_native( "CADCraft", options, @@ -356,6 +368,14 @@ fn main() -> eframe::Result { for f in &files { app.open_path(f); } + // Start reading any launch-time documents before the first frame. Later events use + // this same inbox, including the normal unsaved-changes handling for quit requests. + #[cfg(target_os = "macos")] + let apple_events = { + let inbox = apple_events.connect(&cc.egui_ctx); + apple_events::poll(&inbox, &mut app, &cc.egui_ctx); + inbox + }; if app.session.docs.is_empty() { app.session.new_drawing(false); } @@ -372,6 +392,8 @@ fn main() -> eframe::Result { workspace_error, #[cfg(target_os = "macos")] native_menu: None, + #[cfg(target_os = "macos")] + apple_events, })) }), ) From 7dc9e0ec6f98c071cf9564139b06f04d2afa6918 Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:23:00 -0300 Subject: [PATCH 004/187] Handle Finder opens and preserve unsaved Apple-event quit prompts Add the safe macOS event bridge adapted from #683 and six opening/quit regression tests. All six cargo xtask ci gates passed, with 2,014 tests, plus packaged LaunchServices smoke tests. Co-authored-by: Isaac Levine --- apps/cadcraft/src/apple_events.rs | 195 ++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 apps/cadcraft/src/apple_events.rs diff --git a/apps/cadcraft/src/apple_events.rs b/apps/cadcraft/src/apple_events.rs new file mode 100644 index 000000000..1d68dccc1 --- /dev/null +++ b/apps/cadcraft/src/apple_events.rs @@ -0,0 +1,195 @@ +//! macOS open-documents and quit Apple events (#158). +//! +//! A Finder double-click, Open With, a drop on the Dock icon and `open -a CADCraft plan.dxf` don't +//! put the path in argv: LaunchServices sends the running (or just-launched) app a +//! `kAEOpenDocuments` ('odoc') Apple event. winit 0.30 doesn't handle it and owns the +//! `NSApplicationDelegate`, so AppKit answered "CADCraft cannot open files in the Drawing Exchange +//! Format format". Handling it ourselves needs Objective-C class declarations, i.e. `unsafe`, which +//! this workspace forbids. The pinned `fmv-macos-events` crate wraps exactly that, an +//! `NSAppleEventManager` handler registered before Finder's +//! launch event that leaves winit's delegate alone, behind a safe main-thread API. + +use std::path::PathBuf; + +use cadcraft_ui_egui::CadApp; +use fmv_macos_events::{Event, Inbox, Registration}; + +/// Keeps the Apple-event handlers registered; hold it until the event loop returns. +pub struct AppleEvents { + _registration: Registration, + inbox: Inbox, +} + +impl AppleEvents { + /// Register the handlers. Call on the main thread before the event loop starts, so the event + /// that launched the app (a Finder double-click) is caught too. + pub fn install() -> Self { + let (registration, inbox) = Registration::install(); + Self { _registration: registration, inbox } + } + + /// The queue the app drains every frame ([`poll`]); events arriving later wake `ctx`. + pub fn connect(&self, ctx: &egui::Context) -> Inbox { + let ctx = ctx.clone(); + self.inbox.set_wake(move || ctx.request_repaint()); + self.inbox.clone() + } +} + +/// The paths to hand to OPEN: UTF-8 and non-empty, each once, in the order they arrived. A second +/// copy of the same path (Finder sends one per selected item, and a drop can repeat) would open +/// the drawing twice. +fn openable(paths: impl IntoIterator) -> Vec { + let mut out: Vec = Vec::new(); + for p in paths { + if let Some(s) = p.to_str().filter(|s| !s.is_empty()) + && !out.iter().any(|o| o == s) + { + out.push(s.to_string()); + } + } + out +} + +/// Dispatch a batch through the regular opening and unsaved-changes paths. Returns whether the +/// window may close now; a queued quit must not bypass the Save / Don't Save / Cancel prompt. +fn dispatch(events: impl IntoIterator, app: &mut CadApp) -> bool { + let mut quit = false; + for e in events { + match e { + Event::Open(paths) => { + for p in openable(paths) { + app.open_path(&p); + } + } + Event::Quit => quit = true, + } + } + quit && !app.request_quit() +} + +/// Drain the inbox each frame; a quit closes the window like Cmd+Q, prompting for unsaved drawings. +pub fn poll(inbox: &Inbox, app: &mut CadApp, ctx: &egui::Context) { + if dispatch(inbox.drain(), app) { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } +} + +#[cfg(test)] +mod tests { + use super::{dispatch, openable}; + use cadcraft_engine::Session; + use cadcraft_ui_egui::closing::Choice; + use cadcraft_ui_egui::{CadApp, Services}; + use fmv_macos_events::Event; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::{Duration, Instant}; + + static NEXT_DIR: AtomicUsize = AtomicUsize::new(0); + + struct TestDir(PathBuf); + + impl TestDir { + fn new() -> Self { + let dir = std::env::temp_dir().join(format!("cadcraft-apple-events-{}-{}", std::process::id(), NEXT_DIR.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn app() -> CadApp { + crate::install_io(); + CadApp::new(Session::new(), Services::default()) + } + + fn settle(app: &mut CadApp) { + let deadline = Instant::now() + Duration::from_secs(10); + while app.opening.busy() && Instant::now() < deadline { + app.finish_opening(); + std::thread::sleep(Duration::from_millis(5)); + } + app.finish_opening(); + assert!(!app.opening.busy(), "background opening completed"); + } + + #[test] + fn keeps_order_and_drops_duplicates_and_empty_paths() { + let paths = ["/a/plan.dxf", "", "/b/site.dwg", "/a/plan.dxf"].map(PathBuf::from); + assert_eq!(openable(paths), ["/a/plan.dxf", "/b/site.dwg"]); + assert!(openable(Vec::new()).is_empty()); + } + + #[cfg(unix)] + #[test] + fn skips_paths_that_are_not_utf8() { + use std::os::unix::ffi::OsStringExt; + let bad = PathBuf::from(std::ffi::OsString::from_vec(vec![b'/', 0xff, b'.', b'd', b'x', b'f'])); + assert_eq!(openable([bad, PathBuf::from("/ok.dxf")]), ["/ok.dxf"]); + } + + #[test] + fn opens_dwg_and_dxf_without_replacing_an_unsaved_drawing() { + let dir = TestDir::new(); + let dxf = dir.0.join("planta com espaços.dxf"); + let dwg = dir.0.join("Documentac\u{327}a\u{303}o.dwg"); + let bytes = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n0\n10\n0\n20\n0\n11\n10\n21\n10\n0\nENDSEC\n0\nEOF\n"; + let drawing = cadcraft_io::read(bytes, "synthetic.dxf").unwrap(); + std::fs::write(&dxf, bytes).unwrap(); + std::fs::write(&dwg, cadcraft_io::write(&drawing, "synthetic.dwg").unwrap()).unwrap(); + + let mut app = app(); + app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap(); + let original = app.session.docs[0].uid; + assert!(app.session.docs[0].is_dirty()); + assert!(!dispatch([Event::Open(vec![dxf.clone(), dwg.clone(), dxf.clone(), PathBuf::new()])], &mut app)); + settle(&mut app); + + assert_eq!(app.session.docs.len(), 3, "each file is opened once alongside the unsaved drawing"); + assert_eq!(app.session.docs[0].uid, original); + assert!(app.session.docs[0].is_dirty()); + for path in [&dxf, &dwg] { + assert!(app.session.docs.iter().any(|d| d.path.as_deref() == path.to_str())); + } + } + + #[test] + fn a_failed_open_reports_the_path_and_keeps_existing_drawings() { + let dir = TestDir::new(); + let missing = dir.0.join("missing drawing.dwg"); + let mut app = app(); + let original = app.session.docs[0].uid; + assert!(!dispatch([Event::Open(vec![missing.clone()])], &mut app)); + settle(&mut app); + assert_eq!(app.session.docs.len(), 1); + assert_eq!(app.session.docs[0].uid, original); + assert!(app.session.log.iter().any(|line| line.contains(missing.to_str().unwrap()))); + } + + #[test] + fn a_quit_event_asks_before_closing_unsaved_work_and_can_be_cancelled() { + let mut app = app(); + app.run("line", serde_json::json!({"points": [[0, 0], [1, 1]]})).unwrap(); + assert!(!dispatch([Event::Quit], &mut app), "must not issue a window close before the answer"); + assert!(app.close_prompt().is_some()); + assert!(!app.quit_confirmed); + assert!(!app.quit_requested); + app.answer_close(Choice::Cancel); + assert!(app.close_prompt().is_none()); + assert!(app.session.docs[0].is_dirty()); + assert!(!app.quit_requested); + } + + #[test] + fn a_quit_event_can_close_a_clean_session() { + let mut app = app(); + assert!(dispatch([Event::Quit], &mut app)); + assert!(app.close_prompt().is_none()); + } +} From 45065cc061694491fff674f00a0c5091b6cc9b14 Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:23:21 -0300 Subject: [PATCH 005/187] Record the macOS Finder opening gap as fixed --- docs/gaps.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 0adb80f12..a01c1a833 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-15 · **Change:** minor (macOS Finder opening: U13 and P3 closed) · **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 @@ -60,7 +60,6 @@ Detail and evidence: [ui-parity.md](ui-parity.md). | 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 | | 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 | ## File formats @@ -122,7 +121,6 @@ Detail: [localization-parity.md](localization-parity.md). |---|---|---| | 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 | ## Ecosystem and automation @@ -145,6 +143,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | U13/P3 closed: macOS open-documents events use the regular asynchronous opening path; quit events retain the unsaved-changes prompt (#158) | | 2026-10-12 | minor | Object transparency (entity, ByLayer, ByBlock) is drawn: on screen (TRANSPARENCYDISPLAY, on by default), in PNG/SVG exports, and in plots when the page setup's "Plot transparency" is on (PDF alpha, PNG blending, SVG opacity; PLOTTRANSPARENCYOVERRIDE): F14 narrowed | | 2026-10-12 | minor | Hatch and Gradient dialog (HATCH, GRADIENT; HPDLGMODE) and Hatch Edit dialog (HATCHEDIT, right-click, double-click a hatch): F13 narrowed to Preview, Inherit Properties and boundary add/remove in edit mode | | 2026-10-12 | minor | A bare system variable name typed at the command line (ORTHOMODE, GRIDMODE…) runs SETVAR on that variable, as in AutoCAD; U10 narrowed | From 032b73347cc20cec8797059a9b0dd99e5a5434c9 Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:23:24 -0300 Subject: [PATCH 006/187] Update Finder opening evidence without changing parity scores --- docs/target-app-parity.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bdf89d03f..c21cf5ce0 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-10 · **Last updated:** 2026-10-15 · **Change:** minor (macOS Finder opening fixed; scores 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, @@ -134,7 +134,7 @@ annotation styles, exchange edge cases and everything excluded above. |---|---:|---| | Launch and stability | ×0.90 | startup crash on Intel UHD graphics (#33, fixed in 0.4.0), lines not visible (#44), Linux mouse delay (#25), web open/save broken (#55, #133) | | Discoverability and UI clarity | ×0.92 | no right-click menus (dynamic input got real pointer boxes in #60, which raised this from ×0.90), Print has no plot dialog (#160), some menu items only recently got dialogs (#126) | -| Opening files people send them | ×0.85 | DWGs from others untested on real files; a 10 MB DWG failed (#57); `.dxf` from Finder fails (#158); pre-2007 CJK/Cyrillic DXF garbled (no code pages) | +| Opening files people send them | ×0.85 | DWGs from others untested on real files; a 10 MB DWG failed (#57); macOS Finder opening fixed (#158); pre-2007 CJK/Cyrillic DXF garbled (no code pages) | **Essentials user ≈ 65% × 0.90 × 0.92 × 0.85 ≈ 46%** (estimated). @@ -223,6 +223,7 @@ DWG/DXF corpus (files from people who own them); black-box checks in AutoCAD of | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | macOS Finder opening fixed (#158); broader DWG interoperability scores 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 | From 3e4068246d5c51fe79e0e200a927c8090642af19 Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:23:38 -0300 Subject: [PATCH 007/187] Document Finder opening and unsaved quit handling --- docs/ui-parity.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 5495d4813..e6577a2f4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (animation effects follow the operating system's setting) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (macOS Finder opening and Apple-event quit handling) · **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 @@ -157,6 +157,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. |---|---|---| | 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)) | | Tool Bar, File tabs, Start tab, layout tabs | yes | yes | +| Open DWG/DXF from Finder, Open With or the Dock (macOS) | yes | yes: launch-time and later Apple events use the regular asynchronous opening path; a quit event asks about unsaved changes (#158) | | 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 | | Layer Properties Manager (filters, states, VP overrides) | yes | yes | @@ -202,6 +203,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | macOS Finder/Open With/Dock opening handled at launch and while running; Apple-event quit uses Save / Don't Save / Cancel (#158) | | 2026-10-12 | minor | Selected and hovered objects redrawn in the selection colour (text and arrowheads included); Options ▸ Selection laid out as AutoCAD's: Object grouping, Show grips, grip object limit, selection preview, Visual Effect Settings (selection area, preview filter) | | 2026-10-12 | minor | Animation effects (dialog and menu fades, smoothed wheel scrolling and ⌘/Ctrl+wheel zoom) follow the operating system's setting; View ▸ Accessibility ▸ Animation Effects chooses System, On or Off | | 2026-10-12 | minor | Hatch and Gradient / Hatch Edit dialogs (HATCH, GRADIENT, HATCHEDIT, double-click a hatch; HPDLGMODE) | From 5f44be5bdf48d44458e94431dae70cad659bfb9f Mon Sep 17 00:00:00 2001 From: filipemirilli <158606524+filipemirilli@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:23:43 -0300 Subject: [PATCH 008/187] Recognize AutoCAD DWG and LibreOffice DXF document types --- packaging/macos/Info.plist.in | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in index 5620772e1..101aa7aea 100644 --- a/packaging/macos/Info.plist.in +++ b/packaging/macos/Info.plist.in @@ -79,6 +79,9 @@ + CFBundleDocumentTypes @@ -89,7 +92,7 @@ LSHandlerRank Alternate LSItemContentTypes - ai.storyteller.cadcraft.dxf + ai.storyteller.cadcraft.dxforg.libreoffice.dxf-document CFBundleTypeIconFile CADCraft @@ -101,7 +104,7 @@ LSHandlerRank Alternate LSItemContentTypes - ai.storyteller.cadcraft.dwg + ai.storyteller.cadcraft.dwgcom.autodesk.autocad.dwg CFBundleTypeIconFile CADCraft From 0332836238d33adcbf21f3ff50aaeae09b2c389a Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Tue, 27 Oct 2026 22:31:35 +0100 Subject: [PATCH 009/187] INSERT: Verify and Preset attributes, ATTREQ and ATTDIA with the Edit Attributes dialog (F17) A typed or menu INSERT asks a Verify attribute's value twice and gives Preset (and constant) attributes their defaults without asking. ATTREQ 0 gives every attribute its default; ATTDIA 1 (the default) asks for the values in an Edit Attributes dialog, typed answers still working. Both are user settings, as DWG keeps them in its header only before R2000. Answers are counted per prompt, so two definitions with one tag no longer ask the second for ever. The JSON form never asks. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/blocks.rs | 66 +++-- crates/engine/src/guard.rs | 9 + crates/engine/src/lib.rs | 2 +- crates/engine/src/prompt.rs | 40 +++ crates/engine/src/session/interactive.rs | 6 + crates/engine/src/settings.rs | 8 + crates/engine/src/sysvars/table.rs | 10 +- crates/engine/tests/it/insert_attrib_entry.rs | 227 ++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/attentry.rs | 104 ++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/lib.rs | 1 + .../ui-egui/tests/it/insert_attrib_dialog.rs | 132 ++++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/gaps.md | 5 +- docs/ui-parity.md | 4 +- 18 files changed, 603 insertions(+), 22 deletions(-) create mode 100644 crates/engine/tests/it/insert_attrib_entry.rs create mode 100644 crates/ui-egui/src/attentry.rs create mode 100644 crates/ui-egui/tests/it/insert_attrib_dialog.rs diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index ca4cfffec..e7d2b5862 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -15,7 +15,7 @@ use super::machines::{SelOutcome, SelectPhase, number}; use super::{CommandSpec, bad, bool_or, f64_or, find_command, ok, point_param, point_req, point_value, str_param, targets}; use super::has_doc; -use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; +use crate::{Accept, AttribAsk, AttribEntry, EngineError, Input, Interactive, Prompt, Result, Session, Step}; mod attedit; mod burst; @@ -588,7 +588,15 @@ struct InsertM { x_scale: Option, scale: Option, rotation: Option, - attdefs: Vec<(String, String, String)>, + /// The attributes to ask for, in order: not the constant or Preset ones (they take their + /// value without asking), none with ATTREQ 0 (every one takes its default). + attdefs: Vec, + /// How many of `attdefs` have their value. + asked: usize, + /// A Verify attribute's value waiting to be confirmed. + verifying: Option, + /// ATTDIA 1: the values are asked for in the Edit Attributes dialog. + dialog: bool, values: serde_json::Map, /// `*name`: insert the block's objects (one uniform scale factor, no attribute values). explode: bool, @@ -607,7 +615,7 @@ impl InsertM { InsStage::Attribs }; if self.stage == InsStage::Attribs - && self.values.len() >= self.attdefs.len() + && self.asked >= self.attdefs.len() && let (Some(n), Some(a), Some(sc), Some(r)) = (self.name.clone(), self.at, self.scale, self.rotation) { let h = insert_with(s, &n, a, sc, r, self.base, &self.values)?; @@ -625,20 +633,24 @@ impl InsertM { s.echo(format!("Block \"{name}\" not found.")); return Ok(()); }; - self.attdefs = if self.explode { + let ask = s.settings.attreq; + self.dialog = s.settings.attdia; + self.attdefs = if self.explode || !ask { Vec::new() } else { b.entities .iter() - .filter_map(|e| { - if let EntityKind::AttDef(a) = &e.kind { - (!a.constant).then(|| (a.tag.clone(), a.prompt.clone(), a.text.value.clone())) - } else { - None + .filter_map(|e| match &e.kind { + EntityKind::AttDef(a) if !a.constant && !a.modes.preset => { + Some(AttribAsk { tag: a.tag.clone(), prompt: a.prompt.clone(), default: a.text.value.clone(), verify: a.modes.verify }) } + _ => None, }) .collect() }; + self.asked = 0; + self.verifying = None; + self.values.clear(); s.doc_mut()?.header.set_str("INSNAME", &b.name); self.name = Some(b.name.clone()); self.stage = InsStage::Point; @@ -697,8 +709,11 @@ impl Interactive for InsertM { InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"), InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at), InsStage::Attribs => { - let (_, prompt, default) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); - Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT).default(default) + if let Some(v) = &self.verifying { + return Prompt::new("Verify attribute value", Accept::TEXT).default(v.clone()); + } + let a = self.attdefs.get(self.asked).cloned().unwrap_or_default(); + Prompt::new(if a.prompt.is_empty() { "Enter attribute value".into() } else { a.prompt }, Accept::TEXT).default(a.default) } } } @@ -816,12 +831,24 @@ impl Interactive for InsertM { return self.advance(s); } InsStage::Attribs => { - let (tag, _, default) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); - let v = match i { - Input::Text(t) => t, - _ => default, + let a = self.attdefs.get(self.asked).cloned().unwrap_or_default(); + let v = match (i, self.verifying.take()) { + // Verify: Enter keeps the value given, a typed one replaces it. + (Input::Text(t), Some(_)) => t, + (_, Some(v)) => v, + (Input::Text(t), None) if a.verify => { + self.verifying = Some(t); + return Ok(Step::Continue); + } + (_, None) if a.verify => { + self.verifying = Some(a.default); + return Ok(Step::Continue); + } + (Input::Text(t), None) => t, + (_, None) => a.default, }; - self.values.insert(tag, Value::String(v)); + self.values.insert(a.tag, Value::String(v)); + self.asked += 1; return self.advance(s); } } @@ -843,6 +870,13 @@ impl Interactive for InsertM { let rot = self.rotation.unwrap_or(if self.stage == InsStage::Rotation { at.angle_to(c) } else { 0.0 }); vec![EntityKind::Insert(insert_entity(b, at, scale, rot, self.base))] } + fn attribute_entry(&self) -> Option { + // Only before the first answer: values typed at the command line go on there. + if !self.dialog || self.stage != InsStage::Attribs || self.asked > 0 || self.verifying.is_some() || self.attdefs.is_empty() { + return None; + } + Some(AttribEntry { block: self.name.clone().unwrap_or_default(), rows: self.attdefs.clone() }) + } } #[derive(Default)] diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 8a64e2b74..9e3923376 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -102,6 +102,15 @@ impl Interactive for Guarded { None }) } + fn attribute_entry(&self) -> Option { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.attribute_entry())).unwrap_or_else(|_| { + self.broken.set(Some("panic in prompt")); + None + }) + } } #[cfg(test)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index caeda8d7d..480218474 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -47,7 +47,7 @@ pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; -pub use prompt::{Accept, Drag, Input, Interactive, Picker, Prompt, Step}; +pub use prompt::{Accept, AttribAsk, AttribEntry, Drag, Input, Interactive, Picker, Prompt, Step}; mod doc_state; mod error; diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index c02551b80..3d0ba8063 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -243,6 +243,46 @@ pub trait Interactive: Send { fn editing_mtext(&self) -> Option { None } + /// The attribute values the command waits for, all at once, when the UI should ask for them + /// in the Edit Attributes dialog (INSERT with ATTDIA 1). Typed answers still work. + fn attribute_entry(&self) -> Option { + None + } +} + +/// See [`Interactive::attribute_entry`]: the block being inserted and the attributes asked for, +/// in order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AttribEntry { + pub block: String, + pub rows: Vec, +} + +/// One attribute an INSERT asks for: its tag, prompt and default value; Verify ones are asked +/// twice at the command line. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct AttribAsk { + pub tag: String, + pub prompt: String, + pub default: String, + pub verify: bool, +} + +impl AttribEntry { + /// The answers that give the attributes `values` (one per row, in order; a missing one is + /// the default) when typed in turn: a Verify attribute's value twice, as the dialog has + /// already shown it. + pub fn answers(&self, values: &[String]) -> Vec { + let mut out = Vec::with_capacity(self.rows.len().saturating_mul(2)); + for (i, r) in self.rows.iter().enumerate() { + let v = values.get(i).cloned().unwrap_or_else(|| r.default.clone()); + if r.verify { + out.push(v.clone()); + } + out.push(v); + } + out + } } /// See [`Interactive::drag`]. diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index e7cb07450..2cfbee903 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -435,6 +435,12 @@ impl Session { self.running.as_ref().and_then(|r| r.machine.editing_mtext()) } + /// The attribute values the running command asks for in the Edit Attributes dialog + /// ([`Interactive::attribute_entry`]). + pub fn attribute_entry(&self) -> Option { + self.running.as_ref().and_then(|r| r.machine.attribute_entry()) + } + pub fn current_prompt(&self) -> Option { if let Some(p) = self.lisp_prompt() { return Some(p); diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 32507162f..adbc94fb5 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -127,6 +127,12 @@ pub struct Settings { pub polardist: f64, /// AUDITCTL: 1 creates an audit report (.adt) file when AUDIT is run (default: 0). pub auditctl: bool, + /// ATTREQ: INSERT asks for attribute values (on by default); off gives every attribute its + /// default value. A user setting, as in AutoCAD (not saved in the drawing). + pub attreq: bool, + /// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes + /// dialog (on by default, as in AutoCAD); off asks at the command line. + pub attdia: bool, } impl Default for Settings { @@ -191,6 +197,8 @@ impl Default for Settings { polarsnap: false, polardist: 0.0, auditctl: false, + attreq: true, + attdia: true, } } } diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index fa319d3f1..72af5b9c0 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -81,8 +81,14 @@ const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, /// On/off session settings: name, read, write. type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool)); -const SETTINGS: &[Toggle] = - &[("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v), ("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v)]; +const SETTINGS: &[Toggle] = &[ + // ATTDIA 1: INSERT typed or from a menu asks for attribute values in the Edit Attributes + // dialog; 0: at the command line. ATTREQ 0: INSERT gives every attribute its default. + ("ATTDIA", |s| s.attdia, |s, v| s.attdia = v), + ("ATTREQ", |s| s.attreq, |s, v| s.attreq = v), + ("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v), + ("TRANSPARENCYDISPLAY", |s| s.transparency_display, |s, v| s.transparency_display = v), +]; fn header_var(name: &str) -> Option<&'static (&'static str, Kind, Def)> { HEADER.iter().find(|(n, _, _)| *n == name) diff --git a/crates/engine/tests/it/insert_attrib_entry.rs b/crates/engine/tests/it/insert_attrib_entry.rs new file mode 100644 index 000000000..78e1253c1 --- /dev/null +++ b/crates/engine/tests/it/insert_attrib_entry.rs @@ -0,0 +1,227 @@ +//! INSERT and the attribute modes (gap F17): Verify attributes are asked twice, Preset ones take +//! their default without asking, ATTREQ 0 gives every attribute its default, and ATTDIA 1 asks +//! for the values all at once in the Edit Attributes dialog (`Session::attribute_entry`), typed +//! answers still working. The JSON form never asks. ATTREQ and ATTDIA are user settings, as in +//! AutoCAD (DWG keeps them in its header only before R2000). + +use std::sync::Arc; + +use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Handle, Text}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::{AttribAsk, Input, Session}; +use serde_json::json; + +fn def(tag: &str, prompt: &str, default: &str, y: f64, constant: bool, modes: AttribModes) -> Attrib { + Attrib { + tag: tag.into(), + text: Text { + insert: Vec3::new(0.0, y, 0.0), + align_pt: None, + height: 1.0, + value: default.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }, + invisible: false, + constant, + prompt: prompt.into(), + props: Default::default(), + multiline: None, + modes, + } +} + +/// Block T with the definitions A (Verify), B (Preset), C (plain) and D (constant); ATTREQ and +/// ATTDIA as given (their defaults, 1, otherwise). +fn session(attreq: Option, attdia: Option) -> Session { + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + let mut b = Block::new("T"); + let none = AttribModes::default(); + for a in [ + def("A", "First", "1", 2.0, false, AttribModes { verify: true, ..none }), + def("B", "Second", "two", 4.0, false, AttribModes { preset: true, ..none }), + def("C", "Third", "3", 6.0, false, none), + def("D", "", "fixed", 8.0, true, none), + ] { + let h = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::AttDef(a))); + } + d.blocks.insert("T".into(), Arc::new(b)); + let mut s = Session::empty(); + s.open_drawing(d, "attribs", None); + if let Some(v) = attreq { + s.settings.attreq = v; + } + if let Some(v) = attdia { + s.settings.attdia = v; + } + s +} + +/// Start INSERT of T at 100,0 and answer the scale and rotation prompts. +fn insert_up_to_the_attributes(s: &mut Session) { + s.start("insert").unwrap(); + s.cmdline("T").unwrap(); + s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap(); + s.input(Input::Enter).unwrap(); // X scale 1 + s.input(Input::Enter).unwrap(); // Y scale = X + s.input(Input::Enter).unwrap(); // rotation 0 +} + +/// The attribute values of the last block reference, in order. +fn values(s: &Session) -> Vec<(String, String)> { + let d = s.doc().unwrap(); + let Some(EntityKind::Insert(i)) = d.model.iter().filter(|e| matches!(e.kind, EntityKind::Insert(_))).last().map(|e| e.kind.clone()) else { + panic!("no block reference") + }; + i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect() +} + +fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(t, v)| (t.to_string(), v.to_string())).collect() +} + +#[test] +fn typed_insert_asks_verify_twice_and_skips_preset_and_constant() { + let mut s = session(None, Some(false)); + insert_up_to_the_attributes(&mut s); + assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog"); + assert_eq!(s.prompt_text(), "INSERT First <1>:", "A first"); + s.input(Input::Text("10".into())).unwrap(); + assert_eq!(s.prompt_text(), "INSERT Verify attribute value <10>:"); + s.input(Input::Text("11".into())).unwrap(); // the value typed at Verify replaces it + assert_eq!(s.prompt_text(), "INSERT Third <3>:", "B is Preset: not asked"); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "11"), ("B", "two"), ("C", "3")])); + + // Enter at Verify keeps the value given; Enter at A takes its default, verified. + insert_up_to_the_attributes(&mut s); + s.input(Input::Enter).unwrap(); + assert_eq!(s.prompt_text(), "INSERT Verify attribute value <1>:"); + s.input(Input::Enter).unwrap(); + s.input(Input::Text("c".into())).unwrap(); + assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "c")])); + + // A script answers in turn too. + s.script("-INSERT T 0,50 1 1 0\na\na\nc\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "a"), ("B", "two"), ("C", "c")])); +} + +#[test] +fn attreq_0_gives_every_attribute_its_default() { + let mut s = session(Some(false), None); + insert_up_to_the_attributes(&mut s); + assert!(s.running.is_none(), "no attribute prompt: {}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "1"), ("B", "two"), ("C", "3")])); + // SETVAR changes it. + s.execute("setvar", &json!({ "name": "ATTREQ", "value": 1 })).unwrap(); + s.execute("setvar", &json!({ "name": "ATTDIA", "value": 0 })).unwrap(); + insert_up_to_the_attributes(&mut s); + assert_eq!(s.prompt_text(), "INSERT First <1>:"); +} + +#[test] +fn attdia_1_asks_for_every_value_at_once_and_typed_answers_still_work() { + // AutoCAD's default, ATTDIA 1, with no value in the drawing. + let mut s = session(None, None); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTREQ" })).unwrap()["value"], 1); + s.start("insert").unwrap(); + s.cmdline("T").unwrap(); + assert!(s.attribute_entry().is_none(), "not before the attribute prompts"); + s.input(Input::Point(Vec2::new(100.0, 0.0))).unwrap(); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + let e = s.attribute_entry().expect("the dialog's rows"); + assert_eq!(e.block, "T"); + let ask = + |tag: &str, prompt: &str, default: &str, verify: bool| AttribAsk { tag: tag.into(), prompt: prompt.into(), default: default.into(), verify }; + assert_eq!(e.rows, vec![ask("A", "First", "1", true), ask("C", "Third", "3", false)]); + // The dialog's OK: the answers typed in turn, Verify ones twice. + let answers = e.answers(&["x".into(), String::new()]); + assert_eq!(answers, ["x", "x", ""]); + for a in answers { + s.input(Input::Text(a)).unwrap(); + } + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s), pairs(&[("A", "x"), ("B", "two"), ("C", "")])); + + // Typed instead: the dialog goes away after the first answer. + insert_up_to_the_attributes(&mut s); + assert!(s.attribute_entry().is_some()); + s.input(Input::Text("typed".into())).unwrap(); + assert!(s.attribute_entry().is_none()); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + assert_eq!(values(&s), pairs(&[("A", "typed"), ("B", "two"), ("C", "3")])); + + // Cancel from the dialog inserts nothing. + let before = s.doc().unwrap().model.len(); + insert_up_to_the_attributes(&mut s); + s.cancel(); + assert!(s.running.is_none()); + assert_eq!(s.doc().unwrap().model.len(), before); +} + +#[test] +fn json_insert_never_asks_whatever_attreq_and_attdia_say() { + for (req, dia) in [(false, false), (true, true)] { + let mut s = session(Some(req), Some(dia)); + let r = s.execute("insert", &json!({ "name": "T", "at": [0, 0], "attribs": { "a": "given", "B": "preset given" } })).unwrap(); + assert!(r["handle"].is_string()); + assert!(s.running.is_none() && s.attribute_entry().is_none()); + assert_eq!(values(&s), pairs(&[("A", "given"), ("B", "preset given"), ("C", "3")])); + } +} + +#[test] +fn hostile_values_never_panic() { + let mut s = session(None, None); + insert_up_to_the_attributes(&mut s); + let e = s.attribute_entry().expect("asks"); + // Too few answers take the defaults, too many are ignored. + assert_eq!(e.answers(&[]), ["1", "1", "3"]); + assert_eq!(e.answers(&["p".into(), "q".into(), "r".into()]), ["p", "p", "q"]); + s.cancel(); + for bad in [json!(2), json!(-1), json!("x"), json!(null), json!(1.5)] { + assert!(s.execute("setvar", &json!({ "name": "ATTDIA", "value": bad })).is_err(), "{bad}"); + assert!(s.execute("setvar", &json!({ "name": "ATTREQ", "value": bad })).is_err(), "{bad}"); + } + assert!(s.settings.attdia && s.settings.attreq, "a refused value changes nothing"); + // An INSERT of a block with only Preset and constant attributes asks nothing. + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + let mut b = Block::new("P"); + let h: Handle = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::AttDef(def("P", "p", "v", 0.0, false, AttribModes { preset: true, ..AttribModes::default() })))); + d.blocks.insert("P".into(), Arc::new(b)); + let mut s = Session::empty(); + s.open_drawing(d, "preset", None); + s.script("-INSERT P 0,0 1 1 0\n").unwrap(); + assert!(s.running.is_none() && s.attribute_entry().is_none()); + assert_eq!(values(&s), pairs(&[("P", "v")])); +} + +#[test] +fn two_definitions_with_one_tag_are_both_asked_once() { + // INSERT counted its answers by tag: the second X was asked for ever. + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + let mut b = Block::new("DUP"); + for (prompt, y) in [("first", 0.0), ("second", 2.0)] { + let h = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::AttDef(def("X", prompt, "d", y, false, AttribModes::default())))); + } + d.blocks.insert("DUP".into(), Arc::new(b)); + let mut s = Session::empty(); + s.open_drawing(d, "dup", None); + s.settings.attdia = false; + s.script("-INSERT DUP 0,0 1 1 0\na\nb\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!(values(&s).len(), 2); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4c4a1ce6..bc8546879 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -54,6 +54,7 @@ mod hatch_options; mod helix; mod inquiry_keywords; mod inquiry_z; +mod insert_attrib_entry; mod insert_prompts; mod isometric; mod join_close; diff --git a/crates/ui-egui/src/attentry.rs b/crates/ui-egui/src/attentry.rs new file mode 100644 index 000000000..88b655444 --- /dev/null +++ b/crates/ui-egui/src/attentry.rs @@ -0,0 +1,104 @@ +//! Edit Attributes: INSERT asks for its attribute values in one dialog when ATTDIA is 1 +//! ([`cadcraft_engine::Session::attribute_entry`]). OK answers INSERT's prompts in turn, Cancel +//! cancels the command; values typed at the command line still work, and the dialog goes away +//! after the first one. + +use egui::{RichText, vec2}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The values being edited, for the block they were made for. +#[derive(Clone, Default)] +struct State { + block: String, + values: Vec, + /// The first field has had the keyboard focus once. + focused: bool, +} + +fn state_id() -> egui::Id { + egui::Id::unique("attentry_state") +} + +enum Done { + No, + Ok, + Cancel, +} + +/// Show the dialog while INSERT waits for attribute values with ATTDIA 1. +pub fn show(app: &mut CadApp, ctx: &egui::Context) { + let Some(entry) = app.session.attribute_entry() else { + ctx.data_mut(|d| d.remove::(state_id())); + return; + }; + let t = Tokens::get(); + let mut st = ctx + .data_mut(|d| d.get_temp::(state_id())) + .filter(|s| s.block == entry.block && s.values.len() == entry.rows.len()) + .unwrap_or_else(|| State { block: entry.block.clone(), values: entry.rows.iter().map(|r| r.default.clone()).collect(), focused: false }); + let mut done = Done::No; + let st_focused = st.focused; + st.focused = true; + egui::Window::new(crate::tl!("Edit Attributes")) + .id(egui::Id::unique("Edit Attributes")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Block name:")); + ui.label(RichText::new(&entry.block).strong()); + }); + ui.separator(); + egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, true]).show(ui, |ui| { + egui::Grid::new("attentry_grid").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { + for (i, (row, value)) in entry.rows.iter().zip(st.values.iter_mut()).enumerate() { + let shown = if row.prompt.is_empty() { row.tag.as_str() } else { row.prompt.as_str() }; + let label = ui.label(shown).on_hover_text(crate::tf!("Tag: {tag}", tag = row.tag)); + let field = egui::TextEdit::singleline(value).id(egui::Id::unique(("attentry_value", i))).desired_width(220.0); + let resp = ui.add(field).labelled_by(label.id); + if i == 0 && !st_focused { + resp.request_focus(); + } + // Enter in a field is OK, the dialog's default button. + if resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + done = Done::Ok; + } + ui.end_row(); + } + }); + }); + ui.separator(); + ui.horizontal(|ui| { + if ui.button(crate::tl!("OK")).clicked() { + done = Done::Ok; + } + if ui.button(crate::tl!("Cancel")).clicked() { + done = Done::Cancel; + } + ui.label(RichText::new(crate::tl!("Values typed at the command line work too")).small().color(t.text_dim)); + }); + }); + if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + done = Done::Cancel; + } + match done { + Done::No => { + ctx.data_mut(|d| d.insert_temp(state_id(), st)); + } + Done::Ok => { + ctx.data_mut(|d| d.remove::(state_id())); + for a in entry.answers(&st.values) { + if app.session.input(cadcraft_engine::Input::Text(a)).is_err() { + break; + } + } + } + Done::Cancel => { + ctx.data_mut(|d| d.remove::(state_id())); + app.session.cancel(); + } + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index acdddb552..a0efd20ff 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -10,6 +10,7 @@ use crate::theme::Tokens; pub fn show(app: &mut CadApp, ctx: &egui::Context) { crate::mtext_editor::show(app, ctx); + crate::attentry::show(app, ctx); crate::quick::quick_properties(app, ctx); let Some(d) = app.ui.dialog.clone() else { return }; let mut open = true; diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 634249093..428bbbccd 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1367,3 +1367,7 @@ menu Modify Edita Check for Updates… Verifica aggiornamenti… CADCraft is up to date. CADCraft è aggiornato. Could not check for updates. Impossibile verificare gli aggiornamenti. + Edit Attributes Modifica attributi + Block name: Nome blocco: + Tag: {tag} Etichetta: {tag} + Values typed at the command line work too Anche i valori digitati nella riga di comando vengono accettati diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d71b3ccd7..f9fb46217 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1373,3 +1373,7 @@ Check for Updates… Перевірити оновлення… CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. + Edit Attributes Редагування атрибутів + Block name: Ім’я блока: + Tag: {tag} Мітка: {tag} + Values typed at the command line work too Значення, введені в командному рядку, теж приймаються diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 017cf5a42..773c1a6cd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,7 @@ pub mod aliasdlg; pub mod animation; +pub mod attentry; pub mod autosave; pub mod bedit; pub mod canvas; diff --git a/crates/ui-egui/tests/it/insert_attrib_dialog.rs b/crates/ui-egui/tests/it/insert_attrib_dialog.rs new file mode 100644 index 000000000..1e0783e66 --- /dev/null +++ b/crates/ui-egui/tests/it/insert_attrib_dialog.rs @@ -0,0 +1,132 @@ +//! Edit Attributes (ATTDIA 1): a typed INSERT asks for its attribute values in one dialog. OK +//! gives them to INSERT (a Verify one is not asked again), Enter in a field is OK, Cancel inserts +//! nothing, and with ATTDIA 0 or a JSON call there is no dialog. + +use cadcraft_engine::Input; +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_ui_egui::{CadApp, Services, dialogs}; +use egui::accesskit::Role; +use egui::{Key, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::json; + +/// Block T with the definitions A ("Room", default "101") and B ("Floor", default "1"). +fn app() -> CadApp { + let mut app = CadApp::new(Session::new(), Services::default()); + let a = app.run("attdef", json!({ "tag": "A", "prompt": "Room", "default": "101", "at": [0, 2] })).unwrap(); + let b = app.run("attdef", json!({ "tag": "B", "prompt": "Floor", "default": "1", "at": [0, 4] })).unwrap(); + app.run("block", json!({ "name": "T", "base": [0, 0], "handles": [a["handle"], b["handle"]], "keep": "delete" })).unwrap(); + app +} + +/// INSERT of T typed, answered up to its attribute values. +fn insert(app: &mut CadApp) { + app.start("insert"); + app.cmdline("T"); + for i in [Input::Point(Vec2::new(50.0, 0.0)), Input::Enter, Input::Enter, Input::Enter] { + app.session.input(i).unwrap(); + } +} + +fn harness(app: CadApp) -> Harness<'static, CadApp> { + let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state(|ui, app: &mut CadApp| dialogs::show(app, ui.ctx()), app); + h.run_steps(3); + h +} + +fn values(app: &CadApp) -> Option> { + let d = app.session.doc().unwrap(); + d.model.iter().find_map(|e| match &e.kind { + EntityKind::Insert(i) => Some(i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect()), + _ => None, + }) +} + +fn field<'h>(h: &'h Harness<'static, CadApp>, shown: &'h str) -> egui_kittest::Node<'h> { + h.get(by().role(Role::TextInput).value(shown)) +} + +fn replace(h: &mut Harness<'static, CadApp>, shown: &str, with: &str) { + field(h, shown).focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, Key::A); + h.run_steps(1); + field(h, shown).type_text(with); + h.run_steps(2); +} + +#[test] +fn ok_gives_the_values_to_insert() { + let mut a = app(); + insert(&mut a); + let mut h = harness(a); + h.get_by_label("Edit Attributes"); + // The fields are named by their prompts. + assert_eq!(h.get_by_label("Room").value().as_deref(), Some("101")); + replace(&mut h, "1", "3"); + replace(&mut h, "101", "205"); + h.get_by_label("OK").click(); + h.run_steps(3); + let app = h.state(); + assert!(app.session.running.is_none(), "{}", app.session.prompt_text()); + assert_eq!(values(app), Some(vec![("A".into(), "205".into()), ("B".into(), "3".into())])); + assert!(h.query_by_label("Edit Attributes").is_none(), "closed"); +} + +#[test] +fn enter_in_a_field_is_ok_and_verify_is_not_asked_again() { + let mut a = app(); + a.run("battman", json!({ "name": "T", "action": "edit", "tag": "A", "default": "7" })).unwrap(); + // Make A a Verify attribute in the block definition. + let d = a.session.doc_mut().unwrap(); + let mut b = (**d.block("T").unwrap()).clone(); + for e in b.entities.iter().map(|e| e.handle).collect::>() { + b.entities.modify(e, |e| { + if let EntityKind::AttDef(ad) = &mut e.kind + && ad.tag == "A" + { + ad.modes.verify = true; + } + }); + } + d.blocks.insert("T".into(), std::sync::Arc::new(b)); + insert(&mut a); + let mut h = harness(a); + replace(&mut h, "7", "8"); + h.key_press(Key::Enter); + h.run_steps(3); + let app = h.state(); + assert!(app.session.running.is_none(), "{}", app.session.prompt_text()); + assert_eq!(values(app), Some(vec![("A".into(), "8".into()), ("B".into(), "1".into())])); +} + +#[test] +fn cancel_inserts_nothing() { + let mut a = app(); + insert(&mut a); + let mut h = harness(a); + h.get_by_label("Cancel").click(); + h.run_steps(3); + let app = h.state(); + assert!(app.session.running.is_none()); + assert_eq!(values(app), None); +} + +#[test] +fn no_dialog_with_attdia_0_or_from_json() { + let mut a = app(); + a.session.settings.attdia = false; + insert(&mut a); + let h = harness(a); + assert!(h.query_by_label("Edit Attributes").is_none()); + assert!(h.state().session.prompt_text().contains("Room"), "asked at the command line"); + + let mut a = app(); + a.run("insert", json!({ "name": "T", "at": [0, 0], "attribs": { "A": "x" } })).unwrap(); + let h = harness(a); + assert!(h.query_by_label("Edit Attributes").is_none()); + assert_eq!(values(h.state()), Some(vec![("A".into(), "x".into()), ("B".into(), "1".into())])); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c32012e1a..2af172043 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -13,6 +13,7 @@ mod drafting_spacing; mod file_tab_titles; mod gpu_viewport_stencil; mod hidden_command_line; +mod insert_attrib_dialog; mod instant_modals; mod lisp_files; mod measure_distance_snapping; diff --git a/docs/gaps.md b/docs/gaps.md index 9c0bf3630..6e76a2bca 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 (INSERT follows the attribute modes, ATTREQ and ATTDIA: F17 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 @@ -39,7 +39,7 @@ do them first. | F13 | Hatch: 23 patterns (AutoCAD ~85; ours must stay original); the Hatch and Gradient and Hatch Edit dialogs have no Preview or Inherit Properties (HPDLGMODE 0 keeps HATCH on the command line); no MPolygon; HATCHEDIT and -HATCHEDIT add boundaries from picked points or closed objects and remove chosen loops, but 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 | 6–10 | | 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 and the status-bar scale list landed (#453), MVIEW Restore in #633 | `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; INSERT asks Verify attributes twice, skips Preset ones and follows ATTREQ and ATTDIA, with the Edit Attributes dialog): ATTDEF can't set the Verify, Preset or Lock position modes, locked attributes still have grips, 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 | | 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 | @@ -150,6 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | INSERT asks a Verify attribute's value twice and gives a Preset one its default without asking; ATTREQ 0 gives every attribute its default; ATTDIA 1 (the default) asks for the values in the Edit Attributes dialog when INSERT is typed or picked, typed answers still working; both are user settings (SETVAR), not saved in the drawing, as DWG from R2000 has no place for them: F17 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..c91d85f7e 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 (attribute values when inserting: ATTREQ, ATTDIA and the Edit Attributes dialog) · **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 @@ -149,6 +149,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Clickable keywords in the prompt | yes | yes (`cmdline.rs:253-267`) | | UNDO with Mark, Back, BEgin, End, Auto, Control | yes | count only, whole-document snapshots capped at 2,000 (`lib.rs:477`, `edit.rs:56`) | | SETVAR for every system variable | ~1,000 sysvars | about 60 session/header variables by name (`sysvars.rs`) | +| Attribute values when inserting (ATTREQ, ATTDIA, Verify, Preset) | prompts or the Edit Attributes dialog | both: ATTDIA 1 opens Edit Attributes (OK, Enter, Cancel; typed answers still work), ATTDIA 0 asks at the command line, Verify attributes asked twice there, Preset ones and ATTREQ 0 take their defaults (`attentry.rs`); no Previous/Next pages (one scrolling list) | | Scripts (SCRIPT, `.scr`) | yes | script text via CLI/MCP/control; no `.scr` file command | | Floating/docked command window, transparency, lines of history | yes | floating overlay, history lines setting | @@ -203,6 +204,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | INSERT asks for attribute values as AutoCAD does: the Edit Attributes dialog with ATTDIA 1, the command line with 0 (Verify asked twice), none with ATTREQ 0 or for Preset attributes | | 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 cc0e3c7add6e5d0175d8219a88a6794460c0f6ff Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 13 Oct 2026 08:44:45 -0600 Subject: [PATCH 010/187] Dynamic blocks: a stretch or move carries a multiline attribute's text along The reference's attribute moved with its definition, but a multiline attribute's text (its embedded MTEXT) stayed behind; the grip preview drew it as one line. Both landed before multiline attributes (#854) and couldn't use them. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 2 ++ crates/engine/src/cmd/blocks/dyngrip.rs | 6 +++- crates/io/tests/it/dynblock_read.rs | 43 +++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index ed5281bf6..8ffd90ad4 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -609,6 +609,8 @@ fn apply( if let EntityKind::Text(t) = k { a.text = t; } + // A multiline attribute's text moves with it. + a.transform_multiline(&Mat3::translate(w)); } } } diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index dbc92b7fb..8f3bfc574 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -102,7 +102,11 @@ fn drawn(d: &Drawing, h: Handle) -> Vec { _ => None, }); let common = under(&a.props.over(def.unwrap_or(&by_block)), r); - Entity { handle: Handle(0), common, kind: EntityKind::Text(a.text.clone()) } + let kind = match a.multiline_text() { + Some(m) => EntityKind::MText(m), + None => EntityKind::Text(a.text.clone()), + }; + Entity { handle: Handle(0), common, kind } })); out } diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index d265f9e70..866372c35 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -562,3 +562,46 @@ fn a_dynamic_block_with_handles_above_2_pow_48_is_kept() { let again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); assert_eq!(by_node(dynamic_block(&again, "Door").unwrap()), by_node(before)); } + +/// A multiline attribute (LABEL, two lines) in the stretch's selection: when Width changes, the +/// reference's attribute moves with its definition, its multiline text too. +#[test] +fn a_stretch_moves_a_multiline_attributes_text() { + let attdef = "0 ATTDEF\n5 3A\n330 1D\n100 AcDbEntity\n8 0\n100 AcDbText\n10 35\n20 0\n30 0\n40 1\n1 SITE\n7 Standard\n100 AcDbAttributeDefinition\n280 0\n3 Label\n2 LABEL\n70 0\n280 1\n71 4\n72 0\n11 35\n21 0\n31 0\n101 Embedded Object\n10 35\n20 0\n30 0\n40 1\n41 0\n46 0\n71 1\n72 5\n1 SITE\\PNAME\n7 Standard\n73 1\n44 1\n"; + let src = fixture().replace("71 1\n330 30\n1010 40", "71 2\n330 30\n330 3A\n1010 40"); + // Into Door's block, before its end. + let door = src.find("2 Door\n70 0").unwrap(); + let end = door + src[door..].find("0 ENDBLK").unwrap(); + let src = format!("{}{attdef}{}", &src[..end], &src[end..]); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let def = d + .block("Door") + .unwrap() + .entities + .iter() + .find_map(|e| if let cadcraft_doc::EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }) + .expect("the attribute definition"); + assert!(def.multiline.is_some(), "a multiline definition"); + // A reference at (100, 0) with its attribute where the definition puts it. + let r = door_at_100(&mut d); + d.modify_entity(r, |e| { + if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind { + let mut a = def.clone(); + let m = cadcraft_doc::geom::Mat3::translate(cadcraft_doc::geom::Vec2::new(100.0, 0.0)); + let mut k = cadcraft_doc::EntityKind::Text(a.text.clone()); + k.transform(&m); + if let cadcraft_doc::EntityKind::Text(t) = k { + a.text = t; + } + a.transform_multiline(&m); + i.attribs.push(a); + } + }) + .unwrap(); + // Width 36 → 30: the attribute moves 6 to the left, its multiline text with it. + cadcraft_doc::dynblock::set_property(&mut d, r, "Width", "30").unwrap(); + let Some(cadcraft_doc::EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") }; + let a = &i.attribs[0]; + assert_eq!(a.text.insert.x, 129.0); + assert_eq!(a.multiline.as_ref().unwrap().mtext.insert.x, 129.0); +} From b6cd6667ca3ed501cf12cd469ae6fe93a71be4b4 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:30:28 -0600 Subject: [PATCH 011/187] Test: a stretched multiline attribute survives a save The moved attribute's insertion and its multiline text's are checked again after saving to DXF (in the drawing's version; R2000 DXF has no multiline attributes) and reopening. Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/it/dynblock_read.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index 866372c35..1feda1a91 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -604,4 +604,13 @@ fn a_stretch_moves_a_multiline_attributes_text() { let a = &i.attribs[0]; assert_eq!(a.text.insert.x, 129.0); assert_eq!(a.multiline.as_ref().unwrap().mtext.insert.x, 129.0); + // Saved (in the drawing's version, 2018: R2000 DXF has no multiline attributes) and reopened: + // the moved attribute and its multiline text stay where they went. + let again = cadcraft_io::read(&cadcraft_io::write(&d, "door.dxf").unwrap(), "door.dxf").unwrap(); + let Some(cadcraft_doc::EntityKind::Insert(i)) = again.entity(r).map(|e| &e.kind) else { panic!("no reference after reopening") }; + let a = &i.attribs[0]; + assert_eq!((a.text.insert.x, a.text.insert.y), (129.0, 0.0)); + let m = &a.multiline.as_ref().expect("still multiline").mtext; + assert_eq!((m.insert.x, m.insert.y), (129.0, 0.0)); + assert_eq!(m.contents, r"SITE\PNAME"); } From d35ee3ae71ef6a3eaf7e76b55fcdb40257ac508c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 13 Oct 2026 10:04:30 -0600 Subject: [PATCH 012/187] Block reference grips: none on locked or invisible attributes; a moved multiline attribute moves its text Every attribute of a block reference had a grip, also those locked in position and invisible ones, which AutoCAD gives none. Dragging a multiline attribute's grip moved its position but not its multiline text, so the grip moved and the text stayed. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/entity.rs | 2 +- crates/doc/src/entity/block.rs | 6 +++ crates/engine/src/grips.rs | 5 +- crates/engine/tests/it/attrib_modes.rs | 65 +++++++++++++++++++++++++- 4 files changed, 75 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 089904109..924b53134 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -517,7 +517,7 @@ impl EntityKind { EntityKind::Text(t) => vec![t.justify_point()], EntityKind::MText(t) => vec![t.insert.xy()], EntityKind::AttDef(a) => vec![a.text.justify_point()], - EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.attribs.iter().map(|a| a.text.justify_point())).collect(), + EntityKind::Insert(i) => std::iter::once(i.insert.xy()).chain(i.grip_attribs().map(|(_, a)| a.text.justify_point())).collect(), EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()], EntityKind::MLine(m) => m.points(), EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(), diff --git a/crates/doc/src/entity/block.rs b/crates/doc/src/entity/block.rs index 3d6665e0b..afdb592be 100644 --- a/crates/doc/src/entity/block.rs +++ b/crates/doc/src/entity/block.rs @@ -172,6 +172,12 @@ fn one_u() -> u32 { } impl Insert { + /// The attributes that have a grip of their own (grips 1, 2… after the insertion point), with + /// their index in `attribs`: those shown and not locked in position, as AutoCAD offers them. + pub fn grip_attribs(&self) -> impl Iterator { + self.attribs.iter().enumerate().filter(|(_, a)| !a.invisible && !a.modes.lock_position) + } + /// Block-to-world transform (2D part). pub fn transform(&self, base: Vec2) -> Mat3 { Mat3::translate(self.insert.xy()) diff --git a/crates/engine/src/grips.rs b/crates/engine/src/grips.rs index a3b8921aa..b41d939c9 100644 --- a/crates/engine/src/grips.rs +++ b/crates/engine/src/grips.rs @@ -170,13 +170,16 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option { match index { diff --git a/crates/engine/tests/it/attrib_modes.rs b/crates/engine/tests/it/attrib_modes.rs index 65238823a..260f842c9 100644 --- a/crates/engine/tests/it/attrib_modes.rs +++ b/crates/engine/tests/it/attrib_modes.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use cadcraft_engine::Session; -use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, Text}; +use cadcraft_engine::doc::{Attrib, AttribModes, Block, Entity, EntityKind, MText, MultilineAttrib, Text}; use cadcraft_engine::geom::Vec3; use serde_json::json; @@ -45,3 +45,66 @@ fn references_take_lock_position_from_the_definition() { let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") }; assert_eq!(i.attribs[0].modes, AttribModes { verify: false, preset: false, lock_position: true }); } + +/// A definition at `x` with `modes`, invisible or not, multiline or not. +fn definition(tag: &str, x: f64, modes: AttribModes, invisible: bool, multiline: bool) -> Attrib { + let text = Text { + insert: Vec3::new(x, 0.0, 0.0), + align_pt: None, + height: 2.0, + value: tag.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }; + let multiline = multiline.then(|| { + let mtext = MText { + insert: Vec3::new(x, 0.0, 0.0), + height: 2.0, + width: 0.0, + attach: 7, + rotation: 0.0, + style: "Standard".into(), + contents: format!("{tag}\\PTWO"), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + MultilineAttrib { mtext, read_as: format!("{tag}\nTWO") } + }); + Attrib { tag: tag.into(), text, invisible, constant: false, prompt: tag.into(), props: Default::default(), multiline, modes } +} + +#[test] +fn only_shown_unlocked_attributes_have_grips_and_a_multiline_one_moves_its_text() { + let mut d = cadcraft_engine::doc::Drawing::new_imperial(); + let locked = AttribModes { lock_position: true, ..AttribModes::default() }; + let mut b = Block::new("TAG"); + for a in [ + definition("FREE", 0.0, AttribModes::default(), false, false), + definition("LOCKED", 10.0, locked, false, false), + definition("HIDDEN", 20.0, AttribModes::default(), true, false), + definition("NOTE", 30.0, AttribModes::default(), false, true), + ] { + let h = d.new_handle(); + b.entities.push(Entity::new(h, EntityKind::AttDef(a))); + } + d.blocks.insert("TAG".into(), Arc::new(b)); + let mut s = Session::empty(); + s.open_drawing(d, "tags", None); + let r = s.execute("insert", &json!({ "name": "TAG", "at": [100, 0] })).unwrap(); + let h = cadcraft_engine::doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + // The insertion point, FREE and NOTE: no grip for the locked or the invisible attribute. + let g = s.grips_of(h).unwrap(); + assert_eq!(g.iter().map(|p| p.x).collect::>(), [100.0, 100.0, 130.0]); + // NOTE's grip (index 2) dragged up 5: its multiline text moves with it. + s.execute("grip.stretch", &json!({ "handle": h.hex(), "index": 2, "to": [130, 5] })).unwrap(); + let Some(EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| e.kind.clone()) else { panic!("no reference") }; + let note = i.attribs.iter().find(|a| a.tag == "NOTE").unwrap(); + assert_eq!((note.text.insert.y, note.multiline.as_ref().unwrap().mtext.insert.y), (5.0, 5.0)); + let free = i.attribs.iter().find(|a| a.tag == "FREE").unwrap(); + assert_eq!(free.text.insert.y, 0.0, "the others stay"); +} From d3ec8efe19a345e0077ff8c58ed6789bb11e44f9 Mon Sep 17 00:00:00 2001 From: Francesco BV Date: Thu, 29 Oct 2026 10:37:59 +0100 Subject: [PATCH 013/187] INSERT: ATTDIA defaults to 0, the command line, as in AutoCAD AutoCAD's published system variable reference gives ATTDIA an initial value of 0: a typed INSERT asks for attribute values at the command line, which also keeps scripts and agents typing through the command line as before. ATTDIA 1 still opens the Edit Attributes dialog. The dialog tests set ATTDIA 1 themselves; a new check shows the default opens no dialog. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/settings.rs | 4 ++-- crates/engine/src/sysvars/table.rs | 2 +- crates/engine/tests/it/insert_attrib_entry.rs | 18 ++++++++++-------- .../ui-egui/tests/it/insert_attrib_dialog.rs | 15 +++++++++++++-- docs/gaps.md | 2 +- docs/ui-parity.md | 2 +- 6 files changed, 28 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index adbc94fb5..54c44258a 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -131,7 +131,7 @@ pub struct Settings { /// default value. A user setting, as in AutoCAD (not saved in the drawing). pub attreq: bool, /// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes - /// dialog (on by default, as in AutoCAD); off asks at the command line. + /// dialog; off (the default, as in AutoCAD) asks at the command line. pub attdia: bool, } @@ -198,7 +198,7 @@ impl Default for Settings { polardist: 0.0, auditctl: false, attreq: true, - attdia: true, + attdia: false, } } } diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index 72af5b9c0..43cf14277 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -83,7 +83,7 @@ const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool)); const SETTINGS: &[Toggle] = &[ // ATTDIA 1: INSERT typed or from a menu asks for attribute values in the Edit Attributes - // dialog; 0: at the command line. ATTREQ 0: INSERT gives every attribute its default. + // dialog; 0 (the default): at the command line. ATTREQ 0: INSERT gives every attribute its default. ("ATTDIA", |s| s.attdia, |s, v| s.attdia = v), ("ATTREQ", |s| s.attreq, |s, v| s.attreq = v), ("AUDITCTL", |s| s.auditctl, |s, v| s.auditctl = v), diff --git a/crates/engine/tests/it/insert_attrib_entry.rs b/crates/engine/tests/it/insert_attrib_entry.rs index 78e1253c1..79d37e859 100644 --- a/crates/engine/tests/it/insert_attrib_entry.rs +++ b/crates/engine/tests/it/insert_attrib_entry.rs @@ -1,7 +1,7 @@ //! INSERT and the attribute modes (gap F17): Verify attributes are asked twice, Preset ones take -//! their default without asking, ATTREQ 0 gives every attribute its default, and ATTDIA 1 asks -//! for the values all at once in the Edit Attributes dialog (`Session::attribute_entry`), typed -//! answers still working. The JSON form never asks. ATTREQ and ATTDIA are user settings, as in +//! their default without asking, ATTREQ 0 gives every attribute its default, ATTDIA 0 (the +//! default) asks at the command line and ATTDIA 1 asks for the values all at once in the Edit +//! Attributes dialog (`Session::attribute_entry`), typed answers still working. The JSON form never asks. ATTREQ and ATTDIA are user settings, as in //! AutoCAD (DWG keeps them in its header only before R2000). use std::sync::Arc; @@ -36,7 +36,7 @@ fn def(tag: &str, prompt: &str, default: &str, y: f64, constant: bool, modes: At } /// Block T with the definitions A (Verify), B (Preset), C (plain) and D (constant); ATTREQ and -/// ATTDIA as given (their defaults, 1, otherwise). +/// ATTDIA as given (their defaults, ATTREQ 1 and ATTDIA 0, otherwise). fn session(attreq: Option, attdia: Option) -> Session { let mut d = cadcraft_engine::doc::Drawing::new_imperial(); let mut b = Block::new("T"); @@ -87,7 +87,10 @@ fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { #[test] fn typed_insert_asks_verify_twice_and_skips_preset_and_constant() { - let mut s = session(None, Some(false)); + // AutoCAD's default, ATTDIA 0, with no value in the drawing: the command line asks. + let mut s = session(None, None); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 0); + assert_eq!(s.execute("getvar", &json!({ "name": "ATTREQ" })).unwrap()["value"], 1); insert_up_to_the_attributes(&mut s); assert!(s.attribute_entry().is_none(), "ATTDIA 0: no dialog"); assert_eq!(s.prompt_text(), "INSERT First <1>:", "A first"); @@ -128,10 +131,9 @@ fn attreq_0_gives_every_attribute_its_default() { #[test] fn attdia_1_asks_for_every_value_at_once_and_typed_answers_still_work() { - // AutoCAD's default, ATTDIA 1, with no value in the drawing. let mut s = session(None, None); + s.execute("setvar", &json!({ "name": "ATTDIA", "value": 1 })).unwrap(); assert_eq!(s.execute("getvar", &json!({ "name": "ATTDIA" })).unwrap()["value"], 1); - assert_eq!(s.execute("getvar", &json!({ "name": "ATTREQ" })).unwrap()["value"], 1); s.start("insert").unwrap(); s.cmdline("T").unwrap(); assert!(s.attribute_entry().is_none(), "not before the attribute prompts"); @@ -183,7 +185,7 @@ fn json_insert_never_asks_whatever_attreq_and_attdia_say() { #[test] fn hostile_values_never_panic() { - let mut s = session(None, None); + let mut s = session(None, Some(true)); insert_up_to_the_attributes(&mut s); let e = s.attribute_entry().expect("asks"); // Too few answers take the defaults, too many are ignored. diff --git a/crates/ui-egui/tests/it/insert_attrib_dialog.rs b/crates/ui-egui/tests/it/insert_attrib_dialog.rs index 1e0783e66..f194fe969 100644 --- a/crates/ui-egui/tests/it/insert_attrib_dialog.rs +++ b/crates/ui-egui/tests/it/insert_attrib_dialog.rs @@ -13,9 +13,11 @@ use egui_kittest::Harness; use egui_kittest::kittest::{Queryable, by}; use serde_json::json; -/// Block T with the definitions A ("Room", default "101") and B ("Floor", default "1"). +/// Block T with the definitions A ("Room", default "101") and B ("Floor", default "1"), and +/// ATTDIA 1 (the default is 0, the command line). fn app() -> CadApp { let mut app = CadApp::new(Session::new(), Services::default()); + app.run("setvar", json!({ "name": "ATTDIA", "value": 1 })).unwrap(); let a = app.run("attdef", json!({ "tag": "A", "prompt": "Room", "default": "101", "at": [0, 2] })).unwrap(); let b = app.run("attdef", json!({ "tag": "B", "prompt": "Floor", "default": "1", "at": [0, 4] })).unwrap(); app.run("block", json!({ "name": "T", "base": [0, 0], "handles": [a["handle"], b["handle"]], "keep": "delete" })).unwrap(); @@ -118,7 +120,16 @@ fn cancel_inserts_nothing() { #[test] fn no_dialog_with_attdia_0_or_from_json() { let mut a = app(); - a.session.settings.attdia = false; + a.run("setvar", json!({ "name": "ATTDIA", "value": 0 })).unwrap(); + insert(&mut a); + let h = harness(a); + assert!(h.query_by_label("Edit Attributes").is_none()); + assert!(h.state().session.prompt_text().contains("Room"), "asked at the command line"); + + // ATTDIA's default, 0, asks at the command line too. + let mut a = app(); + a.session.settings = Default::default(); + assert!(!a.session.settings.attdia); insert(&mut a); let h = harness(a); assert!(h.query_by_label("Edit Attributes").is_none()); diff --git a/docs/gaps.md b/docs/gaps.md index 6e76a2bca..e5f820618 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -150,7 +150,7 @@ Detail: [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| -| 2026-10-27 | minor | INSERT asks a Verify attribute's value twice and gives a Preset one its default without asking; ATTREQ 0 gives every attribute its default; ATTDIA 1 (the default) asks for the values in the Edit Attributes dialog when INSERT is typed or picked, typed answers still working; both are user settings (SETVAR), not saved in the drawing, as DWG from R2000 has no place for them: F17 narrowed | +| 2026-10-27 | minor | INSERT asks a Verify attribute's value twice and gives a Preset one its default without asking; ATTREQ 0 gives every attribute its default; ATTDIA 1 asks for the values in the Edit Attributes dialog when INSERT is typed or picked, typed answers still working, and 0 (the default) at the command line; both are user settings (SETVAR), not saved in the drawing, as DWG from R2000 has no place for them: F17 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 c91d85f7e..7c25a473d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -149,7 +149,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Clickable keywords in the prompt | yes | yes (`cmdline.rs:253-267`) | | UNDO with Mark, Back, BEgin, End, Auto, Control | yes | count only, whole-document snapshots capped at 2,000 (`lib.rs:477`, `edit.rs:56`) | | SETVAR for every system variable | ~1,000 sysvars | about 60 session/header variables by name (`sysvars.rs`) | -| Attribute values when inserting (ATTREQ, ATTDIA, Verify, Preset) | prompts or the Edit Attributes dialog | both: ATTDIA 1 opens Edit Attributes (OK, Enter, Cancel; typed answers still work), ATTDIA 0 asks at the command line, Verify attributes asked twice there, Preset ones and ATTREQ 0 take their defaults (`attentry.rs`); no Previous/Next pages (one scrolling list) | +| Attribute values when inserting (ATTREQ, ATTDIA, Verify, Preset) | prompts or the Edit Attributes dialog | both: ATTDIA 1 opens Edit Attributes (OK, Enter, Cancel; typed answers still work), ATTDIA 0 (the default) asks at the command line, Verify attributes asked twice there, Preset ones and ATTREQ 0 take their defaults (`attentry.rs`); no Previous/Next pages (one scrolling list) | | Scripts (SCRIPT, `.scr`) | yes | script text via CLI/MCP/control; no `.scr` file command | | Floating/docked command window, transparency, lines of history | yes | floating overlay, history lines setting | From ee0697955c07bf4039c00a16680fbb8c827c2d6d Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 13 Oct 2026 10:25:42 -0600 Subject: [PATCH 014/187] Dynamic block references: rotation and flip parameters and their rotate and flip actions Angle1 (degrees, as Properties shows them) turns the rotate action's objects about its base point; Flip state1 mirrors the flip action's objects across the current reflection line (text stays readable). Parameters in the selection are carried along, attributes follow, the flip grip's record and the history are written as AutoCAD writes them. Checked against AutoCAD's own output for the same changes: value records, history and geometry match. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 81 ++++++++++-- crates/doc/src/dynblock/apply.rs | 190 ++++++++++++++++++++++++--- crates/doc/src/dynblock/reference.rs | 28 +++- 3 files changed, 268 insertions(+), 31 deletions(-) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index ef0a88be2..3b60c7aca 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -52,6 +52,10 @@ pub struct DynamicBlock { /// the grips shown in them by object). #[serde(skip)] pub grip_objects: Vec<(i32, Handle)>, + /// Where each grip object is in the dynamic block, by graph id (a flip grip's place along its + /// reflection line). + #[serde(skip)] + pub grip_points: Vec<(i32, Vec3)>, } /// One parameter: a property a reference to the block can change. @@ -91,12 +95,14 @@ pub enum ParameterKind { Polar { base: Vec3, end: Vec3 }, /// Horizontal and vertical distances from a base point. Xy { base: Vec3, end: Vec3 }, - /// An angle about a base point. - Rotation { base: Vec3, end: Vec3 }, + /// An angle about a base point (Angle1): the end point turns about the base. The angle is + /// measured from the direction the dynamic block has from base to end. + Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet }, /// Aligns the reference with nearby geometry. Alignment { base: Vec3, end: Vec3 }, - /// Mirrors the objects about a reflection line. - Flip { base: Vec3, end: Vec3 }, + /// Mirrors the objects about the reflection line from base to end (Flip state1); the names + /// of its two states, not flipped and flipped. + Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] }, /// A position (Position1). Point { at: Vec3, label: String, description: String }, /// Named sets of visible objects. @@ -122,6 +128,8 @@ impl ParameterKind { match self { ParameterKind::Linear { label, .. } | ParameterKind::Point { label, .. } + | ParameterKind::Rotation { label, .. } + | ParameterKind::Flip { label, .. } | ParameterKind::Visibility { label, .. } | ParameterKind::Lookup { label, .. } => Some(label), _ => None, @@ -213,7 +221,11 @@ pub enum ActionKind { angle_offset: f64, }, Scale, - Rotate, + /// Turns the objects about its base point by the change of a rotation parameter's angle. + Rotate { + base: ActionBase, + }, + /// Mirrors the objects across a flip parameter's reflection line when its state changes. Flip, Array, PolarStretch, @@ -223,6 +235,16 @@ pub enum ActionKind { }, } +/// Where an action that turns or scales its objects has its base point. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ActionBase { + /// It follows the parameter's base point, at `offset` from it; else it stays at `at`. + pub dependent: bool, + pub offset: Vec3, + pub at: Vec3, +} + /// A lookup table column: the parameter value it reads or sets. #[derive(Clone, Debug, Default, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] @@ -361,6 +383,7 @@ pub fn dynamic_block(d: &Drawing, name: &str) -> Option { } else { if kind.ends_with("GRIP") { out.grip_objects.push((node, o.handle)); + out.grip_points.push((node, Cursor::new(section(&secs, "AcDbBlockGrip")).point(1010))); } out.other.push(o.kind.clone()); } @@ -409,14 +432,28 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind { ParameterKind::Lookup { at: one(), label: c.string(303), description: c.string(304) } } "BLOCKBASEPOINTPARAMETER" => ParameterKind::BasePoint { at: one() }, - "BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKROTATIONPARAMETER" | "BLOCKALIGNMENTPARAMETER" | "BLOCKFLIPPARAMETER" => { + // Its name and description (305, 306), the base angle point (1011) and angle (140), then + // the value set. + "BLOCKROTATIONPARAMETER" => { + let (base, end) = two(); + let mut c = Cursor::new(section(secs, "AcDbBlockRotationParameter")); + let (label, description) = (c.string(305), c.string(306)); + ParameterKind::Rotation { base, end, label, description, values: value_set(&mut c) } + } + // Its name and description (305, 306) and its states' names (307 not flipped, 308 flipped). + "BLOCKFLIPPARAMETER" => { + let (base, end) = two(); + let mut c = Cursor::new(section(secs, "AcDbBlockFlipParameter")); + let (label, description) = (c.string(305), c.string(306)); + let states = [c.string(307), c.string(308)]; + ParameterKind::Flip { base, end, label, description, states } + } + "BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKALIGNMENTPARAMETER" => { let (base, end) = two(); match kind { "BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end }, "BLOCKXYPARAMETER" => ParameterKind::Xy { base, end }, - "BLOCKROTATIONPARAMETER" => ParameterKind::Rotation { base, end }, - "BLOCKALIGNMENTPARAMETER" => ParameterKind::Alignment { base, end }, - _ => ParameterKind::Flip { base, end }, + _ => ParameterKind::Alignment { base, end }, } } other => ParameterKind::Other { dxf_type: other.to_string() }, @@ -471,8 +508,19 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[ (two_connections(tags), ActionKind::Move { multiplier, angle_offset }) } "BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale), - "BLOCKROTATEACTION" => (Vec::new(), ActionKind::Rotate), - "BLOCKFLIPACTION" => (Vec::new(), ActionKind::Flip), + "BLOCKROTATEACTION" => { + let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt")); + let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction")); + connections.push((c.int(94), c.string(303))); + (connections, ActionKind::Rotate { base: action_base(section(secs, "AcDbBlockActionWithBasePt")) }) + } + // Its four connections: the parameter (92-95) and the values it reads (301-304). + "BLOCKFLIPACTION" => { + let tags = section(secs, "AcDbBlockFlipAction"); + let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string(); + let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect(); + (connections, ActionKind::Flip) + } "BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array), "BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch), other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }), @@ -480,6 +528,17 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[ Action { node, handle, name, at, selection, connections, kind } } +/// The base point of an action that has one: after its two connections (92/93, 301/302), the +/// offset from the parameter's base point (1011), whether it follows that point (280), and the +/// point it stays at when it doesn't (1012). +fn action_base(tags: &[RawTag]) -> ActionBase { + let mut c = Cursor::new(tags); + c.next(302); + let offset = c.point(1011); + let dependent = c.int(280) != 0; + ActionBase { dependent, offset, at: c.point(1012) } +} + /// Two connections: parameter ids (92, 93) and the values they read (301, 302). Writers order /// these groups differently (92 93 301 302, or 92 301 93 302), so each is read on its own. fn two_connections(tags: &[RawTag]) -> Vec<(i32, String)> { diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index ed5281bf6..78af9d279 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -92,6 +92,26 @@ enum Val { Point(Vec3), /// A two-point parameter's base and end points. Points(Vec3, Vec3), + /// A flip parameter's reflection line (base, end) and whether it is flipped. + Flip(Vec3, Vec3, bool), + /// A flip grip's state: its value record's last group 70. + State(bool), +} + +/// A rotation parameter's angle (radians, 0 to 2π): its end's direction from its base, from the +/// direction `home` the dynamic block has (base to end). +fn rotation_angle(b: Vec3, e: Vec3, home: (Vec3, Vec3)) -> f64 { + let (now, zero) = ((e - b).xy(), (home.1 - home.0).xy()); + (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU) +} + +/// The end point that gives a rotation parameter with base `b` and end `e` the angle `a` from the +/// direction `home` the dynamic block has. +fn rotation_end(b: Vec3, e: Vec3, home: (Vec3, Vec3), a: f64) -> Vec3 { + let r = (e - b).len(); + let zero = (home.1 - home.0).xy(); + let dir = Vec2::new(zero.y.atan2(zero.x).cos(), zero.y.atan2(zero.x).sin()).rotate(a); + b + (dir * r).to3(0.0) } /// A parameter's current value on the reference: the value it was given, else the block's own. @@ -102,15 +122,16 @@ fn current(m: &DynamicBlock, values: &BTreeMap, node: i32) -> Option (_, Some(Value::Text { value })) => Val::Text(value.clone()), (_, Some(Value::Point { at })) => Val::Point(*at), (_, Some(Value::Points { base, end })) => Val::Points(*base, *end), + (_, Some(Value::Flip { base, end, flipped })) => Val::Flip(*base, *end, *flipped), + (ParameterKind::Flip { base, end, .. }, None) => Val::Flip(*base, *end, false), (ParameterKind::Visibility { states, .. }, None) => Val::Text(states.first().map(|s| s.name.clone()).unwrap_or_default()), (ParameterKind::Point { at, .. }, None) => Val::Point(*at), ( ParameterKind::Linear { base, end, .. } | ParameterKind::Polar { base, end } | ParameterKind::Xy { base, end } - | ParameterKind::Rotation { base, end } - | ParameterKind::Alignment { base, end } - | ParameterKind::Flip { base, end }, + | ParameterKind::Rotation { base, end, .. } + | ParameterKind::Alignment { base, end }, None, ) => Val::Points(*base, *end), _ => return None, @@ -303,6 +324,33 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> let at = if is_x { Vec3::new(block_base.x + v / sx, at.y, at.z) } else { Vec3::new(at.x, block_base.y + v / sy, at.z) }; plan.set.insert(p.node, Val::Point(at)); } + // An angle in degrees, as Properties shows it, snapped to the parameter's values. + (ParameterKind::Rotation { base: hb, end: he, values, label, .. }, None) => { + let typed = number(value)?.to_radians().rem_euclid(std::f64::consts::TAU); + let a = allowed(values, typed); + if !a.is_finite() { + return Err(format!("\"{value}\" is not an angle for {label}.")); + } + let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; + plan.set.insert(p.node, Val::Points(b, rotation_end(b, e, (*hb, *he), a))); + plan.chain(&m, &r.values, p.node, "UpdatedAngle")?; + } + // A state by name (or 0 / 1); its flip grip's record follows. + (ParameterKind::Flip { states, label, .. }, None) => { + let v = value.trim(); + let flipped = if v.eq_ignore_ascii_case(&states[1]) || v == "1" { + true + } else if v.eq_ignore_ascii_case(&states[0]) || v == "0" { + false + } else { + return Err(format!("\"{value}\" is not a state of {label}: {}, {}.", states[0], states[1])); + }; + let Some(Val::Flip(b, e, _)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no reflection line.")) }; + plan.set.insert(p.node, Val::Flip(b, e, flipped)); + if let Some(g) = p.grips.first().filter(|g| **g != 0) { + plan.set.insert(*g, Val::State(flipped)); + } + } _ => return Err(format!("CADCraft can't change {name} yet.")), } apply(d, insert, &r.definition, &r.values, &plan.set, p.node) @@ -357,6 +405,17 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) }; plan.set.insert(node, Val::Point(Vec3::new(q.x, q.y, at.z))); } + // The angle from the base to the point, snapped to the parameter's values. + (ParameterKind::Rotation { base: hb, end: he, values, label, .. }, GripPart::End) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; + let q3 = Vec3::new(q.x, q.y, b.z); + if (q3 - b).len() < 1e-12 { + return Err(format!("{label} needs a point away from its base.")); + } + let a = allowed(values, rotation_angle(b, q3, (*hb, *he))); + plan.set.insert(node, Val::Points(b, rotation_end(b, e, (*hb, *he), a))); + plan.chain(&m, &r.values, node, "UpdatedAngle")?; + } _ => return Err("That grip can't be dragged.".into()), } apply(d, insert, &r.definition, &r.values, &plan.set, node) @@ -445,13 +504,38 @@ fn apply( let copy_of = |dh: &Handle| def_tags.get(dh).and_then(|t| src_by_tag.get(t)).copied(); // New values, starting from the change; actions add the parameters they carry along. let mut new: BTreeMap = set.clone(); - let mut moves: HashMap>, Vec2)>> = HashMap::new(); + let mut moves: HashMap> = HashMap::new(); let param_of: HashMap = m.parameters.iter().map(|p| (p.handle, p.node)).collect(); for a in &m.actions { let changed: Vec<&(i32, String)> = a.connections.iter().filter(|(n, _)| set.contains_key(n)).collect(); if changed.is_empty() { continue; } + // Rotate and flip actions turn or mirror their objects, and carry the parameters in their + // selection the same way. + if let Some(t) = turn_or_mirror(&m, values, set, a) { + for h in &a.selection { + if let Some(node) = param_of.get(h) { + if set.contains_key(node) { + continue; + } + let Some(cur) = new.get(node).cloned().or_else(|| current(&m, values, *node)) else { continue }; + let p = |q: Vec3| t.apply(q.xy()).to3(q.z); + let moved = match cur { + Val::Point(q) => Val::Point(p(q)), + Val::Points(b, e) => Val::Points(p(b), p(e)), + Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f), + other => other, + }; + new.insert(*node, moved); + continue; + } + if let Some(c) = copy_of(h) { + moves.entry(c).or_default().push(Op::Transform(t)); + } + } + continue; + } let (mult, angle, frame, vertices): (f64, f64, &[Vec2], &[(Handle, Vec)]) = match &a.kind { ActionKind::Stretch { frame, vertices, multiplier, angle_offset } => (*multiplier, *angle_offset, frame, vertices), ActionKind::Move { multiplier, angle_offset } => (*multiplier, *angle_offset, &[], &[]), @@ -496,6 +580,8 @@ fn apply( (Val::Point(p), _) => Val::Point(shift(p, None)), (Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))), (Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)), + (Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f), + (Val::Flip(b, e, f), _) => Val::Flip(shift(b, None), shift(e, None), f), (t, _) => t, }; new.insert(*node, moved); @@ -503,7 +589,7 @@ fn apply( } let Some(c) = copy_of(h) else { continue }; let idx = vtx_by_handle.get(h).map(|i| (*i).clone()); - moves.entry(c).or_default().push((idx, v)); + moves.entry(c).or_default().push(Op::Move(idx, v)); } } // Visibility states. @@ -530,15 +616,21 @@ fn apply( for e in src.entities.iter() { copies.insert(e.handle, d.new_handle()); } - // How far each attribute definition moves (block coordinates): the reference's attribute of - // that tag moves with it, as AutoCAD moves it. - let attrib_moves: HashMap = src + // How each attribute definition moves, turns or mirrors (block coordinates): the reference's + // attribute of that tag follows it, as AutoCAD moves it. + let attrib_moves: HashMap = src .entities .iter() .filter_map(|e| match &e.kind { EntityKind::AttDef(ad) => { - let v = moves.get(&e.handle).into_iter().flatten().fold(Vec2::ZERO, |acc, (_, v)| acc + *v); - (v != Vec2::ZERO).then(|| (ad.tag.to_ascii_uppercase(), v)) + let ops = moves.get(&e.handle)?; + let t = ops.iter().fold(Mat3::IDENTITY, |acc, op| { + acc.then(match op { + Op::Move(_, v) => Mat3::translate(*v), + Op::Transform(t) => *t, + }) + }); + Some((ad.tag.to_ascii_uppercase(), t)) } _ => None, }) @@ -556,8 +648,11 @@ fn apply( if let Some(v) = shown_copy.get(&e.handle) { c.common.visible = *v; } - for (idx, v) in moves.get(&e.handle).into_iter().flatten() { - move_entity(&mut c, idx.as_deref(), *v); + for op in moves.get(&e.handle).into_iter().flatten() { + match op { + Op::Move(idx, v) => move_entity(&mut c, idx.as_deref(), *v), + Op::Transform(t) => c.kind.transform(t), + } } if let EntityKind::Hatch(h) = &mut c.kind { for l in &mut h.loops { @@ -594,21 +689,22 @@ fn apply( let xdata = vec![tag(1001, BTAG), tag(1070, "1"), tag(1005, rec.hex())]; f.records.insert(("BLOCK_RECORD".into(), name.to_ascii_uppercase()), ForeignExtra { xdata, ..Default::default() }); } - // The block-to-drawing transform's linear part turns a block-coordinate move into the move of - // the reference's attribute. + // A block-coordinate change of an attribute definition, seen in the drawing (through the + // block-to-drawing transform), is the change of the reference's attribute. let to_world = ins.transform(src.base.xy()); - let origin = to_world.apply(Vec2::ZERO); + let to_block = to_world.inverse().unwrap_or(Mat3::IDENTITY); d.modify_entity(insert, |e| { if let EntityKind::Insert(i) = &mut e.kind { i.block = name.clone(); for a in &mut i.attribs { - if let Some(v) = attrib_moves.get(&a.tag.to_ascii_uppercase()) { - let w = to_world.apply(*v) - origin; + if let Some(t) = attrib_moves.get(&a.tag.to_ascii_uppercase()) { + let w = to_block.then(*t).then(to_world); let mut k = EntityKind::Text(a.text.clone()); - k.transform(&Mat3::translate(w)); + k.transform(&w); if let EntityKind::Text(t) = k { a.text = t; } + a.transform_multiline(&w); } } } @@ -891,6 +987,13 @@ fn write_history(tags: &mut Vec, p: &super::Parameter, old: Option<&Val> (ParameterKind::Visibility { label, .. } | ParameterKind::Lookup { label, .. }, Val::Text(t)) => { vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(1, t.clone())])] } + (ParameterKind::Rotation { label, base: hb, end: he, .. }, Val::Points(b, e)) => { + let a = rotation_angle(*b, *e, (*hb, *he)); + vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(40, a.to_string())])] + } + (ParameterKind::Flip { label, .. }, Val::Flip(_, _, f)) => { + vec![(p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(70, i32::from(*f).to_string())])] + } (ParameterKind::Linear { label, .. }, Val::Points(b, e)) => { let mut c: Vec<(i32, Vec)> = p.grips.iter().filter(|g| **g != 0).map(|g| (*g, Vec::new())).collect(); c.push((p.node, vec![tag(1071, p.node.to_string()), tag(300, label.clone()), tag(40, (*e - *b).len().to_string())])); @@ -928,8 +1031,15 @@ fn write_value(tags: &mut Vec, v: &Val) { return; } Val::Point(p) => vec![*p], - Val::Points(b, e) => vec![*b, *e], + Val::Points(b, e) | Val::Flip(b, e, _) => vec![*b, *e], + Val::State(f) => { + set_state(tags, *f); + return; + } }; + if let Val::Flip(_, _, f) = v { + set_state(tags, *f); + } for (i, p) in points.iter().enumerate() { // The i-th point's groups, else new ones before any text. let find = |tags: &[RawTag], code: i32, n: usize| tags.iter().enumerate().filter(|(_, t)| t.code == code).nth(n).map(|(j, _)| j); @@ -953,6 +1063,48 @@ fn write_value(tags: &mut Vec, v: &Val) { } } +/// Set a record's state, its last group 70 after the header's two (`70 25`, `70 104`), adding +/// it when the record has none. +fn set_state(tags: &mut Vec, on: bool) { + let at: Vec = tags.iter().enumerate().filter(|(_, t)| t.code == 70).map(|(i, _)| i).collect(); + match at.get(2..).and_then(|rest| rest.last()) { + Some(&i) => { + if let Some(t) = tags.get_mut(i) { + t.value = i32::from(on).to_string(); + } + } + None => tags.push(tag(70, i32::from(on).to_string())), + } +} + +/// The turn or mirror action `a` makes with the changes `set`, if it is one and they change it: +/// a rotate action turns about its base point by the change of its rotation parameter's angle; +/// a flip action mirrors across its flip parameter's reflection line when the state changes. +fn turn_or_mirror(m: &DynamicBlock, values: &BTreeMap, set: &BTreeMap, a: &super::Action) -> Option { + match &a.kind { + ActionKind::Rotate { base } => { + let (node, _) = a.connections.iter().find(|(_, c)| c.eq_ignore_ascii_case("AngleDelta"))?; + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return None }; + let turn = (*ne - *nb).xy().angle() - (oe - ob).xy().angle(); + let pivot = if base.dependent { *nb + base.offset } else { base.at }; + (turn.abs() > 1e-12 && turn.is_finite()).then(|| Mat3::rotate_about(pivot.xy(), turn)) + } + ActionKind::Flip => { + let (node, _) = a.connections.first()?; + let (Some(Val::Flip(b, e, now)), Some(Val::Flip(_, _, was))) = (set.get(node), current(m, values, *node)) else { return None }; + (now != &was && (*e - *b).len() > 1e-12).then(|| Mat3::mirror(b.xy(), e.xy())) + } + _ => None, + } +} + +/// One change to a copied object: a move (of the listed vertices, else all of it) or a turn or +/// mirror. +enum Op { + Move(Option>, Vec2), + Transform(Mat3), +} + /// Remove anonymous block `name` when nothing refers to it any more (the block a changed /// reference used to show), with the data kept for its record. fn drop_if_unused(d: &mut Drawing, name: &str) { diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 3465a9f94..89ce5b102 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -29,6 +29,8 @@ pub enum Value { Point { at: Vec3 }, /// A two-point parameter's points. Points { base: Vec3, end: Vec3 }, + /// A flip parameter's reflection line and whether it is flipped. + Flip { base: Vec3, end: Vec3, flipped: bool }, } /// A dynamic block reference. @@ -91,7 +93,8 @@ fn entries(objects: &HashMap, dict: Handle) -> Vec<(Stri out } -/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30). +/// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip +/// parameter's also ends with its state, a group 70 after the header's two (`70 25`, `70 104`). fn value(o: &ForeignObject) -> Option { if let Some(t) = o.tags.iter().find(|t| t.code == 1) { return Some(Value::Text { value: t.value.clone() }); @@ -100,7 +103,9 @@ fn value(o: &ForeignObject) -> Option { o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) }; let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0))); + let states: Vec<&str> = o.tags.iter().filter(|t| t.code == 70).map(|t| t.value.trim()).collect(); match (point(0), point(1)) { + (Some(base), Some(end)) if states.len() > 2 => Some(Value::Flip { base, end, flipped: states.last() == Some(&"1") }), (Some(base), Some(end)) => Some(Value::Points { base, end }), (Some(at), None) => Some(Value::Point { at }), _ => None, @@ -133,6 +138,12 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option { Some(Reference { definition, values }) } +/// An angle (radians) as Properties shows it: degrees with AUPREC decimals. +fn angle_text(d: &Drawing, a: f64) -> String { + let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0); + format!("{:.prec$}", a.to_degrees()) +} + /// A number as the drawing shows lengths (LUPREC decimals). fn number(d: &Drawing, v: f64) -> String { let prec = usize::try_from(d.header.i64("LUPREC", 4).clamp(0, 8)).unwrap_or(4); @@ -247,6 +258,21 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec { + let (b, e) = match v { + Some(Value::Points { base, end }) => (*base, *end), + _ => (*hb, *he), + }; + let now = (e - b).xy(); + let zero = (*he - *hb).xy(); + let a = (now.y.atan2(now.x) - zero.y.atan2(zero.x)).rem_euclid(std::f64::consts::TAU); + out.push(CustomProperty { name: label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true }); + } + ParameterKind::Flip { label, states, .. } => { + let flipped = matches!(v, Some(Value::Flip { flipped: true, .. })); + let value = states[usize::from(flipped)].clone(); + out.push(CustomProperty { name: label.clone(), value, choices: states.to_vec(), editable: true }); + } ParameterKind::Visibility { label, states, .. } => { let value = cur.property(p.node, "VisibilityState").unwrap_or_default(); out.push(CustomProperty { name: label.clone(), value, choices: states.iter().map(|s| s.name.clone()).collect(), editable: true }); From ebeb2638748caff62525ee0e61d8a0e95ca27fb0 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 13 Oct 2026 11:06:18 -0600 Subject: [PATCH 015/187] Dynamic blocks: rotation and flip grips, flip state after the points, tests A rotation parameter's grip (a circle at the radius' end) turns the angle when dragged (a typed number sets it, in degrees); a flip grip (an arrow across the reflection line, placed from its grip object and turning with the line) flips at a click. A flip value record keeps its state after its points, also in a record CADCraft writes without a template. A synthetic Symbol fixture covers reading, turning, flipping, grips and bad values. Also: #967's test expectation counts positions from 0. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 11 +- crates/doc/src/dynblock/grips.rs | 60 ++- crates/doc/src/dynblock/reference.rs | 8 +- crates/engine/src/cmd/blocks.rs | 6 +- crates/engine/src/cmd/blocks/dyngrip.rs | 29 +- crates/io/tests/data/dynblock_symbol.txt | 469 +++++++++++++++++++++++ crates/io/tests/dynblock_rotate_flip.rs | 153 ++++++++ crates/ui-egui/src/dyngrips.rs | 34 +- docs/file-format-parity.md | 1 + docs/gaps.md | 1 + 10 files changed, 745 insertions(+), 27 deletions(-) create mode 100644 crates/io/tests/data/dynblock_symbol.txt create mode 100644 crates/io/tests/dynblock_rotate_flip.rs diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 78af9d279..257aa9e6c 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -1063,11 +1063,16 @@ fn write_value(tags: &mut Vec, v: &Val) { } } -/// Set a record's state, its last group 70 after the header's two (`70 25`, `70 104`), adding -/// it when the record has none. +/// Set a record's state: a flip value's group 70 after its points, a flip grip's last group 70 +/// after the header's two (`70 25`, `70 104`); added at the end when the record has none. fn set_state(tags: &mut Vec, on: bool) { + let first_point = tags.iter().position(|t| t.code == 10); let at: Vec = tags.iter().enumerate().filter(|(_, t)| t.code == 70).map(|(i, _)| i).collect(); - match at.get(2..).and_then(|rest| rest.last()) { + let last = match first_point { + Some(p) => at.iter().rev().find(|i| **i > p), + None => at.get(2..).and_then(|rest| rest.last()), + }; + match last { Some(&i) => { if let Some(t) = tags.get_mut(i) { t.value = i32::from(on).to_string(); diff --git a/crates/doc/src/dynblock/grips.rs b/crates/doc/src/dynblock/grips.rs index 301d9ecad..2a349e73f 100644 --- a/crates/doc/src/dynblock/grips.rs +++ b/crates/doc/src/dynblock/grips.rs @@ -1,7 +1,9 @@ //! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an -//! arrow at each end of a distance (linear parameter), a square at a position (point parameter) -//! and a down-pointing triangle for a list (visibility states, lookup values). Dragging an arrow -//! or square is [`super::drag_grip`]; a list grip offers its property's choices. +//! arrow at each end of a distance (linear parameter), a square at a position (point parameter), +//! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line +//! (flip parameter) and a down-pointing triangle for a list (visibility states, lookup values). +//! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a +//! list grip offers its property's choices. //! //! With a visibility parameter, a state lists the grips shown in it; the others are hidden. @@ -56,6 +58,10 @@ pub enum GripShape { Point, /// A down-pointing triangle: click it for the property's choices. List, + /// A circle at the end of an angle: drag it to turn the angle. + Rotation, + /// An arrow across a reflection line: click it to flip (its choices are the two states). + Flip, } /// One grip of a dynamic block reference. @@ -120,6 +126,7 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { }; // The grips the current visibility state shows (all of them without visibility states). let objects: HashMap = m.grip_objects.iter().copied().collect(); + let points: HashMap = m.grip_points.iter().copied().collect(); let mut shown_in_state: Option> = None; let mut visibility_node = None; for p in &m.parameters { @@ -171,6 +178,53 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { } } } + ParameterKind::Rotation { base, end, label, .. } => { + let (b, e) = match r.values.get(&p.node) { + Some(Value::Points { base, end }) => (*base, *end), + _ => (*base, *end), + }; + if shown(p.node, grip(1)) { + let u = e - b; + let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) }; + let (at, dir) = (world(e), toward(e, u)); + out.push(DynGrip { + node: p.node, + part: GripPart::End, + shape: GripShape::Rotation, + at, + dir, + property: label.clone(), + choices: Vec::new(), + }); + } + } + ParameterKind::Flip { base: hb, end: he, label, states, .. } => { + let (b, e, flipped) = match r.values.get(&p.node) { + Some(Value::Flip { base, end, flipped }) => (*base, *end, *flipped), + _ => (*hb, *he, false), + }; + let id = grip(0); + let (home, now) = ((*he - *hb).xy(), (e - b).xy()); + if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 { + // The grip object's place, kept along and across the reflection line as the + // line turns or moves with other actions. + let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy(); + let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len())); + let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x); + let at = b.xy() + now * along + u.perp() * across; + let across_dir = if flipped { -u.perp() } else { u.perp() }; + let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0))); + out.push(DynGrip { + node: p.node, + part: GripPart::Base, + shape: GripShape::Flip, + at: world(at3), + dir, + property: label.clone(), + choices: states.to_vec(), + }); + } + } ParameterKind::Point { at, label, .. } => { let at = match r.values.get(&p.node) { Some(Value::Point { at }) => *at, diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 89ce5b102..d74888ff1 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -94,7 +94,8 @@ fn entries(objects: &HashMap, dict: Handle) -> Vec<(Stri } /// A value XRECORD: its text (group 1) when it has one, else its points (10/20/30); a flip -/// parameter's also ends with its state, a group 70 after the header's two (`70 25`, `70 104`). +/// parameter's also has its state, a group 70 after its points (the header's `70 25`, `70 104` +/// come before them). fn value(o: &ForeignObject) -> Option { if let Some(t) = o.tags.iter().find(|t| t.code == 1) { return Some(Value::Text { value: t.value.clone() }); @@ -103,9 +104,10 @@ fn value(o: &ForeignObject) -> Option { o.tags.iter().filter(|t| t.code == code).nth(i).and_then(|t| t.value.trim().parse::().ok()).filter(|v| v.is_finite()) }; let point = |i: usize| Some(Vec3::new(num(10, i)?, num(20, i)?, num(30, i).unwrap_or(0.0))); - let states: Vec<&str> = o.tags.iter().filter(|t| t.code == 70).map(|t| t.value.trim()).collect(); + let first_point = o.tags.iter().position(|t| t.code == 10).unwrap_or(o.tags.len()); + let state = o.tags.get(first_point..).unwrap_or_default().iter().rev().find(|t| t.code == 70).map(|t| t.value.trim() == "1"); match (point(0), point(1)) { - (Some(base), Some(end)) if states.len() > 2 => Some(Value::Flip { base, end, flipped: states.last() == Some(&"1") }), + (Some(base), Some(end)) if state.is_some() => Some(Value::Flip { base, end, flipped: state == Some(true) }), (Some(base), Some(end)) => Some(Value::Points { base, end }), (Some(at), None) => Some(Value::Point { at }), _ => None, diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index ca4cfffec..445045677 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -59,14 +59,14 @@ pub fn specs() -> Vec { .enabled(has_doc) .noundo(), CommandSpec::new("blocks.reference.set", "Set Dynamic Property", run_reference_set) - .params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance or \"Position1 X\"), value (lengths in drawing units)} → {properties}") + .params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}") .enabled(has_doc), CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips) - .params("{handle} → [{node, part: base|end|at, shape: linear|point|list, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)") + .params("{handle} → [{node, part: base|end|at, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)") .enabled(has_doc) .noundo(), CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip) - .params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it") + .params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle") .enabled(has_doc), CommandSpec::new("purge", "Purge", purge::run) .alias(&["pu", "-purge"]) diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index dbc92b7fb..ece7d24b7 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -1,7 +1,7 @@ //! Grips of dynamic block references: `blocks.reference.grips` lists them, `blocks.reference.grip` //! drags one (one undo step), and [`Session::start_dyn_grip`] starts the drag the UI's click on a //! grip begins, with the reference re-evaluated under the cursor as its preview. Typing a number -//! at a distance's grip sets the distance. +//! at a distance's grip sets the distance, at a rotation grip the angle (degrees). use cadcraft_doc::color::Color; use cadcraft_doc::dynblock::{self, GripPart, GripShape}; @@ -114,9 +114,9 @@ struct DynGripEdit { part: GripPart, /// Where the grip is (the rubber band's start). from: Vec2, - /// The property it changes, and whether it is a distance (a typed number sets it). + /// The property it changes, and the grip's shape (a typed number sets a distance or angle). property: String, - distance: bool, + shape: GripShape, } impl Interactive for DynGripEdit { @@ -129,10 +129,10 @@ impl Interactive for DynGripEdit { } fn prompt(&self, _s: &Session) -> Prompt { - let (msg, accept) = if self.distance { - ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER) - } else { - ("** STRETCH ** Specify stretch point", Accept::POINT) + let (msg, accept) = match self.shape { + GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER), + GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER), + _ => ("** STRETCH ** Specify stretch point", Accept::POINT), }; Prompt::new(msg, accept).kw(&["eXit"]).base(self.from) } @@ -141,7 +141,7 @@ impl Interactive for DynGripEdit { let to = match i { Input::Point(p) => p, Input::Deferred(d) => d.at, - Input::Text(t) if self.distance => { + Input::Text(t) if matches!(self.shape, GripShape::Linear | GripShape::Rotation) => { let mut d = s.doc()?.clone(); dynblock::set_property(&mut d, self.handle, &self.property, t.trim()).map_err(EngineError::Other)?; *s.doc_mut()? = d; @@ -174,8 +174,8 @@ impl Interactive for DynGripEdit { impl Session { /// Start dragging grip `part` of parameter `node` of dynamic block reference `handle` (the - /// UI's click on a dynamic grip). A list grip (visibility, lookup) has no drag: the UI offers - /// its choices and sets them with `blocks.reference.set`. + /// UI's click on a dynamic grip). A list grip (visibility, lookup) or a flip grip has no + /// drag: the UI offers the choices, or flips, with `blocks.reference.set`. pub fn start_dyn_grip(&mut self, handle: Handle, node: i32, part: GripPart) -> Result<()> { if self.running.is_some() { self.cancel(); @@ -184,17 +184,18 @@ impl Session { .into_iter() .find(|g| g.node == node && g.part == part) .ok_or_else(|| EngineError::Other("no such grip".into()))?; - if g.shape == GripShape::List { - return Err(EngineError::Other("a list grip is chosen from, not dragged".into())); + if matches!(g.shape, GripShape::List | GripShape::Flip) { + return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into())); } - let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, distance: g.shape == GripShape::Linear }; + let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" }; + let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape }; let machine = crate::guard::Guarded::wrap(Box::new(edit)); let st = self.state()?; let (before, selection_before) = (st.doc.clone(), st.selection.clone()); self.running = Some(Running { id: "grip".into(), machine, before, selection_before }); self.pending_window = None; self.point_mods.clear(); - self.echo("** STRETCH **"); + self.echo(label); Ok(()) } } diff --git a/crates/io/tests/data/dynblock_symbol.txt b/crates/io/tests/data/dynblock_symbol.txt new file mode 100644 index 000000000..09dbdc486 --- /dev/null +++ b/crates/io/tests/data/dynblock_symbol.txt @@ -0,0 +1,469 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 200 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 3 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Symbol +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Symbol +70 2 +10 0 +20 0 +30 0 +3 Symbol +1 +0 CIRCLE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbCircle +10 0 +20 0 +30 0 +40 1 +0 LINE +5 31 +330 1D +100 AcDbEntity +8 0 +100 AcDbLine +10 0 +20 0 +30 0 +11 0 +21 3 +31 0 +0 ATTDEF +5 32 +330 1D +100 AcDbEntity +8 0 +100 AcDbText +10 1 +20 2 +30 0 +40 1 +1 X +50 90 +7 Standard +100 AcDbAttributeDefinition +3 Tag +2 TAG +70 0 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +102 {ACAD_REACTORS +330 60 +102 } +330 60 +100 AcDbEvalGraph +96 8 +97 8 +91 0 +93 32 +95 15 +360 62 +92 -1 +92 -1 +92 -1 +92 -1 +91 1 +93 32 +95 16 +360 63 +92 -1 +92 -1 +92 -1 +92 -1 +91 2 +93 32 +95 19 +360 64 +92 -1 +92 -1 +92 -1 +92 -1 +91 3 +93 32 +95 20 +360 65 +92 -1 +92 -1 +92 -1 +92 -1 +91 4 +93 32 +95 21 +360 66 +92 -1 +92 -1 +92 -1 +92 -1 +91 5 +93 32 +95 25 +360 67 +92 -1 +92 -1 +92 -1 +92 -1 +91 6 +93 32 +95 26 +360 68 +92 -1 +92 -1 +92 -1 +92 -1 +91 7 +93 32 +95 30 +360 69 +0 BLOCKROTATIONPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 15 +98 33 +99 232 +100 AcDbBlockElement +300 Rotation +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 0 +91 16 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockRotationParameter +305 Angle1 +306 +1011 2 +1021 0 +1031 0 +140 0 +307 +96 3 +141 0 +142 6.283185307179586 +143 0 +175 0 +0 BLOCKROTATIONGRIP +5 63 +330 61 +100 AcDbEvalExpr +90 16 +98 33 +99 232 +100 AcDbBlockElement +300 Grip +98 33 +99 232 +1071 0 +100 AcDbBlockGrip +91 0 +92 0 +1010 2 +1020 0 +1030 0 +280 0 +93 -1 +100 AcDbBlockRotationGrip +0 BLOCKROTATEACTION +5 64 +330 61 +100 AcDbEvalExpr +90 19 +98 33 +99 232 +100 AcDbBlockElement +300 Rotate +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 2 +91 0 +91 0 +71 4 +330 31 +330 32 +330 65 +330 68 +1010 1 +1020 1 +1030 0 +100 AcDbBlockActionWithBasePt +92 15 +93 15 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockRotationAction +94 15 +303 AngleDelta +0 BLOCKFLIPPARAMETER +5 65 +330 61 +100 AcDbEvalExpr +90 20 +98 33 +99 232 +100 AcDbBlockElement +300 Flip +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 -10 +1021 0 +1031 0 +170 4 +91 21 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockFlipParameter +305 Flip state1 +306 +307 Not flipped +308 Flipped +1012 -12 +1022 0 +1032 0 +309 UpdatedFlip +96 21 +0 BLOCKFLIPGRIP +5 66 +330 61 +100 AcDbEvalExpr +90 21 +98 33 +99 232 +100 AcDbBlockElement +300 Grip +98 33 +99 232 +1071 0 +100 AcDbBlockGrip +91 0 +92 0 +1010 -2 +1020 0 +1030 0 +280 0 +93 -1 +100 AcDbBlockFlipGrip +0 BLOCKFLIPACTION +5 67 +330 61 +100 AcDbEvalExpr +90 25 +98 33 +99 232 +100 AcDbBlockElement +300 Flip1 +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 2 +91 0 +91 0 +71 3 +330 31 +330 32 +330 68 +1010 -6 +1020 0 +1030 0 +100 AcDbBlockFlipAction +92 20 +93 20 +94 20 +95 20 +301 Flip +302 UpdatedFlip +303 UpdatedBase +304 UpdatedEnd +0 BLOCKPOINTPARAMETER +5 68 +330 61 +100 AcDbEvalExpr +90 26 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 0 +1020 3 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 0 +1021 4 +1031 0 +0 BLOCKMOVEACTION +5 69 +330 61 +100 AcDbEvalExpr +90 30 +98 33 +99 232 +100 AcDbBlockElement +300 Move +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 2 +91 0 +91 0 +71 1 +330 32 +1010 0 +1020 4 +1030 0 +100 AcDbBlockMoveAction +92 26 +93 26 +301 XDelta +302 YDelta +140 1 +141 0 +0 ENDSEC +0 EOF diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs new file mode 100644 index 000000000..3ba13176d --- /dev/null +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -0,0 +1,153 @@ +//! Rotation and flip parameters of dynamic blocks: their rotate and flip actions turn and mirror +//! the objects (text stays readable), carry the parameters in their selection, record the +//! change as AutoCAD does, and give the reference a rotation grip and a flip grip. +//! +//! The fixture is synthetic: block Symbol (a circle, a line from the origin to (0, 3) and an +//! attribute TAG at (1, 2) turned 90°) with Angle1 (base at the origin, radius to (2, 0)) and its +//! rotate action, Flip state1 (reflection line from the origin to (-10, 0)) and its flip action, +//! and Position1 at (0, 3) with a move action. + +use cadcraft_doc::dynblock::{ActionKind, GripPart, GripShape, ParameterKind, custom_properties, drag_grip, dynamic_block, grips, set_property}; +use cadcraft_doc::geom::{Vec2, Vec3}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// Symbol and a reference to it at (100, 100) with its attribute. +fn symbol() -> (Drawing, Handle) { + let src = include_str!("data/dynblock_symbol.txt").replace("\r\n", "\n"); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let def = + d.block("Symbol").unwrap().entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap(); + let mut a = def.clone(); + a.text.insert = a.text.insert + Vec3::new(100.0, 100.0, 0.0); + let ins = cadcraft_doc::Insert { + block: "Symbol".into(), + insert: Vec3::new(100.0, 100.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: vec![a], + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }; + let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect() +} + +/// The reference's block: its line's end and attribute definition (insertion, rotation in degrees). +fn shown(d: &Drawing, r: Handle) -> (Vec2, Vec2, f64) { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") }; + let b = d.block(&i.block).unwrap(); + let line = b.entities.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.b.xy()) } else { None }).unwrap(); + let (at, rot) = + b.entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some((a.text.insert.xy(), a.text.rotation)) } else { None }).unwrap(); + (line, at, rot.to_degrees()) +} + +fn near(a: Vec2, b: (f64, f64)) -> bool { + (a.x - b.0).abs() < 1e-6 && (a.y - b.1).abs() < 1e-6 +} + +#[test] +fn rotation_and_flip_are_read() { + let (d, _) = symbol(); + let m = dynamic_block(&d, "Symbol").unwrap(); + let p = |node: i32| &m.parameters.iter().find(|p| p.node == node).unwrap().kind; + assert!(matches!(p(15), ParameterKind::Rotation { label, values, .. } if label == "Angle1" && values.maximum > 6.28)); + assert!( + matches!(p(20), ParameterKind::Flip { label, states, .. } if label == "Flip state1" && states == &["Not flipped".to_string(), "Flipped".to_string()]) + ); + let a = |node: i32| m.actions.iter().find(|a| a.node == node).unwrap(); + assert!(matches!(&a(19).kind, ActionKind::Rotate { base } if base.dependent)); + assert_eq!(a(19).connections.last(), Some(&(15, "AngleDelta".to_string()))); + assert!(matches!(a(25).kind, ActionKind::Flip)); + assert_eq!(a(25).connections.len(), 4); +} + +#[test] +fn an_angle_turns_and_a_flip_mirrors_what_their_actions_hold() { + let (mut d, r) = symbol(); + assert_eq!(props(&d, r), pairs(&[("Angle1", "0"), ("Flip state1", "Not flipped"), ("Position1 X", "0.0000"), ("Position1 Y", "3.0000")])); + + // 30°: the line, the attribute and Position1 turn about the origin; the text turns with them. + set_property(&mut d, r, "angle1", "30").unwrap(); + let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let (line, at, rot) = shown(&d, r); + assert!(near(line, (-3.0 * s, 3.0 * c)), "{line:?}"); + assert!(near(at, (c - 2.0 * s, s + 2.0 * c)), "{at:?}"); + assert!((rot - 120.0).abs() < 1e-9); + assert_eq!(props(&d, r), pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped"), ("Position1 X", "-1.5000"), ("Position1 Y", "2.5981")])); + // The reference's attribute follows its definition. + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("no reference") }; + assert!(near(i.attribs[0].text.insert.xy(), (100.0 + at.x, 100.0 + at.y))); + + // Flipped: mirrored across the reflection line, which turned with them (now at 30°); the + // text keeps reading left to right. + set_property(&mut d, r, "Flip state1", "Flipped").unwrap(); + let (s2, c2) = (60f64.to_radians().sin(), 60f64.to_radians().cos()); + let mirror = |p: Vec2| (p.x * c2 + p.y * s2, p.x * s2 - p.y * c2); + let (line2, at2, rot) = shown(&d, r); + assert!(near(line2, mirror(line)), "{line2:?}"); + assert!(near(at2, mirror(at)), "{at2:?}"); + assert!((rot - 120.0).abs() < 1e-9, "readable"); + assert_eq!(props(&d, r)[1..], pairs(&[("Flip state1", "Flipped"), ("Position1 X", "1.5000"), ("Position1 Y", "-2.5981")])); + + // Both survive a save. + let again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&again, r), props(&d, r)); + // Back to not flipped: back to the turned geometry. + set_property(&mut d, r, "Flip state1", "0").unwrap(); + assert!(near(shown(&d, r).1, (at.x, at.y))); +} + +#[test] +fn rotation_and_flip_grips() { + let (mut d, r) = symbol(); + set_property(&mut d, r, "Angle1", "30").unwrap(); + let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let g = grips(&d, r); + let rot = g.iter().find(|g| g.shape == GripShape::Rotation).unwrap(); + assert_eq!((rot.node, rot.part), (15, GripPart::End)); + assert!(near(rot.at, (100.0 + 2.0 * c, 100.0 + 2.0 * s)), "at the radius' end: {:?}", rot.at); + let flip = g.iter().find(|g| g.shape == GripShape::Flip).unwrap(); + assert_eq!((flip.node, flip.part, flip.choices.len()), (20, GripPart::Base, 2)); + // The flip grip object at (-2, 0) turned with the reflection line. + assert!(near(flip.at, (100.0 - 2.0 * c, 100.0 - 2.0 * s)), "{:?}", flip.at); + + // Dragging the rotation grip straight up from the base: 90°. + drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 105.0)).unwrap(); + assert_eq!(props(&d, r)[0].1, "90"); + // A flip grip is clicked, not dragged; the base of the angle is not a point to aim at. + assert!(drag_grip(&mut d, r, 20, GripPart::Base, Vec2::new(90.0, 90.0)).is_err()); + assert!(drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 100.0)).is_err()); +} + +#[test] +fn bad_angles_and_states_change_nothing() { + let (mut d, r) = symbol(); + let before = d.clone(); + for (name, value) in [("Angle1", "steep"), ("Angle1", "inf"), ("Flip state1", "Sideways"), ("Flip state1", "2")] { + assert!(set_property(&mut d, r, name, value).is_err(), "{name}={value}"); + } + assert_eq!(d, before); +} diff --git a/crates/ui-egui/src/dyngrips.rs b/crates/ui-egui/src/dyngrips.rs index 7c30447c4..db9377c92 100644 --- a/crates/ui-egui/src/dyngrips.rs +++ b/crates/ui-egui/src/dyngrips.rs @@ -1,6 +1,7 @@ //! Dynamic block grips on the canvas, as AutoCAD shows them on a selected dynamic block //! reference: an arrow at a distance's end (drag it to change the distance), a square at a -//! position (drag it to move it) and a down-pointing triangle for a list (click it for the +//! position (drag it to move it), a circle at an angle's end (drag it to turn), an arrow across a +//! reflection line (click it to flip) and a down-pointing triangle for a list (click it for the //! visibility states or lookup values). Dragging runs the engine's dynamic grip edit //! ([`cadcraft_engine::Session::start_dyn_grip`]); a list choice runs `blocks.reference.set`. @@ -62,6 +63,21 @@ fn outline(xf: &Xf, g: &DynGrip, gs: f32) -> Vec { let w = gs * 1.3; vec![c + vec2(-w, -w * 0.6), c + vec2(w, -w * 0.6), c + vec2(0.0, w * 0.9)] } + GripShape::Rotation => (0..16) + .map(|i| { + let a = std::f32::consts::TAU * i as f32 / 16.0; + c + vec2(a.cos(), a.sin()) * (gs * 1.1) + }) + .collect(), + // An arrow pointing across the reflection line, the way it flips. + GripShape::Flip => { + let ahead = xf.to_screen(g.at + g.dir) - c; + let u = if ahead.length() > 1e-6 { ahead / ahead.length() } else { vec2(0.0, -1.0) }; + let n = vec2(-u.y, u.x); + // Longer and narrower than a distance's arrow (the painter fills convex shapes). + let (len, half) = (gs * 2.4, gs * 0.8); + vec![c - u * (len * 0.5) + n * half, c + u * (len * 0.6), c - u * (len * 0.5) - n * half] + } } } @@ -104,6 +120,22 @@ pub(crate) fn at(app: &mut CadApp, xf: &Xf, hover: Option) -> Option<(Hand /// A click on dynamic grip `g` of reference `h`: drag it, or open its list. pub(crate) fn click(app: &mut CadApp, (h, g): (Handle, DynGrip)) { + // A flip grip flips at once: the state that isn't the current one. + if g.shape == GripShape::Flip { + let current = app + .session + .state() + .ok() + .and_then(|st| cadcraft_engine::doc::dynblock::custom_properties(&st.doc, h)) + .and_then(|(_, ps)| ps.into_iter().find(|p| p.name.eq_ignore_ascii_case(&g.property))) + .map(|p| p.value) + .unwrap_or_default(); + let Some(next) = g.choices.iter().find(|c| !c.eq_ignore_ascii_case(¤t)).cloned() else { return }; + if let Err(e) = app.run("blocks.reference.set", json!({ "handle": h.hex(), "name": g.property, "value": next })) { + app.session.echo(e); + } + return; + } if g.shape == GripShape::List { app.canvas.dyn_menu = Some((h, g)); app.canvas.dyn_menu_fresh = true; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d2af85803..a385479f0 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -148,6 +148,7 @@ our output in AutoCAD black-box. | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | +| 2026-10-13 | minor | Dynamic blocks: rotation and flip parameters and actions read; changed references saved with AutoCAD's value records and history (flip state after the points, flip grip state) | | 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 b270525d6..41c7f9eb3 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -166,6 +166,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-15 | minor | BREAKLINE (Tools ▸ Express Tools ▸ Break-line Symbol): one polyline between two points with a break symbol, Block/Size/Extension options, size times DIMSCALE: E3 narrowed | | 2026-10-15 | minor | TXT2MTXT (Tools ▸ Express Tools ▸ Convert Text to Mtext): selected TEXT, and MTEXT, combined into one MTEXT top-down or in selection order with optional word wrap, or one MTEXT per TEXT; SEttings remembered for the session: E3 narrowed | | 2026-10-13 | minor | Selection window gesture preference (PICKDRAG 0/2) added to Options ▸ Selection and saved in the profile (U6), with Portuguese and Ukrainian labels | +| 2026-10-13 | minor | F3: dynamic block rotation and flip parameters (Angle1, Flip state1) with their rotate and flip actions, Properties and grips; checked against AutoCAD's output | | 2026-10-12 | minor | Object transparency (entity, ByLayer, ByBlock) is drawn: on screen (TRANSPARENCYDISPLAY, on by default), in PNG/SVG exports, and in plots when the page setup's "Plot transparency" is on (PDF alpha, PNG blending, SVG opacity; PLOTTRANSPARENCYOVERRIDE): F14 narrowed | | 2026-10-12 | minor | Hatch and Gradient dialog (HATCH, GRADIENT; HPDLGMODE) and Hatch Edit dialog (HATCHEDIT, right-click, double-click a hatch): F13 narrowed to Preview, Inherit Properties and boundary add/remove in edit mode | | 2026-10-12 | minor | A bare system variable name typed at the command line (ORTHOMODE, GRIDMODE…) runs SETVAR on that variable, as in AutoCAD; U10 narrowed | From 6977a58a59bf7705adecc460b5453411a4d91da3 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:25:14 -0600 Subject: [PATCH 016/187] Dynamic blocks: rotation test compares with a plain bound, not an approximate TAU Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/dynblock_rotate_flip.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs index 3ba13176d..82af5a1c6 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -73,7 +73,7 @@ fn rotation_and_flip_are_read() { let (d, _) = symbol(); let m = dynamic_block(&d, "Symbol").unwrap(); let p = |node: i32| &m.parameters.iter().find(|p| p.node == node).unwrap().kind; - assert!(matches!(p(15), ParameterKind::Rotation { label, values, .. } if label == "Angle1" && values.maximum > 6.28)); + assert!(matches!(p(15), ParameterKind::Rotation { label, values, .. } if label == "Angle1" && values.maximum > 6.0)); assert!( matches!(p(20), ParameterKind::Flip { label, states, .. } if label == "Flip state1" && states == &["Not flipped".to_string(), "Flipped".to_string()]) ); From e0fa2af3b0e3faa9103bf88faa19301fa1b384e2 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:10:41 -0600 Subject: [PATCH 017/187] Dynamic blocks: the rotation grip is where its grip object is, and a drag turns by the cursor's turn AutoCAD draws a rotation parameter's grip where the block's grip object is, which need not be the radius' end (a well-centre symbol has it a quarter turn round), and turns it with the angle. CADCraft drew it at the radius' end. The grip is now placed from its grip object, kept along and across the radius as it turns (as the flip grip already was), and dragging it subtracts the grip's offset from the radius, so the block turns by the cursor's turn instead of jumping to the cursor's direction. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 11 ++++++++- crates/doc/src/dynblock/grips.rs | 30 ++++++++++++++++++------- crates/io/tests/dynblock_rotate_flip.rs | 28 +++++++++++++++++++++-- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 257aa9e6c..2d07a901c 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -412,7 +412,16 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa if (q3 - b).len() < 1e-12 { return Err(format!("{label} needs a point away from its base.")); } - let a = allowed(values, rotation_angle(b, q3, (*hb, *he))); + // The grip is where its grip object is, which can be off the radius' end: the + // cursor turns the grip, so the angle is the cursor's less that offset. + let offset = p + .grips + .get(1) + .and_then(|id| m.grip_points.iter().find(|(g, _)| g == id)) + .map(|(_, g)| rotation_angle(*hb, *g, (*hb, *he))) + .filter(|_| (*he - *hb).len() > 1e-12) + .unwrap_or(0.0); + let a = allowed(values, (rotation_angle(b, q3, (*hb, *he)) - offset).rem_euclid(std::f64::consts::TAU)); plan.set.insert(node, Val::Points(b, rotation_end(b, e, (*hb, *he), a))); plan.chain(&m, &r.values, node, "UpdatedAngle")?; } diff --git a/crates/doc/src/dynblock/grips.rs b/crates/doc/src/dynblock/grips.rs index 2a349e73f..5c0df044c 100644 --- a/crates/doc/src/dynblock/grips.rs +++ b/crates/doc/src/dynblock/grips.rs @@ -108,6 +108,15 @@ fn ends_used(m: &DynamicBlock, node: i32) -> Option<(bool, bool)> { used } +/// Where a grip object at `g` (from its parameter's base, in the dynamic block) is when the +/// parameter's line `home` (base to end, in the block) is now `now` from `base`: kept along and +/// across the line as it turns, moves or stretches. `home` and `now` aren't zero. +fn carried(g: Vec2, home: Vec2, base: Vec2, now: Vec2) -> Vec2 { + let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len())); + let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x); + base + now * along + u.perp() * across +} + fn point(p: &Vec2, s: S) -> Result { [p.x, p.y].serialize(s) } @@ -178,15 +187,21 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { } } } - ParameterKind::Rotation { base, end, label, .. } => { + ParameterKind::Rotation { base: hb, end: he, label, .. } => { let (b, e) = match r.values.get(&p.node) { Some(Value::Points { base, end }) => (*base, *end), - _ => (*base, *end), + _ => (*hb, *he), }; - if shown(p.node, grip(1)) { - let u = e - b; + let id = grip(1); + let (home, now) = ((*he - *hb).xy(), (e - b).xy()); + if shown(p.node, id) && home.len() > 1e-12 && now.len() > 1e-12 { + // The grip object's place (AutoCAD draws the circle there, not at the radius' + // end), turned and moved with the radius. + let at = carried(points.get(&id).copied().unwrap_or(*he).xy() - hb.xy(), home, b.xy(), now); + let at = Vec3::new(at.x, at.y, b.z); + let u = at - b; let u = if u.len() > 1e-12 { u * (1.0 / u.len()) } else { Vec3::new(1.0, 0.0, 0.0) }; - let (at, dir) = (world(e), toward(e, u)); + let (at, dir) = (world(at), toward(at, u)); out.push(DynGrip { node: p.node, part: GripPart::End, @@ -209,9 +224,8 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { // The grip object's place, kept along and across the reflection line as the // line turns or moves with other actions. let g = points.get(&id).copied().unwrap_or(*hb).xy() - hb.xy(); - let (u0, u) = (home * (1.0 / home.len()), now * (1.0 / now.len())); - let (along, across) = (g.dot(u0) / home.len(), u0.x * g.y - u0.y * g.x); - let at = b.xy() + now * along + u.perp() * across; + let at = carried(g, home, b.xy(), now); + let u = now * (1.0 / now.len()); let across_dir = if flipped { -u.perp() } else { u.perp() }; let (at3, dir) = (Vec3::new(at.x, at.y, b.z), toward(Vec3::new(at.x, at.y, b.z), across_dir.to3(0.0))); out.push(DynGrip { diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs index 82af5a1c6..ee8a10b13 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -25,8 +25,12 @@ fn dxf(src: &str) -> String { /// Symbol and a reference to it at (100, 100) with its attribute. fn symbol() -> (Drawing, Handle) { - let src = include_str!("data/dynblock_symbol.txt").replace("\r\n", "\n"); - let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + symbol_from(&include_str!("data/dynblock_symbol.txt").replace("\r\n", "\n")) +} + +/// As [`symbol`], from the fixture's text `src` (changed by a test). +fn symbol_from(src: &str) -> (Drawing, Handle) { + let mut d = read_dxf(dxf(src).as_bytes()).unwrap(); let def = d.block("Symbol").unwrap().entities.iter().find_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some(a.clone()) } else { None }).unwrap(); let mut a = def.clone(); @@ -142,6 +146,26 @@ fn rotation_and_flip_grips() { assert!(drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 100.0)).is_err()); } +#[test] +fn a_rotation_grip_off_the_radius_stays_where_its_grip_object_is() { + // The grip object a quarter turn round from the radius' end (as AutoCAD saves blocks whose + // grip was moved there): the circle is drawn there and turns with the angle, and dragging + // it turns the block by the cursor's turn, not to the cursor's direction. + let src = include_str!("data/dynblock_symbol.txt") + .replace("\r\n", "\n") + .replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n"); + let (mut d, r) = symbol_from(&src); + let at = |d: &Drawing| grips(d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap(); + assert!(near(at(&d), (100.0, 102.0)), "{:?}", at(&d)); + // Dropped where it is: no turn. + drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(100.0, 102.0)).unwrap(); + assert!(props(&d, r).contains(&("Angle1".to_string(), "0".to_string())), "{:?}", props(&d, r)); + // A quarter turn further round: Angle1 90, and the grip is there. + drag_grip(&mut d, r, 15, GripPart::End, Vec2::new(98.0, 100.0)).unwrap(); + assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r)); + assert!(near(at(&d), (98.0, 100.0)), "{:?}", at(&d)); +} + #[test] fn bad_angles_and_states_change_nothing() { let (mut d, r) = symbol(); From 95f7f6687ab607e2fb28d04579e8fc3dec99ecd6 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:19:15 -0600 Subject: [PATCH 018/187] Dynamic blocks: an angle parameter shows and is typed as the drawing measures angles AutoCAD shows an angle parameter's value as it shows any angle: from ANGBASE, clockwise when ANGDIR is 1. In a drawing measured clockwise from north it shows an Angle1 of 0 as 90, and 0.5 rad as 61.35 (checked in AutoCAD). Properties and typed values (blocks.reference.set, a value typed at the rotation grip) now convert the same way; the stored value is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 3 ++- crates/doc/src/dynblock/reference.rs | 19 ++++++++++++++++++- crates/io/tests/dynblock_rotate_flip.rs | 16 ++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 2d07a901c..66a022a30 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -326,7 +326,8 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> } // An angle in degrees, as Properties shows it, snapped to the parameter's values. (ParameterKind::Rotation { base: hb, end: he, values, label, .. }, None) => { - let typed = number(value)?.to_radians().rem_euclid(std::f64::consts::TAU); + // Typed as the drawing shows angles (from ANGBASE, clockwise when ANGDIR is 1). + let typed = super::reference::angle_from_shown(d, number(value)?.to_radians()); let a = allowed(values, typed); if !a.is_finite() { return Err(format!("\"{value}\" is not an angle for {label}.")); diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index d74888ff1..2c23227a6 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -141,9 +141,26 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option { } /// An angle (radians) as Properties shows it: degrees with AUPREC decimals. +/// An angle parameter's value `a` (radians, counterclockwise) as the drawing shows angles: from +/// ANGBASE, clockwise when ANGDIR is 1 (AutoCAD shows a 0 angle as 90 in a drawing measured +/// clockwise from north, and 0.5 rad as 61.35). +pub(super) fn angle_shown(d: &Drawing, a: f64) -> f64 { + let base = d.header.f64("ANGBASE", 0.0); + let shown = if d.header.i64("ANGDIR", 0) == 1 { base - a } else { a - base }; + shown.rem_euclid(std::f64::consts::TAU) +} + +/// The value of an angle parameter shown (or typed) as `v` (radians): the inverse of +/// [`angle_shown`]. +pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 { + let base = d.header.f64("ANGBASE", 0.0); + let a = if d.header.i64("ANGDIR", 0) == 1 { base - v } else { v + base }; + a.rem_euclid(std::f64::consts::TAU) +} + fn angle_text(d: &Drawing, a: f64) -> String { let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0); - format!("{:.prec$}", a.to_degrees()) + format!("{:.prec$}", angle_shown(d, a).to_degrees()) } /// A number as the drawing shows lengths (LUPREC decimals). diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs index ee8a10b13..1acb72a7c 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -166,6 +166,22 @@ fn a_rotation_grip_off_the_radius_stays_where_its_grip_object_is() { assert!(near(at(&d), (98.0, 100.0)), "{:?}", at(&d)); } +#[test] +fn an_angle_shows_and_is_typed_as_the_drawing_measures_angles() { + // Angles measured clockwise from north (ANGBASE 90°, ANGDIR 1): AutoCAD shows Angle1 0 as + // 90 and 0.5 rad as 61.35, and a typed angle is read the same way. + let (mut d, r) = symbol(); + d.header.set_f64("ANGBASE", std::f64::consts::FRAC_PI_2); + d.header.set_i64("ANGDIR", 1); + assert!(props(&d, r).contains(&("Angle1".to_string(), "90".to_string())), "{:?}", props(&d, r)); + // 60 shown is 30° counterclockwise: the grip turns from (102, 100) to there. + set_property(&mut d, r, "Angle1", "60").unwrap(); + assert!(props(&d, r).contains(&("Angle1".to_string(), "60".to_string())), "{:?}", props(&d, r)); + let at = grips(&d, r).into_iter().find(|g| g.shape == GripShape::Rotation).map(|g| g.at).unwrap(); + let want = (100.0 + 2.0 * 30f64.to_radians().cos(), 100.0 + 2.0 * 30f64.to_radians().sin()); + assert!(near(at, want), "{at:?} vs {want:?}"); +} + #[test] fn bad_angles_and_states_change_nothing() { let (mut d, r) = symbol(); From 84310182ca3b46ec39b632d566657989193e79ce Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:29:08 -0600 Subject: [PATCH 019/187] Dynamic blocks: the flip grip is a block arrow, as AutoCAD draws it The flip grip was a narrow triangle; AutoCAD draws a block arrow, a short shaft and a head about as wide as a square grip. Its shaft and head are filled apart (the painter fills convex shapes) and outlined as one. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dyngrips.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dyngrips.rs b/crates/ui-egui/src/dyngrips.rs index db9377c92..1808d573a 100644 --- a/crates/ui-egui/src/dyngrips.rs +++ b/crates/ui-egui/src/dyngrips.rs @@ -74,9 +74,18 @@ fn outline(xf: &Xf, g: &DynGrip, gs: f32) -> Vec { let ahead = xf.to_screen(g.at + g.dir) - c; let u = if ahead.length() > 1e-6 { ahead / ahead.length() } else { vec2(0.0, -1.0) }; let n = vec2(-u.y, u.x); - // Longer and narrower than a distance's arrow (the painter fills convex shapes). - let (len, half) = (gs * 2.4, gs * 0.8); - vec![c - u * (len * 0.5) + n * half, c + u * (len * 0.6), c - u * (len * 0.5) - n * half] + // A block arrow, as AutoCAD draws it: a short shaft and a head about as wide as a + // square grip. Tail, shaft's end and head's back on one side, the tip, then back. + let (tail, neck, tip, shaft, head) = (gs * 1.4, gs * 0.2, gs * 1.4, gs * 0.5, gs * 1.4); + vec![ + c - u * tail + n * shaft, + c - u * neck + n * shaft, + c - u * neck + n * head, + c + u * tip, + c - u * neck - n * head, + c - u * neck - n * shaft, + c - u * tail - n * shaft, + ] } } } @@ -107,7 +116,18 @@ pub(crate) fn draw(app: &mut CadApp, painter: &Painter, xf: &Xf, rect: Rect, hov } else { t.grip_dyn }; - painter.add(Shape::convex_polygon(pts, fill, Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80)))); + let stroke = Stroke::new(1.0, Color32::from_rgb(0x10, 0x30, 0x80)); + match (g.shape, pts.as_slice()) { + // The flip arrow isn't convex: its shaft and head are filled apart, then outlined. + (GripShape::Flip, [t0, n0, h0, tip, h1, n1, t1]) => { + painter.add(Shape::convex_polygon(vec![*t0, *n0, *n1, *t1], fill, Stroke::NONE)); + painter.add(Shape::convex_polygon(vec![*h0, *tip, *h1], fill, Stroke::NONE)); + painter.add(Shape::closed_line(pts.clone(), stroke)); + } + _ => { + painter.add(Shape::convex_polygon(pts, fill, stroke)); + } + } } } From 98db1164ffb41b760e17ce59105127c93146e7d2 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 09:45:44 -0600 Subject: [PATCH 020/187] Dynamic blocks: flipped text keeps its mirrored footprint, as AutoCAD draws it A flip mirrors text and attributes but AutoCAD draws them readable (MIRRTEXT 0): the text keeps the mirrored footprint, so text that ran away from the symbol still runs away from it on the other side. CADCraft mirrored only the text's anchor, so flipped text ran back across the block. Text carried by an action that mirrors now reads in whichever mirrored direction is nearer its own, and swaps left and right justification when its footprint is reversed along it (AutoCAD keeps the justification and moves the start back by the text's width, which draws the same; it re-derives attributes from the block when it next changes them), top and bottom when reversed across it. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 61 ++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 66a022a30..760503977 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -18,7 +18,7 @@ use cadcraft_geom::{Mat3, Vec2, Vec3}; use super::{ActionKind, DynamicBlock, ParameterKind, Value, dynamic_block, reference}; use crate::foreign::{ForeignExtra, ForeignObject}; -use crate::{Block, Drawing, Entity, EntityKind, Handle, RawTag}; +use crate::{Block, Drawing, Entity, EntityKind, HAlign, Handle, RawTag, Text, VAlign}; /// Xdata application naming a copied object's object in the dynamic block (its element tag). const ETAG: &str = "AcDbBlockRepETag"; @@ -114,6 +114,52 @@ fn rotation_end(b: Vec3, e: Vec3, home: (Vec3, Vec3), a: f64) -> Vec3 { b + (dir * r).to3(0.0) } +/// Text `t` carried by `m`, kept readable as AutoCAD keeps it (MIRRTEXT 0). A transform that +/// mirrors keeps the text's mirrored footprint: the text reads in whichever mirrored direction is +/// nearer its own, and a footprint reversed along the text swaps left and right justification +/// (AutoCAD moves the start back by the text's width instead, which draws the same), one reversed +/// across it swaps top and bottom. +fn carry_text(t: &mut Text, m: &Mat3) { + let u = Vec2::new(t.rotation.cos(), t.rotation.sin()); + let mut k = EntityKind::Text(t.clone()); + k.transform(m); + let EntityKind::Text(mut after) = k else { return }; + let o = m.apply(Vec2::ZERO); + let (ex, ey, mu) = (m.apply(Vec2::new(1.0, 0.0)) - o, m.apply(Vec2::new(0.0, 1.0)) - o, m.apply(u) - o); + if ex.x * ey.y - ex.y * ey.x < 0.0 && mu.len() > 1e-12 { + // The point the text is placed by, before its justification changes. + let at = after.justify_point(); + if mu.dot(u) >= 0.0 { + after.rotation = cadcraft_geom::norm_angle(mu.angle()); + after.valign = match after.valign { + VAlign::Top => VAlign::Bottom, + VAlign::Bottom | VAlign::Baseline => VAlign::Top, + v => v, + }; + } else { + after.rotation = cadcraft_geom::norm_angle((mu * -1.0).angle()); + match after.halign { + HAlign::Left => after.halign = HAlign::Right, + HAlign::Right => after.halign = HAlign::Left, + // Placed by both points: they swap ends. + HAlign::Aligned | HAlign::Fit => { + if let Some(a) = after.align_pt { + after.align_pt = Some(after.insert); + after.insert = a; + } + } + _ => {} + } + } + if !matches!(after.halign, HAlign::Aligned | HAlign::Fit) { + let at = at.to3(after.insert.z); + after.insert = at; + after.align_pt = (!matches!((after.halign, after.valign), (HAlign::Left, VAlign::Baseline))).then_some(at); + } + } + *t = after; +} + /// A parameter's current value on the reference: the value it was given, else the block's own. fn current(m: &DynamicBlock, values: &BTreeMap, node: i32) -> Option { let p = m.parameters.iter().find(|p| p.node == node)?; @@ -661,7 +707,12 @@ fn apply( for op in moves.get(&e.handle).into_iter().flatten() { match op { Op::Move(idx, v) => move_entity(&mut c, idx.as_deref(), *v), - Op::Transform(t) => c.kind.transform(t), + // Text and attribute definitions keep reading as AutoCAD keeps them. + Op::Transform(t) => match &mut c.kind { + EntityKind::Text(x) => carry_text(x, t), + EntityKind::AttDef(a) if a.multiline.is_none() => carry_text(&mut a.text, t), + k => k.transform(t), + }, } } if let EntityKind::Hatch(h) = &mut c.kind { @@ -709,11 +760,7 @@ fn apply( for a in &mut i.attribs { if let Some(t) = attrib_moves.get(&a.tag.to_ascii_uppercase()) { let w = to_block.then(*t).then(to_world); - let mut k = EntityKind::Text(a.text.clone()); - k.transform(&w); - if let EntityKind::Text(t) = k { - a.text = t; - } + carry_text(&mut a.text, &w); a.transform_multiline(&w); } } From 74498ff4b0aaff35c0d44bd83b1238a44dac5301 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:18:21 -0600 Subject: [PATCH 021/187] Dynamic blocks: the rotation grip's Dynamic Input shows one angle box At a rotation grip AutoCAD's Dynamic Input asks for the angle alone; CADCraft showed a distance and an angle from the grip. A prompt can now say it asks for an angle about its base (`Prompt::angle`), and a command can give the value the cursor would give (`Interactive::live_value`, under the crash guard; `Session::live_value`). The rotation grip does both, with the angle as Properties will show it, and the canvas draws one box: what was typed, else that live value. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/blocks/dyngrip.rs | 15 +++++++- crates/engine/src/guard.rs | 9 +++++ crates/engine/src/prompt.rs | 14 +++++++ crates/engine/src/session/interactive.rs | 6 +++ crates/engine/tests/rotation_grip_input.rs | 44 ++++++++++++++++++++++ crates/ui-egui/src/canvas/dyn_boxes.rs | 44 ++++++++++++++++++++++ 6 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 crates/engine/tests/rotation_grip_input.rs diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index ece7d24b7..548be78d8 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -134,7 +134,9 @@ impl Interactive for DynGripEdit { GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER), _ => ("** STRETCH ** Specify stretch point", Accept::POINT), }; - Prompt::new(msg, accept).kw(&["eXit"]).base(self.from) + let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from); + // A rotation grip asks for an angle: Dynamic Input shows one angle box. + if self.shape == GripShape::Rotation { p.angle() } else { p } } fn input(&mut self, s: &mut Session, i: Input) -> Result { @@ -160,6 +162,17 @@ impl Interactive for DynGripEdit { vec![crate::cmd::helpers::line(self.from, c)] } + /// A rotation grip's angle at the cursor, as Properties will show it. + fn live_value(&self, s: &Session, c: Vec2) -> Option { + if self.shape != GripShape::Rotation { + return None; + } + let mut d = s.doc().ok()?.clone(); + dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c).ok()?; + let (_, props) = dynblock::custom_properties(&d, self.handle)?; + props.into_iter().find(|p| p.name.eq_ignore_ascii_case(&self.property)).map(|p| format!("{}°", p.value)) + } + /// The reference re-evaluated at the cursor, drawn as it will look (its own colours, so /// text stays readable on a filled block). fn preview_objects(&self, s: &Session, c: Vec2) -> Vec { diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 8a64e2b74..a04810ad7 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -84,6 +84,15 @@ impl Interactive for Guarded { Vec::new() }) } + fn live_value(&self, s: &Session, cursor: Vec2) -> Option { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.live_value(s, cursor))).unwrap_or_else(|_| { + self.broken.set(Some("panic in preview")); + None + }) + } fn drag(&self, s: &Session, cursor: Vec2) -> Option { if self.broken.get().is_some() { return None; diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index c02551b80..9102727ba 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -66,6 +66,10 @@ pub struct Prompt { /// the routine writes, so it cannot be read for the word "Select" (#1598). #[serde(skip_serializing_if = "std::ops::Not::not")] pub picks_one: bool, + /// The value asked for is an angle about the base (a rotation grip): Dynamic Input shows one + /// angle box, with the command's live value ([`Interactive::live_value`]). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub angle: bool, } /// Parse `@distance Self { + self.angle = true; + self + } pub fn picker(mut self, p: Picker) -> Self { self.picker = Some(p); self @@ -232,6 +241,11 @@ pub trait Interactive: Send { fn preview_objects(&self, _s: &Session, _cursor: Vec2) -> Vec { Vec::new() } + /// The value the cursor would give, as the prompt asks for it (an angle as the drawing + /// shows angles): what Dynamic Input shows in its box before anything is typed. + fn live_value(&self, _s: &Session, _cursor: Vec2) -> Option { + None + } /// The preview as existing objects under one transform, when it is that (MOVE, COPY, /// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding /// the transformed copies every frame; `None` falls back to [`Interactive::preview`]. diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index e7cb07450..7cf47e8a9 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -502,6 +502,12 @@ impl Session { out } + /// The value the cursor would give at the active command's prompt (see + /// [`Interactive::live_value`]). + pub fn live_value(&self, cursor: Vec2) -> Option { + self.running.as_ref()?.machine.live_value(self, cursor) + } + /// The active command's preview as a transform of existing objects (see /// [`Interactive::drag`]), with its extra rubber-band geometry as entities. pub fn drag(&self, cursor: Vec2) -> Option<(Drag, Vec)> { diff --git a/crates/engine/tests/rotation_grip_input.rs b/crates/engine/tests/rotation_grip_input.rs new file mode 100644 index 000000000..6a713c535 --- /dev/null +++ b/crates/engine/tests/rotation_grip_input.rs @@ -0,0 +1,44 @@ +//! The rotation grip of a dynamic block asks for an angle: Dynamic Input shows one angle box, +//! holding the angle the cursor would give as Properties will show it. The drawing is the +//! synthetic Symbol block of the io tests (Angle1 about its base, its grip at the radius' end). + +use cadcraft_engine::Session; +use cadcraft_engine::doc::Handle; +use cadcraft_engine::doc::dynblock::GripPart; +use cadcraft_engine::geom::Vec2; +use serde_json::json; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// A session with Symbol and a reference to it at (100, 100). +fn session() -> (Session, Handle) { + let src = include_str!("../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n"); + let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "symbol", None); + let r = s.execute("insert", &json!({ "name": "Symbol", "at": [100, 100] })).unwrap(); + (s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap()) +} + +#[test] +fn the_rotation_grip_asks_for_an_angle_and_shows_it_live() { + let (mut s, h) = session(); + s.start_dyn_grip(h, 15, GripPart::End).unwrap(); + assert!(s.current_prompt().is_some_and(|p| p.angle), "{:?}", s.current_prompt()); + // The grip is at (102, 100); straight above the base is a quarter turn. + assert_eq!(s.live_value(Vec2::new(100.0, 102.0)).as_deref(), Some("90°")); + assert_eq!(s.live_value(Vec2::new(98.0, 100.0)).as_deref(), Some("180°")); + // Nothing is changed by looking. + let props = s.execute("blocks.reference", &json!({ "handle": h.hex() })).unwrap(); + let angle = props["properties"].as_array().unwrap().iter().find(|p| p["name"] == "Angle1").unwrap()["value"].clone(); + assert_eq!(angle, json!("0")); +} diff --git a/crates/ui-egui/src/canvas/dyn_boxes.rs b/crates/ui-egui/src/canvas/dyn_boxes.rs index b0bcfb9e2..783cfce7b 100644 --- a/crates/ui-egui/src/canvas/dyn_boxes.rs +++ b/crates/ui-egui/src/canvas/dyn_boxes.rs @@ -19,6 +19,19 @@ pub(super) fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2, fi // DYNPROMPT = 0: no prompt beside the cursor (the value boxes stay). let show_prompt = app.session.settings.dynprompt; let options = show_prompt && !prompt.keywords.is_empty(); + // An angle about the base (a rotation grip): one angle box, as AutoCAD shows it. + if !fields + && prompt.angle + && crate::cmdline::dyn_frame(app).is_some() + && let Some(c) = app.canvas.cursor + { + let message = if show_prompt { crate::i18n::t(&prompt.message) } else { "" }; + let typed = !app.cmd.buffer.is_empty(); + let value = if typed { app.cmd.buffer.clone() } else { app.session.live_value(c).unwrap_or_default() }; + let r = angle_box(p, at, message, &value, typed, options); + options_menu(app, p, r, hover); + return; + } if !fields && let Some(f) = crate::cmdline::dyn_frame(app) && let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f) @@ -119,6 +132,37 @@ fn tooltip_frame(p: &egui::Painter, at: Pos2, size: egui::Vec2) -> Rect { r } +/// The Dynamic Input tooltip for an angle: the prompt and one box, holding what was typed (full +/// text colour, with the caret) or the live value (dimmed). +fn angle_box(p: &egui::Painter, at: Pos2, message: &str, value: &str, typed: bool, options: bool) -> Rect { + let t = Tokens::get(); + let font = crate::theme::small(); + let msg = p.layout_no_wrap(message.to_owned(), font.clone(), t.text_dim); + let val = p.layout_no_wrap(value.to_owned(), font, if typed { t.text } else { t.text_faint }); + let (pad, gap) = (6.0, 6.0); + let box_h = msg.size().y + 6.0; + let bw = (val.size().x + 10.0).max(48.0); + let hint = if options { OPTIONS_HINT_W } else { 0.0 }; + let r = tooltip_frame(p, at, vec2(pad + msg.size().x + gap + bw + pad + hint, box_h + 2.0 * pad - 2.0)); + if options { + options_hint(p, r); + } + let cy = r.center().y; + let x = r.left() + pad; + let msg_w = msg.size().x; + p.galley(pos2(x, cy - msg.size().y / 2.0), msg, t.text_dim); + let b = Rect::from_min_size(pos2(x + msg_w + gap, cy - box_h / 2.0), vec2(bw, box_h)); + p.rect_filled(b, 2.0, t.chrome_dark); + p.rect_stroke(b, 2.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + let vw = val.size().x; + p.galley(pos2(b.left() + 5.0, cy - val.size().y / 2.0), val, t.text); + if typed { + let cx = b.left() + 6.0 + vw; + p.line_segment([pos2(cx, b.top() + 3.0), pos2(cx, b.bottom() - 3.0)], Stroke::new(1.0, t.text)); + } + r +} + /// The Dynamic Input value boxes: X and Y, or distance and angle. Typed values show in full /// text colour, a locked value (a separator typed after it) gets a lock, the active box gets the /// accent outline, and open boxes show the cursor's live value, dimmed. Values measured from the From 7f85a5473ad48f7d9de7775f739a47eee1b8e548 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:23:17 -0600 Subject: [PATCH 022/187] Dynamic blocks: a value record takes its shape from its parameter A flip record was told from another two-point record by a group 70 after its points. A stray 70 on a linear or rotation record made its value a flip (and ignored), and a flip record without its state was read as plain points. The parameter the record is keyed by now decides. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/reference.rs | 10 ++++++- crates/io/tests/dynblock_rotate_flip.rs | 39 +++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 2c23227a6..5704e591a 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -129,11 +129,19 @@ pub fn reference(d: &Drawing, insert: Handle) -> Option { let target = data.tags.iter().find(|t| t.code == 340).and_then(|t| Handle::parse_hex(&t.value))?; let (kind, name) = d.foreign.targets.get(&target)?; let definition = d.block(name).filter(|_| kind == "BLOCK_RECORD")?.name.clone(); - dynamic_block(d, &definition)?; + let m = dynamic_block(d, &definition)?; let mut values = BTreeMap::new(); let cache = entry(&objects, rep, "AppDataCache").and_then(|c| entry(&objects, c, "ACAD_ENHANCEDBLOCKDATA")); for (key, h) in cache.map(|c| entries(&objects, c)).unwrap_or_default().into_iter().take(MAX_VALUES) { if let (Ok(node), Some(v)) = (key.trim().parse::(), objects.get(&h).and_then(|o| value(o))) { + // The record's groups alone can't tell a flip from another two-point parameter (a stray + // 70, or a flip without its state): the parameter it belongs to decides. + let flip = m.parameters.iter().any(|p| p.node == node && matches!(p.kind, ParameterKind::Flip { .. })); + let v = match (flip, v) { + (false, Value::Flip { base, end, .. }) => Value::Points { base, end }, + (true, Value::Points { base, end }) => Value::Flip { base, end, flipped: false }, + (_, v) => v, + }; values.insert(node, v); } } diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs index 1acb72a7c..06b7737a8 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -7,9 +7,11 @@ //! rotate action, Flip state1 (reflection line from the origin to (-10, 0)) and its flip action, //! and Position1 at (0, 3) with a move action. -use cadcraft_doc::dynblock::{ActionKind, GripPart, GripShape, ParameterKind, custom_properties, drag_grip, dynamic_block, grips, set_property}; +use cadcraft_doc::dynblock::{ + ActionKind, GripPart, GripShape, ParameterKind, Value, custom_properties, drag_grip, dynamic_block, grips, reference, set_property, +}; use cadcraft_doc::geom::{Vec2, Vec3}; -use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_doc::{Drawing, EntityKind, Handle, RawTag}; use cadcraft_io::{read_dxf, write_dxf}; fn dxf(src: &str) -> String { @@ -191,3 +193,36 @@ fn bad_angles_and_states_change_nothing() { } assert_eq!(d, before); } + +/// The saved value record of parameter `node` on the reference (the XRECORD its +/// `ACAD_ENHANCEDBLOCKDATA` entry names), as its index in the drawing's kept objects. +fn record(d: &Drawing, node: i32) -> usize { + let objects = &d.foreign.objects; + let after = |o: &cadcraft_doc::foreign::ForeignObject, key: &str| { + let i = o.tags.iter().position(|t| t.code == 3 && t.value == key)?; + Handle::parse_hex(&o.tags.get(i + 1)?.value) + }; + let cache = objects.iter().find_map(|o| after(o, "ACAD_ENHANCEDBLOCKDATA")).unwrap(); + let dict = objects.iter().find(|o| o.handle == cache).unwrap(); + let h = after(dict, &node.to_string()).unwrap(); + objects.iter().position(|o| o.handle == h).unwrap() +} + +#[test] +fn a_value_record_takes_its_shape_from_its_parameter() { + let (mut d, r) = symbol(); + set_property(&mut d, r, "Angle1", "30").unwrap(); + set_property(&mut d, r, "Flip state1", "Flipped").unwrap(); + let mut again = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + // A stray group 70 after the rotation's points, and a flip record without its state. + let rot = record(&again, 15); + std::sync::Arc::make_mut(&mut again.foreign).objects[rot].tags.push(RawTag { code: 70, value: "1".into() }); + let flip = record(&again, 20); + let tags = &mut std::sync::Arc::make_mut(&mut again.foreign).objects[flip].tags; + let last70 = tags.iter().rposition(|t| t.code == 70).unwrap(); + tags.remove(last70); + let values = reference(&again, r).unwrap().values; + assert!(matches!(values.get(&15), Some(Value::Points { .. })), "{:?}", values.get(&15)); + assert!(matches!(values.get(&20), Some(Value::Flip { flipped: false, .. })), "{:?}", values.get(&20)); + assert_eq!(props(&again, r)[..2], pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped")])); +} From cae6f75b4e8a409aae61f995c60d7f8396bbafd2 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:59:45 -0600 Subject: [PATCH 023/187] Docs: the dynamic block data row says what can be changed now It still said only visibility states and lookups could be changed and that only stretch and lookup actions were read. Distances and positions (stretch, move), angles (rotate) and flip states (flip) can be changed, and their value records are saved. Co-Authored-By: Claude Opus 5.5 --- 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 a385479f0..e8fedd459 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch and move actions), angles (rotate actions) and flip states (flip actions) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); other parameters' actions not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block) | | 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 From b19fa363968b6feb24be3d51430b4c16b56a904e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:39:21 -0600 Subject: [PATCH 024/187] Dynamic blocks: a flip value's state is written after both its points A new flip value from a one-point record had its state (70) written before the end point was added, between the two points. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 760503977..f15e0d8d4 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -1094,11 +1094,8 @@ fn write_value(tags: &mut Vec, v: &Val) { return; } }; - if let Val::Flip(_, _, f) = v { - set_state(tags, *f); - } for (i, p) in points.iter().enumerate() { - // The i-th point's groups, else new ones before any text. + // The i-th point's groups, else new ones before any text or a state after the points. let find = |tags: &[RawTag], code: i32, n: usize| tags.iter().enumerate().filter(|(_, t)| t.code == code).nth(n).map(|(j, _)| j); match (find(tags, 10, i), find(tags, 20, i)) { (Some(jx), Some(jy)) => { @@ -1113,11 +1110,17 @@ fn write_value(tags: &mut Vec, v: &Val) { } } _ => { - let at = tags.iter().position(|t| t.code == 1).unwrap_or(tags.len()); + let first = tags.iter().position(|t| t.code == 10); + let at = + tags.iter().enumerate().position(|(j, t)| t.code == 1 || (t.code == 70 && first.is_some_and(|f| j > f))).unwrap_or(tags.len()); tags.splice(at..at, [tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())]); } } } + // A flip value's state follows both its points. + if let Val::Flip(_, _, f) = v { + set_state(tags, *f); + } } /// Set a record's state: a flip value's group 70 after its points, a flip grip's last group 70 @@ -1215,4 +1218,17 @@ mod tests { assert_eq!(by_tag(&d, &def), vec![(10, Handle(1)), (20, Handle(2))]); assert_eq!(by_tag(&d, &anon), vec![(20, Handle(5)), (1_000_001, Handle(6))]); } + + #[test] + fn a_flip_value_s_state_follows_both_its_points() { + // A one-point record, with and without its state: the end point goes in before the state. + let one = || vec![tag(10, "0"), tag(20, "0"), tag(30, "0")]; + let flip = Val::Flip(Vec3::ZERO, Vec3::new(1.0, 0.0, 0.0), true); + for mut tags in [one(), [one(), vec![tag(70, "0")]].concat()] { + write_value(&mut tags, &flip); + let codes: Vec = tags.iter().map(|t| t.code).collect(); + assert_eq!(codes, [10, 20, 30, 10, 20, 30, 70]); + assert_eq!(tags.last().map(|t| t.value.as_str()), Some("1")); + } + } } From ca56d0097e5e90b4cdb0b05b7ab4e376073dfb02 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:39:39 -0600 Subject: [PATCH 025/187] Prompt: the picker's doc stays on picker, the angle's on angle Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/prompt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index 9102727ba..22fb9f825 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -99,12 +99,12 @@ impl Prompt { self.grip = Some(g); self } - /// The visual chooser the UI can show (the `picker` field). /// An angle about the base is asked for (the `angle` field). pub fn angle(mut self) -> Self { self.angle = true; self } + /// The visual chooser the UI can show (the `picker` field). pub fn picker(mut self, p: Picker) -> Self { self.picker = Some(p); self From 7f6033c0aace6d38ba504136776bceaa4b5e7979 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 10:35:51 -0600 Subject: [PATCH 026/187] Dynamic blocks: a rotate or flip selection that repeats an object turns or mirrors it once A repeated handle queued the transform twice: a flip mirrored the object back while its value recorded the flip. Repeats are skipped, as the stretch and move path does. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 7 ++++++- crates/io/tests/dynblock_rotate_flip.rs | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index f15e0d8d4..55e915cf0 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -568,9 +568,14 @@ fn apply( continue; } // Rotate and flip actions turn or mirror their objects, and carry the parameters in their - // selection the same way. + // selection the same way. A handle the selection repeats is handled once (twice would + // turn it twice, or mirror it back). if let Some(t) = turn_or_mirror(&m, values, set, a) { + let mut handled: HashSet = HashSet::new(); for h in &a.selection { + if !handled.insert(*h) { + continue; + } if let Some(node) = param_of.get(h) { if set.contains_key(node) { continue; diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs index 06b7737a8..baa916417 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -226,3 +226,20 @@ fn a_value_record_takes_its_shape_from_its_parameter() { assert!(matches!(values.get(&20), Some(Value::Flip { flipped: false, .. })), "{:?}", values.get(&20)); assert_eq!(props(&again, r)[..2], pairs(&[("Angle1", "30"), ("Flip state1", "Not flipped")])); } + +#[test] +fn a_flip_selection_that_repeats_its_objects_mirrors_them_once() { + // The flip action's selection lists the line, the circle and Position1 twice: each is mirrored + // once, as with the selection listing them once (twice would mirror them back). + let src = include_str!("data/dynblock_symbol.txt").replace("\r\n", "\n"); + let once = "71 3\n330 31\n330 32\n330 68\n1010 -6"; + assert_eq!(src.matches(once).count(), 1); + let (mut twice, r) = symbol_from(&src.replace(once, "71 6\n330 31\n330 32\n330 68\n330 31\n330 32\n330 68\n1010 -6")); + let (mut plain, _) = symbol(); + for d in [&mut twice, &mut plain] { + set_property(d, r, "Flip state1", "Flipped").unwrap(); + } + let ((l1, a1, r1), (l2, a2, r2)) = (shown(&twice, r), shown(&plain, r)); + assert!(near(l1, (l2.x, l2.y)) && near(a1, (a2.x, a2.y)) && (r1 - r2).abs() < 1e-9, "{l1:?} {l2:?}"); + assert_eq!(props(&twice, r), props(&plain, r)); +} From 28d240ca67cf75b574a9ef97fd1cab544a9b172c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:47:57 -0600 Subject: [PATCH 027/187] Dynamic blocks: the actions' bookkeeping moves into ActionRun main now denies cognitive_complexity over 30: apply() was at 35 with the rotate and flip actions. The action loop becomes ActionRun, one method per kind of action (rotate and flip, stretch and move), and the carrying of a parameter by a stretch is shifted(). No change in what the actions do. Co-Authored-By: Claude Sonnet 5.5 --- crates/doc/src/dynblock/apply.rs | 234 +++++++++++++++++++------------ 1 file changed, 141 insertions(+), 93 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 55e915cf0..5b9d71e29 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -538,6 +538,134 @@ fn in_frame(frame: &[Vec2], p: Vec2) -> bool { } } +/// What the actions of one change read (the dynamic block, the parameters' values and the change) +/// and what they write: the values they carry along (`new`, starting from the change) and what +/// happens to each copied object (`moves`). +struct ActionRun<'a> { + m: &'a DynamicBlock, + values: &'a BTreeMap, + set: &'a BTreeMap, + param_of: HashMap, + /// The reference's copy of each of the dynamic block's objects. + copy_map: &'a HashMap, + new: BTreeMap, + moves: HashMap>, +} + +impl ActionRun<'_> { + fn copy_of(&self, dh: &Handle) -> Option { + self.copy_map.get(dh).copied() + } + + /// The value of parameter `node` so far: carried along by an action already, else the + /// reference's. + fn value_of(&self, node: i32) -> Option { + self.new.get(&node).cloned().or_else(|| current(self.m, self.values, node)) + } + + /// Action `a`, when one of its connections follows a parameter the change sets. + fn action(&mut self, a: &super::Action) { + if !a.connections.iter().any(|(n, _)| self.set.contains_key(n)) { + return; + } + match turn_or_mirror(self.m, self.values, self.set, a) { + Some(t) => self.turn_or_mirror(a, t), + None => self.stretch(a), + } + } + + /// A rotate or flip action turns or mirrors its objects, and carries the parameters in its + /// selection the same way. A handle the selection repeats is handled once (twice would turn it + /// twice, or mirror it back). + fn turn_or_mirror(&mut self, a: &super::Action, t: Mat3) { + let mut handled: HashSet = HashSet::new(); + for h in &a.selection { + if !handled.insert(*h) { + continue; + } + if let Some(node) = self.param_of.get(h).copied() { + if self.set.contains_key(&node) { + continue; + } + let Some(cur) = self.value_of(node) else { continue }; + let p = |q: Vec3| t.apply(q.xy()).to3(q.z); + let moved = match cur { + Val::Point(q) => Val::Point(p(q)), + Val::Points(b, e) => Val::Points(p(b), p(e)), + Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f), + other => other, + }; + self.new.insert(node, moved); + } else if let Some(c) = self.copy_of(h) { + self.moves.entry(c).or_default().push(Op::Transform(t)); + } + } + } + + /// A stretch or move action moves its objects (the vertices of a stretch's frame) by the change + /// of its two connections, and carries the parameters in its selection. + fn stretch(&mut self, a: &super::Action) { + let (mult, angle, frame, vertices): (f64, f64, &[Vec2], &[(Handle, Vec)]) = match &a.kind { + ActionKind::Stretch { frame, vertices, multiplier, angle_offset } => (*multiplier, *angle_offset, frame, vertices), + ActionKind::Move { multiplier, angle_offset } => (*multiplier, *angle_offset, &[], &[]), + _ => return, + }; + // The two connections give the change in x and y. + let comp = |i: usize| { + a.connections.get(i).map_or(0.0, |(n, conn)| match (self.set.get(n), current(self.m, self.values, *n)) { + (Some(nv), Some(ov)) => delta(&ov, nv, conn), + _ => 0.0, + }) + }; + let mult = if mult == 0.0 { 1.0 } else { mult }; + let v = Vec2::new(comp(0), comp(1)).rotate(angle) * mult; + if !(v.x.is_finite() && v.y.is_finite()) || (v.x == 0.0 && v.y == 0.0) { + return; + } + // Index this action's vertex lists by handle once, and skip handles already handled in + // this action's selection, so a selection that repeats a handle does not re-scan the + // vertex list and re-clone its index vector per occurrence (CWE-400). + let vtx_by_handle: HashMap> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect(); + let mut handled: HashSet = HashSet::new(); + for h in &a.selection { + if !handled.insert(*h) { + continue; + } + if let Some(node) = self.param_of.get(h).copied() { + // A parameter in the selection is carried along: its points in the frame. Which + // points are in it is decided where the dynamic block has them (AutoCAD evaluates + // the actions from the block itself, so a point another action has moved out of + // the frame still follows). + if self.set.contains_key(&node) { + continue; + } + let Some(cur) = self.value_of(node) else { continue }; + let home = current(self.m, &BTreeMap::new(), node); + self.new.insert(node, shifted(cur, home, frame, v)); + continue; + } + let Some(c) = self.copy_of(h) else { continue }; + let idx = vtx_by_handle.get(h).map(|i| (*i).clone()); + self.moves.entry(c).or_default().push(Op::Move(idx, v)); + } + } +} + +/// Parameter value `cur` carried by `v`: the points in `frame` (empty: all of them), judged where +/// the dynamic block has them (`home`), move. +fn shifted(cur: Val, home: Option, frame: &[Vec2], v: Vec2) -> Val { + let shift = |p: Vec3, at: Option| if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p }; + match (cur, home) { + (Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))), + (Val::Point(p), _) => Val::Point(shift(p, None)), + (Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))), + (Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)), + (Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f), + (Val::Flip(b, e, f), _) => Val::Flip(shift(b, None), shift(e, None), f), + (t, _) => t, + } +} + /// Give `insert` a new anonymous block with the plan's values applied (visibility states, and /// the stretch and move actions of the changed parameters, with the parameters in their selections /// carried along), and record the new values on it. @@ -557,102 +685,22 @@ fn apply( // The dynamic block's objects and the reference's copies of them, by element tag. let def_tags: HashMap = by_tag(d, &def).into_iter().map(|(t, h)| (h, t)).collect(); let src_by_tag: HashMap = by_tag(d, &src).into_iter().collect(); - let copy_of = |dh: &Handle| def_tags.get(dh).and_then(|t| src_by_tag.get(t)).copied(); + let copy_map: HashMap = def_tags.iter().filter_map(|(dh, tag)| Some((*dh, *src_by_tag.get(tag)?))).collect(); + let copy_of = |dh: &Handle| copy_map.get(dh).copied(); // New values, starting from the change; actions add the parameters they carry along. - let mut new: BTreeMap = set.clone(); - let mut moves: HashMap> = HashMap::new(); - let param_of: HashMap = m.parameters.iter().map(|p| (p.handle, p.node)).collect(); + let mut run = ActionRun { + m: &m, + values, + set, + param_of: m.parameters.iter().map(|p| (p.handle, p.node)).collect(), + copy_map: ©_map, + new: set.clone(), + moves: HashMap::new(), + }; for a in &m.actions { - let changed: Vec<&(i32, String)> = a.connections.iter().filter(|(n, _)| set.contains_key(n)).collect(); - if changed.is_empty() { - continue; - } - // Rotate and flip actions turn or mirror their objects, and carry the parameters in their - // selection the same way. A handle the selection repeats is handled once (twice would - // turn it twice, or mirror it back). - if let Some(t) = turn_or_mirror(&m, values, set, a) { - let mut handled: HashSet = HashSet::new(); - for h in &a.selection { - if !handled.insert(*h) { - continue; - } - if let Some(node) = param_of.get(h) { - if set.contains_key(node) { - continue; - } - let Some(cur) = new.get(node).cloned().or_else(|| current(&m, values, *node)) else { continue }; - let p = |q: Vec3| t.apply(q.xy()).to3(q.z); - let moved = match cur { - Val::Point(q) => Val::Point(p(q)), - Val::Points(b, e) => Val::Points(p(b), p(e)), - Val::Flip(b, e, f) => Val::Flip(p(b), p(e), f), - other => other, - }; - new.insert(*node, moved); - continue; - } - if let Some(c) = copy_of(h) { - moves.entry(c).or_default().push(Op::Transform(t)); - } - } - continue; - } - let (mult, angle, frame, vertices): (f64, f64, &[Vec2], &[(Handle, Vec)]) = match &a.kind { - ActionKind::Stretch { frame, vertices, multiplier, angle_offset } => (*multiplier, *angle_offset, frame, vertices), - ActionKind::Move { multiplier, angle_offset } => (*multiplier, *angle_offset, &[], &[]), - _ => continue, - }; - // The two connections give the change in x and y. - let comp = |i: usize| { - a.connections.get(i).map_or(0.0, |(n, conn)| match (set.get(n), current(&m, values, *n)) { - (Some(nv), Some(ov)) => delta(&ov, nv, conn), - _ => 0.0, - }) - }; - let mult = if mult == 0.0 { 1.0 } else { mult }; - let v = Vec2::new(comp(0), comp(1)).rotate(angle) * mult; - if !(v.x.is_finite() && v.y.is_finite()) || (v.x == 0.0 && v.y == 0.0) { - continue; - } - // Index this action's vertex lists by handle once, and skip handles already handled in - // this action's selection, so a selection that repeats a handle does not re-scan the - // vertex list and re-clone its index vector per occurrence (CWE-400). - let vtx_by_handle: HashMap> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect(); - let mut handled: HashSet = HashSet::new(); - for h in &a.selection { - if !handled.insert(*h) { - continue; - } - if let Some(node) = param_of.get(h) { - // A parameter in the selection is carried along: its points in the frame. Which - // points are in it is decided where the dynamic block has them (AutoCAD evaluates - // the actions from the block itself, so a point another action has moved out of - // the frame still follows). - if set.contains_key(node) { - continue; - } - let Some(cur) = new.get(node).cloned().or_else(|| current(&m, values, *node)) else { continue }; - let home = current(&m, &BTreeMap::new(), *node); - let shift = |p: Vec3, at: Option| { - if frame.is_empty() || in_frame(frame, at.unwrap_or(p).xy()) { p + v.to3(0.0) } else { p } - }; - let moved = match (cur, home) { - (Val::Point(p), Some(Val::Point(h))) => Val::Point(shift(p, Some(h))), - (Val::Point(p), _) => Val::Point(shift(p, None)), - (Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(shift(b, Some(hb)), shift(e, Some(he))), - (Val::Points(b, e), _) => Val::Points(shift(b, None), shift(e, None)), - (Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(shift(b, Some(hb)), shift(e, Some(he)), f), - (Val::Flip(b, e, f), _) => Val::Flip(shift(b, None), shift(e, None), f), - (t, _) => t, - }; - new.insert(*node, moved); - continue; - } - let Some(c) = copy_of(h) else { continue }; - let idx = vtx_by_handle.get(h).map(|i| (*i).clone()); - moves.entry(c).or_default().push(Op::Move(idx, v)); - } + run.action(a); } + let ActionRun { new, moves, .. } = run; // Visibility states. let mut shown: HashMap = HashMap::new(); for (node, v) in &new { From eeb213dccd5c2c591499b6908372768ca5e23539 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:48:53 -0600 Subject: [PATCH 028/187] Dynamic blocks: a grip on a value list or increments marks its stops while dragged A distance or angle whose values are a list, or go by an increment, stops only at those values; while its grip is dragged, the preview marks each stop with a short tick across the grip's travel (a few pixels, whatever the zoom), as AutoCAD does. `dynblock::grip_stops` gives the stops: along a distance from the point that stays, or from its midpoint, and round an angle's circle (a full turn being no turn). Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 2 +- crates/doc/src/dynblock/apply.rs | 75 +++++++++++++++++++++++++ crates/engine/src/cmd/blocks/dyngrip.rs | 24 ++++++-- crates/engine/tests/it/dynamic_grips.rs | 27 +++++++++ crates/io/tests/dynblock_rotate_flip.rs | 25 ++++++++- 5 files changed, 147 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 3b60c7aca..685c80b28 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag}; mod apply; mod grips; mod reference; -pub use apply::{drag_grip, set_property}; +pub use apply::{drag_grip, grip_stops, set_property}; pub use grips::{DynGrip, GripPart, GripShape, grips}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 5b9d71e29..ee2dbd40e 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -477,6 +477,81 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa apply(d, insert, &r.definition, &r.values, &plan.set, node) } +/// Most stops one grip shows. +const MAX_STOPS: usize = 200; + +/// The values a value set stops at, for tick marks: its list, or each increment from its minimum +/// to its maximum (to `open_to` without a maximum). None for a value set that takes any value. +fn stops(set: &super::ValueSet, open_to: f64) -> Vec { + let within = |v: f64| { + v.is_finite() && (!set.has_minimum() || v >= set.minimum - 1e-9) && (!set.has_maximum() || set.maximum <= 0.0 || v <= set.maximum + 1e-9) + }; + if set.is_list() { + return set.list.iter().copied().filter(|v| within(*v)).take(MAX_STOPS).collect(); + } + if !(set.has_increment() && set.increment > 0.0 && set.increment.is_finite()) { + return Vec::new(); + } + let from = if set.has_minimum() { set.minimum } else { 0.0 }; + let to = if set.has_maximum() && set.maximum > 0.0 { set.maximum } else { open_to }; + (0..MAX_STOPS).map(|k| from + k as f64 * set.increment).take_while(|v| *v <= to + 1e-9).filter(|v| within(*v)).collect() +} + +/// Where grip `part` of parameter `node` of dynamic block reference `insert` can stop when its +/// parameter's values are a list or go by an increment, as AutoCAD marks them while the grip is +/// dragged: each stop's point and the way the grip travels there (unit vectors, drawing +/// coordinates). Empty when the grip goes anywhere. +pub fn grip_stops(d: &Drawing, insert: Handle, node: i32, part: super::GripPart) -> Vec<(Vec2, Vec2)> { + use super::GripPart; + let Some(r) = reference(d, insert) else { return Vec::new() }; + let Some(m) = dynamic_block(d, &r.definition) else { return Vec::new() }; + let Some(EntityKind::Insert(ins)) = d.entity(insert).map(|e| &e.kind) else { return Vec::new() }; + let Some(p) = m.parameters.iter().find(|p| p.node == node) else { return Vec::new() }; + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Vec::new() }; + let len = (e - b).len(); + if len < 1e-12 { + return Vec::new(); + } + let u = (e - b) * (1.0 / len); + // In the block: (point, travel direction). + let local: Vec<(Vec3, Vec3)> = match (&p.kind, part) { + (ParameterKind::Linear { values, from_midpoint, .. }, GripPart::Base | GripPart::End) => { + let mid = (b + e) * 0.5; + stops(values, 2.0 * len) + .into_iter() + .filter(|v| *v > 0.0) + .map(|v| match (from_midpoint, part) { + (true, GripPart::Base) => (mid - u * (v / 2.0), u * -1.0), + (true, _) => (mid + u * (v / 2.0), u), + (false, GripPart::Base) => (e - u * v, u * -1.0), + (false, _) => (b + u * v, u), + }) + .collect() + } + // A full turn is where no turn is. + (ParameterKind::Rotation { base: hb, end: he, values, .. }, GripPart::End) => stops(values, std::f64::consts::TAU) + .into_iter() + .filter(|a| *a < std::f64::consts::TAU - 1e-9) + .map(|a| { + let at = rotation_end(b, e, (*hb, *he), a); + let radial = (at - b).xy(); + (at, radial.perp().to3(0.0)) + }) + .collect(), + _ => Vec::new(), + }; + let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); + let xf = ins.transform(base); + local + .into_iter() + .filter_map(|(at, way)| { + let (p, ahead) = (xf.apply(at.xy()), xf.apply(at.xy() + way.xy())); + let dir = ahead - p; + (dir.len() > 1e-12 && p.is_finite()).then(|| (p, dir * (1.0 / dir.len()))) + }) + .collect() +} + /// The change of each parameter value an action can follow, by parameter graph id and the /// connection's name ("EndXDelta", "XDelta"…), from `old` and `new` values. fn delta(old: &Val, new: &Val, connection: &str) -> f64 { diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index 548be78d8..41064189e 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -117,8 +117,13 @@ struct DynGripEdit { /// The property it changes, and the grip's shape (a typed number sets a distance or angle). property: String, shape: GripShape, + /// Where the grip can stop (a value list or increments): tick marks across its travel. + stops: Vec<(Vec2, Vec2)>, } +/// Half a tick mark's length, in pixels. +const TICK_PX: f64 = 6.0; + impl Interactive for DynGripEdit { fn name(&self) -> &'static str { "GRIP" @@ -157,9 +162,19 @@ impl Interactive for DynGripEdit { Ok(Step::Done) } - /// The rubber band from the grip. - fn preview(&self, _s: &Session, c: Vec2) -> Vec { - vec![crate::cmd::helpers::line(self.from, c)] + /// The rubber band from the grip, and ticks at the stops of a value list or increments. + fn preview(&self, s: &Session, c: Vec2) -> Vec { + let half = TICK_PX * s.pixel_size(); + let mut out: Vec = self + .stops + .iter() + .map(|(at, way)| { + let n = way.perp() * half; + crate::cmd::helpers::line(*at - n, *at + n) + }) + .collect(); + out.push(crate::cmd::helpers::line(self.from, c)); + out } /// A rotation grip's angle at the cursor, as Properties will show it. @@ -201,7 +216,8 @@ impl Session { return Err(EngineError::Other("a list or flip grip is clicked, not dragged".into())); } let label = if g.shape == GripShape::Rotation { "** ROTATE **" } else { "** STRETCH **" }; - let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape }; + let stops = dynblock::grip_stops(self.doc()?, handle, node, part); + let edit = DynGripEdit { handle, node, part, from: g.at, property: g.property, shape: g.shape, stops }; let machine = crate::guard::Guarded::wrap(Box::new(edit)); let st = self.state()?; let (before, selection_before) = (st.doc.clone(), st.selection.clone()); diff --git a/crates/engine/tests/it/dynamic_grips.rs b/crates/engine/tests/it/dynamic_grips.rs index 75ed1b787..9512d279d 100644 --- a/crates/engine/tests/it/dynamic_grips.rs +++ b/crates/engine/tests/it/dynamic_grips.rs @@ -145,3 +145,30 @@ fn a_grip_drag_previews_the_reference_in_its_own_colours() { let blue = cadcraft_engine::doc::color::Color::True(cadcraft_engine::doc::color::Rgb(0x2f, 0x6b, 0xff)); assert!(preview[n..].iter().all(|e| e.common.color == blue)); } + +#[test] +fn a_grip_with_a_value_list_marks_its_stops_while_dragged() { + let (mut s, h) = session(); + // Width is a list (30, 32, 36) from (0, -4): its end can stop 30, 32 or 36 along it. + let stops = cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 2, GripPart::End); + let at: Vec<(f64, f64)> = stops.iter().map(|(p, _)| (p.x, p.y)).collect(); + assert_eq!(at, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]); + assert!(stops.iter().all(|(_, way)| (way.x - 1.0).abs() < 1e-12 && way.y.abs() < 1e-12)); + // A grip that isn't on a list or increments has none; nor a list grip. + assert!(cadcraft_engine::doc::dynblock::grip_stops(s.doc().unwrap(), h, 1, GripPart::At).is_empty()); + + // The preview marks each stop with a tick across the travel, a few pixels long. + s.start_dyn_grip(h, 2, GripPart::End).unwrap(); + let half = 6.0 * s.pixel_size(); + let ticks: Vec<(f64, f64)> = s + .preview(Vec2::new(133.0, 0.0)) + .into_iter() + .filter_map(|e| match e.kind { + cadcraft_engine::doc::EntityKind::Line(l) if (l.a.x - l.b.x).abs() < 1e-9 && ((l.b.y - l.a.y).abs() - 2.0 * half).abs() < 1e-9 => { + Some((l.a.x, (l.a.y + l.b.y) / 2.0)) + } + _ => None, + }) + .collect(); + assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]); +} diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs index baa916417..46a8d2f31 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -8,7 +8,7 @@ //! and Position1 at (0, 3) with a move action. use cadcraft_doc::dynblock::{ - ActionKind, GripPart, GripShape, ParameterKind, Value, custom_properties, drag_grip, dynamic_block, grips, reference, set_property, + ActionKind, GripPart, GripShape, ParameterKind, Value, custom_properties, drag_grip, dynamic_block, grip_stops, grips, reference, set_property, }; use cadcraft_doc::geom::{Vec2, Vec3}; use cadcraft_doc::{Drawing, EntityKind, Handle, RawTag}; @@ -184,6 +184,29 @@ fn an_angle_shows_and_is_typed_as_the_drawing_measures_angles() { assert!(near(at, want), "{at:?} vs {want:?}"); } +#[test] +fn an_angle_by_increments_marks_its_stops_round_the_circle() { + // Angle1 by 90° from 0 to a full turn: its grip stops at four points round the base, the + // full turn being no turn; the way it travels there is round the circle. + let src = include_str!("data/dynblock_symbol.txt") + .replace("\r\n", "\n") + .replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n"); + let (d, r) = symbol_from(&src); + let stops = grip_stops(&d, r, 15, GripPart::End); + let at: Vec = stops.iter().map(|(p, _)| *p).collect(); + assert_eq!(at.len(), 4, "{at:?}"); + for (p, want) in at.iter().zip([(102.0, 100.0), (100.0, 102.0), (98.0, 100.0), (100.0, 98.0)]) { + assert!(near(*p, want), "{p:?} vs {want:?}"); + } + for (p, way) in &stops { + assert!((*p - Vec2::new(100.0, 100.0)).dot(*way).abs() < 1e-9, "across the radius"); + } + // The block as it comes (any angle) marks nothing; nor does a flip grip. + let (d, r) = symbol(); + assert!(grip_stops(&d, r, 15, GripPart::End).is_empty()); + assert!(grip_stops(&d, r, 20, GripPart::Base).is_empty()); +} + #[test] fn bad_angles_and_states_change_nothing() { let (mut d, r) = symbol(); From 4f671b775918565f1b4c63e69ea12ae98c835b69 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:31:34 -0600 Subject: [PATCH 029/187] Dynamic blocks: an angle's tick marks are where its grip will be The rotation grip is drawn where its grip object is, which can be off the radius' end; its stops are now marked there too (the grip object's angle and distance from the base added to each value), not at the radius' end. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/apply.rs | 29 +++++++++++++++++-------- crates/io/tests/dynblock_rotate_flip.rs | 16 ++++++++++++++ 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index ee2dbd40e..7a4a5228a 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -529,15 +529,26 @@ pub fn grip_stops(d: &Drawing, insert: Handle, node: i32, part: super::GripPart) .collect() } // A full turn is where no turn is. - (ParameterKind::Rotation { base: hb, end: he, values, .. }, GripPart::End) => stops(values, std::f64::consts::TAU) - .into_iter() - .filter(|a| *a < std::f64::consts::TAU - 1e-9) - .map(|a| { - let at = rotation_end(b, e, (*hb, *he), a); - let radial = (at - b).xy(); - (at, radial.perp().to3(0.0)) - }) - .collect(), + // Where the grip is at each angle: its grip object can be off the radius' end, by an + // angle and at a distance of its own. + (ParameterKind::Rotation { base: hb, end: he, values, .. }, GripPart::End) => { + let g = p.grips.get(1).and_then(|id| m.grip_points.iter().find(|(gi, _)| gi == id)).map(|(_, g)| *g); + let home = (*he - *hb).len(); + let (offset, reach) = match g { + Some(g) if home > 1e-12 && (g - *hb).len() > 1e-12 => (rotation_angle(*hb, g, (*hb, *he)), (g - *hb).len() * len / home), + _ => (0.0, len), + }; + let reach_end = b + u * reach; + stops(values, std::f64::consts::TAU) + .into_iter() + .filter(|a| *a < std::f64::consts::TAU - 1e-9) + .map(|a| { + let at = rotation_end(b, reach_end, (*hb, *he), a + offset); + let radial = (at - b).xy(); + (at, radial.perp().to3(0.0)) + }) + .collect() + } _ => Vec::new(), }; let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/dynblock_rotate_flip.rs index 46a8d2f31..1815283fc 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/dynblock_rotate_flip.rs @@ -207,6 +207,22 @@ fn an_angle_by_increments_marks_its_stops_round_the_circle() { assert!(grip_stops(&d, r, 20, GripPart::Base).is_empty()); } +#[test] +fn an_angle_s_stops_follow_a_grip_off_the_radius() { + // The grip object a quarter turn round and 90° increments: each stop is where the grip is + // at that angle, the first (0) where it is now. + let src = include_str!("data/dynblock_symbol.txt") + .replace("\r\n", "\n") + .replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n") + .replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n"); + let (d, r) = symbol_from(&src); + let at: Vec = grip_stops(&d, r, 15, GripPart::End).into_iter().map(|(p, _)| p).collect(); + assert_eq!(at.len(), 4, "{at:?}"); + for (p, want) in at.iter().zip([(100.0, 102.0), (98.0, 100.0), (100.0, 98.0), (102.0, 100.0)]) { + assert!(near(*p, want), "{p:?} vs {want:?}"); + } +} + #[test] fn bad_angles_and_states_change_nothing() { let (mut d, r) = symbol(); From 46acac72eb79f54fff5b93e7182a1dc09594378e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:57:03 -0600 Subject: [PATCH 030/187] Dynamic blocks: array actions, polar and XY parameters A dynamic block reference now repeats its arrayed objects as AutoCAD does: along a linear or polar parameter one copy per whole column offset in its distance, across an XY parameter a whole number of columns by rows (just the object when either is short of one), following the parameter's base point. Copies after the first carry AutoCAD's AcDbBlockArrayActionTag; without it AutoCAD can't change the reference again ("Invalid input"). Polar parameters show Distance1 and Angle1, XY parameters X Distance1 and Y Distance1, in Properties (editable, value sets applied; an XY distance below its minimum is refused as AutoCAD refuses it), with square grips at the base and end and an XY parameter's two other corners. Checked against AutoCAD with a linear, a polar and an XY array block: copy counts and positions match for each value tried, AutoCAD reads CADCraft's saved values and geometry, and changes them again. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 115 ++++- crates/doc/src/dynblock/apply.rs | 253 ++++++++++- crates/doc/src/dynblock/grips.rs | 37 ++ crates/doc/src/dynblock/reference.rs | 21 + crates/engine/src/cmd/blocks.rs | 2 +- crates/engine/src/cmd/blocks/dyngrip.rs | 3 +- crates/io/tests/data/dynblock_arrays.txt | 508 +++++++++++++++++++++++ crates/io/tests/dynblock_array.rs | 205 +++++++++ docs/file-format-parity.md | 1 + docs/gaps.md | 3 +- 10 files changed, 1119 insertions(+), 29 deletions(-) create mode 100644 crates/io/tests/data/dynblock_arrays.txt create mode 100644 crates/io/tests/dynblock_array.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 685c80b28..8a70ce090 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -91,10 +91,30 @@ pub enum ParameterKind { /// The value changes the end point (`false`) or both points from the midpoint (`true`). from_midpoint: bool, }, - /// A distance and an angle from a base point. - Polar { base: Vec3, end: Vec3 }, - /// Horizontal and vertical distances from a base point. - Xy { base: Vec3, end: Vec3 }, + /// A distance and an angle from a base point (Distance1, Angle1): the end point's distance + /// from the base and its direction (counterclockwise from the X axis of the block). + Polar { + base: Vec3, + end: Vec3, + label: String, + description: String, + angle_label: String, + angle_description: String, + values: ValueSet, + angle_values: ValueSet, + }, + /// Horizontal and vertical distances from a base point (X Distance1, Y Distance1): how far + /// the end point is from the base along the block's X and Y axes. + Xy { + base: Vec3, + end: Vec3, + x_label: String, + y_label: String, + x_description: String, + y_description: String, + x_values: ValueSet, + y_values: ValueSet, + }, /// An angle about a base point (Angle1): the end point turns about the base. The angle is /// measured from the direction the dynamic block has from base to end. Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet }, @@ -135,6 +155,16 @@ impl ParameterKind { _ => None, } } + + /// Every property name a reference shows for the parameter: a polar parameter's distance + /// and angle, an XY parameter's two distances, else its one label. + pub fn labels(&self) -> Vec<&str> { + match self { + ParameterKind::Polar { label, angle_label, .. } => vec![label, angle_label], + ParameterKind::Xy { x_label, y_label, .. } => vec![x_label, y_label], + other => other.label().into_iter().collect(), + } + } } /// One visibility state: its name and the objects shown in it (the parameter's other controlled @@ -227,7 +257,13 @@ pub enum ActionKind { }, /// Mirrors the objects across a flip parameter's reflection line when its state changes. Flip, - Array, + /// Repeats the objects as far as the parameter it follows reaches: along a distance (linear + /// or polar parameter) every `column` units, or in a grid of columns and rows across an XY + /// parameter's distances. The objects follow the parameter's base point. + Array { + column: f64, + row: f64, + }, PolarStretch, /// An action type not modelled yet. Other { @@ -392,15 +428,21 @@ pub fn dynamic_block(d: &Drawing, name: &str) -> Option { } /// A parameter's grip ids: after a two-point parameter's points, the grip count (170) and the -/// base and end grips (91); after a one-point parameter's point, its grip (93). +/// base and end grips (91), then an XY parameter's corner grips (base X and end Y, base Y and end +/// X); after a one-point parameter's point, its grip (93). fn grip_ids(secs: &[(&str, &[RawTag])]) -> Vec { let two = section(secs, "AcDbBlock2PtParameter"); if !two.is_empty() { let mut c = Cursor::new(two); c.point(1010); c.point(1011); - let n = c.count(170).min(2); - return (0..n).map(|_| c.int(91)).collect(); + let n = c.count(170).min(4); + let mut ids: Vec = (0..n).map(|_| c.int(91)).collect(); + // Corner grips only an XY parameter has (the others write 0 for them). + while ids.len() > 2 && ids.last() == Some(&0) { + ids.pop(); + } + return ids; } let mut c = Cursor::new(section(secs, "AcDbBlock1PtParameter")); c.point(1010); @@ -448,13 +490,31 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind { let states = [c.string(307), c.string(308)]; ParameterKind::Flip { base, end, label, description, states } } - "BLOCKPOLARPARAMETER" | "BLOCKXYPARAMETER" | "BLOCKALIGNMENTPARAMETER" => { + // The distance's name and description (305, 306), the angle's (307, 308), the label + // offset (140), then the distance's value set (309, 96, 141–144, 175) and the angle's + // (410, 97, 145–148, 176). + "BLOCKPOLARPARAMETER" => { let (base, end) = two(); - match kind { - "BLOCKPOLARPARAMETER" => ParameterKind::Polar { base, end }, - "BLOCKXYPARAMETER" => ParameterKind::Xy { base, end }, - _ => ParameterKind::Alignment { base, end }, - } + let mut c = Cursor::new(section(secs, "AcDbBlockPolarParameter")); + let (label, description, angle_label, angle_description) = (c.string(305), c.string(306), c.string(307), c.string(308)); + let values = value_set_at(&mut c, [309, 96, 141, 175]); + let angle_values = value_set_at(&mut c, [410, 97, 145, 176]); + ParameterKind::Polar { base, end, label, description, angle_label, angle_description, values, angle_values } + } + // The vertical distance's name (305) before the horizontal's (306), then their + // descriptions (307, 308), label offsets (141, 140), the vertical value set (309, 97, + // 146–149, 176) and the horizontal one (410, 96, 142–145, 175). + "BLOCKXYPARAMETER" => { + let (base, end) = two(); + let mut c = Cursor::new(section(secs, "AcDbBlockXYParameter")); + let (y_label, x_label, y_description, x_description) = (c.string(305), c.string(306), c.string(307), c.string(308)); + let y_values = value_set_at(&mut c, [309, 97, 146, 176]); + let x_values = value_set_at(&mut c, [410, 96, 142, 175]); + ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values } + } + "BLOCKALIGNMENTPARAMETER" => { + let (base, end) = two(); + ParameterKind::Alignment { base, end } } other => ParameterKind::Other { dxf_type: other.to_string() }, } @@ -463,11 +523,17 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind { /// A value set after a parameter's name and description: description (307), flags (96), /// minimum, maximum and increment (141–143), then the listed values (175 count, 144 each). fn value_set(c: &mut Cursor) -> ValueSet { - c.next(307); - let flags = c.int(96); - let (minimum, maximum, increment) = (c.real(141), c.real(142), c.real(143)); - let n = c.count(175); - let list = (0..n).filter_map(|_| c.next(144).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite())).collect(); + value_set_at(c, [307, 96, 141, 175]) +} + +/// A value set written with codes `[description, flags, minimum, count]`: the maximum and +/// increment follow the minimum's code, each listed value is the code after the increment's. +fn value_set_at(c: &mut Cursor, [description, flags, min, count]: [i32; 4]) -> ValueSet { + c.next(description); + let flags = c.int(flags); + let (minimum, maximum, increment) = (c.real(min), c.real(min + 1), c.real(min + 2)); + let n = c.count(count); + let list = (0..n).filter_map(|_| c.next(min + 3).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite())).collect(); ValueSet { flags, minimum, maximum, increment, list } } @@ -521,7 +587,16 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[ let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect(); (connections, ActionKind::Flip) } - "BLOCKARRAYACTION" => (Vec::new(), ActionKind::Array), + // Its four connections (92-95 with 301-304, as a flip action's), then the row (140) and + // column (141) offsets. + "BLOCKARRAYACTION" => { + let tags = section(secs, "AcDbBlockArrayAction"); + let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string(); + let connections = (0..4).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect(); + let mut c = Cursor::new(tags); + let (row, column) = (c.real(140), c.real(141)); + (connections, ActionKind::Array { column, row }) + } "BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch), other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }), }; diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 7a4a5228a..4fac458fa 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -174,8 +174,8 @@ fn current(m: &DynamicBlock, values: &BTreeMap, node: i32) -> Option (ParameterKind::Point { at, .. }, None) => Val::Point(*at), ( ParameterKind::Linear { base, end, .. } - | ParameterKind::Polar { base, end } - | ParameterKind::Xy { base, end } + | ParameterKind::Polar { base, end, .. } + | ParameterKind::Xy { base, end, .. } | ParameterKind::Rotation { base, end, .. } | ParameterKind::Alignment { base, end }, None, @@ -332,11 +332,45 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> .parameters .iter() .find(|p| { - p.show_properties && p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(want) || (axis.is_some() && l.eq_ignore_ascii_case(label))) + p.show_properties && p.kind.labels().iter().any(|l| l.eq_ignore_ascii_case(want) || (axis.is_some() && l.eq_ignore_ascii_case(label))) }) .ok_or_else(|| format!("The reference has no property \"{name}\"."))?; + // Which of a two-property parameter's properties it is: a polar parameter's distance or + // angle, an XY parameter's horizontal or vertical distance. + let second = p.kind.labels().iter().position(|l| l.eq_ignore_ascii_case(want)) == Some(1); let mut plan = Plan::default(); match (&p.kind, axis) { + (ParameterKind::Polar { values, angle_values, label, angle_label, .. }, _) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; + let (len, a) = ((e - b).len(), (e - b).xy().angle()); + let (len, a) = if second { + // Typed as the drawing shows angles (from ANGBASE, clockwise when ANGDIR is 1). + let a = allowed(angle_values, super::reference::angle_from_shown(d, number(value)?.to_radians())); + if !a.is_finite() { + return Err(format!("\"{value}\" is not an angle for {angle_label}.")); + } + (len, a) + } else { + let dist = allowed(values, number(value)? / sx); + if !(dist > 0.0 && dist.is_finite()) { + return Err(format!("{label} must be more than 0.")); + } + (dist, a) + }; + plan.set.insert(p.node, Val::Points(b, b + Vec2::new(a.cos(), a.sin()).to3(0.0) * len)); + } + (ParameterKind::Xy { x_values, y_values, x_label, y_label, .. }, _) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; + let (set, scale, label) = if second { (y_values, sy, y_label) } else { (x_values, sx, x_label) }; + let v = number(value)? / scale; + // AutoCAD refuses a distance below the minimum rather than taking the minimum. + if set.has_minimum() && v < set.minimum - 1e-9 { + return Err(format!("{label} must be at least {}.", set.minimum * scale)); + } + let v = allowed(set, v); + let e2 = if second { Vec3::new(e.x, b.y + v, e.z) } else { Vec3::new(b.x + v, e.y, e.z) }; + plan.set.insert(p.node, Val::Points(b, e2)); + } (ParameterKind::Visibility { states, label, .. }, _) => { let s = states.iter().find(|s| s.name.eq_ignore_ascii_case(value.trim())).ok_or_else(|| { format!("\"{value}\" is not a state of {label}: {}.", states.iter().map(|s| s.name.as_str()).collect::>().join(", ")) @@ -452,6 +486,56 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) }; plan.set.insert(node, Val::Point(Vec3::new(q.x, q.y, at.z))); } + // The end grip goes where it is dragged (its distance snapped to the value set); the base + // grip moves the base, keeping the end. + (ParameterKind::Polar { values, label, .. }, GripPart::Base | GripPart::End) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; + let q3 = Vec3::new(q.x, q.y, b.z); + let (b2, e2) = if part == GripPart::Base { + (q3, e) + } else { + let raw = (q3 - b).len(); + let dist = allowed(values, raw); + if !(raw > 1e-12 && dist > 0.0 && dist.is_finite()) { + return Err(format!("{label} must be more than 0.")); + } + (b, b + (q3 - b) * (dist / raw)) + }; + plan.set.insert(node, Val::Points(b2, e2)); + } + // Each grip sets the coordinates it stands for: the base's or the end's, or the base's X + // with the end's Y (and the other way round) at the two other corners. A distance below a + // value set's minimum is refused, as AutoCAD refuses it. + (ParameterKind::Xy { x_values, y_values, x_label, y_label, .. }, _) => { + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{x_label} has no points.")) }; + let (mut b2, mut e2) = (b, e); + match part { + GripPart::Base => (b2.x, b2.y) = (q.x, q.y), + GripPart::End => (e2.x, e2.y) = (q.x, q.y), + GripPart::BaseXEndY => (b2.x, e2.y) = (q.x, q.y), + GripPart::BaseYEndX => (e2.x, b2.y) = (q.x, q.y), + GripPart::At => return Err("That grip can't be dragged.".into()), + } + let fit = |set: &super::ValueSet, v: f64, label: &str| { + if set.has_minimum() && v < set.minimum - 1e-9 { + Err(format!("{label} must be at least {}.", set.minimum)) + } else { + Ok(allowed(set, v)) + } + }; + let (dx, dy) = (fit(x_values, e2.x - b2.x, x_label)?, fit(y_values, e2.y - b2.y, y_label)?); + // The moved point keeps the snapped distances from the one that stays. + if matches!(part, GripPart::Base) { + (b2.x, b2.y) = (e2.x - dx, e2.y - dy); + } else if matches!(part, GripPart::End) { + (e2.x, e2.y) = (b2.x + dx, b2.y + dy); + } else if part == GripPart::BaseXEndY { + (b2.x, e2.y) = (e2.x - dx, b2.y + dy); + } else { + (e2.x, b2.y) = (b2.x + dx, e2.y - dy); + } + plan.set.insert(node, Val::Points(b2, e2)); + } // The angle from the base to the point, snapped to the parameter's values. (ParameterKind::Rotation { base: hb, end: he, values, label, .. }, GripPart::End) => { let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; @@ -660,6 +744,34 @@ impl ActionRun<'_> { } } + /// Arrays, made again from the first copy of each arrayed object for the parameter's value now + /// (whatever changed): the copy follows the parameter's base point, the others repeat it. The + /// offsets of each arrayed object's other copies, by the object's copy in the reference. + fn arrays(&mut self) -> Result>, String> { + let mut arrays: HashMap> = HashMap::new(); + for a in &self.m.actions { + let ActionKind::Array { column, row } = a.kind else { continue }; + let Some((node, _)) = a.connections.first() else { continue }; + let Some(p) = self.m.parameters.iter().find(|p| p.node == *node) else { continue }; + let (Some(Val::Points(was, _)), Some(Val::Points(b, e))) = (current(self.m, self.values, *node), self.value_of(*node)) else { + continue; + }; + let offsets = array_offsets(&p.kind, b, e, column, row)?; + let shift = (b - was).xy(); + for h in a.selection.iter().filter(|h| !self.param_of.contains_key(h)) { + let Some(c) = self.copy_of(h) else { continue }; + if shift.x != 0.0 || shift.y != 0.0 { + self.moves.entry(c).or_default().push(Op::Move(None, shift)); + } + arrays.insert(c, offsets.clone()); + } + } + if arrays.values().map(Vec::len).sum::() > MAX_ARRAY { + return Err(format!("The arrays would make more than {MAX_ARRAY} copies.")); + } + Ok(arrays) + } + /// A rotate or flip action turns or mirrors its objects, and carries the parameters in its /// selection the same way. A handle the selection repeats is handled once (twice would turn it /// twice, or mirror it back). @@ -737,6 +849,28 @@ impl ActionRun<'_> { } } +/// The reference's copies by element tag: each copy's tag, and the first copy of each tag (an +/// arrayed object's copies all carry its tag; the first is the one the array starts from). +fn tags_of_copies(d: &Drawing, src: &Block) -> (HashMap, HashMap) { + let tags = by_tag(d, src); + let of_copy = tags.iter().map(|(t, h)| (*h, *t)).collect(); + let mut first: HashMap = HashMap::new(); + for (t, h) in tags { + first.entry(t).or_insert(h); + } + (of_copy, first) +} + +/// The earlier copies of arrayed objects (the arrays replace them). +fn earlier_copies(src: &Block, src_tag: &HashMap, arrays: &HashMap>) -> HashSet { + let arrayed_tags: HashSet = arrays.keys().filter_map(|h| src_tag.get(h)).copied().collect(); + src.entities + .iter() + .filter(|e| !arrays.contains_key(&e.handle) && src_tag.get(&e.handle).is_some_and(|t| arrayed_tags.contains(t))) + .map(|e| e.handle) + .collect() +} + /// Parameter value `cur` carried by `v`: the points in `frame` (empty: all of them), judged where /// the dynamic block has them (`home`), move. fn shifted(cur: Val, home: Option, frame: &[Vec2], v: Vec2) -> Val { @@ -770,7 +904,7 @@ fn apply( let src = d.block(&ins.block).cloned().ok_or("The reference's block is missing.")?; // The dynamic block's objects and the reference's copies of them, by element tag. let def_tags: HashMap = by_tag(d, &def).into_iter().map(|(t, h)| (h, t)).collect(); - let src_by_tag: HashMap = by_tag(d, &src).into_iter().collect(); + let (src_tag, src_by_tag) = tags_of_copies(d, &src); let copy_map: HashMap = def_tags.iter().filter_map(|(dh, tag)| Some((*dh, *src_by_tag.get(tag)?))).collect(); let copy_of = |dh: &Handle| copy_map.get(dh).copied(); // New values, starting from the change; actions add the parameters they carry along. @@ -786,6 +920,8 @@ fn apply( for a in &m.actions { run.action(a); } + let arrays = run.arrays()?; + let earlier = earlier_copies(&src, &src_tag, &arrays); let ActionRun { new, moves, .. } = run; // Visibility states. let mut shown: HashMap = HashMap::new(); @@ -808,9 +944,11 @@ fn apply( let mut b = Block { name: name.clone(), anonymous: true, xref_path: None, array: None, units: 0, entities: crate::EntityStore::new(), ..(*src).clone() }; let mut copies: HashMap = HashMap::new(); - for e in src.entities.iter() { + for e in src.entities.iter().filter(|e| !earlier.contains(&e.handle)) { copies.insert(e.handle, d.new_handle()); } + // The array copies made of each object: (its copy in the reference, the new copy). + let mut repeats: Vec<(Handle, Handle)> = Vec::new(); // How each attribute definition moves, turns or mirrors (block coordinates): the reference's // attribute of that tag follows it, as AutoCAD moves it. let attrib_moves: HashMap = src @@ -859,7 +997,33 @@ fn apply( l.sources = l.sources.iter().map(|s| copies.get(s).copied().unwrap_or(*s)).collect(); } } + // An arrayed object's other copies (attribute definitions aren't repeated: the + // reference has one attribute per tag), marked as AutoCAD marks them; the first isn't. + let offsets = arrays.get(&e.handle).filter(|_| !matches!(c.kind, EntityKind::AttDef(_))); + if offsets.is_some() { + mark_repeat(&mut c.common.xdata, false); + } + let again: Vec = offsets + .into_iter() + .flatten() + .map(|v| { + let mut r = c.clone(); + r.handle = d.new_handle(); + for t in &mut r.common.xdata { + if t.code == 1005 && Handle::parse_hex(&t.value) == Some(nh) { + t.value = r.handle.hex(); + } + } + mark_repeat(&mut r.common.xdata, true); + r.kind.transform(&Mat3::translate(*v)); + repeats.push((e.handle, r.handle)); + r + }) + .collect(); b.entities.push(c); + for r in again { + b.entities.push(r); + } } refill_hatches(&mut b); let def_record = Some(record_handle(d, definition).unwrap_or_else(|| { @@ -871,13 +1035,16 @@ fn apply( let old = ins.block.clone(); d.blocks.insert(name.clone(), std::sync::Arc::new(b)); let f = std::sync::Arc::make_mut(&mut d.foreign); - for (old_h, new_h) in &copies { + for (i, (old_h, new_h)) in copies.iter().chain(repeats.iter().map(|(a, b)| (a, b))).enumerate() { if let Some(mut x) = f.entities.get(old_h).cloned() { for t in &mut x.xdata { if t.code == 1005 && Handle::parse_hex(&t.value) == Some(*old_h) { t.value = new_h.hex(); } } + if arrays.contains_key(old_h) && etag_in(&x.xdata).is_some() { + mark_repeat(&mut x.xdata, i >= copies.len()); + } x.xdict = None; // Reactors within the block (an associative hatch's outline) follow to the copies; // ones outside it are not ours. @@ -912,6 +1079,67 @@ fn apply( Ok(()) } +/// Xdata application AutoCAD marks an array's copies with (all but the first). +const ARRAY_TAG: &str = "AcDbBlockArrayActionTag"; + +/// Mark xdata `x` as an array's copy (`on`) or not: without the mark AutoCAD can't change the +/// reference again ("Invalid input"). +fn mark_repeat(x: &mut Vec, on: bool) { + if let Some(at) = x.iter().position(|t| t.code == 1001 && t.value.eq_ignore_ascii_case(ARRAY_TAG)) { + let end = x.iter().skip(at + 1).position(|t| t.code == 1001).map_or(x.len(), |n| at + 1 + n); + x.drain(at..end); + } + if on { + x.push(tag(1001, ARRAY_TAG)); + x.push(tag(1070, "1")); + } +} + +/// Most copies one change's arrays make. +const MAX_ARRAY: usize = 100_000; + +/// Where an array action repeats its objects (offsets from the first copy, which isn't listed) +/// for parameter `kind` with points `b` and `e`, as AutoCAD repeats them: along a linear or polar +/// parameter, one copy for each whole `column` in its distance; across an XY parameter, a whole +/// number of `column`s along X by `row`s along Y, toward the end. Fewer than one of either leaves +/// the object alone. +fn array_offsets(kind: &ParameterKind, b: Vec3, e: Vec3, column: f64, row: f64) -> Result, String> { + // How many whole steps of `step` fit in `span` (a little short still counts as whole). + let fits = |span: f64, step: f64| -> Result { + if !(step > 0.0 && step.is_finite() && span.is_finite()) { + return Ok(0); + } + let n = (span.abs() / step + 1e-9).floor(); + if n > MAX_ARRAY as f64 { + return Err(format!("The array would make more than {MAX_ARRAY} copies.")); + } + Ok(n as usize) + }; + let d = (e - b).xy(); + match kind { + ParameterKind::Linear { .. } | ParameterKind::Polar { .. } => { + let n = fits(d.len(), column)?; + if n < 2 { + return Ok(Vec::new()); + } + let u = d * (1.0 / d.len()); + Ok((1..n).map(|k| u * (k as f64 * column)).collect()) + } + ParameterKind::Xy { .. } => { + let (cols, rows) = (fits(d.x, column)?, fits(d.y, row)?); + if cols < 1 || rows < 1 || cols.saturating_mul(rows) < 2 { + return Ok(Vec::new()); + } + if cols.saturating_mul(rows) > MAX_ARRAY { + return Err(format!("The array would make more than {MAX_ARRAY} copies.")); + } + let (sx, sy) = (if d.x < 0.0 { -column } else { column }, if d.y < 0.0 { -row } else { row }); + Ok((0..rows).flat_map(|j| (0..cols).map(move |i| Vec2::new(i as f64 * sx, j as f64 * sy))).skip(1).collect()) + } + _ => Ok(Vec::new()), + } +} + /// 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) { @@ -1196,6 +1424,19 @@ fn write_history(tags: &mut Vec, p: &super::Parameter, old: Option<&Val> c } (ParameterKind::Point { at, .. }, Val::Point(q)) => grips(&[(was.unwrap_or(*at), *q, *at)]), + // As drags of the base and end grips from where the dynamic block has them: the entries + // of all its grips (an XY parameter's corners too) give way to these two. + (ParameterKind::Polar { base: hb, end: he, .. } | ParameterKind::Xy { base: hb, end: he, .. }, Val::Points(b, e)) => p + .grips + .iter() + .enumerate() + .filter(|(_, g)| **g != 0) + .map(|(i, g)| match i { + 0 => grip(*g, *b - *hb), + 1 => grip(*g, *e - *he), + _ => (*g, Vec::new()), + }) + .collect(), _ => return, }; // The header, then the entries (each from its 1071). diff --git a/crates/doc/src/dynblock/grips.rs b/crates/doc/src/dynblock/grips.rs index 5c0df044c..32a5ab33f 100644 --- a/crates/doc/src/dynblock/grips.rs +++ b/crates/doc/src/dynblock/grips.rs @@ -28,6 +28,10 @@ pub enum GripPart { End, /// A one-point parameter's point (a position, a visibility or lookup grip). At, + /// An XY parameter's corner at the base's X and the end's Y. + BaseXEndY, + /// An XY parameter's corner at the end's X and the base's Y. + BaseYEndX, } impl GripPart { @@ -36,6 +40,8 @@ impl GripPart { GripPart::Base => "base", GripPart::End => "end", GripPart::At => "at", + GripPart::BaseXEndY => "basex-endy", + GripPart::BaseYEndX => "basey-endx", } } pub fn from_name(s: &str) -> Option { @@ -43,6 +49,8 @@ impl GripPart { "base" => Some(GripPart::Base), "end" => Some(GripPart::End), "at" => Some(GripPart::At), + "basex-endy" => Some(GripPart::BaseXEndY), + "basey-endx" => Some(GripPart::BaseYEndX), _ => None, } } @@ -239,6 +247,35 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { }); } } + // Squares at the base and the end (a polar parameter), and at the two other corners of + // the rectangle they span (an XY parameter), for the grips the parameter has; an end + // no action follows has none. + ParameterKind::Polar { base, end, label, .. } | ParameterKind::Xy { base, end, x_label: label, .. } => { + let (b, e) = match r.values.get(&p.node) { + Some(Value::Points { base, end }) => (*base, *end), + _ => (*base, *end), + }; + let used = ends_used(&m, p.node).map_or([true, true], |(base, end)| [base, end]); + let mut corners = vec![(0, GripPart::Base, b, used[0]), (1, GripPart::End, e, used[1])]; + if matches!(p.kind, ParameterKind::Xy { .. }) { + let both = used[0] && used[1]; + corners.push((2, GripPart::BaseXEndY, Vec3::new(b.x, e.y, b.z), both)); + corners.push((3, GripPart::BaseYEndX, Vec3::new(e.x, b.y, b.z), both)); + } + for (i, part, at, used) in corners { + if used && shown(p.node, grip(i)) { + out.push(DynGrip { + node: p.node, + part, + shape: GripShape::Point, + at: world(at), + dir: Vec2::ZERO, + property: label.clone(), + choices: Vec::new(), + }); + } + } + } ParameterKind::Point { at, label, .. } => { let at = match r.values.get(&p.node) { Some(Value::Point { at }) => *at, diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 5704e591a..e5e7baa42 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -277,6 +277,27 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec { + let (b, e) = match v { + Some(Value::Points { base, end }) => (*base, *end), + _ => (*b, *e), + }; + let choices = if values.is_list() { values.list.iter().map(|x| number(d, x * sx)).collect() } else { Vec::new() }; + out.push(CustomProperty { name: label.clone(), value: number(d, (e - b).len() * sx), choices, editable: true }); + let a = (e - b).xy().angle().rem_euclid(std::f64::consts::TAU); + out.push(CustomProperty { name: angle_label.clone(), value: angle_text(d, a), choices: Vec::new(), editable: true }); + } + // How far the end is from the base along X and along Y. + ParameterKind::Xy { base: b, end: e, x_label, y_label, .. } => { + let (b, e) = match v { + Some(Value::Points { base, end }) => (*base, *end), + _ => (*b, *e), + }; + out.push(CustomProperty { name: x_label.clone(), value: number(d, (e.x - b.x) * sx), choices: Vec::new(), editable: true }); + out.push(CustomProperty { name: y_label.clone(), value: number(d, (e.y - b.y) * sy), choices: Vec::new(), editable: true }); + } ParameterKind::Point { at, label, .. } => { let at = match v { Some(Value::Point { at }) => *at, diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 445045677..6b15eb6c9 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -66,7 +66,7 @@ pub fn specs() -> Vec { .enabled(has_doc) .noundo(), CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip) - .params("{handle, node (the parameter's graph id), part: base|end|at, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle") + .params("{handle, node (the parameter's graph id), part: base|end|at|basex-endy|basey-endx, to: [x,y] (drawing coordinates)} → {properties}: a distance's arrow changes the distance (snapped to its values), a position's square moves it, a rotation's circle turns its angle, a polar or XY parameter's squares move its base, end or corners") .enabled(has_doc), CommandSpec::new("purge", "Purge", purge::run) .alias(&["pu", "-purge"]) diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index 41064189e..baac76c07 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -30,7 +30,8 @@ pub(super) fn run_grip(s: &mut Session, p: &Value) -> Result { .and_then(Value::as_i64) .and_then(|n| i32::try_from(n).ok()) .ok_or_else(|| bad(cmd, "`node` (a parameter's graph id) is required"))?; - let part = str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end or at"))?; + let part = + str_param(p, "part").and_then(GripPart::from_name).ok_or_else(|| bad(cmd, "`part` must be base, end, at, basex-endy or basey-endx"))?; let to = point_param(p, "to").ok_or_else(|| bad(cmd, "`to` [x, y] is required"))?; drag(s, h, node, part, to).map_err(|e| bad(cmd, e))?; let properties = dynblock::custom_properties(s.doc()?, h).map(|(_, p)| p).unwrap_or_default(); diff --git a/crates/io/tests/data/dynblock_arrays.txt b/crates/io/tests/data/dynblock_arrays.txt new file mode 100644 index 000000000..26de27b00 --- /dev/null +++ b/crates/io/tests/data/dynblock_arrays.txt @@ -0,0 +1,508 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 200 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 5 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Row +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1C +102 {ACAD_XDICTIONARY +360 70 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Fan +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1B +102 {ACAD_XDICTIONARY +360 80 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Grid +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Row +70 2 +10 0 +20 0 +30 0 +3 Row +1 +0 LWPOLYLINE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 0 +1005 30 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 26 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Fan +70 2 +10 0 +20 0 +30 0 +3 Fan +1 +0 CIRCLE +5 40 +330 1C +100 AcDbEntity +8 0 +100 AcDbCircle +10 0 +20 0 +30 0 +40 1 +1001 AcDbBlockRepETag +1070 1 +1071 0 +1005 40 +0 ENDBLK +5 27 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 28 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Grid +70 2 +10 0 +20 0 +30 0 +3 Grid +1 +0 CIRCLE +5 50 +330 1B +100 AcDbEntity +8 0 +100 AcDbCircle +10 0 +20 0 +30 0 +40 1 +1001 AcDbBlockRepETag +1070 1 +1071 0 +1005 50 +0 ENDBLK +5 29 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +330 60 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 62 +91 1 +93 32 +95 4 +360 63 +0 BLOCKLINEARPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKARRAYACTION +5 63 +330 61 +100 AcDbEvalExpr +90 4 +98 33 +99 232 +100 AcDbBlockElement +300 Array +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 30 +1010 4 +1020 3 +1030 0 +100 AcDbBlockArrayAction +92 1 +93 1 +94 1 +95 1 +301 Base +302 End +303 UpdatedBase +304 UpdatedEnd +140 1 +141 3 +0 DICTIONARY +5 70 +330 1C +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 71 +0 ACAD_EVALUATION_GRAPH +5 71 +330 70 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 72 +91 1 +93 32 +95 4 +360 73 +0 BLOCKPOLARPARAMETER +5 72 +330 71 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Polar +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 3 +1021 4 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockPolarParameter +305 Distance1 +306 +307 Angle1 +308 +140 0 +309 +96 0 +141 0 +142 0 +143 0 +175 0 +410 +97 0 +145 0 +146 0 +147 0 +176 0 +0 BLOCKARRAYACTION +5 73 +330 71 +100 AcDbEvalExpr +90 4 +98 33 +99 232 +100 AcDbBlockElement +300 Array +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 40 +1010 4 +1020 5 +1030 0 +100 AcDbBlockArrayAction +92 1 +93 1 +94 1 +95 1 +301 Base +302 End +303 UpdatedBase +304 UpdatedEnd +140 1 +141 2 +0 DICTIONARY +5 80 +330 1B +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 81 +0 ACAD_EVALUATION_GRAPH +5 81 +330 80 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 82 +91 1 +93 32 +95 6 +360 83 +0 BLOCKXYPARAMETER +5 82 +330 81 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 XY +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 10 +1021 10 +1031 0 +170 4 +91 3 +91 2 +91 4 +91 5 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockXYParameter +305 Y Distance1 +306 X Distance1 +307 +308 +141 0 +140 0 +309 +97 1 +146 0 +147 0 +148 0 +176 0 +410 +96 1 +142 0 +143 0 +144 0 +175 0 +0 BLOCKARRAYACTION +5 83 +330 81 +100 AcDbEvalExpr +90 6 +98 33 +99 232 +100 AcDbBlockElement +300 Array +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 50 +1010 12 +1020 12 +1030 0 +100 AcDbBlockArrayAction +92 1 +93 1 +94 1 +95 1 +301 Base +302 End +303 UpdatedBase +304 UpdatedEnd +140 4 +141 5 +0 ENDSEC +0 EOF diff --git a/crates/io/tests/dynblock_array.rs b/crates/io/tests/dynblock_array.rs new file mode 100644 index 000000000..c93b11419 --- /dev/null +++ b/crates/io/tests/dynblock_array.rs @@ -0,0 +1,205 @@ +//! Array actions of dynamic blocks: a reference repeats the arrayed objects as far as its linear, +//! polar or XY parameter reaches, as AutoCAD does (one copy per whole column along a distance; a +//! whole number of columns by rows across an XY parameter, or just the object when either is +//! short of one), marks the copies as AutoCAD marks them, and keeps the right number of copies +//! through later changes and a save. +//! +//! The fixture is synthetic: block Row (a 2×2 square, Distance1 from the origin to (2, 0), copies +//! every 3), Fan (a circle, Distance1/Angle1 from the origin to (3, 4), copies every 2) and Grid +//! (a circle, X Distance1/Y Distance1 from the origin to (10, 10), columns every 5 and rows every +//! 4, distances at least 0). + +use cadcraft_doc::dynblock::{ActionKind, GripPart, GripShape, ParameterKind, custom_properties, drag_grip, dynamic_block, grips, set_property}; +use cadcraft_doc::geom::{Vec2, Vec3}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// The fixture with a reference to `block` at (100, 100). +fn reference(block: &str) -> (Drawing, Handle) { + let mut d = read_dxf(dxf(&include_str!("data/dynblock_arrays.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: block.into(), + insert: Vec3::new(100.0, 100.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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +fn pairs(v: &[(&str, &str)]) -> Vec<(String, String)> { + v.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect() +} + +/// Where each object of the reference's block is (a circle's centre, a polyline's first vertex). +fn places(d: &Drawing, r: Handle) -> Vec<(f64, f64)> { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + let round = |v: f64| (v * 1000.0).round() / 1000.0; + d.block(&i.block) + .unwrap() + .entities + .iter() + .map(|e| match &e.kind { + EntityKind::Circle(c) => (round(c.center.x), round(c.center.y)), + EntityKind::LwPolyline(p) => (round(p.vertices[0].p.x), round(p.vertices[0].p.y)), + k => panic!("unexpected {k:?}"), + }) + .collect() +} + +/// Whether each object of the reference's block is marked as an array's copy. +fn marked(d: &Drawing, r: Handle) -> Vec { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + let mark = |e: &cadcraft_doc::Entity| e.common.xdata.iter().any(|t| t.code == 1001 && t.value == "AcDbBlockArrayActionTag"); + d.block(&i.block).unwrap().entities.iter().map(|e| mark(e)).collect() +} + +#[test] +fn reads_array_actions_and_polar_and_xy_parameters() { + let (d, _) = reference("Row"); + let m = dynamic_block(&d, "Row").unwrap(); + assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 3.0, row: 1.0 })); + assert_eq!(m.actions[0].connections.len(), 4); + let m = dynamic_block(&d, "Fan").unwrap(); + let ParameterKind::Polar { label, angle_label, .. } = &m.parameters[0].kind else { panic!("a polar parameter") }; + assert_eq!((label.as_str(), angle_label.as_str()), ("Distance1", "Angle1")); + let m = dynamic_block(&d, "Grid").unwrap(); + let ParameterKind::Xy { x_label, y_label, x_values, y_values, .. } = &m.parameters[0].kind else { panic!("an XY parameter") }; + assert_eq!((x_label.as_str(), y_label.as_str()), ("X Distance1", "Y Distance1")); + assert!(x_values.has_minimum() && y_values.has_minimum()); + assert_eq!(m.parameters[0].grips, vec![3, 2, 4, 5], "base, end and the two corner grips"); + assert!(matches!(m.actions[0].kind, ActionKind::Array { column: 5.0, row: 4.0 })); +} + +#[test] +fn polar_and_xy_parameters_show_their_two_properties() { + let (d, r) = reference("Fan"); + assert_eq!(props(&d, r), pairs(&[("Distance1", "5.0000"), ("Angle1", "53")])); + let (d, r) = reference("Grid"); + assert_eq!(props(&d, r), pairs(&[("X Distance1", "10.0000"), ("Y Distance1", "10.0000")])); +} + +#[test] +fn a_distance_repeats_the_objects_once_per_whole_column() { + let (mut d, r) = reference("Row"); + set_property(&mut d, r, "Distance1", "9").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0), (6.0, 0.0)]); + assert_eq!(marked(&d, r), vec![false, true, true], "AutoCAD marks every copy but the first"); + // Short of a whole column: one fewer; short of one: the object alone. + set_property(&mut d, r, "Distance1", "8.9").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (3.0, 0.0)]); + set_property(&mut d, r, "Distance1", "2.5").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0)]); + assert_eq!(marked(&d, r), vec![false]); + set_property(&mut d, r, "Distance1", "12").unwrap(); + assert_eq!(places(&d, r).len(), 4); +} + +#[test] +fn a_polar_parameter_repeats_along_its_angle() { + let (mut d, r) = reference("Fan"); + set_property(&mut d, r, "Distance1", "7").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (1.2, 1.6), (2.4, 3.2)]); + set_property(&mut d, r, "Angle1", "90").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]); + assert_eq!(props(&d, r), pairs(&[("Distance1", "7.0000"), ("Angle1", "90")])); +} + +#[test] +fn an_xy_parameter_repeats_in_columns_and_rows() { + let (mut d, r) = reference("Grid"); + // 10 × 10 with columns every 5 and rows every 4: 2 by 2. + set_property(&mut d, r, "Y Distance1", "10").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (5.0, 0.0), (0.0, 4.0), (5.0, 4.0)]); + set_property(&mut d, r, "Y Distance1", "13").unwrap(); + assert_eq!(places(&d, r).len(), 6, "2 columns by 3 rows, the earlier copies replaced"); + assert_eq!(marked(&d, r), vec![false, true, true, true, true, true]); + // Short of one column: the object alone, however many rows fit. + set_property(&mut d, r, "X Distance1", "4").unwrap(); + assert_eq!(places(&d, r), vec![(0.0, 0.0)]); + // Below the value set's minimum: refused, as AutoCAD refuses it. + assert!(set_property(&mut d, r, "X Distance1", "-10").is_err()); + assert_eq!(props(&d, r), pairs(&[("X Distance1", "4.0000"), ("Y Distance1", "13.0000")])); +} + +#[test] +fn xy_grips_move_the_base_end_and_corners() { + let (mut d, r) = reference("Grid"); + let gs = grips(&d, r); + let summary: Vec<(GripPart, GripShape, (f64, f64))> = gs.iter().map(|g| (g.part, g.shape, (g.at.x, g.at.y))).collect(); + assert_eq!( + summary, + vec![ + (GripPart::Base, GripShape::Point, (100.0, 100.0)), + (GripPart::End, GripShape::Point, (110.0, 110.0)), + (GripPart::BaseXEndY, GripShape::Point, (100.0, 110.0)), + (GripPart::BaseYEndX, GripShape::Point, (110.0, 100.0)), + ] + ); + // The base X and end Y corner, dragged left and up: the base moves left (the circle with + // it, as AutoCAD's arrays follow the base), the end up. + drag_grip(&mut d, r, 1, GripPart::BaseXEndY, Vec2::new(95.0, 112.0)).unwrap(); + assert_eq!(props(&d, r), pairs(&[("X Distance1", "15.0000"), ("Y Distance1", "12.0000")])); + assert_eq!(places(&d, r), vec![(-5.0, 0.0), (0.0, 0.0), (5.0, 0.0), (-5.0, 4.0), (0.0, 4.0), (5.0, 4.0), (-5.0, 8.0), (0.0, 8.0), (5.0, 8.0)]); + // A corner past the base: below the minimum, refused. + assert!(drag_grip(&mut d, r, 1, GripPart::BaseYEndX, Vec2::new(90.0, 100.0)).is_err()); + assert!(drag_grip(&mut d, r, 1, GripPart::At, Vec2::new(90.0, 100.0)).is_err()); +} + +#[test] +fn polar_grips_move_the_end_and_the_base() { + let (mut d, r) = reference("Fan"); + let parts: Vec = grips(&d, r).into_iter().map(|g| g.part).collect(); + assert_eq!(parts, vec![GripPart::Base, GripPart::End]); + drag_grip(&mut d, r, 1, GripPart::End, Vec2::new(100.0, 106.0)).unwrap(); + assert_eq!(props(&d, r), pairs(&[("Distance1", "6.0000"), ("Angle1", "90")])); + assert_eq!(places(&d, r), vec![(0.0, 0.0), (0.0, 2.0), (0.0, 4.0)]); +} + +#[test] +fn copies_and_values_survive_a_save() { + let (mut d, r) = reference("Grid"); + set_property(&mut d, r, "X Distance1", "12").unwrap(); + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&back, r), props(&d, r)); + assert_eq!(places(&back, r), places(&d, r)); + // Changed again after the save: still one set of copies. + let mut back = back; + set_property(&mut back, r, "Y Distance1", "5").unwrap(); + assert_eq!(places(&back, r), vec![(0.0, 0.0), (5.0, 0.0)]); +} + +#[test] +fn hostile_arrays_are_refused_not_built() { + let (mut d, r) = reference("Grid"); + // A billion columns: refused before any copy is made. + assert!(set_property(&mut d, r, "X Distance1", "1e10").is_err()); + assert!(set_property(&mut d, r, "X Distance1", "NaN").is_err()); + assert!(set_property(&mut d, r, "X Distance1", "inf").is_err()); + assert_eq!(places(&d, r), vec![(0.0, 0.0)]); + let (mut d, r) = reference("Row"); + assert!(set_property(&mut d, r, "Distance1", "1e300").is_err()); + let (mut d, r) = reference("Fan"); + assert!(set_property(&mut d, r, "Angle1", "nan").is_err()); + assert!(set_property(&mut d, r, "Distance1", "0").is_err()); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index e8fedd459..053ddfba5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -147,6 +147,7 @@ our output in AutoCAD black-box. | 2026-10-19 | minor | A file's own arrowhead blocks with standard names (AutoCAD's `_Dot`, `_DotSmall`), named only by a dimension style, are kept and saved as they were instead of being replaced by CADCraft's solids; PURGE keeps arrowhead blocks dimension styles name | | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | +| 2026-10-19 | minor | Dynamic blocks: polar and XY parameters (names, value sets, corner grips) and array actions (row and column offsets) read; arrayed copies saved with AutoCAD's `AcDbBlockArrayActionTag`, without which AutoCAD can't change the reference again | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | | 2026-10-13 | minor | Dynamic blocks: rotation and flip parameters and actions read; changed references saved with AutoCAD's value records and history (flip state after the points, flip grip state) | | 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 | diff --git a/docs/gaps.md b/docs/gaps.md index 41c7f9eb3..936a7fd73 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| 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, polar and XY parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -156,6 +156,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | +| 2026-10-19 | minor | F3: dynamic block polar (Distance1, Angle1) and XY (X Distance1, Y Distance1) parameters in Properties and as grips, and their array actions repeat the objects as AutoCAD does; checked against AutoCAD's output | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | From 7cd5ef36dcc5a50b5d20b84ac26bf7b6348514c8 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:34:16 -0600 Subject: [PATCH 031/187] Dynamic block grips: list XY corner parts as a drag takes them blocks.reference.grips listed an XY parameter's corner grips as baseXEndY and baseYEndX (serde's camelCase), but blocks.reference.grip takes basex-endy and basey-endx, so a caller passing a listed grip back was refused. The corners are now listed by the names a drag takes, and the command's params doc names them. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/grips.rs | 20 +++++++++++++++++++- crates/engine/src/cmd/blocks.rs | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/dynblock/grips.rs b/crates/doc/src/dynblock/grips.rs index 32a5ab33f..1ae859851 100644 --- a/crates/doc/src/dynblock/grips.rs +++ b/crates/doc/src/dynblock/grips.rs @@ -28,9 +28,12 @@ pub enum GripPart { End, /// A one-point parameter's point (a position, a visibility or lookup grip). At, - /// An XY parameter's corner at the base's X and the end's Y. + /// An XY parameter's corner at the base's X and the end's Y (listed as `blocks.reference.grip` + /// takes it, as [`GripPart::name`] names it). + #[serde(rename = "basex-endy")] BaseXEndY, /// An XY parameter's corner at the end's X and the base's Y. + #[serde(rename = "basey-endx")] BaseYEndX, } @@ -56,6 +59,21 @@ impl GripPart { } } +#[cfg(test)] +mod tests { + use super::GripPart; + + /// A grip is listed with the part name `blocks.reference.grip` takes back. + #[test] + fn listed_part_names_are_the_names_a_drag_takes() { + for p in [GripPart::Base, GripPart::End, GripPart::At, GripPart::BaseXEndY, GripPart::BaseYEndX] { + let listed = serde_json::to_value(p).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); + assert_eq!(listed, p.name()); + assert_eq!(GripPart::from_name(&listed), Some(p)); + } + } +} + /// How a grip looks and what it does. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 6b15eb6c9..192b5f460 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { .params("{handle (a dynamic block reference), name (a custom property as Properties names it: a visibility state, a lookup, a distance, \"Position1 X\", an angle or a flip state), value (lengths in drawing units, angles in degrees; a flip state by name or 0/1)} → {properties}") .enabled(has_doc), CommandSpec::new("blocks.reference.grips", "Dynamic Block Grips", dyngrip::run_grips) - .params("{handle} → [{node, part: base|end|at, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)") + .params("{handle} → [{node, part: base|end|at|basex-endy|basey-endx, shape: linear|point|list|rotation|flip, at: [x,y], dir: [x,y], property, choices?}] (empty: not a dynamic block reference)") .enabled(has_doc) .noundo(), CommandSpec::new("blocks.reference.grip", "Drag Dynamic Grip", dyngrip::run_grip) From 5721b77933e3c40556fc7d9a50d4f1feb4da9ef3 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:01:17 -0600 Subject: [PATCH 032/187] Docs: the dynamic block data row lists polar, XY and array changes Co-Authored-By: Claude Opus 5.5 --- 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 053ddfba5..ebe4feaa5 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch and move actions), angles (rotate actions) and flip states (flip actions) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); other parameters' actions 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch and move actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array actions, their copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); scale and polar stretch actions, base point and alignment parameters not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block) | | 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 From e6fce40d6ec09b6cc543b6b136422e9a37741d8a Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:38:29 -0600 Subject: [PATCH 033/187] Dynamic blocks: an angle just short of a full turn shows as 0, not 360 Custom angle properties were formatted to AUPREC decimals straight from the value, so 359.7 degrees with no decimals showed as "360". They are now rounded first and wrapped back into 0 to 360. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock/reference.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index e5e7baa42..2a05d1211 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -168,7 +168,11 @@ pub(super) fn angle_from_shown(d: &Drawing, v: f64) -> f64 { fn angle_text(d: &Drawing, a: f64) -> String { let prec = usize::try_from(d.header.i64("AUPREC", 0).clamp(0, 8)).unwrap_or(0); - format!("{:.prec$}", angle_shown(d, a).to_degrees()) + // Rounded to the shown decimals first: an angle just short of a full turn shows as 0, not 360. + let step = 10f64.powi(i32::try_from(prec).unwrap_or(0)); + let shown = (angle_shown(d, a).to_degrees() * step).round() / step; + let shown = if shown >= 360.0 { shown - 360.0 } else { shown }; + format!("{:.prec$}", shown + 0.0) } /// A number as the drawing shows lengths (LUPREC decimals). @@ -355,3 +359,20 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool { } any } + +#[cfg(test)] +mod tests { + use super::angle_text; + use crate::Drawing; + + #[test] + fn an_angle_just_short_of_a_full_turn_shows_as_zero() { + let mut d = Drawing::new_imperial(); + d.header.set_i64("AUPREC", 0); + assert_eq!(angle_text(&d, 359.7f64.to_radians()), "0"); + assert_eq!(angle_text(&d, 359.4f64.to_radians()), "359"); + d.header.set_i64("AUPREC", 2); + assert_eq!(angle_text(&d, 359.996f64.to_radians()), "0.00"); + assert_eq!(angle_text(&d, 90f64.to_radians()), "90.00"); + } +} From 201b5688a434cfa91ff517f7a30312518e07703b Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:44:16 -0600 Subject: [PATCH 034/187] Tests: the array and rotate/flip tests join the io and engine test binaries Upstream (#1989) builds each crate's tests as one binary, tests/it/main.rs; these files moved with their fixture paths. Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/{ => it}/rotation_grip_input.rs | 2 +- crates/io/tests/{ => it}/dynblock_array.rs | 2 +- crates/io/tests/{ => it}/dynblock_rotate_flip.rs | 10 +++++----- crates/io/tests/it/main.rs | 2 ++ 5 files changed, 10 insertions(+), 7 deletions(-) rename crates/engine/tests/{ => it}/rotation_grip_input.rs (95%) rename crates/io/tests/{ => it}/dynblock_array.rs (98%) rename crates/io/tests/{ => it}/dynblock_rotate_flip.rs (97%) diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ed88a2316..94b707d75 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -110,6 +110,7 @@ mod refedit; mod region; mod rename_cmdline; mod rotate_reference; +mod rotation_grip_input; mod select_keywords; mod select_similar; mod select_underscore_keywords; diff --git a/crates/engine/tests/rotation_grip_input.rs b/crates/engine/tests/it/rotation_grip_input.rs similarity index 95% rename from crates/engine/tests/rotation_grip_input.rs rename to crates/engine/tests/it/rotation_grip_input.rs index 6a713c535..ed2d49f47 100644 --- a/crates/engine/tests/rotation_grip_input.rs +++ b/crates/engine/tests/it/rotation_grip_input.rs @@ -21,7 +21,7 @@ fn dxf(src: &str) -> String { /// A session with Symbol and a reference to it at (100, 100). fn session() -> (Session, Handle) { - let src = include_str!("../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n"); + let src = include_str!("../../../io/tests/data/dynblock_symbol.txt").replace("\r\n", "\n"); let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap(); let mut s = Session::empty(); s.open_drawing(d, "symbol", None); diff --git a/crates/io/tests/dynblock_array.rs b/crates/io/tests/it/dynblock_array.rs similarity index 98% rename from crates/io/tests/dynblock_array.rs rename to crates/io/tests/it/dynblock_array.rs index c93b11419..0bcba7c64 100644 --- a/crates/io/tests/dynblock_array.rs +++ b/crates/io/tests/it/dynblock_array.rs @@ -27,7 +27,7 @@ fn dxf(src: &str) -> String { /// The fixture with a reference to `block` at (100, 100). fn reference(block: &str) -> (Drawing, Handle) { - let mut d = read_dxf(dxf(&include_str!("data/dynblock_arrays.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); + let mut d = read_dxf(dxf(&include_str!("../data/dynblock_arrays.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); let ins = cadcraft_doc::Insert { block: block.into(), insert: Vec3::new(100.0, 100.0, 0.0), diff --git a/crates/io/tests/dynblock_rotate_flip.rs b/crates/io/tests/it/dynblock_rotate_flip.rs similarity index 97% rename from crates/io/tests/dynblock_rotate_flip.rs rename to crates/io/tests/it/dynblock_rotate_flip.rs index 1815283fc..cceef1739 100644 --- a/crates/io/tests/dynblock_rotate_flip.rs +++ b/crates/io/tests/it/dynblock_rotate_flip.rs @@ -27,7 +27,7 @@ fn dxf(src: &str) -> String { /// Symbol and a reference to it at (100, 100) with its attribute. fn symbol() -> (Drawing, Handle) { - symbol_from(&include_str!("data/dynblock_symbol.txt").replace("\r\n", "\n")) + symbol_from(&include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n")) } /// As [`symbol`], from the fixture's text `src` (changed by a test). @@ -153,7 +153,7 @@ fn a_rotation_grip_off_the_radius_stays_where_its_grip_object_is() { // The grip object a quarter turn round from the radius' end (as AutoCAD saves blocks whose // grip was moved there): the circle is drawn there and turns with the angle, and dragging // it turns the block by the cursor's turn, not to the cursor's direction. - let src = include_str!("data/dynblock_symbol.txt") + let src = include_str!("../data/dynblock_symbol.txt") .replace("\r\n", "\n") .replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n"); let (mut d, r) = symbol_from(&src); @@ -188,7 +188,7 @@ fn an_angle_shows_and_is_typed_as_the_drawing_measures_angles() { fn an_angle_by_increments_marks_its_stops_round_the_circle() { // Angle1 by 90° from 0 to a full turn: its grip stops at four points round the base, the // full turn being no turn; the way it travels there is round the circle. - let src = include_str!("data/dynblock_symbol.txt") + let src = include_str!("../data/dynblock_symbol.txt") .replace("\r\n", "\n") .replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n"); let (d, r) = symbol_from(&src); @@ -211,7 +211,7 @@ fn an_angle_by_increments_marks_its_stops_round_the_circle() { fn an_angle_s_stops_follow_a_grip_off_the_radius() { // The grip object a quarter turn round and 90° increments: each stop is where the grip is // at that angle, the first (0) where it is now. - let src = include_str!("data/dynblock_symbol.txt") + let src = include_str!("../data/dynblock_symbol.txt") .replace("\r\n", "\n") .replace("96 3\n141 0\n142 6.283185307179586\n143 0\n", "96 7\n141 0\n142 6.283185307179586\n143 1.5707963267948966\n") .replace("100 AcDbBlockGrip\n91 0\n92 0\n1010 2\n1020 0\n", "100 AcDbBlockGrip\n91 0\n92 0\n1010 0\n1020 2\n"); @@ -270,7 +270,7 @@ fn a_value_record_takes_its_shape_from_its_parameter() { fn a_flip_selection_that_repeats_its_objects_mirrors_them_once() { // The flip action's selection lists the line, the circle and Position1 twice: each is mirrored // once, as with the selection listing them once (twice would mirror them back). - let src = include_str!("data/dynblock_symbol.txt").replace("\r\n", "\n"); + let src = include_str!("../data/dynblock_symbol.txt").replace("\r\n", "\n"); let once = "71 3\n330 31\n330 32\n330 68\n1010 -6"; assert_eq!(src.matches(once).count(), 1); let (mut twice, r) = symbol_from(&src.replace(once, "71 6\n330 31\n330 32\n330 68\n330 31\n330 32\n330 68\n1010 -6")); diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 51e7f1965..d6e3d290c 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -22,7 +22,9 @@ mod dwg_layout_owner; mod dwg_roundtrip_losses; mod dwt_template; mod dxf_versions; +mod dynblock_array; mod dynblock_read; +mod dynblock_rotate_flip; mod entity_props_roundtrip; mod followups_626; mod groups_roundtrip; From b471e5974af6192cf6f844ef3f8d2713e36984b4 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 19 Oct 2026 21:59:50 -0600 Subject: [PATCH 035/187] Dynamic blocks: scale actions A scale action scales its objects about its base point by how much the distance it follows grew (an XY parameter's horizontal and vertical distances each on their own axis), as AutoCAD does, carrying the parameters in its selection. Factors that would scale to nothing or overflow are refused. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 19 +- crates/doc/src/dynblock/apply.rs | 111 ++++- crates/io/tests/data/dynblock_scale.txt | 584 ++++++++++++++++++++++++ crates/io/tests/dynblock_scale.rs | 145 ++++++ 4 files changed, 836 insertions(+), 23 deletions(-) create mode 100644 crates/io/tests/data/dynblock_scale.txt create mode 100644 crates/io/tests/dynblock_scale.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 8a70ce090..c20753bbb 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -250,7 +250,13 @@ pub enum ActionKind { multiplier: f64, angle_offset: f64, }, - Scale, + /// Scales the objects about its base point by how much the distances it follows grew: a + /// distance's (linear or polar parameter) for both axes, or an XY parameter's horizontal and + /// vertical distances for each axis on its own. Its connections name what each reads ("Scale", + /// "XScale", "YScale"). + Scale { + base: ActionBase, + }, /// Turns the objects about its base point by the change of a rotation parameter's angle. Rotate { base: ActionBase, @@ -573,7 +579,16 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[ let (multiplier, angle_offset) = (c.real(140), c.real(141)); (two_connections(tags), ActionKind::Move { multiplier, angle_offset }) } - "BLOCKSCALEACTION" => (Vec::new(), ActionKind::Scale), + // The base point's two connections (as a rotate action's), then the scale's three: the + // parameters (94-96) and what each reads (303-305, "Scale", "XScale", "YScale"). + "BLOCKSCALEACTION" => { + let with_base = section(secs, "AcDbBlockActionWithBasePt"); + let mut connections = two_connections(with_base); + let tags = section(secs, "AcDbBlockScaleAction"); + let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string(); + connections.extend((0..3).map(|i| (first(94 + i).trim().parse().unwrap_or(0), first(303 + i)))); + (connections, ActionKind::Scale { base: action_base(with_base) }) + } "BLOCKROTATEACTION" => { let mut connections = two_connections(section(secs, "AcDbBlockActionWithBasePt")); let mut c = Cursor::new(section(secs, "AcDbBlockRotationAction")); diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 4fac458fa..c23a4ccf2 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -8,9 +8,9 @@ //! `AcDbBlockRepresentation` data holds its values (created when it had none) and its history //! says what was done to it (AutoCAD replays the history when the dynamic block is redefined). //! -//! What can change so far: a visibility state, a lookup value, a distance and a position, with -//! the stretch and move actions they drive and the lookups that follow. The other parameters' -//! actions come later. +//! What can change: a visibility state, a lookup value, a distance (linear, polar or XY), an angle, +//! a position and a flip state, with the stretch, move, rotate, flip, scale and array actions they +//! drive and the lookups that follow. use std::collections::{BTreeMap, HashMap, HashSet}; @@ -734,14 +734,15 @@ impl ActionRun<'_> { } /// Action `a`, when one of its connections follows a parameter the change sets. - fn action(&mut self, a: &super::Action) { + fn action(&mut self, a: &super::Action) -> Result<(), String> { if !a.connections.iter().any(|(n, _)| self.set.contains_key(n)) { - return; + return Ok(()); } - match turn_or_mirror(self.m, self.values, self.set, a) { - Some(t) => self.turn_or_mirror(a, t), + match transform_of(self.m, self.values, self.set, a)? { + Some(t) => self.transform(a, t), None => self.stretch(a), } + Ok(()) } /// Arrays, made again from the first copy of each arrayed object for the parameter's value now @@ -772,10 +773,10 @@ impl ActionRun<'_> { Ok(arrays) } - /// A rotate or flip action turns or mirrors its objects, and carries the parameters in its - /// selection the same way. A handle the selection repeats is handled once (twice would turn it - /// twice, or mirror it back). - fn turn_or_mirror(&mut self, a: &super::Action, t: Mat3) { + /// A rotate, flip or scale action turns, mirrors or scales its objects, and carries the + /// parameters in its selection the same way. A handle the selection repeats is handled once + /// (twice would turn or scale it twice, or mirror it back). + fn transform(&mut self, a: &super::Action, t: Mat3) { let mut handled: HashSet = HashSet::new(); for h in &a.selection { if !handled.insert(*h) { @@ -918,7 +919,7 @@ fn apply( moves: HashMap::new(), }; for a in &m.actions { - run.action(a); + run.action(a)?; } let arrays = run.arrays()?; let earlier = earlier_copies(&src, &src_tag, &arrays); @@ -1522,25 +1523,93 @@ fn set_state(tags: &mut Vec, on: bool) { } } -/// The turn or mirror action `a` makes with the changes `set`, if it is one and they change it: -/// a rotate action turns about its base point by the change of its rotation parameter's angle; -/// a flip action mirrors across its flip parameter's reflection line when the state changes. -fn turn_or_mirror(m: &DynamicBlock, values: &BTreeMap, set: &BTreeMap, a: &super::Action) -> Option { - match &a.kind { +/// The transform action `a` makes with the changes `set`, if it is one and they change it: a +/// rotate action turns about its base point by the change of its rotation parameter's angle; a flip +/// action mirrors across its flip parameter's reflection line when the state changes; a scale +/// action scales about its base point by how much its distances grew. +fn transform_of(m: &DynamicBlock, values: &BTreeMap, set: &BTreeMap, a: &super::Action) -> Result, String> { + Ok(match &a.kind { ActionKind::Rotate { base } => { - let (node, _) = a.connections.iter().find(|(_, c)| c.eq_ignore_ascii_case("AngleDelta"))?; - let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return None }; + let Some((node, _)) = a.connections.iter().find(|(_, c)| c.eq_ignore_ascii_case("AngleDelta")) else { return Ok(None) }; + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; let turn = (*ne - *nb).xy().angle() - (oe - ob).xy().angle(); let pivot = if base.dependent { *nb + base.offset } else { base.at }; (turn.abs() > 1e-12 && turn.is_finite()).then(|| Mat3::rotate_about(pivot.xy(), turn)) } ActionKind::Flip => { - let (node, _) = a.connections.first()?; - let (Some(Val::Flip(b, e, now)), Some(Val::Flip(_, _, was))) = (set.get(node), current(m, values, *node)) else { return None }; + let Some((node, _)) = a.connections.first() else { return Ok(None) }; + let (Some(Val::Flip(b, e, now)), Some(Val::Flip(_, _, was))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; (now != &was && (*e - *b).len() > 1e-12).then(|| Mat3::mirror(b.xy(), e.xy())) } + ActionKind::Scale { base } => scale_of(m, values, set, a, base)?, _ => None, + }) +} + +/// The scale factors one change of a scale action may make: past them the objects would vanish +/// or their sizes overflow. +const MIN_SCALE: f64 = 1e-9; +const MAX_SCALE: f64 = 1e9; + +/// A scale action's transform for the changes `set`: each axis scales by the ratio of the new +/// distance it reads to the old one (a linear or polar parameter's distance; an XY parameter's +/// horizontal distance for "XScale", vertical for "YScale", both for "Scale"), about the base point, +/// which follows the parameter's base point when the action says so. +fn scale_of( + m: &DynamicBlock, + values: &BTreeMap, + set: &BTreeMap, + a: &super::Action, + base: &super::ActionBase, +) -> Result, String> { + // The ratio connection `name` reads, when its parameter changed; `None` when it didn't. + let ratio = |name: &str| -> Result, String> { + let Some((node, _)) = a.connections.iter().find(|(n, c)| *n != 0 && c.eq_ignore_ascii_case(name)) else { return Ok(None) }; + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; + let Some(p) = m.parameters.iter().find(|p| p.node == *node) else { return Ok(None) }; + let (now, was) = ((*ne - *nb).xy(), (oe - ob).xy()); + let r = |n: f64, w: f64| -> Result { + let r = n.abs() / w.abs(); + if w.abs() < 1e-12 || !r.is_finite() { + // From nothing no ratio is known: AutoCAD can't scale back up from zero either. + return Err(format!("{} can't scale objects from a distance of 0.", a.name)); + } + Ok(r) + }; + Ok(Some(match (&p.kind, name.to_ascii_lowercase().as_str()) { + (ParameterKind::Xy { .. }, "xscale") => (r(now.x, was.x)?, 1.0), + (ParameterKind::Xy { .. }, "yscale") => (1.0, r(now.y, was.y)?), + (ParameterKind::Xy { .. }, _) => (r(now.x, was.x)?, r(now.y, was.y)?), + _ => { + let s = r(now.len(), was.len())?; + (s, s) + } + })) + }; + // Independent axes when the X and Y connections read different values of an XY parameter; + // else the one factor. + let (x, y) = (ratio("XScale")?, ratio("YScale")?); + let (sx, sy) = match (x, y, ratio("Scale")?) { + (Some((sx, _)), Some((_, sy)), _) if x != y => (sx, sy), + (_, _, Some(s)) => s, + (Some(s), _, _) | (None, Some(s), _) => s, + (None, None, None) => return Ok(None), + }; + if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { + return Ok(None); } + if !(sx >= MIN_SCALE && sy >= MIN_SCALE) { + return Err(format!("{} would scale objects to nothing.", a.name)); + } + if !(sx <= MAX_SCALE && sy <= MAX_SCALE) { + return Err(format!("{} would scale objects more than {MAX_SCALE} times.", a.name)); + } + let pivot = match a.connections.first().and_then(|(n, _)| set.get(n).cloned().or_else(|| current(m, values, *n))) { + Some(Val::Points(b, _)) if base.dependent => b + base.offset, + _ => base.at, + }; + let p = pivot.xy(); + Ok(Some(Mat3::translate(p * -1.0).then(Mat3::scale(sx, sy)).then(Mat3::translate(p)))) } /// One change to a copied object: a move (of the listed vertices, else all of it) or a turn or diff --git a/crates/io/tests/data/dynblock_scale.txt b/crates/io/tests/data/dynblock_scale.txt new file mode 100644 index 000000000..85039fc6e --- /dev/null +++ b/crates/io/tests/data/dynblock_scale.txt @@ -0,0 +1,584 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 200 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 5 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Grow +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1C +102 {ACAD_XDICTIONARY +360 70 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Pinned +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1B +102 {ACAD_XDICTIONARY +360 80 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Sheet +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Grow +70 2 +10 0 +20 0 +30 0 +3 Grow +1 +0 LWPOLYLINE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 30 +0 CIRCLE +5 31 +330 1D +100 AcDbEntity +8 0 +100 AcDbCircle +10 1 +20 1 +30 0 +40 0.5 +1001 AcDbBlockRepETag +1070 1 +1071 2 +1005 31 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 26 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Pinned +70 2 +10 0 +20 0 +30 0 +3 Pinned +1 +0 LWPOLYLINE +5 40 +330 1C +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 40 +0 ENDBLK +5 27 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 28 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Sheet +70 2 +10 0 +20 0 +30 0 +3 Sheet +1 +0 LWPOLYLINE +5 50 +330 1B +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 2 +20 0 +10 2 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 50 +0 ENDBLK +5 29 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +330 60 +100 AcDbEvalGraph +96 3 +97 3 +91 0 +93 32 +95 1 +360 62 +91 1 +93 32 +95 2 +360 63 +91 2 +93 32 +95 3 +360 64 +0 BLOCKLINEARPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 1 +141 0 +142 0 +143 0 +175 0 +0 BLOCKPOINTPARAMETER +5 63 +330 61 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 2 +1020 2 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 2 +1021 2 +1031 0 +0 BLOCKSCALEACTION +5 64 +330 61 +100 AcDbEvalExpr +90 3 +98 33 +99 232 +100 AcDbBlockElement +300 Scale +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 3 +330 30 +330 31 +330 63 +1010 4 +1020 3 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockScaleAction +94 1 +95 1 +96 1 +303 Scale +304 XScale +305 YScale +0 DICTIONARY +5 70 +330 1C +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 71 +0 ACAD_EVALUATION_GRAPH +5 71 +330 70 +100 AcDbEvalGraph +96 2 +97 2 +91 0 +93 32 +95 1 +360 72 +91 1 +93 32 +95 2 +360 73 +0 BLOCKLINEARPARAMETER +5 72 +330 71 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKSCALEACTION +5 73 +330 71 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Scale +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 40 +1010 4 +1020 3 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 0 +1012 2 +1022 2 +1032 0 +100 AcDbBlockScaleAction +94 1 +95 1 +96 1 +303 Scale +304 XScale +305 YScale +0 DICTIONARY +5 80 +330 1B +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 81 +0 ACAD_EVALUATION_GRAPH +5 81 +330 80 +100 AcDbEvalGraph +96 2 +97 2 +91 0 +93 32 +95 1 +360 82 +91 1 +93 32 +95 2 +360 83 +0 BLOCKXYPARAMETER +5 82 +330 81 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 XY +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 2 +1021 2 +1031 0 +170 4 +91 3 +91 2 +91 4 +91 5 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockXYParameter +305 Y Distance1 +306 X Distance1 +307 +308 +141 0 +140 0 +309 +97 0 +146 0 +147 0 +148 0 +176 0 +410 +96 0 +142 0 +143 0 +144 0 +175 0 +0 BLOCKSCALEACTION +5 83 +330 81 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Scale +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 50 +1010 4 +1020 3 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockScaleAction +94 0 +95 1 +96 1 +303 Scale +304 XScale +305 YScale +0 ENDSEC +0 EOF diff --git a/crates/io/tests/dynblock_scale.rs b/crates/io/tests/dynblock_scale.rs new file mode 100644 index 000000000..dad79813f --- /dev/null +++ b/crates/io/tests/dynblock_scale.rs @@ -0,0 +1,145 @@ +//! Scale actions of dynamic blocks: a reference scales the action's objects about its base point +//! by how much the distance it follows grew, as AutoCAD does (a 2×2 square scaled by a distance +//! going from 2 to 4 is 4×4), carries the parameters in its selection with them, and keeps the +//! result through a save. +//! +//! The fixture is synthetic: block Grow (a 2×2 square and a circle at (1, 1), Distance1 from the +//! origin to (2, 0), scaled about the distance's base; Position1 at (2, 2) is in the selection), +//! Pinned (the square, scaled about the fixed point (2, 2)) and Sheet (the square, scaled on each +//! axis by X Distance1 and Y Distance1, from the origin to (2, 2)). + +use cadcraft_doc::dynblock::{ActionKind, custom_properties, dynamic_block, set_property}; +use cadcraft_doc::geom::Vec3; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +/// The fixture with a reference to `block` at (100, 100). +fn reference(block: &str) -> (Drawing, Handle) { + let mut d = read_dxf(dxf(&include_str!("data/dynblock_scale.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: block.into(), + insert: Vec3::new(100.0, 100.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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +/// Each object of the reference's block, in block coordinates: a polyline's corners (lowest and +/// highest), a circle's centre and radius. +fn shapes(d: &Drawing, r: Handle) -> Vec<[f64; 4]> { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + let round = |v: f64| (v * 1000.0).round() / 1000.0 + 0.0; + d.block(&i.block) + .unwrap() + .entities + .iter() + .map(|e| match &e.kind { + EntityKind::LwPolyline(p) => { + let xs = p.vertices.iter().map(|v| v.p.x); + let ys = p.vertices.iter().map(|v| v.p.y); + [ + round(xs.clone().fold(f64::MAX, f64::min)), + round(ys.clone().fold(f64::MAX, f64::min)), + round(xs.fold(f64::MIN, f64::max)), + round(ys.fold(f64::MIN, f64::max)), + ] + } + EntityKind::Circle(c) => [round(c.center.x), round(c.center.y), round(c.radius), 0.0], + k => panic!("unexpected {k:?}"), + }) + .collect() +} + +#[test] +fn reads_the_scale_actions_base_and_connections() { + let (d, _) = reference("Grow"); + let m = dynamic_block(&d, "Grow").unwrap(); + let a = m.actions.iter().find(|a| matches!(a.kind, ActionKind::Scale { .. })).unwrap(); + let ActionKind::Scale { base } = a.kind else { unreachable!() }; + assert!(base.dependent); + let names: Vec<&str> = a.connections.iter().map(|(_, c)| c.as_str()).collect(); + assert_eq!(names, ["UpdatedBaseX", "UpdatedBaseY", "Scale", "XScale", "YScale"]); + let m = dynamic_block(&d, "Pinned").unwrap(); + let ActionKind::Scale { base } = m.actions[0].kind else { panic!("a scale action") }; + assert!(!base.dependent); + assert_eq!((base.at.x, base.at.y), (2.0, 2.0)); +} + +#[test] +fn a_distance_scales_its_objects_about_the_base() { + let (mut d, r) = reference("Grow"); + set_property(&mut d, r, "Distance1", "4").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 4.0], [2.0, 2.0, 1.0, 0.0]]); + // The point parameter in the selection is scaled with them. + let p = props(&d, r); + assert!(p.contains(&("Position1 X".into(), "4.0000".into())), "{p:?}"); + assert!(p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}"); + // From there, by the ratio of the new distance to the one it has now. + set_property(&mut d, r, "Distance1", "1").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.0, 1.0], [0.5, 0.5, 0.25, 0.0]]); +} + +#[test] +fn a_fixed_base_point_stays() { + let (mut d, r) = reference("Pinned"); + set_property(&mut d, r, "Distance1", "4").unwrap(); + assert_eq!(shapes(&d, r), vec![[-2.0, -2.0, 2.0, 2.0]]); +} + +#[test] +fn an_xy_parameter_scales_each_axis_on_its_own() { + let (mut d, r) = reference("Sheet"); + set_property(&mut d, r, "X Distance1", "4").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 2.0]]); + set_property(&mut d, r, "Y Distance1", "1").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 1.0]]); +} + +#[test] +fn scaled_objects_and_values_survive_a_save() { + let (mut d, r) = reference("Grow"); + set_property(&mut d, r, "Distance1", "3").unwrap(); + let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&back, r), props(&d, r)); + assert_eq!(shapes(&back, r), shapes(&d, r)); + set_property(&mut back, r, "Distance1", "6").unwrap(); + assert_eq!(shapes(&back, r), vec![[0.0, 0.0, 6.0, 6.0], [3.0, 3.0, 1.5, 0.0]]); +} + +#[test] +fn hostile_scales_are_refused_and_change_nothing() { + let (mut d, r) = reference("Grow"); + for v in ["0", "-3", "NaN", "inf", "1e-300", "1e200"] { + assert!(set_property(&mut d, r, "Distance1", v).is_err(), "{v}"); + } + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.0, 2.0], [1.0, 1.0, 0.5, 0.0]]); + // A large factor within the limit is a large block. + set_property(&mut d, r, "Distance1", "2e6").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2e6, 2e6], [1e6, 1e6, 5e5, 0.0]]); + // An XY distance of 0 would scale the objects to nothing. + let (mut d, r) = reference("Sheet"); + assert!(set_property(&mut d, r, "X Distance1", "0").is_err()); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.0, 2.0]]); +} From fc8caca7b39a4e72d9e019519f6cfb0f4991dd6c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:01:20 -0600 Subject: [PATCH 036/187] Dynamic blocks: polar stretch actions; scale by an XY parameter's diagonal A polar stretch action turns its objects about the polar parameter's base by the change of its angle and moves the vertices in its frame (and the objects it doesn't stretch) with the end, as AutoCAD does; its rotate-only objects just turn. Parameters in its selection are carried. A scale action driven by an XY parameter scales uniformly by the parameter's diagonal, as AutoCAD does (the X-only and Y-only choices live only in DWG data that isn't read). Stretch and move actions on polar and XY parameters were checked against AutoCAD: they already match. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 85 +++++-- crates/doc/src/dynblock/apply.rs | 147 +++++++---- ...ock_scale.txt => dynblock_scale_polar.txt} | 233 +++++++++++++++++- ...block_scale.rs => dynblock_scale_polar.rs} | 98 ++++++-- docs/file-format-parity.md | 3 +- docs/gaps.md | 5 +- 6 files changed, 485 insertions(+), 86 deletions(-) rename crates/io/tests/data/{dynblock_scale.txt => dynblock_scale_polar.txt} (72%) rename crates/io/tests/{dynblock_scale.rs => dynblock_scale_polar.rs} (52%) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index c20753bbb..eacf590b6 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -241,40 +241,37 @@ pub enum ActionKind { angle_offset: f64, }, /// A table: each row sets the listed parameter values together. - Lookup { - columns: Vec, - rows: Vec>, - }, + Lookup { columns: Vec, rows: Vec> }, /// Moves the objects by the change of the parameter values it follows. - Move { - multiplier: f64, - angle_offset: f64, - }, + Move { multiplier: f64, angle_offset: f64 }, /// Scales the objects about its base point by how much the distances it follows grew: a /// distance's (linear or polar parameter) for both axes, or an XY parameter's horizontal and /// vertical distances for each axis on its own. Its connections name what each reads ("Scale", /// "XScale", "YScale"). - Scale { - base: ActionBase, - }, + Scale { base: ActionBase }, /// Turns the objects about its base point by the change of a rotation parameter's angle. - Rotate { - base: ActionBase, - }, + Rotate { base: ActionBase }, /// Mirrors the objects across a flip parameter's reflection line when its state changes. Flip, /// Repeats the objects as far as the parameter it follows reaches: along a distance (linear /// or polar parameter) every `column` units, or in a grid of columns and rows across an XY /// parameter's distances. The objects follow the parameter's base point. - Array { - column: f64, - row: f64, + Array { column: f64, row: f64 }, + /// Follows a polar parameter: turns its objects about the parameter's base point by the change + /// of its angle, and moves the vertices inside `frame` of the objects listed (all of an object + /// not listed) along the parameter's new direction by the change of its distance. The + /// `rotate_only` objects (outside the selection) only turn. + PolarStretch { + frame: Vec, + #[serde(serialize_with = "hex_vertices")] + vertices: Vec<(Handle, Vec)>, + #[serde(serialize_with = "hexes")] + rotate_only: Vec, + multiplier: f64, + angle_offset: f64, }, - PolarStretch, /// An action type not modelled yet. - Other { - dxf_type: String, - }, + Other { dxf_type: String }, } /// Where an action that turns or scales its objects has its base point. @@ -612,7 +609,7 @@ fn action(handle: Handle, node: i32, name: String, kind: &str, secs: &[(&str, &[ let (row, column) = (c.real(140), c.real(141)); (connections, ActionKind::Array { column, row }) } - "BLOCKPOLARSTRETCHACTION" => (Vec::new(), ActionKind::PolarStretch), + "BLOCKPOLARSTRETCHACTION" => polar_stretch(section(secs, "AcDbBlockPolarStretchAction")), other => (Vec::new(), ActionKind::Other { dxf_type: other.to_string() }), }; Action { node, handle, name, at, selection, connections, kind } @@ -663,6 +660,42 @@ fn stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) { (connections, ActionKind::Stretch { frame, vertices, multiplier, angle_offset }) } +/// A polar stretch action: its six connections (92-97 with 301-306), the frame (73 count, +/// 1011/1021 points), the objects it only turns (72 count, 331 each), the objects whose vertices it +/// moves (74 count; each a 332 handle, a 75 count and 76 vertex indices), more vertex lists (78 +/// count; each a 98 code, a 79 count and 76 indices), then the distance multiplier (141) and angle +/// offset (140). +fn polar_stretch(tags: &[RawTag]) -> (Vec<(i32, String)>, ActionKind) { + let first = |code: i32| Cursor::new(tags).next(code).unwrap_or_default().to_string(); + let connections = (0..6).map(|i| (first(92 + i).trim().parse().unwrap_or(0), first(301 + i))).collect(); + let mut c = Cursor::new(tags); + let n = c.count(73); + let frame = (0..n) + .map(|_| { + let x = c.real(1011); + Vec2::new(x, c.real(1021)) + }) + .collect(); + let n = c.count(72); + let rotate_only = c.handles(331, n); + let objects = c.count(74); + let vertices = (0..objects) + .filter_map(|_| { + let h = c.handle(332)?; + let n = c.count(75); + Some((h, (0..n).map(|_| c.int(76)).collect())) + }) + .collect(); + for _ in 0..c.count(78) { + c.next(98); + for _ in 0..c.count(79) { + c.next(76); + } + } + let (multiplier, angle_offset) = (c.real(141), c.real(140)); + (connections, ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset }) +} + /// A lookup table: rows (92) and columns (93), the cells row by row (302, after a 301 header), /// then each column: unmatched name (303 then 305), parameter id (94), lookup flag (282) and the /// parameter value it stands for (304). @@ -710,5 +743,13 @@ mod tests { let (_, ActionKind::Stretch { vertices, .. }) = stretch(&tags) else { panic!("a stretch action") }; let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum(); assert!(ints <= 16 * tags.len() + 1024, "{ints}"); + + let mut tags = vec![tag(74, &n.to_string())]; + tags.extend((0..n).flat_map(|_| [tag(332, "1F"), tag(75, &n.to_string())])); + tags.push(tag(78, &n.to_string())); + tags.extend((0..n).map(|_| tag(79, &n.to_string()))); + let (_, ActionKind::PolarStretch { vertices, .. }) = polar_stretch(&tags) else { panic!("a polar stretch action") }; + let ints: usize = vertices.iter().map(|(_, v)| v.len()).sum(); + assert!(ints <= 16 * tags.len() + 1024, "{ints}"); } } diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index c23a4ccf2..63cda4842 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -738,9 +738,10 @@ impl ActionRun<'_> { if !a.connections.iter().any(|(n, _)| self.set.contains_key(n)) { return Ok(()); } - match transform_of(self.m, self.values, self.set, a)? { - Some(t) => self.transform(a, t), - None => self.stretch(a), + match (transform_of(self.m, self.values, self.set, a)?, &a.kind) { + (Some(t), _) => self.transform(a, t), + (None, ActionKind::PolarStretch { .. }) => self.polar_stretch(a), + (None, _) => self.stretch(a), } Ok(()) } @@ -801,6 +802,44 @@ impl ActionRun<'_> { } } + /// A polar stretch action turns its objects about its parameter's base point and moves the + /// ones in its frame after the turn, and carries the parameters in its selection. The objects it + /// only turns (`rotate_only`) are not also stretched. + fn polar_stretch(&mut self, a: &super::Action) { + let ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, angle_offset } = &a.kind else { return }; + let Some((turn, v)) = polar_stretch(self.m, self.values, self.set, a, *multiplier, *angle_offset) else { return }; + // As for stretch actions: vertex lists indexed once, a repeated handle handled once. + let vtx_by_handle: HashMap> = vertices.iter().rev().map(|(vh, i)| (*vh, i)).collect(); + let mut handled: HashSet = HashSet::new(); + for h in &a.selection { + if !handled.insert(*h) { + continue; + } + if let Some(node) = self.param_of.get(h).copied() { + // Its points turn, and the ones in the frame (where the dynamic block has them) + // follow the distance. + if self.set.contains_key(&node) { + continue; + } + let Some(cur) = self.value_of(node) else { continue }; + let home = current(self.m, &BTreeMap::new(), node); + self.new.insert(node, turned_and_shifted(cur, home, frame, (turn, v))); + continue; + } + let Some(c) = self.copy_of(h) else { continue }; + let idx = vtx_by_handle.get(h).map(|i| (*i).clone()); + let ops = self.moves.entry(c).or_default(); + ops.push(Op::Transform(turn)); + ops.push(Op::Move(idx, v)); + } + // Objects only turned (an object also in the selection is stretched, as AutoCAD does). + for h in rotate_only.iter().filter(|h| !handled.contains(h) && !self.param_of.contains_key(h)).collect::>() { + if let Some(c) = self.copy_of(h) { + self.moves.entry(c).or_default().push(Op::Transform(turn)); + } + } + } + /// A stretch or move action moves its objects (the vertices of a stretch's frame) by the change /// of its two connections, and carries the parameters in its selection. fn stretch(&mut self, a: &super::Action) { @@ -872,6 +911,24 @@ fn earlier_copies(src: &Block, src_tag: &HashMap, arrays: &HashMap< .collect() } +/// A parameter value `cur` turned by `turn`, and carried by `v` where its points are in `frame` +/// (judged where the dynamic block has them, `home`), after a polar stretch. +fn turned_and_shifted(cur: Val, home: Option, frame: &[Vec2], (turn, v): (Mat3, Vec2)) -> Val { + let carry = |p: Vec3, at: Vec3| { + let q = turn.apply(p.xy()).to3(p.z); + if in_frame(frame, at.xy()) { q + v.to3(0.0) } else { q } + }; + match (cur, home) { + (Val::Point(p), Some(Val::Point(h))) => Val::Point(carry(p, h)), + (Val::Point(p), _) => Val::Point(carry(p, p)), + (Val::Points(b, e), Some(Val::Points(hb, he))) => Val::Points(carry(b, hb), carry(e, he)), + (Val::Points(b, e), _) => Val::Points(carry(b, b), carry(e, e)), + (Val::Flip(b, e, f), Some(Val::Flip(hb, he, _))) => Val::Flip(carry(b, hb), carry(e, he), f), + (Val::Flip(b, e, f), _) => Val::Flip(carry(b, b), carry(e, e), f), + (t, _) => t, + } +} + /// Parameter value `cur` carried by `v`: the points in `frame` (empty: all of them), judged where /// the dynamic block has them (`home`), move. fn shifted(cur: Val, home: Option, frame: &[Vec2], v: Vec2) -> Val { @@ -1546,15 +1603,40 @@ fn transform_of(m: &DynamicBlock, values: &BTreeMap, set: &BTreeMap< }) } +/// What polar stretch action `a` does with the changes `set`: the turn about its parameter's base +/// point by the change of its angle, and how far the points in its frame move after it (the end +/// point's move less the turn's, times the multiplier, turned by the angle offset). `None` when its +/// parameter didn't change. +fn polar_stretch( + m: &DynamicBlock, + values: &BTreeMap, + set: &BTreeMap, + a: &super::Action, + multiplier: f64, + angle_offset: f64, +) -> Option<(Mat3, Vec2)> { + let (node, _) = a.connections.iter().find(|(n, _)| set.contains_key(n))?; + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return None }; + let (was, now) = ((oe - ob).xy(), (*ne - *nb).xy()); + // A distance of 0 has no direction: nothing turns. + let delta = if was.len() > 1e-12 && now.len() > 1e-12 { now.angle() - was.angle() } else { 0.0 }; + let turn = Mat3::rotate_about(ob.xy(), delta); + let mult = if multiplier == 0.0 { 1.0 } else { multiplier }; + let v = (ne.xy() - turn.apply(oe.xy())).rotate(angle_offset) * mult; + let still = delta.abs() < 1e-12 && v.len() < 1e-12; + (delta.is_finite() && v.is_finite() && !still).then_some((turn, v)) +} + /// The scale factors one change of a scale action may make: past them the objects would vanish /// or their sizes overflow. const MIN_SCALE: f64 = 1e-9; const MAX_SCALE: f64 = 1e9; -/// A scale action's transform for the changes `set`: each axis scales by the ratio of the new -/// distance it reads to the old one (a linear or polar parameter's distance; an XY parameter's -/// horizontal distance for "XScale", vertical for "YScale", both for "Scale"), about the base point, -/// which follows the parameter's base point when the action says so. +/// A scale action's transform for the changes `set`: it scales uniformly by the ratio of the new +/// distance from its parameter's base to its end to the old one (an XY parameter's diagonal, as +/// AutoCAD scales by it), about the base point, which follows the parameter's base point when the +/// action says so. (AutoCAD can scale by an XY parameter's X or Y distance alone, but keeps that +/// choice only in DWG data that isn't read.) fn scale_of( m: &DynamicBlock, values: &BTreeMap, @@ -1562,54 +1644,31 @@ fn scale_of( a: &super::Action, base: &super::ActionBase, ) -> Result, String> { - // The ratio connection `name` reads, when its parameter changed; `None` when it didn't. - let ratio = |name: &str| -> Result, String> { - let Some((node, _)) = a.connections.iter().find(|(n, c)| *n != 0 && c.eq_ignore_ascii_case(name)) else { return Ok(None) }; - let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; - let Some(p) = m.parameters.iter().find(|p| p.node == *node) else { return Ok(None) }; - let (now, was) = ((*ne - *nb).xy(), (oe - ob).xy()); - let r = |n: f64, w: f64| -> Result { - let r = n.abs() / w.abs(); - if w.abs() < 1e-12 || !r.is_finite() { - // From nothing no ratio is known: AutoCAD can't scale back up from zero either. - return Err(format!("{} can't scale objects from a distance of 0.", a.name)); - } - Ok(r) - }; - Ok(Some(match (&p.kind, name.to_ascii_lowercase().as_str()) { - (ParameterKind::Xy { .. }, "xscale") => (r(now.x, was.x)?, 1.0), - (ParameterKind::Xy { .. }, "yscale") => (1.0, r(now.y, was.y)?), - (ParameterKind::Xy { .. }, _) => (r(now.x, was.x)?, r(now.y, was.y)?), - _ => { - let s = r(now.len(), was.len())?; - (s, s) - } - })) + let names = ["Scale", "XScale", "YScale"]; + let Some((node, _)) = a.connections.iter().find(|(n, c)| set.contains_key(n) && names.iter().any(|x| c.eq_ignore_ascii_case(x))) else { + return Ok(None); }; - // Independent axes when the X and Y connections read different values of an XY parameter; - // else the one factor. - let (x, y) = (ratio("XScale")?, ratio("YScale")?); - let (sx, sy) = match (x, y, ratio("Scale")?) { - (Some((sx, _)), Some((_, sy)), _) if x != y => (sx, sy), - (_, _, Some(s)) => s, - (Some(s), _, _) | (None, Some(s), _) => s, - (None, None, None) => return Ok(None), - }; - if (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12 { + let (Some(Val::Points(nb, ne)), Some(Val::Points(ob, oe))) = (set.get(node), current(m, values, *node)) else { return Ok(None) }; + let (now, was) = ((*ne - *nb).xy().len(), (oe - ob).xy().len()); + if was < 1e-12 { + // From nothing no ratio is known. + return Err(format!("{} can't scale objects from a distance of 0.", a.name)); + } + let s = now / was; + if (s - 1.0).abs() < 1e-12 { return Ok(None); } - if !(sx >= MIN_SCALE && sy >= MIN_SCALE) { + if s.is_nan() || s < MIN_SCALE { return Err(format!("{} would scale objects to nothing.", a.name)); } - if !(sx <= MAX_SCALE && sy <= MAX_SCALE) { + if s > MAX_SCALE { return Err(format!("{} would scale objects more than {MAX_SCALE} times.", a.name)); } let pivot = match a.connections.first().and_then(|(n, _)| set.get(n).cloned().or_else(|| current(m, values, *n))) { Some(Val::Points(b, _)) if base.dependent => b + base.offset, _ => base.at, }; - let p = pivot.xy(); - Ok(Some(Mat3::translate(p * -1.0).then(Mat3::scale(sx, sy)).then(Mat3::translate(p)))) + Ok(Some(Mat3::scale_about(pivot.xy(), s))) } /// One change to a copied object: a move (of the listed vertices, else all of it) or a turn or diff --git a/crates/io/tests/data/dynblock_scale.txt b/crates/io/tests/data/dynblock_scale_polar.txt similarity index 72% rename from crates/io/tests/data/dynblock_scale.txt rename to crates/io/tests/data/dynblock_scale_polar.txt index 85039fc6e..dfaad96ff 100644 --- a/crates/io/tests/data/dynblock_scale.txt +++ b/crates/io/tests/data/dynblock_scale_polar.txt @@ -12,7 +12,7 @@ 5 1 330 0 100 AcDbSymbolTable -70 5 +70 6 0 BLOCK_RECORD 5 1F 330 1 @@ -66,6 +66,19 @@ 70 0 280 1 281 1 +0 BLOCK_RECORD +5 1A +102 {ACAD_XDICTIONARY +360 90 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Tag +340 0 +70 0 +280 1 +281 1 0 ENDTAB 0 ENDSEC 0 SECTION @@ -220,6 +233,69 @@ 100 AcDbEntity 8 0 100 AcDbBlockEnd +0 BLOCK +5 2A +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Tag +70 2 +10 0 +20 0 +30 0 +3 Tag +1 +0 LINE +5 B0 +330 1A +100 AcDbEntity +8 0 +100 AcDbLine +10 1 +20 0 +30 0 +11 4 +21 0 +31 0 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 B0 +0 CIRCLE +5 B1 +330 1A +100 AcDbEntity +8 0 +100 AcDbCircle +10 4 +20 0 +30 0 +40 0.25 +1001 AcDbBlockRepETag +1070 1 +1071 2 +1005 B1 +0 CIRCLE +5 B2 +330 1A +100 AcDbEntity +8 0 +100 AcDbCircle +10 2 +20 2 +30 0 +40 0.5 +1001 AcDbBlockRepETag +1070 1 +1071 3 +1005 B2 +0 ENDBLK +5 2B +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockEnd 0 ENDSEC 0 SECTION 2 ENTITIES @@ -574,11 +650,164 @@ 1022 0 1032 0 100 AcDbBlockScaleAction -94 0 +94 1 95 1 96 1 303 Scale 304 XScale 305 YScale +0 DICTIONARY +5 90 +330 1A +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 91 +0 ACAD_EVALUATION_GRAPH +5 91 +330 90 +100 AcDbEvalGraph +96 3 +97 3 +91 0 +93 32 +95 1 +360 92 +91 1 +93 32 +95 2 +360 93 +91 2 +93 32 +95 3 +360 94 +0 BLOCKPOLARPARAMETER +5 92 +330 91 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Polar +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 4 +1021 0 +1031 0 +170 4 +91 3 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockPolarParameter +305 Distance1 +306 +307 Angle1 +308 +140 0 +309 +96 0 +141 0 +142 0 +143 0 +175 0 +410 +97 0 +145 0 +146 0 +147 0 +176 0 +0 BLOCKPOINTPARAMETER +5 93 +330 91 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 4 +1020 1 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 4 +1021 1 +1031 0 +0 BLOCKPOLARSTRETCHACTION +5 94 +330 91 +100 AcDbEvalExpr +90 3 +98 33 +99 232 +100 AcDbBlockElement +300 Polar Stretch +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 3 +330 B0 +330 B1 +330 93 +1010 5 +1020 -1 +1030 0 +100 AcDbBlockPolarStretchAction +92 1 +301 EndXDelta +93 1 +302 EndYDelta +94 1 +303 Base +95 1 +304 End +96 1 +305 UpdatedBase +97 1 +306 UpdatedEnd +73 2 +1011 3.5 +1021 -0.5 +1011 4.5 +1021 1.5 +72 1 +331 B2 +74 1 +332 B0 +75 1 +76 1 +78 0 +141 1 +140 0 +77 0 0 ENDSEC 0 EOF diff --git a/crates/io/tests/dynblock_scale.rs b/crates/io/tests/dynblock_scale_polar.rs similarity index 52% rename from crates/io/tests/dynblock_scale.rs rename to crates/io/tests/dynblock_scale_polar.rs index dad79813f..5d2be7f8f 100644 --- a/crates/io/tests/dynblock_scale.rs +++ b/crates/io/tests/dynblock_scale_polar.rs @@ -1,12 +1,17 @@ -//! Scale actions of dynamic blocks: a reference scales the action's objects about its base point -//! by how much the distance it follows grew, as AutoCAD does (a 2×2 square scaled by a distance -//! going from 2 to 4 is 4×4), carries the parameters in its selection with them, and keeps the -//! result through a save. +//! Scale and polar stretch actions of dynamic blocks, as AutoCAD applies them: a scale action +//! scales its objects about its base point by how much the distance it follows grew (a 2×2 square +//! scaled by a distance going from 2 to 4 is 4×4); a polar stretch turns its objects about the +//! polar parameter's base by the change of its angle and moves the vertices in its frame (and the +//! objects it doesn't stretch) with the end, while its rotate-only objects just turn. Both carry +//! the parameters in their selection, and the results survive a save. //! //! The fixture is synthetic: block Grow (a 2×2 square and a circle at (1, 1), Distance1 from the //! origin to (2, 0), scaled about the distance's base; Position1 at (2, 2) is in the selection), -//! Pinned (the square, scaled about the fixed point (2, 2)) and Sheet (the square, scaled on each -//! axis by X Distance1 and Y Distance1, from the origin to (2, 2)). +//! Pinned (the square, scaled about the fixed point (2, 2)) and Sheet (the square, scaled by the +//! diagonal of X Distance1 and Y Distance1, from the origin to (2, 2), as AutoCAD scales by an XY +//! parameter); Tag (a line from (1, 0) to (4, 0), a circle at its end and one at (2, 2), a polar +//! Distance1/Angle1 from the origin to (4, 0); the polar stretch's frame holds the line's end and +//! Position1 at (4, 1); the circle at (2, 2) only turns). use cadcraft_doc::dynblock::{ActionKind, custom_properties, dynamic_block, set_property}; use cadcraft_doc::geom::Vec3; @@ -26,7 +31,7 @@ fn dxf(src: &str) -> String { /// The fixture with a reference to `block` at (100, 100). fn reference(block: &str) -> (Drawing, Handle) { - let mut d = read_dxf(dxf(&include_str!("data/dynblock_scale.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); + let mut d = read_dxf(dxf(&include_str!("data/dynblock_scale_polar.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); let ins = cadcraft_doc::Insert { block: block.into(), insert: Vec3::new(100.0, 100.0, 0.0), @@ -47,7 +52,7 @@ fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { } /// Each object of the reference's block, in block coordinates: a polyline's corners (lowest and -/// highest), a circle's centre and radius. +/// highest), a circle's centre and radius, a line's ends. fn shapes(d: &Drawing, r: Handle) -> Vec<[f64; 4]> { let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; let round = |v: f64| (v * 1000.0).round() / 1000.0 + 0.0; @@ -67,6 +72,7 @@ fn shapes(d: &Drawing, r: Handle) -> Vec<[f64; 4]> { ] } EntityKind::Circle(c) => [round(c.center.x), round(c.center.y), round(c.radius), 0.0], + EntityKind::Line(l) => [round(l.a.x), round(l.a.y), round(l.b.x), round(l.b.y)], k => panic!("unexpected {k:?}"), }) .collect() @@ -109,12 +115,16 @@ fn a_fixed_base_point_stays() { } #[test] -fn an_xy_parameter_scales_each_axis_on_its_own() { +fn an_xy_parameter_scales_by_its_diagonal() { let (mut d, r) = reference("Sheet"); + // From (2, 2) to (4, 2): the diagonal grows from √8 to √20. set_property(&mut d, r, "X Distance1", "4").unwrap(); - assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 2.0]]); - set_property(&mut d, r, "Y Distance1", "1").unwrap(); - assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 4.0, 1.0]]); + let s = (20.0f64 / 8.0).sqrt() * 2.0; + let round = |v: f64| (v * 1000.0).round() / 1000.0; + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, round(s), round(s)]]); + // A distance of 0 along one axis still leaves a diagonal: 4 long, twice the square's √8 / 2. + set_property(&mut d, r, "Y Distance1", "0").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.828, 2.828]]); } #[test] @@ -138,8 +148,66 @@ fn hostile_scales_are_refused_and_change_nothing() { // A large factor within the limit is a large block. set_property(&mut d, r, "Distance1", "2e6").unwrap(); assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2e6, 2e6], [1e6, 1e6, 5e5, 0.0]]); - // An XY distance of 0 would scale the objects to nothing. + // Both XY distances 0 would scale the objects to nothing; from there no ratio is known. let (mut d, r) = reference("Sheet"); - assert!(set_property(&mut d, r, "X Distance1", "0").is_err()); - assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 2.0, 2.0]]); + set_property(&mut d, r, "X Distance1", "0").unwrap(); + assert!(set_property(&mut d, r, "Y Distance1", "0").is_err()); + assert_eq!(shapes(&d, r), vec![[0.0, 0.0, 1.414, 1.414]]); +} + +#[test] +fn reads_the_polar_stretch_action() { + let (d, _) = reference("Tag"); + let m = dynamic_block(&d, "Tag").unwrap(); + let ActionKind::PolarStretch { frame, vertices, rotate_only, multiplier, .. } = &m.actions[0].kind else { panic!("a polar stretch") }; + assert_eq!(frame.len(), 2); + assert_eq!(vertices, &vec![(Handle(0xB0), vec![1])]); + assert_eq!(rotate_only, &vec![Handle(0xB2)]); + assert_eq!(*multiplier, 1.0); + assert_eq!(m.actions[0].connections.len(), 6); +} + +#[test] +fn a_polar_distance_stretches_the_frame_along_it() { + let (mut d, r) = reference("Tag"); + set_property(&mut d, r, "Distance1", "6").unwrap(); + // The line's end and the head follow the end; the rotate-only circle stays. + assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 6.0, 0.0], [6.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]); + let p = props(&d, r); + assert!(p.contains(&("Position1 X".into(), "6.0000".into())), "{p:?}"); +} + +#[test] +fn a_polar_angle_turns_everything_about_the_base() { + let (mut d, r) = reference("Tag"); + set_property(&mut d, r, "Angle1", "90").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 4.0], [0.0, 4.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]); + let p = props(&d, r); + assert!(p.contains(&("Position1 X".into(), "-1.0000".into())) && p.contains(&("Position1 Y".into(), "4.0000".into())), "{p:?}"); + // Then a distance along the new direction, and back to the start. + set_property(&mut d, r, "Distance1", "6").unwrap(); + assert_eq!(shapes(&d, r), vec![[0.0, 1.0, 0.0, 6.0], [0.0, 6.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]); + set_property(&mut d, r, "Angle1", "0").unwrap(); + set_property(&mut d, r, "Distance1", "4").unwrap(); + assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]); +} + +#[test] +fn polar_stretched_objects_survive_a_save() { + let (mut d, r) = reference("Tag"); + set_property(&mut d, r, "Angle1", "90").unwrap(); + let mut back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(props(&back, r), props(&d, r)); + assert_eq!(shapes(&back, r), shapes(&d, r)); + set_property(&mut back, r, "Distance1", "2").unwrap(); + assert_eq!(shapes(&back, r), vec![[0.0, 1.0, 0.0, 2.0], [0.0, 2.0, 0.25, 0.0], [-2.0, 2.0, 0.5, 0.0]]); +} + +#[test] +fn hostile_polar_values_are_refused() { + let (mut d, r) = reference("Tag"); + for (n, v) in [("Distance1", "0"), ("Distance1", "NaN"), ("Distance1", "-inf"), ("Angle1", "nan"), ("Angle1", "1e400")] { + assert!(set_property(&mut d, r, n, v).is_err(), "{n} {v}"); + } + assert_eq!(shapes(&d, r), vec![[1.0, 0.0, 4.0, 0.0], [4.0, 0.0, 0.25, 0.0], [2.0, 2.0, 0.5, 0.0]]); } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ebe4feaa5..88908f269 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (attribute value edits refresh exported baselines) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (attribute value edits refresh exported baselines; dynamic block scale and polar stretch actions read) · **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 @@ -147,6 +147,7 @@ our output in AutoCAD black-box. | 2026-10-19 | minor | A file's own arrowhead blocks with standard names (AutoCAD's `_Dot`, `_DotSmall`), named only by a dimension style, are kept and saved as they were instead of being replaced by CADCraft's solids; PURGE keeps arrowhead blocks dimension styles name | | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | +| 2026-10-19 | minor | Dynamic blocks: scale actions (base point, connections) and polar stretch actions (frame, stretched vertices, rotate-only objects) read | | 2026-10-19 | minor | Dynamic blocks: polar and XY parameters (names, value sets, corner grips) and array actions (row and column offsets) read; arrayed copies saved with AutoCAD's `AcDbBlockArrayActionTag`, without which AutoCAD can't change the reference again | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | | 2026-10-13 | minor | Dynamic blocks: rotation and flip parameters and actions read; changed references saved with AutoCAD's value records and history (flip state after the points, flip grip state) | diff --git a/docs/gaps.md b/docs/gaps.md index 936a7fd73..7b03bbf16 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks: F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic block scale and polar stretch actions: F3 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, polar and XY parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| 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, polar stretch, move, scale, lookups, polar and XY parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -156,6 +156,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | +| 2026-10-19 | minor | F3: dynamic block scale actions (by a distance, or an XY parameter's diagonal) and polar stretch actions (turn, stretch the frame, rotate-only objects) change references as AutoCAD does; checked against AutoCAD's output | | 2026-10-19 | minor | F3: dynamic block polar (Distance1, Angle1) and XY (X Distance1, Y Distance1) parameters in Properties and as grips, and their array actions repeat the objects as AutoCAD does; checked against AutoCAD's output | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | From 50060af67daf9c34d4d201c22de2a827c1bad6d1 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:01:34 -0600 Subject: [PATCH 037/187] Docs: the dynamic block data row lists scale and polar stretch actions Co-Authored-By: Claude Opus 5.5 --- 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 88908f269..41d1cab94 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch and move actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array actions, their copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); scale and polar stretch actions, base point and alignment parameters 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); base point and alignment parameters not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block) | | 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 From e74cac535b804015c3b99c1aeecc29626f57f695 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:33:55 -0600 Subject: [PATCH 038/187] Docs: DWG save of drawings with scale actions needs #1725 Co-Authored-By: Claude Opus 5.5 --- 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 41d1cab94..81d5070c3 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); base point and alignment parameters 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); base point and alignment parameters not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block), except that a DWG saved from a drawing with a scale action can't be opened by AutoCAD until #1725 (acadrust 0.6.5) lands: DXF save works | | 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 From dc55e72d490f4927d5fb85f8dfc814365b54e934 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:45:29 -0600 Subject: [PATCH 039/187] Tests: scale and polar stretch tests join the io test binary; Scale's doc says diagonal Upstream gathered each crate's integration tests into one binary (tests/it); the scale and polar stretch tests move there. The scale action's doc now says an XY parameter scales by its diagonal, as the code does. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 7 +++---- crates/io/tests/{ => it}/dynblock_scale_polar.rs | 2 +- crates/io/tests/it/main.rs | 1 + 3 files changed, 5 insertions(+), 5 deletions(-) rename crates/io/tests/{ => it}/dynblock_scale_polar.rs (98%) diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index eacf590b6..e4c9f2617 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -244,10 +244,9 @@ pub enum ActionKind { Lookup { columns: Vec, rows: Vec> }, /// Moves the objects by the change of the parameter values it follows. Move { multiplier: f64, angle_offset: f64 }, - /// Scales the objects about its base point by how much the distances it follows grew: a - /// distance's (linear or polar parameter) for both axes, or an XY parameter's horizontal and - /// vertical distances for each axis on its own. Its connections name what each reads ("Scale", - /// "XScale", "YScale"). + /// Scales the objects about its base point by how much the distance it follows grew (a linear + /// or polar parameter's distance, an XY parameter's diagonal). Its connections name what each + /// reads ("Scale", "XScale", "YScale"). Scale { base: ActionBase }, /// Turns the objects about its base point by the change of a rotation parameter's angle. Rotate { base: ActionBase }, diff --git a/crates/io/tests/dynblock_scale_polar.rs b/crates/io/tests/it/dynblock_scale_polar.rs similarity index 98% rename from crates/io/tests/dynblock_scale_polar.rs rename to crates/io/tests/it/dynblock_scale_polar.rs index 5d2be7f8f..4cf5e0f58 100644 --- a/crates/io/tests/dynblock_scale_polar.rs +++ b/crates/io/tests/it/dynblock_scale_polar.rs @@ -31,7 +31,7 @@ fn dxf(src: &str) -> String { /// The fixture with a reference to `block` at (100, 100). fn reference(block: &str) -> (Drawing, Handle) { - let mut d = read_dxf(dxf(&include_str!("data/dynblock_scale_polar.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); + let mut d = read_dxf(dxf(&include_str!("../data/dynblock_scale_polar.txt").replace("\r\n", "\n")).as_bytes()).unwrap(); let ins = cadcraft_doc::Insert { block: block.into(), insert: Vec3::new(100.0, 100.0, 0.0), diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index d6e3d290c..069b9991c 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -25,6 +25,7 @@ mod dxf_versions; mod dynblock_array; mod dynblock_read; mod dynblock_rotate_flip; +mod dynblock_scale_polar; mod entity_props_roundtrip; mod followups_626; mod groups_roundtrip; From fc82a2f9039a4e316b20de50283e8af7bee1a0c0 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:29:49 -0600 Subject: [PATCH 040/187] Dynamic blocks: base point and alignment parameters; lookups of angles, flips, XY distances and positions - An action that moves a base point parameter moves the reference's insertion point with it and the block's objects and parameters back, as AutoCAD saves it. - Alignment parameters: type read, a grip at the base point; dragged next to an object the reference moves onto it and turns along it, its right side toward the cursor (measured in AutoCAD). - Lookup columns UpdatedAngle, UpdatedFlip, UpdatedDistanceX/Y, UpdatedX/Y (and polar distance and angle) set and read, including the reverse lookup; any changed parameter re-evaluates the lookups that read it. - A distance of 0 is taken, as AutoCAD takes it. - A first-time flip value is saved with its state after its points and the flip grip's record without a point; AutoCAD dropped the reference's dynamic properties otherwise. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/dynblock.rs | 22 +- crates/doc/src/dynblock/apply.rs | 288 ++++-- crates/doc/src/dynblock/grips.rs | 27 +- crates/doc/src/dynblock/reference.rs | 36 +- crates/engine/src/cmd/blocks/dyngrip.rs | 19 +- crates/engine/src/snap.rs | 49 +- crates/engine/tests/it/dynamic_grips.rs | 26 + crates/io/tests/data/dynblock_params.txt | 1060 ++++++++++++++++++++++ crates/io/tests/dynblock_params.rs | 285 ++++++ crates/io/tests/it/dynblock_read.rs | 4 +- crates/ui-egui/src/dyngrips.rs | 12 +- docs/file-format-parity.md | 3 +- docs/gaps.md | 5 +- 13 files changed, 1733 insertions(+), 103 deletions(-) create mode 100644 crates/io/tests/data/dynblock_params.txt create mode 100644 crates/io/tests/dynblock_params.rs diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index e4c9f2617..b4dbd02dc 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -22,7 +22,7 @@ use crate::{Drawing, Handle, RawTag}; mod apply; mod grips; mod reference; -pub use apply::{drag_grip, grip_stops, set_property}; +pub use apply::{align_grip, drag_grip, grip_stops, set_property}; pub use grips::{DynGrip, GripPart, GripShape, grips}; pub use reference::{CustomProperty, Reference, Value, custom_properties, reference}; @@ -56,6 +56,9 @@ pub struct DynamicBlock { /// reflection line). #[serde(skip)] pub grip_points: Vec<(i32, Vec3)>, + /// The block's base point (where a base point parameter is in the block). + #[serde(skip)] + pub base: Vec3, } /// One parameter: a property a reference to the block can change. @@ -118,8 +121,11 @@ pub enum ParameterKind { /// An angle about a base point (Angle1): the end point turns about the base. The angle is /// measured from the direction the dynamic block has from base to end. Rotation { base: Vec3, end: Vec3, label: String, description: String, values: ValueSet }, - /// Aligns the reference with nearby geometry. - Alignment { base: Vec3, end: Vec3 }, + /// Aligns the reference with nearby geometry: dragged next to an object, its base point lands + /// on the object and the direction from base to end runs along it. `perpendicular` is the + /// parameter's type (perpendicular, else tangent); AutoCAD aligned both types the same way in + /// every case measured. + Alignment { base: Vec3, end: Vec3, perpendicular: bool }, /// Mirrors the objects about the reflection line from base to end (Flip state1); the names /// of its two states, not flipped and flipped. Flip { base: Vec3, end: Vec3, label: String, description: String, states: [String; 2] }, @@ -136,7 +142,9 @@ pub enum ParameterKind { }, /// A named value chosen from a lookup table. Lookup { at: Vec3, label: String, description: String }, - /// Moves the block's base point. + /// The block's base point: the reference's insertion point is here, and an action that moves + /// it moves the reference's insertion point. `at` is where the block editor showed it; the + /// block itself has it at its base point (AutoCAD moves the block's objects to put it there). BasePoint { at: Vec3 }, /// A parameter type not modelled yet. Other { dxf_type: String }, @@ -406,7 +414,7 @@ fn graph_members<'a>(objects: &HashMap, xdict: Handle pub fn dynamic_block(d: &Drawing, name: &str) -> Option { let xdict = d.foreign.records.get(&("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()))?.xdict?; let objects: HashMap = d.foreign.objects.iter().map(|o| (o.handle, o)).collect(); - let mut out = DynamicBlock::default(); + let mut out = DynamicBlock { base: d.block(name.trim()).map(|b| b.base).unwrap_or_default(), ..Default::default() }; for o in graph_members(&objects, xdict)? { let secs = sections(&o.tags); let node = Cursor::new(section(&secs, "AcDbEvalExpr")).int(90); @@ -514,9 +522,11 @@ fn parameter(kind: &str, secs: &[(&str, &[RawTag])]) -> ParameterKind { let x_values = value_set_at(&mut c, [410, 96, 142, 175]); ParameterKind::Xy { base, end, x_label, y_label, x_description, y_description, x_values, y_values } } + // Its type (280): 1 perpendicular, 0 tangent. "BLOCKALIGNMENTPARAMETER" => { let (base, end) = two(); - ParameterKind::Alignment { base, end } + let perpendicular = Cursor::new(section(secs, "AcDbBlockAlignmentParameter")).int(280) != 0; + ParameterKind::Alignment { base, end, perpendicular } } other => ParameterKind::Other { dxf_type: other.to_string() }, } diff --git a/crates/doc/src/dynblock/apply.rs b/crates/doc/src/dynblock/apply.rs index 63cda4842..153c2cf46 100644 --- a/crates/doc/src/dynblock/apply.rs +++ b/crates/doc/src/dynblock/apply.rs @@ -172,12 +172,14 @@ fn current(m: &DynamicBlock, values: &BTreeMap, node: i32) -> Option (ParameterKind::Flip { base, end, .. }, None) => Val::Flip(*base, *end, false), (ParameterKind::Visibility { states, .. }, None) => Val::Text(states.first().map(|s| s.name.clone()).unwrap_or_default()), (ParameterKind::Point { at, .. }, None) => Val::Point(*at), + // The block has it at its base point. + (ParameterKind::BasePoint { .. }, None) => Val::Point(m.base), ( ParameterKind::Linear { base, end, .. } | ParameterKind::Polar { base, end, .. } | ParameterKind::Xy { base, end, .. } | ParameterKind::Rotation { base, end, .. } - | ParameterKind::Alignment { base, end }, + | ParameterKind::Alignment { base, end, .. }, None, ) => Val::Points(*base, *end), _ => return None, @@ -205,11 +207,10 @@ fn allowed(set: &super::ValueSet, v: f64) -> f64 { } /// A linear parameter's points for distance `dist`: the end point moves along the parameter, or -/// both points move apart from the midpoint. -fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool) -> (Vec3, Vec3) { - let dir = end - base; - let len = dir.len(); - let u = if len > 1e-12 { dir * (1.0 / len) } else { Vec3::new(1.0, 0.0, 0.0) }; +/// both points move apart from the midpoint. At a distance of 0 the parameter goes the way `home` +/// (its base to its end in the dynamic block) does. +fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool, home: Vec3) -> (Vec3, Vec3) { + let u = unit_along(end - base, home); if from_midpoint { let mid = (base + end) * 0.5; (mid - u * (dist / 2.0), mid + u * (dist / 2.0)) @@ -218,6 +219,17 @@ fn linear_points(base: Vec3, end: Vec3, dist: f64, from_midpoint: bool) -> (Vec3 } } +/// `dir` as a unit vector, else `home`'s (a distance of 0 has no direction of its own), else X. +fn unit_along(dir: Vec3, home: Vec3) -> Vec3 { + if dir.len() > 1e-12 { + dir * (1.0 / dir.len()) + } else if home.len() > 1e-12 { + home * (1.0 / home.len()) + } else { + Vec3::new(1.0, 0.0, 0.0) + } +} + /// The changes one property change makes, before actions run: parameter values by graph id. #[derive(Default)] struct Plan { @@ -225,26 +237,49 @@ struct Plan { } impl Plan { - /// Set the value a lookup table cell gives property `property` of parameter `node`. + /// Set the value a lookup table cell gives property `property` of parameter `node` (block + /// units; angles in radians, as AutoCAD writes them). fn cell(&mut self, m: &DynamicBlock, values: &BTreeMap, node: i32, property: &str, cell: &str) -> Result<(), String> { let p = m.parameters.iter().find(|p| p.node == node).ok_or("A lookup table refers to a missing parameter.")?; - match (&p.kind, property.to_ascii_lowercase().as_str()) { - (_, "lookupstring") | (ParameterKind::Visibility { .. }, "visibilitystate") => { - self.set.insert(node, Val::Text(cell.to_string())); - } - (ParameterKind::Linear { from_midpoint, .. }, "updateddistance" | "distance") => { - let dist = cell - .trim() - .parse::() - .ok() - .filter(|v| v.is_finite()) - .ok_or_else(|| format!("A lookup table gives \"{cell}\" for a distance."))?; - let Some(Val::Points(b, e)) = self.set.get(&node).cloned().or_else(|| current(m, values, node)) else { return Ok(()) }; - let (b2, e2) = linear_points(b, e, dist, *from_midpoint); - self.set.insert(node, Val::Points(b2, e2)); - } - (_, other) => return Err(format!("A lookup table sets {other}, which CADCraft can't change yet.")), + let col = column(&p.kind, property).ok_or_else(|| format!("A lookup table sets {property}, which CADCraft can't change yet."))?; + if col == Column::Text { + self.set.insert(node, Val::Text(cell.to_string())); + return Ok(()); } + let v = + cell.trim().parse::().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("A lookup table gives \"{cell}\" for {property}."))?; + let Some(cur) = self.set.get(&node).cloned().or_else(|| current(m, values, node)) else { return Ok(()) }; + // A polar parameter's direction (along X when it has none). + let along = |b: Vec3, e: Vec3| { + let d = (e - b).xy(); + if d.len() > 1e-12 { d * (1.0 / d.len()) } else { Vec2::new(1.0, 0.0) } + }; + let now = match (col, &p.kind, cur) { + (Column::Distance, ParameterKind::Linear { from_midpoint, base: hb, end: he, .. }, Val::Points(b, e)) => { + let (b2, e2) = linear_points(b, e, v, *from_midpoint, *he - *hb); + Val::Points(b2, e2) + } + (Column::Distance, ParameterKind::Polar { .. }, Val::Points(b, e)) => Val::Points(b, b + (along(b, e) * v).to3(0.0)), + (Column::Angle, ParameterKind::Rotation { base: hb, end: he, .. }, Val::Points(b, e)) => { + Val::Points(b, rotation_end(b, e, (*hb, *he), v)) + } + (Column::Angle, ParameterKind::Polar { .. }, Val::Points(b, e)) => { + Val::Points(b, b + (Vec2::new(v.cos(), v.sin()) * (e - b).xy().len()).to3(0.0)) + } + (Column::DistanceX, ParameterKind::Xy { .. }, Val::Points(b, e)) => Val::Points(b, Vec3::new(b.x + v, e.y, e.z)), + (Column::DistanceY, ParameterKind::Xy { .. }, Val::Points(b, e)) => Val::Points(b, Vec3::new(e.x, b.y + v, e.z)), + (Column::X, ParameterKind::Point { .. }, Val::Point(at)) => Val::Point(Vec3::new(m.base.x + v, at.y, at.z)), + (Column::Y, ParameterKind::Point { .. }, Val::Point(at)) => Val::Point(Vec3::new(at.x, m.base.y + v, at.z)), + // Its flip grip's record follows. + (Column::Flip, ParameterKind::Flip { .. }, Val::Flip(b, e, _)) => { + if let Some(g) = p.grips.first().filter(|g| **g != 0) { + self.set.insert(*g, Val::State(v != 0.0)); + } + Val::Flip(b, e, v != 0.0) + } + _ => return Ok(()), + }; + self.set.insert(node, now); Ok(()) } @@ -267,21 +302,17 @@ impl Plan { Ok(found) } - /// After input property `property` of parameter `node` changed: a lookup table with that input - /// whose inputs (with the new value) match a row gives its lookup value, and the lookup's - /// other tables then set their inputs for that value (as AutoCAD does). - fn chain(&mut self, m: &DynamicBlock, values: &BTreeMap, node: i32, property: &str) -> Result<(), String> { + /// After parameter `node` changed: a lookup table with it as an input whose inputs (with the + /// new values) match a row gives its lookup value, and the lookup's other tables then set + /// their inputs for that value (as AutoCAD does). + fn chain(&mut self, m: &DynamicBlock, values: &BTreeMap, node: i32) -> Result<(), String> { let read = |plan: &Plan, n: i32, prop: &str| -> Option { let v = plan.set.get(&n).cloned().or_else(|| current(m, values, n))?; - match (v, prop.to_ascii_lowercase().as_str()) { - (Val::Text(t), "visibilitystate" | "lookupstring") => Some(t), - (Val::Points(b, e), "updateddistance" | "distance") => Some(format!("{}", (e - b).len())), - _ => None, - } + column_text(m, n, prop, &v) }; for (i, a) in m.actions.iter().enumerate() { let ActionKind::Lookup { columns, rows } = &a.kind else { continue }; - if !columns.iter().any(|c| !c.lookup && c.node == node && c.property.eq_ignore_ascii_case(property)) { + if !columns.iter().any(|c| !c.lookup && c.node == node) { continue; } let Some(out) = columns.iter().position(|c| c.lookup) else { continue }; @@ -301,6 +332,68 @@ impl Plan { } } +/// What a lookup table column stands for: a text (visibility state, lookup value), a distance, an +/// angle (radians), an XY parameter's horizontal or vertical distance, a position's X or Y (from +/// the block's base point) or a flip state (0 or 1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Column { + Text, + Distance, + Angle, + DistanceX, + DistanceY, + X, + Y, + Flip, +} + +/// The column a lookup table property (as AutoCAD names them) is for a parameter of `kind`, when +/// CADCraft can set and read it. +pub(super) fn column(kind: &ParameterKind, property: &str) -> Option { + Some(match (kind, property.to_ascii_lowercase().as_str()) { + (ParameterKind::Lookup { .. }, "lookupstring") | (ParameterKind::Visibility { .. }, "visibilitystate") => Column::Text, + (ParameterKind::Linear { .. } | ParameterKind::Polar { .. }, "updateddistance" | "distance") => Column::Distance, + (ParameterKind::Rotation { .. } | ParameterKind::Polar { .. }, "updatedangle") => Column::Angle, + (ParameterKind::Xy { .. }, "updateddistancex") => Column::DistanceX, + (ParameterKind::Xy { .. }, "updateddistancey") => Column::DistanceY, + (ParameterKind::Point { .. }, "updatedx") => Column::X, + (ParameterKind::Point { .. }, "updatedy") => Column::Y, + (ParameterKind::Flip { .. }, "updatedflip") => Column::Flip, + _ => return None, + }) +} + +/// Property `property` of parameter `node` with value `v`, as a lookup table cell writes it. +fn column_text(m: &DynamicBlock, node: i32, property: &str, v: &Val) -> Option { + let p = m.parameters.iter().find(|p| p.node == node)?; + // From 0 to 2π, a full turn being none. + let angle = |a: f64| { + let a = a.rem_euclid(std::f64::consts::TAU); + if std::f64::consts::TAU - a < 1e-9 { 0.0 } else { a } + }; + let out = match (column(&p.kind, property)?, &p.kind, v) { + (Column::Text, _, Val::Text(t)) => t.clone(), + (Column::Distance, _, Val::Points(b, e)) => (*e - *b).len().to_string(), + (Column::Angle, ParameterKind::Rotation { base: hb, end: he, .. }, Val::Points(b, e)) => { + angle(rotation_angle(*b, *e, (*hb, *he))).to_string() + } + (Column::Angle, _, Val::Points(b, e)) => angle((*e - *b).xy().angle()).to_string(), + (Column::DistanceX, _, Val::Points(b, e)) => (e.x - b.x).to_string(), + (Column::DistanceY, _, Val::Points(b, e)) => (e.y - b.y).to_string(), + (Column::X, _, Val::Point(at)) => (at.x - m.base.x).to_string(), + (Column::Y, _, Val::Point(at)) => (at.y - m.base.y).to_string(), + (Column::Flip, _, Val::Flip(_, _, f)) => i32::from(*f).to_string(), + _ => return None, + }; + Some(out) +} + +/// Property `property` of parameter `node` on a reference with values `values`, as a lookup table +/// cell writes it. +pub(super) fn property_text(m: &DynamicBlock, values: &BTreeMap, node: i32, property: &str) -> Option { + column_text(m, node, property, ¤t(m, values, node)?) +} + /// Whether table cell `cell` reads as `value` (numbers compare as numbers). fn same(cell: &str, value: &str) -> bool { match (cell.trim().parse::(), value.trim().parse::()) { @@ -358,6 +451,7 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> (dist, a) }; plan.set.insert(p.node, Val::Points(b, b + Vec2::new(a.cos(), a.sin()).to3(0.0) * len)); + plan.chain(&m, &r.values, p.node)?; } (ParameterKind::Xy { x_values, y_values, x_label, y_label, .. }, _) => { let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; @@ -370,13 +464,14 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> let v = allowed(set, v); let e2 = if second { Vec3::new(e.x, b.y + v, e.z) } else { Vec3::new(b.x + v, e.y, e.z) }; plan.set.insert(p.node, Val::Points(b, e2)); + plan.chain(&m, &r.values, p.node)?; } (ParameterKind::Visibility { states, label, .. }, _) => { let s = states.iter().find(|s| s.name.eq_ignore_ascii_case(value.trim())).ok_or_else(|| { format!("\"{value}\" is not a state of {label}: {}.", states.iter().map(|s| s.name.as_str()).collect::>().join(", ")) })?; plan.set.insert(p.node, Val::Text(s.name.clone())); - plan.chain(&m, &r.values, p.node, "VisibilityState")?; + plan.chain(&m, &r.values, p.node)?; } (ParameterKind::Lookup { label, .. }, _) => { plan.set.insert(p.node, Val::Text(value.trim().to_string())); @@ -384,25 +479,27 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> return Err(format!("\"{value}\" is not a value of {label}.")); } } - (ParameterKind::Linear { values, from_midpoint, .. }, None) => { + // AutoCAD takes a distance of 0 (a value list can offer it), not one below. + (ParameterKind::Linear { values, from_midpoint, base: hb, end: he, .. }, None) => { let typed = number(value)? / sx; - if typed <= 0.0 { - return Err(format!("{name} must be more than 0.")); + if typed < 0.0 { + return Err(format!("{name} can't be less than 0.")); } let dist = allowed(values, typed); - if dist <= 0.0 { - return Err(format!("{name} must be more than 0.")); + if !(dist >= 0.0 && dist.is_finite()) { + return Err(format!("{name} can't be less than 0.")); } let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; - let (b2, e2) = linear_points(b, e, dist, *from_midpoint); + let (b2, e2) = linear_points(b, e, dist, *from_midpoint, *he - *hb); plan.set.insert(p.node, Val::Points(b2, e2)); - plan.chain(&m, &r.values, p.node, "UpdatedDistance")?; + plan.chain(&m, &r.values, p.node)?; } (ParameterKind::Point { .. }, Some(is_x)) => { let Some(Val::Point(at)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no position.")) }; let v = number(value)?; let at = if is_x { Vec3::new(block_base.x + v / sx, at.y, at.z) } else { Vec3::new(at.x, block_base.y + v / sy, at.z) }; plan.set.insert(p.node, Val::Point(at)); + plan.chain(&m, &r.values, p.node)?; } // An angle in degrees, as Properties shows it, snapped to the parameter's values. (ParameterKind::Rotation { base: hb, end: he, values, label, .. }, None) => { @@ -414,7 +511,7 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> } let Some(Val::Points(b, e)) = current(&m, &r.values, p.node) else { return Err(format!("{name} has no points.")) }; plan.set.insert(p.node, Val::Points(b, rotation_end(b, e, (*hb, *he), a))); - plan.chain(&m, &r.values, p.node, "UpdatedAngle")?; + plan.chain(&m, &r.values, p.node)?; } // A state by name (or 0 / 1); its flip grip's record follows. (ParameterKind::Flip { states, label, .. }, None) => { @@ -431,6 +528,7 @@ pub fn set_property(d: &mut Drawing, insert: Handle, name: &str, value: &str) -> if let Some(g) = p.grips.first().filter(|g| **g != 0) { plan.set.insert(*g, Val::State(flipped)); } + plan.chain(&m, &r.values, p.node)?; } _ => return Err(format!("CADCraft can't change {name} yet.")), } @@ -453,15 +551,14 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); let q = ins.transform(base).inverse().ok_or("The reference has a zero scale.")?.apply(to); let p = m.parameters.iter().find(|p| p.node == node).ok_or("The reference has no such parameter.")?; + if matches!(p.kind, ParameterKind::Alignment { .. }) { + return align_grip(d, insert, node, to, None); + } let mut plan = Plan::default(); match (&p.kind, part) { - (ParameterKind::Linear { values, from_midpoint, label, .. }, GripPart::Base | GripPart::End) => { + (ParameterKind::Linear { values, from_midpoint, label, base: hb, end: he, .. }, GripPart::Base | GripPart::End) => { let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err(format!("{label} has no points.")) }; - let len = (e - b).len(); - if len < 1e-12 { - return Err(format!("{label} has no direction.")); - } - let u = (e - b) * (1.0 / len); + let u = unit_along(e - b, *he - *hb); let q = Vec3::new(q.x, q.y, b.z); let raw = if *from_midpoint { 2.0 * (q - (b + e) * 0.5).dot(u).abs() @@ -475,12 +572,11 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa return Err(format!("{label} must be more than 0.")); } let (b2, e2) = match (from_midpoint, part) { - (true, _) => linear_points(b, e, dist, true), + (true, _) => linear_points(b, e, dist, true, u), (false, GripPart::Base) => (e - u * dist, e), (false, _) => (b, b + u * dist), }; plan.set.insert(node, Val::Points(b2, e2)); - plan.chain(&m, &r.values, node, "UpdatedDistance")?; } (ParameterKind::Point { label, .. }, GripPart::At) => { let Some(Val::Point(at)) = current(&m, &r.values, node) else { return Err(format!("{label} has no position.")) }; @@ -554,13 +650,52 @@ pub fn drag_grip(d: &mut Drawing, insert: Handle, node: i32, part: super::GripPa .unwrap_or(0.0); let a = allowed(values, (rotation_angle(b, q3, (*hb, *he)) - offset).rem_euclid(std::f64::consts::TAU)); plan.set.insert(node, Val::Points(b, rotation_end(b, e, (*hb, *he), a))); - plan.chain(&m, &r.values, node, "UpdatedAngle")?; } _ => return Err("That grip can't be dragged.".into()), } + plan.chain(&m, &r.values, node)?; apply(d, insert, &r.definition, &r.values, &plan.set, node) } +/// Drag the grip of alignment parameter `node` of dynamic block reference `insert` to `to` +/// (drawing coordinates), as AutoCAD does: with `near`, the nearest point of an object at the +/// cursor and the object's direction there, the reference moves so the parameter's base point is +/// on that point and turns so the parameter's direction (base to end) runs along the object, its +/// right-hand side toward the cursor (toward where the grip was when the cursor is on the object); +/// without, the base point just follows the cursor. Only the reference's position and rotation +/// change (AutoCAD records no value for it). +pub fn align_grip(d: &mut Drawing, insert: Handle, node: i32, to: Vec2, near: Option<(Vec2, Vec2)>) -> Result<(), String> { + if !to.is_finite() || near.is_some_and(|(at, along)| !(at.is_finite() && along.is_finite())) { + return Err("Invalid point.".into()); + } + let r = reference(d, insert).ok_or("Not a dynamic block reference.")?; + let m = dynamic_block(d, &r.definition).ok_or("Not a dynamic block reference.")?; + let EntityKind::Insert(ins) = &d.entity(insert).ok_or("No such object.")?.kind else { return Err("Not a block reference.".into()) }; + let p = m.parameters.iter().find(|p| p.node == node).ok_or("The reference has no such parameter.")?; + if !matches!(p.kind, ParameterKind::Alignment { .. }) { + return Err("That isn't an alignment grip.".into()); + } + let Some(Val::Points(b, e)) = current(&m, &r.values, node) else { return Err("The alignment has no points.".into()) }; + let base = d.block(&r.definition).map(|b| b.base.xy()).unwrap_or_default(); + let xf = ins.transform(base); + let (wb, way) = (xf.apply(b.xy()), xf.apply(e.xy()) - xf.apply(b.xy())); + let (at, turn) = match near { + Some((at, along)) if along.len() > 1e-12 && way.len() > 1e-12 => { + let u = along * (1.0 / along.len()); + let side = if (to - at).len() > 1e-9 { to - at } else { wb - at }; + let dir = if Vec2::new(u.y, -u.x).dot(side) < 0.0 { u * -1.0 } else { u }; + (at, dir.angle() - way.angle()) + } + Some((at, _)) => (at, 0.0), + None => (to, 0.0), + }; + let t = Mat3::rotate_about(wb, turn).then(Mat3::translate(at - wb)); + if !(turn.is_finite() && t.apply(Vec2::ZERO).is_finite()) { + return Err("Invalid point.".into()); + } + d.modify_entity(insert, |e| e.kind.transform(&t)).map_err(|e| e.to_string()) +} + /// Most stops one grip shows. const MAX_STOPS: usize = 200; @@ -774,6 +909,41 @@ impl ActionRun<'_> { Ok(arrays) } + /// A base point parameter the actions moved: AutoCAD keeps it at the block's base point, so the + /// block's objects and parameters move back by its move, and the reference's insertion point + /// moves forward by it (the returned move: the reference stays where it was, but for what the + /// actions changed). (A fixed base point of a rotate or scale action stays where the dynamic + /// block has it.) + fn rebase(&mut self, src: &Block) -> Vec2 { + let mut rebase = Vec2::ZERO; + if let Some(p) = self.m.parameters.iter().find(|p| matches!(p.kind, ParameterKind::BasePoint { .. })) + && let (Some(Val::Point(was)), Some(Val::Point(now))) = (current(self.m, self.values, p.node), self.new.get(&p.node).cloned()) + { + let v = (now - was).xy(); + if v.len() > 1e-12 && v.is_finite() { + rebase = v; + self.new.insert(p.node, Val::Point(was)); + } + } + if rebase == Vec2::ZERO { + return rebase; + } + for e in src.entities.iter() { + self.moves.entry(e.handle).or_default().push(Op::Move(None, rebase * -1.0)); + } + let back = |q: Vec3| q - rebase.to3(0.0); + for p in self.m.parameters.iter().filter(|p| !matches!(p.kind, ParameterKind::BasePoint { .. })) { + let moved = match self.value_of(p.node) { + Some(Val::Point(q)) => Val::Point(back(q)), + Some(Val::Points(b, e)) => Val::Points(back(b), back(e)), + Some(Val::Flip(b, e, f)) => Val::Flip(back(b), back(e), f), + _ => continue, + }; + self.new.insert(p.node, moved); + } + rebase + } + /// A rotate, flip or scale action turns, mirrors or scales its objects, and carries the /// parameters in its selection the same way. A handle the selection repeats is handled once /// (twice would turn or scale it twice, or mirror it back). @@ -979,6 +1149,7 @@ fn apply( run.action(a)?; } let arrays = run.arrays()?; + let rebase = run.rebase(&src); let earlier = earlier_copies(&src, &src_tag, &arrays); let ActionRun { new, moves, .. } = run; // Visibility states. @@ -1118,12 +1289,15 @@ fn apply( // block-to-drawing transform), is the change of the reference's attribute. let to_world = ins.transform(src.base.xy()); let to_block = to_world.inverse().unwrap_or(Mat3::IDENTITY); + // The insertion point's move for a moved base point (the block's objects moved back by it). + let shift = to_world.apply(rebase) - to_world.apply(Vec2::ZERO); d.modify_entity(insert, |e| { if let EntityKind::Insert(i) = &mut e.kind { i.block = name.clone(); + i.insert = i.insert + shift.to3(0.0); for a in &mut i.attribs { if let Some(t) = attrib_moves.get(&a.tag.to_ascii_uppercase()) { - let w = to_block.then(*t).then(to_world); + let w = to_block.then(*t).then(Mat3::translate(rebase)).then(to_world); carry_text(&mut a.text, &w); a.transform_multiline(&w); } @@ -1388,9 +1562,13 @@ fn record_values( } None => { let h = d.new_handle(); - let mut tags = templates.get(&key).cloned().unwrap_or_else(|| { - let p = at(*node); - vec![tag(100, "AcDbXrecord"), tag(280, "1"), tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())] + let mut tags = templates.get(&key).cloned().unwrap_or_else(|| match v { + // A flip grip's record: its header's groups and two states, the last one its own. + Val::State(_) => vec![tag(100, "AcDbXrecord"), tag(280, "1"), tag(70, "25"), tag(70, "104"), tag(70, "0"), tag(70, "0")], + _ => { + let p = at(*node); + vec![tag(100, "AcDbXrecord"), tag(280, "1"), tag(10, p.x.to_string()), tag(20, p.y.to_string()), tag(30, p.z.to_string())] + } }); write_value(&mut tags, v); objects.push(ForeignObject { handle: h, kind: "XRECORD".into(), tags: own(tags, h, data) }); diff --git a/crates/doc/src/dynblock/grips.rs b/crates/doc/src/dynblock/grips.rs index 1ae859851..cbc04775e 100644 --- a/crates/doc/src/dynblock/grips.rs +++ b/crates/doc/src/dynblock/grips.rs @@ -1,7 +1,9 @@ //! The grips of a dynamic block reference, as AutoCAD shows them on a selected reference: an //! arrow at each end of a distance (linear parameter), a square at a position (point parameter), //! a circle at the end of an angle (rotation parameter), a flip arrow across a reflection line -//! (flip parameter) and a down-pointing triangle for a list (visibility states, lookup values). +//! (flip parameter), a down-pointing triangle for a list (visibility states, lookup values) and a +//! pentagon pointing across the alignment direction at an alignment's base point (alignment +//! parameter; dragged next to an object it aligns the reference with it, [`super::align_grip`]). //! Dragging an arrow, square or circle is [`super::drag_grip`]; a flip grip flips at a click; a //! list grip offers its property's choices. //! @@ -88,6 +90,9 @@ pub enum GripShape { Rotation, /// An arrow across a reflection line: click it to flip (its choices are the two states). Flip, + /// A pentagon pointing to the left of an alignment's direction: drag it next to an object to + /// align the reference with it. + Alignment, } /// One grip of a dynamic block reference. @@ -312,6 +317,26 @@ pub fn grips(d: &Drawing, insert: Handle) -> Vec { }); } } + // At the base point, pointing to the left of the direction (as AutoCAD draws it). + ParameterKind::Alignment { base, end, .. } => { + let (b, e) = match r.values.get(&p.node) { + Some(Value::Points { base, end }) => (*base, *end), + _ => (*base, *end), + }; + let u = (e - b).xy(); + if shown(p.node, grip(0)) && u.len() > 1e-12 { + let (at, dir) = (world(b), toward(b, u.perp().to3(0.0))); + out.push(DynGrip { + node: p.node, + part: GripPart::Base, + shape: GripShape::Alignment, + at, + dir, + property: String::new(), + choices: Vec::new(), + }); + } + } ParameterKind::Visibility { at, label, .. } | ParameterKind::Lookup { at, label, .. } => { let Some(list) = choices.get(&label.to_ascii_uppercase()).filter(|c| !c.is_empty()) else { continue }; if shown(p.node, grip(0)) { diff --git a/crates/doc/src/dynblock/reference.rs b/crates/doc/src/dynblock/reference.rs index 2a05d1211..8ab0a1420 100644 --- a/crates/doc/src/dynblock/reference.rs +++ b/crates/doc/src/dynblock/reference.rs @@ -53,8 +53,8 @@ pub struct CustomProperty { /// The values it may be set to, when it is a choice (visibility states, lookup values, a /// distance's list). pub choices: Vec, - /// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, a - /// position, or a lookup whose tables set only those. + /// CADCraft can change it ([`super::set_property`]): a visibility state, a distance, an angle, + /// a position, a flip state, or a lookup whose tables set only those. pub editable: bool, } @@ -198,26 +198,7 @@ struct Current<'a> { impl Current<'_> { /// Parameter `node`'s value of property `property`, as table cells write it. fn property(&self, node: i32, property: &str) -> Option { - let p = self.m.parameters.iter().find(|p| p.node == node)?; - let v = self.values.get(&node); - match (&p.kind, property.to_ascii_lowercase().as_str()) { - (ParameterKind::Visibility { states, .. }, "visibilitystate") => match v { - Some(Value::Text { value }) => Some(value.clone()), - _ => states.first().map(|s| s.name.clone()), - }, - (ParameterKind::Linear { base, end, .. }, "updateddistance" | "distance") => { - let (b, e) = match v { - Some(Value::Points { base, end }) => (*base, *end), - _ => (*base, *end), - }; - Some(format!("{}", (e - b).len())) - } - (ParameterKind::Lookup { .. }, "lookupstring") => match v { - Some(Value::Text { value }) => Some(value.clone()), - _ => None, - }, - _ => None, - } + super::apply::property_text(self.m, self.values, node, property) } /// Lookup parameter `node`'s value: the value every lookup table that sets it gives for the @@ -341,7 +322,8 @@ pub fn custom_properties(d: &Drawing, insert: Handle) -> Option<(String, Vec bool { let mut any = false; for a in &m.actions { @@ -350,10 +332,10 @@ fn lookup_sets_what_changes(m: &DynamicBlock, node: i32) -> bool { continue; } any = true; - if !columns - .iter() - .all(|c| matches!(c.property.to_ascii_lowercase().as_str(), "lookupstring" | "visibilitystate" | "updateddistance" | "distance")) - { + let settable = |c: &super::LookupColumn| { + m.parameters.iter().find(|p| p.node == c.node).is_some_and(|p| super::apply::column(&p.kind, &c.property).is_some()) + }; + if !columns.iter().all(settable) { return false; } } diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index baac76c07..26eca6c0d 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -47,11 +47,25 @@ fn drag(s: &mut Session, h: Handle, node: i32, part: GripPart, to: Vec2) -> std: return Err("the reference is on a locked layer".into()); } let mut d = s.doc().map_err(|e| e.to_string())?.clone(); - dynblock::drag_grip(&mut d, h, node, part, to)?; + drag_in(s, &mut d, h, node, part, to)?; *s.doc_mut().map_err(|e| e.to_string())? = d; Ok(()) } +/// Drag grip (`node`, `part`) of reference `h` to `to` in drawing `d`; an alignment grip aligns +/// the reference with the object at the cursor (within the aperture), as AutoCAD does. +fn drag_in(s: &Session, d: &mut Drawing, h: Handle, node: i32, part: GripPart, to: Vec2) -> std::result::Result<(), String> { + let alignment = dynblock::reference(d, h) + .and_then(|r| dynblock::dynamic_block(d, &r.definition)) + .is_some_and(|m| m.parameters.iter().any(|p| p.node == node && matches!(p.kind, dynblock::ParameterKind::Alignment { .. }))); + if !alignment { + return dynblock::drag_grip(d, h, node, part, to); + } + let aperture = s.pixel_size() * s.settings.aperture.max(1.0); + let near = crate::snap::nearest_with_direction(d, &s.space(), to, aperture, h); + dynblock::align_grip(d, h, node, to, near) +} + /// The properties an object of a block draws with in reference `r`: on layer 0 it is on the /// reference's layer, and its ByBlock colour, linetype, lineweight and transparency are the /// reference's (as the renderer draws a block's contents). @@ -138,6 +152,7 @@ impl Interactive for DynGripEdit { let (msg, accept) = match self.shape { GripShape::Linear => ("** STRETCH ** Specify stretch point or distance", Accept::POINT_OR_NUMBER), GripShape::Rotation => ("** ROTATE ** Specify rotation point or angle", Accept::POINT_OR_NUMBER), + GripShape::Alignment => ("Specify point location", Accept::POINT), _ => ("** STRETCH ** Specify stretch point", Accept::POINT), }; let p = Prompt::new(msg, accept).kw(&["eXit"]).base(self.from); @@ -194,7 +209,7 @@ impl Interactive for DynGripEdit { fn preview_objects(&self, s: &Session, c: Vec2) -> Vec { let Ok(d) = s.doc() else { return Vec::new() }; let mut d = d.clone(); - match dynblock::drag_grip(&mut d, self.handle, self.node, self.part, c) { + match drag_in(s, &mut d, self.handle, self.node, self.part, c) { Ok(()) => drawn(&d, self.handle), Err(_) => Vec::new(), } diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 8def404d2..154ef5b85 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -7,7 +7,7 @@ mod viewport; pub use viewport::ViewportPoint; -use cadcraft_doc::{Drawing, EntityKind, Insert, MAX_BLOCK_DEPTH, Prim, Space}; +use cadcraft_doc::{Drawing, EntityKind, Handle, Insert, MAX_BLOCK_DEPTH, Prim, Space}; use cadcraft_geom::{Bounds2, Circle, EPS, Ellipse, Mat3, PI, Segment, Vec2, intersect_ext}; use serde::Serialize; @@ -308,7 +308,7 @@ fn osnap_in_with_prims( frozen: &[String], clip: Option, ) -> Option<(Option, Vec)> { - let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen)?; + let (mut cands, near_prims) = gather_in(d, space, ix, cursor, aperture, osmode, frozen, None)?; // Intersections between nearby primitives; Apparent Intersection also where their extensions // meet (lines extended, arcs as full circles: in 2D, the "apparent" crossing of objects // that don't reach each other). @@ -398,7 +398,47 @@ pub(crate) fn gather( aperture: f64, osmode: u32, ) -> Option<(Vec<(u32, Vec2)>, Vec)> { - gather_in(d, space, ix, cursor, aperture, osmode, &[]) + gather_in(d, space, ix, cursor, aperture, osmode, &[], None) +} + +/// The point nearest `cursor` within `aperture` on the visible objects of `space` other than +/// `skip` (and on the objects inside block references), with the object's direction there (a unit +/// vector; a circle's or arc's runs counterclockwise): what an alignment grip aligns a dynamic +/// block reference with. +pub(crate) fn nearest_with_direction(d: &Drawing, space: &Space, cursor: Vec2, aperture: f64, skip: Handle) -> Option<(Vec2, Vec2)> { + let ix = crate::spatial::index(d, space); + let (_, prims) = gather_in(d, space, &ix, cursor, aperture, 0, &[], Some(skip))?; + let mut best: Option<(f64, Vec2, Vec2)> = None; + let mut consider = |at: Vec2, dir: Vec2| { + let dd = at.dist(cursor); + if at.is_finite() && dir.len() > 1e-12 && dir.is_finite() && dd <= aperture && best.is_none_or(|(bd, _, _)| dd < bd) { + best = Some((dd, at, dir * (1.0 / dir.len()))); + } + }; + for p in prims.iter().take(2000) { + if let Prim::Circle(c) = p { + let at = c.closest(cursor); + consider(at, (at - c.center).perp()); + continue; + } + if let Prim::Infinite { base, dir, .. } = p { + let len = dir.len(); + if len > 1e-12 { + let u = *dir * (1.0 / len); + consider(*base + u * (cursor - *base).dot(u), u); + } + continue; + } + for seg in prim_segments(p) { + let seg = fix_circle(&seg); + let at = seg.closest(cursor); + match seg { + Segment::Line(l) => consider(at, l.b - l.a), + Segment::Arc { arc, .. } => consider(at, (at - arc.center).perp()), + } + } + } + best.map(|(_, at, dir)| (at, dir)) } fn gather_in( @@ -409,6 +449,7 @@ fn gather_in( aperture: f64, osmode: u32, frozen: &[String], + skip: Option, ) -> Option<(Vec<(u32, Vec2)>, Vec)> { let probe = Bounds2::new(cursor, cursor).expand(aperture); let mut cands: Vec<(u32, Vec2)> = Vec::new(); @@ -416,7 +457,7 @@ fn gather_in( let mut count = 0usize; let mut budget = MAX_BLOCK_LEAVES; for (e, known) in crate::select::candidates(d, space, ix, &probe.expand(aperture), true, false)? { - if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) { + if !d.is_visible(e) || frozen.iter().any(|l| l.eq_ignore_ascii_case(&e.common.layer)) || Some(e.handle) == skip { continue; } let inf = crate::select::is_infinite(e); diff --git a/crates/engine/tests/it/dynamic_grips.rs b/crates/engine/tests/it/dynamic_grips.rs index 9512d279d..e95c4825a 100644 --- a/crates/engine/tests/it/dynamic_grips.rs +++ b/crates/engine/tests/it/dynamic_grips.rs @@ -172,3 +172,29 @@ fn a_grip_with_a_value_list_marks_its_stops_while_dragged() { .collect(); assert_eq!(ticks, [(130.0, -4.0), (132.0, -4.0), (136.0, -4.0)]); } + +/// An alignment grip dragged onto a line (the synthetic Align block of the io tests, a line at +/// 30° from (120, 100)): the reference moves onto the line and turns along it, as AutoCAD does; +/// away from objects it only moves. +#[test] +fn an_alignment_grip_aligns_with_the_line_at_the_cursor() { + let src = include_str!("../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n"); + let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap(); + let mut s = Session::empty(); + s.open_drawing(d, "params", None); + let r = s.execute("insert", &json!({ "name": "Align", "at": [100, 100] })).unwrap(); + let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + let g = s.execute("blocks.reference.grips", &json!({ "handle": h.hex() })).unwrap(); + assert_eq!(g[0]["shape"], "alignment"); + // A point on the line, a little below it. + let (c, sn) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let to = [120.0 + 10.0 * c + 0.01 * sn, 100.0 + 10.0 * sn - 0.01 * c]; + s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": to })).unwrap(); + let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") }; + assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6, "{}", i.rotation.to_degrees()); + assert!((i.insert.x - (120.0 + 10.0 * c)).abs() < 1e-6 && (i.insert.y - (100.0 + 10.0 * sn)).abs() < 1e-6, "{:?}", i.insert); + // Far from anything: it only moves. + s.execute("blocks.reference.grip", &json!({ "handle": h.hex(), "node": 1, "part": "base", "to": [0, -50] })).unwrap(); + let Some(cadcraft_engine::doc::EntityKind::Insert(i)) = s.doc().unwrap().entity(h).map(|e| &e.kind) else { panic!("a reference") }; + assert!((i.rotation.to_degrees() - 30.0).abs() < 1e-6 && i.insert.x.abs() < 1e-9 && (i.insert.y + 50.0).abs() < 1e-9); +} diff --git a/crates/io/tests/data/dynblock_params.txt b/crates/io/tests/data/dynblock_params.txt new file mode 100644 index 000000000..7b39a199c --- /dev/null +++ b/crates/io/tests/data/dynblock_params.txt @@ -0,0 +1,1060 @@ +0 SECTION +2 HEADER +9 $ACADVER +1 AC1032 +9 $HANDSEED +5 400 +0 ENDSEC +0 SECTION +2 TABLES +0 TABLE +2 BLOCK_RECORD +5 1 +330 0 +100 AcDbSymbolTable +70 6 +0 BLOCK_RECORD +5 1F +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Model_Space +340 0 +0 BLOCK_RECORD +5 1E +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 *Paper_Space +340 0 +0 BLOCK_RECORD +5 1D +102 {ACAD_XDICTIONARY +360 60 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Shift +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1C +102 {ACAD_XDICTIONARY +360 70 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Align +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1B +102 {ACAD_XDICTIONARY +360 80 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Turn +340 0 +70 0 +280 1 +281 1 +0 BLOCK_RECORD +5 1A +102 {ACAD_XDICTIONARY +360 90 +102 } +330 1 +100 AcDbSymbolTableRecord +100 AcDbBlockTableRecord +2 Many +340 0 +70 0 +280 1 +281 1 +0 ENDTAB +0 ENDSEC +0 SECTION +2 BLOCKS +0 BLOCK +5 20 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Model_Space +70 0 +10 0 +20 0 +30 0 +3 *Model_Space +1 +0 ENDBLK +5 21 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 22 +330 1E +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 *Paper_Space +70 0 +10 0 +20 0 +30 0 +3 *Paper_Space +1 +0 ENDBLK +5 23 +330 1E +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 24 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Shift +70 2 +10 0 +20 0 +30 0 +3 Shift +1 +0 LWPOLYLINE +5 30 +330 1D +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 -10 +20 -2.5 +10 0 +20 -2.5 +10 0 +20 2.5 +10 -10 +20 2.5 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 30 +0 ATTDEF +5 31 +330 1D +100 AcDbEntity +8 0 +100 AcDbText +10 -8 +20 0 +30 0 +40 1 +1 X +7 Standard +100 AcDbAttributeDefinition +3 Tag +2 TAG +70 0 +1001 AcDbBlockRepETag +1070 1 +1071 2 +1005 31 +0 ENDBLK +5 25 +330 1D +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 26 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Align +70 2 +10 0 +20 0 +30 0 +3 Align +1 +0 LWPOLYLINE +5 40 +330 1C +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 4 +20 0 +10 4 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 40 +0 ENDBLK +5 27 +330 1C +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 28 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Turn +70 2 +10 0 +20 0 +30 0 +3 Turn +1 +0 LWPOLYLINE +5 50 +330 1B +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 4 +20 0 +10 4 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 50 +0 ENDBLK +5 29 +330 1B +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 BLOCK +5 2A +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockBegin +2 Many +70 2 +10 0 +20 0 +30 0 +3 Many +1 +0 LWPOLYLINE +5 A0 +330 1A +100 AcDbEntity +8 0 +100 AcDbPolyline +90 4 +70 1 +10 0 +20 0 +10 4 +20 0 +10 4 +20 2 +10 0 +20 2 +1001 AcDbBlockRepETag +1070 1 +1071 1 +1005 A0 +0 ENDBLK +5 2B +330 1A +100 AcDbEntity +8 0 +100 AcDbBlockEnd +0 ENDSEC +0 SECTION +2 ENTITIES +0 INSERT +5 E0 +330 1F +100 AcDbEntity +8 0 +100 AcDbBlockReference +66 1 +2 Shift +10 100 +20 100 +30 0 +0 ATTRIB +5 E1 +330 E0 +100 AcDbEntity +8 0 +100 AcDbText +10 92 +20 100 +30 0 +40 1 +1 X +7 Standard +100 AcDbAttribute +2 TAG +70 0 +0 SEQEND +5 E2 +330 E0 +100 AcDbEntity +8 0 +0 LINE +5 E3 +330 1F +100 AcDbEntity +8 0 +100 AcDbLine +10 120 +20 100 +30 0 +11 140 +21 111.54700538379251 +31 0 +0 ENDSEC +0 SECTION +2 OBJECTS +0 DICTIONARY +5 C +330 0 +100 AcDbDictionary +281 1 +0 DICTIONARY +5 60 +330 1D +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 61 +0 ACAD_EVALUATION_GRAPH +5 61 +330 60 +100 AcDbEvalGraph +96 3 +97 3 +91 0 +93 32 +95 1 +360 62 +91 1 +93 32 +95 2 +360 63 +91 2 +93 32 +95 3 +360 64 +0 BLOCKBASEPOINTPARAMETER +5 62 +330 61 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Base Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 10 +1020 2.5 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockBasepointParameter +1011 0 +1021 0 +1031 0 +1012 0 +1022 0 +1032 0 +0 BLOCKLINEARPARAMETER +5 63 +330 61 +100 AcDbEvalExpr +90 2 +98 33 +99 232 +100 AcDbBlockElement +300 Linear +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 -10 +1020 -2.5 +1030 0 +1011 0 +1021 -2.5 +1031 0 +170 4 +91 0 +91 4 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockLinearParameter +305 Distance1 +306 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKSTRETCHACTION +5 64 +330 61 +100 AcDbEvalExpr +90 3 +98 33 +99 232 +100 AcDbBlockElement +300 Stretch +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 2 +330 30 +330 62 +1010 2 +1020 3 +1030 0 +100 AcDbBlockStretchAction +92 2 +301 EndXDelta +93 2 +302 EndYDelta +72 2 +1011 -2 +1021 -3.5 +1011 2 +1021 3.5 +73 1 +331 30 +74 2 +94 1 +94 2 +75 0 +140 1 +141 0 +0 DICTIONARY +5 70 +330 1C +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 71 +0 ACAD_EVALUATION_GRAPH +5 71 +330 70 +100 AcDbEvalGraph +96 1 +97 1 +91 0 +93 32 +95 1 +360 72 +0 BLOCKALIGNMENTPARAMETER +5 72 +330 71 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Alignment +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 4 +1021 0 +1031 0 +170 4 +91 2 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockAlignmentParameter +280 1 +0 DICTIONARY +5 80 +330 1B +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 81 +0 ACAD_EVALUATION_GRAPH +5 81 +330 80 +100 AcDbEvalGraph +96 4 +97 4 +91 0 +93 32 +95 1 +360 82 +91 1 +93 32 +95 5 +360 83 +91 2 +93 32 +95 6 +360 84 +91 3 +93 32 +95 10 +360 85 +0 BLOCKROTATIONPARAMETER +5 82 +330 81 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Rotation +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 3 +1021 0 +1031 0 +170 4 +91 0 +91 2 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockRotationParameter +305 Angle1 +306 +1011 3 +1021 0 +1031 0 +140 0 +307 +96 0 +141 0 +142 0 +143 0 +175 0 +0 BLOCKROTATEACTION +5 83 +330 81 +100 AcDbEvalExpr +90 5 +98 33 +99 232 +100 AcDbBlockElement +300 Rotate +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 1 +330 50 +1010 5 +1020 0 +1030 0 +100 AcDbBlockActionWithBasePt +92 1 +93 1 +301 UpdatedBaseX +302 UpdatedBaseY +1011 0 +1021 0 +1031 0 +280 1 +1012 0 +1022 0 +1032 0 +100 AcDbBlockRotationAction +94 1 +303 AngleDelta +0 BLOCKLOOKUPPARAMETER +5 84 +330 81 +100 AcDbEvalExpr +90 6 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 6 +1020 4 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockLookUpParameter +303 Lookup1 +304 +94 0 +0 BLOCKLOOKUPACTION +5 85 +330 81 +100 AcDbEvalExpr +90 10 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup1 +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 0 +1010 6 +1020 5 +1030 0 +100 AcDbBlockLookupAction +92 3 +93 2 +301 +302 1.570796326794896 +302 Up +302 3.141592653589793 +302 Left +302 0 +302 Zero +303 +94 1 +95 40 +96 1 +282 0 +305 Custom +281 0 +304 UpdatedAngle +303 +94 6 +95 1 +96 0 +282 1 +305 Custom +281 1 +304 lookupString +280 1 +0 DICTIONARY +5 90 +330 1A +100 AcDbDictionary +280 1 +281 1 +3 ACAD_ENHANCEDBLOCK +360 91 +0 ACAD_EVALUATION_GRAPH +5 91 +330 90 +100 AcDbEvalGraph +96 6 +97 6 +91 0 +93 32 +95 1 +360 92 +91 1 +93 32 +95 6 +360 93 +91 2 +93 32 +95 10 +360 94 +91 3 +93 32 +95 14 +360 95 +91 4 +93 32 +95 18 +360 96 +91 5 +93 32 +95 22 +360 97 +0 BLOCKFLIPPARAMETER +5 92 +330 91 +100 AcDbEvalExpr +90 1 +98 33 +99 232 +100 AcDbBlockElement +300 Flip +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 -1 +1030 0 +1011 4 +1021 -1 +1031 0 +170 4 +91 2 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockFlipParameter +305 Flip state1 +306 +307 Not flipped +308 Flipped +1012 2 +1022 -2 +1032 0 +309 UpdatedFlip +96 2 +0 BLOCKXYPARAMETER +5 93 +330 91 +100 AcDbEvalExpr +90 6 +98 33 +99 232 +100 AcDbBlockElement +300 XY +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 4 +1021 2 +1031 0 +170 4 +91 0 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockXYParameter +305 Y Distance1 +306 X Distance1 +307 +308 +141 0 +140 0 +309 +97 0 +146 0 +147 0 +148 0 +176 0 +410 +96 0 +142 0 +143 0 +144 0 +175 0 +0 BLOCKPOLARPARAMETER +5 94 +330 91 +100 AcDbEvalExpr +90 10 +98 33 +99 232 +100 AcDbBlockElement +300 Polar +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock2PtParameter +1010 0 +1020 0 +1030 0 +1011 3 +1021 3 +1031 0 +170 4 +91 0 +91 0 +91 0 +91 0 +171 0 +172 0 +173 0 +174 0 +177 0 +100 AcDbBlockPolarParameter +305 Distance1 +306 +307 Angle1 +308 +140 0 +309 +96 0 +141 0 +142 0 +143 0 +175 0 +410 +97 0 +145 0 +146 0 +147 0 +176 0 +0 BLOCKPOINTPARAMETER +5 95 +330 91 +100 AcDbEvalExpr +90 14 +98 33 +99 232 +100 AcDbBlockElement +300 Point +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 2 +1020 1 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockPointParameter +303 Position1 +304 +1011 2 +1021 3 +1031 0 +0 BLOCKLOOKUPPARAMETER +5 96 +330 91 +100 AcDbEvalExpr +90 18 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup +98 33 +99 232 +1071 0 +100 AcDbBlockParameter +280 1 +281 0 +100 AcDbBlock1PtParameter +1010 6 +1020 4 +1030 0 +93 0 +170 0 +171 0 +100 AcDbBlockLookUpParameter +303 Lookup1 +304 +94 0 +0 BLOCKLOOKUPACTION +5 97 +330 91 +100 AcDbEvalExpr +90 22 +98 33 +99 232 +100 AcDbBlockElement +300 Lookup1 +98 33 +99 232 +1071 0 +100 AcDbBlockAction +70 0 +71 0 +1010 6 +1020 5 +1030 0 +100 AcDbBlockLookupAction +92 2 +93 8 +301 +302 1 +302 6 +302 3 +302 5 +302 0.5235987755982987 +302 1 +302 0.5 +302 A +302 0 +302 4 +302 2 +302 4.242640689999999 +302 0.7853981633974482 +302 2 +302 1 +302 B +303 +94 1 +95 70 +96 0 +282 0 +305 Custom +281 0 +304 UpdatedFlip +303 +94 6 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedDistanceX +303 +94 6 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedDistanceY +303 +94 10 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedDistance +303 +94 10 +95 40 +96 1 +282 0 +305 Custom +281 0 +304 UpdatedAngle +303 +94 14 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedX +303 +94 14 +95 40 +96 2 +282 0 +305 Custom +281 0 +304 UpdatedY +303 +94 18 +95 1 +96 0 +282 1 +305 Custom +281 1 +304 lookupString +280 1 +0 ENDSEC +0 EOF diff --git a/crates/io/tests/dynblock_params.rs b/crates/io/tests/dynblock_params.rs new file mode 100644 index 000000000..c0a2275e3 --- /dev/null +++ b/crates/io/tests/dynblock_params.rs @@ -0,0 +1,285 @@ +//! Base point and alignment parameters of dynamic blocks, and lookup tables that set angles, flip +//! states, XY distances and positions, as AutoCAD applies them: +//! - an action that moves a base point parameter moves the reference's insertion point with it, +//! and the block's objects move back so the parameter stays at the block's base point; +//! - an alignment grip dragged next to an object moves the reference so the alignment's base is on +//! the object and turns it so the alignment runs along the object, its right side toward the +//! cursor; +//! - lookup tables set and read rotation angles (`UpdatedAngle`, radians), flip states +//! (`UpdatedFlip`), XY distances (`UpdatedDistanceX`/`Y`), polar distances and angles and +//! positions (`UpdatedX`/`Y`, from the block's base point). +//! +//! The fixture is synthetic, laid out as AutoCAD writes these blocks: Shift (a 10×5 rectangle left +//! of the origin, Distance1 along its bottom, a stretch of its right side holding the base point +//! parameter, an attribute TAG at (-8, 0); a reference at (100, 100) with its attribute at (92, 100)), +//! Align (a 4×2 rectangle, a perpendicular alignment from the origin along X), Turn (a 4×2 +//! rectangle turned by Angle1 about the origin; Lookup1 gives Up 90°, Left 180°, Zero 0°) and Many +//! (Flip state1, X/Y Distance1, polar Distance1/Angle1 and Position1, all set by Lookup1's rows A +//! and B, B being the block's own values). A line at 30° runs from (120, 100) to (140, 111.547). + +use cadcraft_doc::dynblock::{GripShape, ParameterKind, Value, align_grip, custom_properties, dynamic_block, grips, reference, set_property}; +use cadcraft_doc::geom::{Vec2, Vec3}; +use cadcraft_doc::{Drawing, EntityKind, Handle}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn dxf(src: &str) -> String { + src.lines() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| { + let (code, value) = l.split_once(' ').unwrap_or((l, "")); + format!("{code}\n{value}\n") + }) + .collect() +} + +fn fixture() -> Drawing { + read_dxf(dxf(&include_str!("data/dynblock_params.txt").replace("\r\n", "\n")).as_bytes()).unwrap() +} + +/// The fixture with a reference to `block` at (100, 100) turned by `rotation`. +fn reference_to(block: &str, rotation: f64) -> (Drawing, Handle) { + let mut d = fixture(); + let ins = cadcraft_doc::Insert { + block: block.into(), + insert: Vec3::new(100.0, 100.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + rotation, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + }; + let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + (d, r) +} + +fn props(d: &Drawing, r: Handle) -> Vec<(String, String)> { + custom_properties(d, r).unwrap().1.into_iter().map(|p| (p.name, p.value)).collect() +} + +fn prop(d: &Drawing, r: Handle, name: &str) -> String { + props(d, r).into_iter().find(|(n, _)| n == name).map(|(_, v)| v).unwrap_or_else(|| panic!("no {name}")) +} + +fn round(v: f64) -> f64 { + (v * 1000.0).round() / 1000.0 + 0.0 +} + +fn insert(d: &Drawing, r: Handle) -> &cadcraft_doc::Insert { + let Some(EntityKind::Insert(i)) = d.entity(r).map(|e| &e.kind) else { panic!("a reference") }; + i +} + +/// The reference's polyline corners (lowest and highest) in block coordinates. +fn outline(d: &Drawing, r: Handle) -> [f64; 4] { + let b = d.block(&insert(d, r).block).unwrap(); + let pl = b + .entities + .iter() + .find_map(|e| match &e.kind { + EntityKind::LwPolyline(p) => Some(p), + _ => None, + }) + .unwrap(); + let xs = pl.vertices.iter().map(|v| v.p.x); + let ys = pl.vertices.iter().map(|v| v.p.y); + [ + round(xs.clone().fold(f64::MAX, f64::min)), + round(ys.clone().fold(f64::MAX, f64::min)), + round(xs.fold(f64::MIN, f64::max)), + round(ys.fold(f64::MIN, f64::max)), + ] +} + +fn at(d: &Drawing, r: Handle) -> (f64, f64) { + let i = insert(d, r); + (round(i.insert.x), round(i.insert.y)) +} + +#[test] +fn reads_the_alignment_type_and_shows_its_grip() { + let (d, r) = reference_to("Align", 0.0); + let m = dynamic_block(&d, "Align").unwrap(); + assert!(matches!(m.parameters[0].kind, ParameterKind::Alignment { perpendicular: true, .. })); + let g = grips(&d, r); + let a = g.iter().find(|g| g.shape == GripShape::Alignment).expect("an alignment grip"); + // At the base point, pointing to the left of the alignment's direction (as AutoCAD draws it). + assert_eq!((round(a.at.x), round(a.at.y)), (100.0, 100.0)); + assert_eq!((round(a.dir.x), round(a.dir.y)), (0.0, 1.0)); +} + +#[test] +fn a_moved_base_point_moves_the_insertion_point() { + let mut d = fixture(); + let r = Handle(0xE0); + set_property(&mut d, r, "Distance1", "15").unwrap(); + // Measured in AutoCAD: the reference moves to (105, 100) and its block runs from -15 to 0. + assert_eq!(at(&d, r), (105.0, 100.0)); + assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]); + assert_eq!(prop(&d, r, "Distance1"), "15.0000"); + // The values as AutoCAD records them: the base point at the block's base, the distance moved back. + let v = reference(&d, r).unwrap().values; + assert_eq!(v.get(&1), Some(&Value::Point { at: Vec3::new(0.0, 0.0, 0.0) })); + assert_eq!(v.get(&2), Some(&Value::Points { base: Vec3::new(-15.0, -2.5, 0.0), end: Vec3::new(0.0, -2.5, 0.0) })); + // The attribute stays where it was in the drawing (its definition didn't move). + let a = &insert(&d, r).attribs[0]; + assert_eq!((round(a.text.insert.x), round(a.text.insert.y)), (92.0, 100.0)); + // And back, from there. + set_property(&mut d, r, "Distance1", "12").unwrap(); + assert_eq!(at(&d, r), (102.0, 100.0)); + assert_eq!(outline(&d, r), [-12.0, -2.5, 0.0, 2.5]); + // A save keeps it. + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(at(&back, r), (102.0, 100.0)); + assert_eq!(prop(&back, r, "Distance1"), "12.0000"); +} + +/// AutoCAD takes a distance of 0 (title block value lists offer it); the distance keeps its +/// direction for the next change. +#[test] +fn a_distance_of_0_keeps_its_direction() { + let mut d = fixture(); + let r = Handle(0xE0); + set_property(&mut d, r, "Distance1", "0").unwrap(); + assert_eq!(prop(&d, r, "Distance1"), "0.0000"); + assert_eq!(at(&d, r), (90.0, 100.0)); + set_property(&mut d, r, "Distance1", "15").unwrap(); + assert_eq!(at(&d, r), (105.0, 100.0)); + assert_eq!(outline(&d, r), [-15.0, -2.5, 0.0, 2.5]); + assert!(set_property(&mut d, r, "Distance1", "-1").is_err()); +} + +#[test] +fn a_turned_reference_moves_along_its_own_axis() { + let (mut d, r) = reference_to("Shift", std::f64::consts::FRAC_PI_2); + set_property(&mut d, r, "Distance1", "15").unwrap(); + assert_eq!(at(&d, r), (100.0, 105.0)); +} + +#[test] +fn an_alignment_follows_a_line() { + let line = Vec2::new(30f64.to_radians().cos(), 30f64.to_radians().sin()); + let foot = Vec2::new(120.0, 100.0) + line * 10.0; + // Measured in AutoCAD: from below the line the reference turns to 30°, from above to 210°, its + // alignment's base on the line. + for (side, rotation) in [(-0.5, 30.0), (0.5, 210.0)] { + let (mut d, r) = reference_to("Align", 0.0); + let cursor = foot + line.perp() * side; + align_grip(&mut d, r, 1, cursor, Some((foot, line))).unwrap(); + assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation); + assert_eq!(at(&d, r), (round(foot.x), round(foot.y))); + } +} + +#[test] +fn an_alignment_follows_a_circle() { + // A circle about (150, 150), its nearest point at 225°: outside, the reference turns to 315° + // (counterclockwise along the circle), inside to 135°, as in AutoCAD. + let c = Vec2::new(150.0, 150.0); + let out = Vec2::new(225f64.to_radians().cos(), 225f64.to_radians().sin()); + let foot = c + out * 10.0; + for (r_cursor, rotation) in [(10.5, 315.0), (9.5, 135.0)] { + let (mut d, r) = reference_to("Align", 0.0); + align_grip(&mut d, r, 1, c + out * r_cursor, Some((foot, out.perp()))).unwrap(); + assert_eq!(round(insert(&d, r).rotation.to_degrees()), rotation); + } +} + +#[test] +fn an_alignment_grip_away_from_objects_only_moves() { + let (mut d, r) = reference_to("Align", 0.5); + align_grip(&mut d, r, 1, Vec2::new(90.0, 80.0), None).unwrap(); + assert_eq!(at(&d, r), (90.0, 80.0)); + assert_eq!(insert(&d, r).rotation, 0.5); + // On the object itself, the side the grip came from decides. + let (mut d, r) = reference_to("Align", 0.0); + let line = Vec2::new(1.0, 0.0); + align_grip(&mut d, r, 1, Vec2::new(110.0, 90.0), Some((Vec2::new(110.0, 90.0), line))).unwrap(); + // The grip was above the line (y = 90): its right side faces up, so the alignment runs to -X. + assert_eq!(round(insert(&d, r).rotation.to_degrees()), 180.0); + assert!(align_grip(&mut d, r, 1, Vec2::new(f64::NAN, 0.0), None).is_err()); + assert!(align_grip(&mut d, r, 7, Vec2::new(0.0, 0.0), None).is_err()); +} + +#[test] +fn a_lookup_sets_and_reads_an_angle() { + let (mut d, r) = reference_to("Turn", 0.0); + assert_eq!(prop(&d, r, "Lookup1"), "Zero"); + set_property(&mut d, r, "Lookup1", "Up").unwrap(); + assert_eq!(prop(&d, r, "Angle1"), "90"); + assert_eq!(outline(&d, r), [-2.0, 0.0, 0.0, 4.0]); + // Reverse: an angle in the table gives its row. + set_property(&mut d, r, "Angle1", "180").unwrap(); + assert_eq!(prop(&d, r, "Lookup1"), "Left"); + set_property(&mut d, r, "Angle1", "45").unwrap(); + assert_eq!(prop(&d, r, "Lookup1"), "Custom"); + assert!(custom_properties(&d, r).unwrap().1.iter().any(|p| p.name == "Lookup1" && p.editable)); +} + +#[test] +fn a_lookup_sets_flips_xy_polar_and_positions() { + let (mut d, r) = reference_to("Many", 0.0); + // The block's own values are row B. + assert_eq!(prop(&d, r, "Lookup1"), "B"); + set_property(&mut d, r, "Lookup1", "A").unwrap(); + // As AutoCAD sets them. + for (name, value) in [ + ("Flip state1", "Flipped"), + ("X Distance1", "6.0000"), + ("Y Distance1", "3.0000"), + ("Distance1", "5.0000"), + ("Angle1", "30"), + ("Position1 X", "1.0000"), + ("Position1 Y", "0.5000"), + ("Lookup1", "A"), + ] { + assert_eq!(prop(&d, r, name), value, "{name}"); + } + // The values are recorded as AutoCAD lays them out (it doesn't take the reference otherwise): a + // flip state after its points, and the flip grip's state on its own after two header groups. + let codes: Vec> = d + .foreign + .objects + .iter() + .filter(|o| o.kind == "XRECORD") + .map(|o| o.tags.iter().map(|t| t.code).filter(|c| [10, 70].contains(c)).collect()) + .collect(); + assert!(codes.contains(&vec![10, 10, 70]), "{codes:?}"); + assert!(codes.contains(&vec![70, 70, 70, 70]), "{codes:?}"); + // A save keeps it, and the reverse lookup reads it back. + let back = read_dxf(write_dxf(&d).as_bytes()).unwrap(); + assert_eq!(prop(&back, r, "Lookup1"), "A"); + assert_eq!(prop(&back, r, "Flip state1"), "Flipped"); + // One input off the table's rows: no row matches. + set_property(&mut d, r, "Flip state1", "Not flipped").unwrap(); + assert_eq!(prop(&d, r, "Lookup1"), "Custom"); + set_property(&mut d, r, "Lookup1", "B").unwrap(); + assert_eq!(prop(&d, r, "X Distance1"), "4.0000"); + assert_eq!(prop(&d, r, "Position1 X"), "2.0000"); +} + +#[test] +fn a_lookup_cell_that_isnt_a_number_is_refused() { + let src = include_str!("data/dynblock_params.txt").replace("\r\n", "\n").replace("302 1.570796326794896", "302 up-ish"); + let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); + let ins = cadcraft_doc::Insert { + block: "Turn".into(), + insert: Vec3::new(0.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 r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); + let before = insert(&d, r).block.clone(); + assert!(set_property(&mut d, r, "Lookup1", "Up").is_err()); + assert_eq!(insert(&d, r).block, before); + // The other rows still work, and reading the table doesn't trip on the bad cell. + set_property(&mut d, r, "Lookup1", "Left").unwrap(); + assert_eq!(prop(&d, r, "Angle1"), "180"); +} diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index d265f9e70..246c05b2f 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -301,9 +301,7 @@ fn bad_values_are_refused_and_change_nothing() { let ps = cadcraft_doc::dynblock::custom_properties(&d, h("80")).unwrap().1; let editable: Vec<(&str, bool)> = ps.iter().map(|p| (p.name.as_str(), p.editable)).collect(); assert_eq!(editable, [("Visibility1", true), ("Width", true), ("Size", true)]); - for (name, value) in - [("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "0"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")] - { + for (name, value) in [("Visibility1", "Ajar"), ("Size", "Huge"), ("Width", "wide"), ("Width", "-3"), ("Width", "inf"), ("Nope", "x"), ("", "")] { assert!(cadcraft_doc::dynblock::set_property(&mut d, h("80"), name, value).is_err(), "{name}={value}"); } assert!(cadcraft_doc::dynblock::set_property(&mut d, h("30"), "Visibility1", "Open").is_err(), "not a reference"); diff --git a/crates/ui-egui/src/dyngrips.rs b/crates/ui-egui/src/dyngrips.rs index 1808d573a..0c5b0a9c1 100644 --- a/crates/ui-egui/src/dyngrips.rs +++ b/crates/ui-egui/src/dyngrips.rs @@ -1,8 +1,9 @@ //! Dynamic block grips on the canvas, as AutoCAD shows them on a selected dynamic block //! reference: an arrow at a distance's end (drag it to change the distance), a square at a //! position (drag it to move it), a circle at an angle's end (drag it to turn), an arrow across a -//! reflection line (click it to flip) and a down-pointing triangle for a list (click it for the -//! visibility states or lookup values). Dragging runs the engine's dynamic grip edit +//! reflection line (click it to flip), a down-pointing triangle for a list (click it for the +//! visibility states or lookup values) and a pentagon at an alignment's base point (drag it next to +//! an object to align the reference with it). Dragging runs the engine's dynamic grip edit //! ([`cadcraft_engine::Session::start_dyn_grip`]); a list choice runs `blocks.reference.set`. use std::sync::Arc; @@ -87,6 +88,13 @@ fn outline(xf: &Xf, g: &DynGrip, gs: f32) -> Vec { c - u * tail - n * shaft, ] } + // A square with a point on the side the grip points to (across the alignment direction). + GripShape::Alignment => { + let ahead = xf.to_screen(g.at + g.dir) - c; + let u = if ahead.length() > 1e-6 { ahead / ahead.length() } else { vec2(0.0, -1.0) }; + let n = vec2(-u.y, u.x); + vec![c - u * gs - n * gs, c + u * (gs * 0.2) - n * gs, c + u * (gs * 1.4), c + u * (gs * 0.2) + n * gs, c - u * gs + n * gs] + } } } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 81d5070c3..68a41d4b6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (attribute value edits refresh exported baselines; dynamic block scale and polar stretch actions read) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (attribute value edits refresh exported baselines; dynamic block scale and polar stretch actions read; dynamic block alignment type and lookup columns read; base point moves saved) · **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 @@ -147,6 +147,7 @@ our output in AutoCAD black-box. | 2026-10-19 | minor | A file's own arrowhead blocks with standard names (AutoCAD's `_Dot`, `_DotSmall`), named only by a dimension style, are kept and saved as they were instead of being replaced by CADCraft's solids; PURGE keeps arrowhead blocks dimension styles name | | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | +| 2026-10-20 | minor | Dynamic blocks: alignment type (perpendicular or tangent) and lookup columns of angles, flip states, XY distances and positions read; a moved base point saved as AutoCAD saves it (the block's objects moved back, the reference's insertion point forward); a new reference's flip grip state saved in AutoCAD's layout (AutoCAD dropped the reference's dynamic properties otherwise) | | 2026-10-19 | minor | Dynamic blocks: scale actions (base point, connections) and polar stretch actions (frame, stretched vertices, rotate-only objects) read | | 2026-10-19 | minor | Dynamic blocks: polar and XY parameters (names, value sets, corner grips) and array actions (row and column offsets) read; arrayed copies saved with AutoCAD's `AcDbBlockArrayActionTag`, without which AutoCAD can't change the reference again | | 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) | diff --git a/docs/gaps.md b/docs/gaps.md index 7b03bbf16..aa0e264d2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where CADCraft falls short of AutoCAD -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic block scale and polar stretch actions: F3 updated) · **Target:** Autodesk AutoCAD 2027 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (BEDIT in the Block Editor switches blocks; dynamic block scale and polar stretch actions, base point and alignment parameters, lookups of angles, flips, XY distances and positions: F3 updated) · **Target:** Autodesk AutoCAD 2027 Every known shortfall, one row each, ranked within each section by user impact. This is the work list: agents pick from here (top of a section first), and remove or update a row in the same PR @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch, polar stretch, move, scale, lookups, polar and XY parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| 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, polar stretch, move, scale, lookups of every parameter value, polar, XY, base point and alignment parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -156,6 +156,7 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | +| 2026-10-20 | minor | F3: dynamic block base point parameters (an action that moves one moves the reference's insertion point), alignment grips (onto the nearest object, turned along it) and lookup tables that set and read angles, flip states, XY distances and positions; checked against AutoCAD's output | | 2026-10-19 | minor | F3: dynamic block scale actions (by a distance, or an XY parameter's diagonal) and polar stretch actions (turn, stretch the frame, rotate-only objects) change references as AutoCAD does; checked against AutoCAD's output | | 2026-10-19 | minor | F3: dynamic block polar (Distance1, Angle1) and XY (X Distance1, Y Distance1) parameters in Properties and as grips, and their array actions repeat the objects as AutoCAD does; checked against AutoCAD's output | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | From e265c5cadd82b0f1d5bf6a41f832f6a3aa427d0e Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:01:59 -0600 Subject: [PATCH 041/187] Docs: the dynamic block data row lists base point, alignment and lookup changes Co-Authored-By: Claude Opus 5.5 --- 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 68a41d4b6..c25e0ee66 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); base point and alignment parameters not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block), except that a DWG saved from a drawing with a scale action can't be opened by AutoCAD until #1725 (acadrust 0.6.5) lands: DXF save works | +| Objects: dynamic block data (ACAD_EVALUATION_GRAPH, BLOCK…PARAMETER, BLOCK…ACTION, grips) | read into a model (`dynblock`, `blocks.dynamic`): parameters, visibility states, value sets, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups (of every value AutoCAD puts in them), distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions), polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`), base points (the reference's insertion point moves, as in AutoCAD) and alignments (the grip dragged onto an object) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); DWG open and save keep it too (checked with an AutoCAD dynamic block), except that a DWG saved from a drawing with a scale action can't be opened by AutoCAD until #1725 (acadrust 0.6.5) lands: DXF save works | | 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 From 241cc6a9d46dc6ba3099689aa4e4dc0451cddea9 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:36:07 -0600 Subject: [PATCH 042/187] Docs: the dynamic block data row names the fixed-base rotate and scale limit A rotate or scale action with a fixed base point still acts about where the dynamic block has it after a base point parameter has moved the reference; AutoCAD replays the whole history instead. The PR said so; the row now does. Co-Authored-By: Claude Opus 5.5 --- 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 c25e0ee66..dc31aa879 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups (of every value AutoCAD puts in them), distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions), polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`), base points (the reference's insertion point moves, as in AutoCAD) and alignments (the grip dragged onto an object) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); DWG open and save keep it too (checked with an AutoCAD dynamic block), except that a DWG saved from a drawing with a scale action can't be opened by AutoCAD until #1725 (acadrust 0.6.5) lands: DXF save works | +| Objects: dynamic block data (ACAD_EVALUATION_GRAPH, BLOCK…PARAMETER, BLOCK…ACTION, grips) | read into a model (`dynblock`, `blocks.dynamic`): parameters, visibility states, value sets, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups (of every value AutoCAD puts in them), distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions), polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`), base points (the reference's insertion point moves, as in AutoCAD; a rotate or scale action with a fixed base point still turns or scales about where the dynamic block has it after the base point has moved, where AutoCAD replays the reference's whole history) and alignments (the grip dragged onto an object) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); DWG open and save keep it too (checked with an AutoCAD dynamic block), except that a DWG saved from a drawing with a scale action can't be opened by AutoCAD until #1725 (acadrust 0.6.5) lands: DXF save works | | 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 From db3e14f494b66971d30a386460457d07579595a4 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:51:47 -0600 Subject: [PATCH 043/187] Tests: the base point, alignment and lookup tests join the io test binary Upstream (#1989) builds each crate's tests as one binary; dynblock_params.rs moves into tests/it, and dynamic_grips.rs's new fixture path is one level deeper. Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/it/dynamic_grips.rs | 2 +- crates/io/tests/{ => it}/dynblock_params.rs | 4 ++-- crates/io/tests/it/main.rs | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) rename crates/io/tests/{ => it}/dynblock_params.rs (98%) diff --git a/crates/engine/tests/it/dynamic_grips.rs b/crates/engine/tests/it/dynamic_grips.rs index e95c4825a..7f48d8528 100644 --- a/crates/engine/tests/it/dynamic_grips.rs +++ b/crates/engine/tests/it/dynamic_grips.rs @@ -178,7 +178,7 @@ fn a_grip_with_a_value_list_marks_its_stops_while_dragged() { /// away from objects it only moves. #[test] fn an_alignment_grip_aligns_with_the_line_at_the_cursor() { - let src = include_str!("../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n"); + let src = include_str!("../../../io/tests/data/dynblock_params.txt").replace("\r\n", "\n"); let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap(); let mut s = Session::empty(); s.open_drawing(d, "params", None); diff --git a/crates/io/tests/dynblock_params.rs b/crates/io/tests/it/dynblock_params.rs similarity index 98% rename from crates/io/tests/dynblock_params.rs rename to crates/io/tests/it/dynblock_params.rs index c0a2275e3..78e309dfd 100644 --- a/crates/io/tests/dynblock_params.rs +++ b/crates/io/tests/it/dynblock_params.rs @@ -34,7 +34,7 @@ fn dxf(src: &str) -> String { } fn fixture() -> Drawing { - read_dxf(dxf(&include_str!("data/dynblock_params.txt").replace("\r\n", "\n")).as_bytes()).unwrap() + read_dxf(dxf(&include_str!("../data/dynblock_params.txt").replace("\r\n", "\n")).as_bytes()).unwrap() } /// The fixture with a reference to `block` at (100, 100) turned by `rotation`. @@ -262,7 +262,7 @@ fn a_lookup_sets_flips_xy_polar_and_positions() { #[test] fn a_lookup_cell_that_isnt_a_number_is_refused() { - let src = include_str!("data/dynblock_params.txt").replace("\r\n", "\n").replace("302 1.570796326794896", "302 up-ish"); + let src = include_str!("../data/dynblock_params.txt").replace("\r\n", "\n").replace("302 1.570796326794896", "302 up-ish"); let mut d = read_dxf(dxf(&src).as_bytes()).unwrap(); let ins = cadcraft_doc::Insert { block: "Turn".into(), diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 069b9991c..a138eba57 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -23,6 +23,7 @@ mod dwg_roundtrip_losses; mod dwt_template; mod dxf_versions; mod dynblock_array; +mod dynblock_params; mod dynblock_read; mod dynblock_rotate_flip; mod dynblock_scale_polar; From 5e8d4e7f399bda6fc5120e442ed0e2ceae883f03 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:57:19 -0600 Subject: [PATCH 044/187] Snap: gather_in takes the object to skip, like its siblings' argument lists Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/snap.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 154ef5b85..258f710e2 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -441,6 +441,7 @@ pub(crate) fn nearest_with_direction(d: &Drawing, space: &Space, cursor: Vec2, a best.map(|(_, at, dir)| (at, dir)) } +#[allow(clippy::too_many_arguments)] fn gather_in( d: &Drawing, space: &Space, From 41d20af874eeb5f6c0329b7964a9095035126708 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:17:39 -0600 Subject: [PATCH 045/187] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/file-format-parity.md | 5 +---- docs/gaps.md | 5 +---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 8f5d5ec20..d85415123 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); base point and alignment parameters not yet; DWG open and save keep it too (checked with an AutoCAD dynamic block), except that a DWG saved from a drawing with a scale action can't be opened by AutoCAD until #1725 (acadrust 0.6.5) lands: DXF save works | +| 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) | | 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 @@ -149,10 +149,7 @@ our output in AutoCAD black-box. | 2026-10-19 | minor | Pre-2007 DXF saves write text in the file's code page (`Ação` as ANSI_1252 bytes, not `A\U+00E7\U+00E3o`); characters outside it stay `\U+` escapes | | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | -| 2026-10-19 | minor | Dynamic blocks: scale actions (base point, connections) and polar stretch actions (frame, stretched vertices, rotate-only objects) read | -| 2026-10-19 | minor | Dynamic blocks: polar and XY parameters (names, value sets, corner grips) and array actions (row and column offsets) read; arrayed copies saved with AutoCAD's `AcDbBlockArrayActionTag`, without which AutoCAD can't change the reference again | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | -| 2026-10-13 | minor | Dynamic blocks: rotation and flip parameters and actions read; changed references saved with AutoCAD's value records and history (flip state after the points, flip grip state) | | 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 103f1523c..f8ddac941 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch, polar stretch, move, scale, lookups, polar and XY parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -157,8 +157,6 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-19 | minor | F3: dynamic block scale actions (by a distance, or an XY parameter's diagonal) and polar stretch actions (turn, stretch the frame, rotate-only objects) change references as AutoCAD does; checked against AutoCAD's output | -| 2026-10-19 | minor | F3: dynamic block polar (Distance1, Angle1) and XY (X Distance1, Y Distance1) parameters in Properties and as grips, and their array actions repeat the objects as AutoCAD does; checked against AutoCAD's output | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | @@ -169,7 +167,6 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-15 | minor | BREAKLINE (Tools ▸ Express Tools ▸ Break-line Symbol): one polyline between two points with a break symbol, Block/Size/Extension options, size times DIMSCALE: E3 narrowed | | 2026-10-15 | minor | TXT2MTXT (Tools ▸ Express Tools ▸ Convert Text to Mtext): selected TEXT, and MTEXT, combined into one MTEXT top-down or in selection order with optional word wrap, or one MTEXT per TEXT; SEttings remembered for the session: E3 narrowed | | 2026-10-13 | minor | Selection window gesture preference (PICKDRAG 0/2) added to Options ▸ Selection and saved in the profile (U6), with Portuguese and Ukrainian labels | -| 2026-10-13 | minor | F3: dynamic block rotation and flip parameters (Angle1, Flip state1) with their rotate and flip actions, Properties and grips; checked against AutoCAD's output | | 2026-10-12 | minor | Object transparency (entity, ByLayer, ByBlock) is drawn: on screen (TRANSPARENCYDISPLAY, on by default), in PNG/SVG exports, and in plots when the page setup's "Plot transparency" is on (PDF alpha, PNG blending, SVG opacity; PLOTTRANSPARENCYOVERRIDE): F14 narrowed | | 2026-10-12 | minor | Hatch and Gradient dialog (HATCH, GRADIENT; HPDLGMODE) and Hatch Edit dialog (HATCHEDIT, right-click, double-click a hatch): F13 narrowed to Preview, Inherit Properties and boundary add/remove in edit mode | | 2026-10-12 | minor | A bare system variable name typed at the command line (ORTHOMODE, GRIDMODE…) runs SETVAR on that variable, as in AutoCAD; U10 narrowed | From 2513204737acda7a5330cc013a8c78ad7f7e985c Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:17:43 -0600 Subject: [PATCH 046/187] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/file-format-parity.md | 4 +--- docs/gaps.md | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index a2c4e6896..d85415123 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups, distances and positions (stretch and move actions), angles (rotate actions), flip states (flip actions) and polar and XY parameters' values (array actions, their copies tagged `AcDbBlockArrayActionTag`) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); scale and polar stretch actions, base point and alignment parameters 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, 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) | | 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 @@ -149,9 +149,7 @@ our output in AutoCAD black-box. | 2026-10-19 | minor | Pre-2007 DXF saves write text in the file's code page (`Ação` as ANSI_1252 bytes, not `A\U+00E7\U+00E3o`); characters outside it stay `\U+` escapes | | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | -| 2026-10-19 | minor | Dynamic blocks: polar and XY parameters (names, value sets, corner grips) and array actions (row and column offsets) read; arrayed copies saved with AutoCAD's `AcDbBlockArrayActionTag`, without which AutoCAD can't change the reference again | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | -| 2026-10-13 | minor | Dynamic blocks: rotation and flip parameters and actions read; changed references saved with AutoCAD's value records and history (flip state after the points, flip grip state) | | 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 d24aae98a..f8ddac941 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, polar and XY parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -157,7 +157,6 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-19 | minor | F3: dynamic block polar (Distance1, Angle1) and XY (X Distance1, Y Distance1) parameters in Properties and as grips, and their array actions repeat the objects as AutoCAD does; checked against AutoCAD's output | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | @@ -168,7 +167,6 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-15 | minor | BREAKLINE (Tools ▸ Express Tools ▸ Break-line Symbol): one polyline between two points with a break symbol, Block/Size/Extension options, size times DIMSCALE: E3 narrowed | | 2026-10-15 | minor | TXT2MTXT (Tools ▸ Express Tools ▸ Convert Text to Mtext): selected TEXT, and MTEXT, combined into one MTEXT top-down or in selection order with optional word wrap, or one MTEXT per TEXT; SEttings remembered for the session: E3 narrowed | | 2026-10-13 | minor | Selection window gesture preference (PICKDRAG 0/2) added to Options ▸ Selection and saved in the profile (U6), with Portuguese and Ukrainian labels | -| 2026-10-13 | minor | F3: dynamic block rotation and flip parameters (Angle1, Flip state1) with their rotate and flip actions, Properties and grips; checked against AutoCAD's output | | 2026-10-12 | minor | Object transparency (entity, ByLayer, ByBlock) is drawn: on screen (TRANSPARENCYDISPLAY, on by default), in PNG/SVG exports, and in plots when the page setup's "Plot transparency" is on (PDF alpha, PNG blending, SVG opacity; PLOTTRANSPARENCYOVERRIDE): F14 narrowed | | 2026-10-12 | minor | Hatch and Gradient dialog (HATCH, GRADIENT; HPDLGMODE) and Hatch Edit dialog (HATCHEDIT, right-click, double-click a hatch): F13 narrowed to Preview, Inherit Properties and boundary add/remove in edit mode | | 2026-10-12 | minor | A bare system variable name typed at the command line (ORTHOMODE, GRIDMODE…) runs SETVAR on that variable, as in AutoCAD; U10 narrowed | From 309c9023297fc1157ba80cd5ec474cbe71f445ea Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:19:04 -0600 Subject: [PATCH 047/187] Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them) Co-Authored-By: Claude Sonnet 5.5 --- docs/file-format-parity.md | 6 +----- docs/gaps.md | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0e6541b89..d85415123 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -98,7 +98,7 @@ on read with a note, so such files no longer exceed the DXF limit (#1482). **DWG | Objects: GROUP, MLINESTYLE, MLEADERSTYLE, IMAGEDEF, SCALE | yes | yes (groups #417, scale list #468) | | | Objects: VISUALSTYLE, PLOTSETTINGS, materials, field objects and other unmodelled objects | kept raw (#528) | written back as read; a proxy object (ACAD_PROXY_OBJECT) keeps its class: its group 91 is renumbered to the written CLASSES, which keep the class it names, and one whose number names no class is dropped (#1812) | not editable | | 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, 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: its value records, a flip's state after its points, and its history) | visibility states, lookups (of every value AutoCAD puts in them), distances and positions (stretch, move, scale and polar stretch actions), angles (rotate actions), flip states (flip actions), polar and XY parameters' values (array and scale actions, array copies tagged `AcDbBlockArrayActionTag`), base points (the reference's insertion point moves, as in AutoCAD; a rotate or scale action with a fixed base point still turns or scales about where the dynamic block has it after the base point has moved, where AutoCAD replays the reference's whole history) and alignments (the grip dragged onto an object) can be changed (`blocks.reference.set`, Properties ▸ Custom, grips); DWG open and save keep it too (checked with an AutoCAD dynamic block), except that a DWG saved from a drawing with a scale action can't be opened by AutoCAD until #1725 (acadrust 0.6.5) lands: DXF save works | +| 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) | | 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 @@ -149,11 +149,7 @@ our output in AutoCAD black-box. | 2026-10-19 | minor | Pre-2007 DXF saves write text in the file's code page (`Ação` as ANSI_1252 bytes, not `A\U+00E7\U+00E3o`); characters outside it stay `\U+` escapes | | 2026-10-20 | minor | DIMENSION: the `*D` block's MTEXT, and the MTEXT EXPLODE leaves, hold the diameter sign as `%%c` instead of the decoded U+2300, which no SHX font has, so other programs plotted diameter dimensions in an SHX style without the sign (#1645) | | 2026-10-21 | minor | Proxy objects and entities keep their class through a save: group 91 renumbered to the written CLASSES (the class it names is kept), a proxy whose number names no class dropped (#1812) | -| 2026-10-20 | minor | Dynamic blocks: alignment type (perpendicular or tangent) and lookup columns of angles, flip states, XY distances and positions read; a moved base point saved as AutoCAD saves it (the block's objects moved back, the reference's insertion point forward); a new reference's flip grip state saved in AutoCAD's layout (AutoCAD dropped the reference's dynamic properties otherwise) | -| 2026-10-19 | minor | Dynamic blocks: scale actions (base point, connections) and polar stretch actions (frame, stretched vertices, rotate-only objects) read | -| 2026-10-19 | minor | Dynamic blocks: polar and XY parameters (names, value sets, corner grips) and array actions (row and column offsets) read; arrayed copies saved with AutoCAD's `AcDbBlockArrayActionTag`, without which AutoCAD can't change the reference again | | 2026-10-17 | minor | DWG read: DGN line style components no line style definition reaches are left out before the DXF bridge, with a read note; an 83 MB site plan with 888,483 of them (1.2 GB of DXF, over the limit) now opens (#1482) | -| 2026-10-13 | minor | Dynamic blocks: rotation and flip parameters and actions read; changed references saved with AutoCAD's value records and history (flip state after the points, flip grip state) | | 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 95a5d8c74..f8ddac941 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -26,7 +26,7 @@ do them first. |---|---|---|---|---| | F1 | **[alpha blocker]** Prompt options that still print "not available yet": -ATTEDIT one-at-a-time Position, Height, Angle and Style, colour books in -ATTEDIT Color, -RENAME of materials, plot styles and viewport configurations. SPLINEDIT Join, Edit vertex Add and Elevate order (#559), PEDIT Edit vertex and the other SPLINEDIT options (#558) done: Edit vertex Tangent directions last for the PEDIT session only (LWPOLYLINE stores none). MTEXT Dynamic/Static columns done (#547). SPLINE, MTEXT and MLEADER options done (#408): SPLINE Object fits the polyline's vertices (no spline frame is kept) (STRETCH polygon, CP and WP, and fence selection done; TRIM/EXTEND, PLINE arc mode and Length, XLINE done (#397); OFFSET, ROTATE and FILLET options done earlier) | `cmd/blocks/attedit.rs`, `cmd/props/rename.rs` | Low: the most-used commands are done | 1–3 | | F2 | XREF editing in place and clipping: XCLIP is missing. REFEDIT, REFSET and REFCLOSE edit a block reference in place (working set, faded rest of the block, everything else locked, save or discard; #813); left: editing an xref in place (its source drawing is not written back; XOPEN opens it), picking nested references, a dimmed look for the locked drawing and a banner with Save and Discard, attribute sync of other references (ATTSYNC). XATTACH, the External References palette, -XREF (Bind/Detach/Path/Unload/Reload/Overlay), XBIND, XOPEN, overlays, relative paths and loading at open are done (#525). Unloaded state and xref-layer overrides last only for the session | `cmd/blocks/xref.rs` | Medium: xrefs can't be edited in place or clipped | 15–25 | -| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch, polar stretch, move, scale, lookups of every parameter value, polar, XY, base point and alignment parameters, arrays, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | +| F3 | **[alpha blocker]** (dynamic-block authoring is beta) No dynamic-block authoring: parameters and actions can't be added in the Block Editor. Dynamic blocks from other files are read and their references edited (visibility, distances, stretch and move, lookups, grips). BEDIT (with the Edit Block Definition dialog, which also starts new blocks and, in the Block Editor, switches to another block after asking to save), BSAVE, BSAVEAS and BCLOSE edit a static block definition, and every reference updates; REFEDIT edits a reference in place; no authoring palettes yet | issue #185 offers help | High: standard libraries are dynamic | 40–65 | | F4 | Autosave leftovers: no autosave in the web build (browser storage); autosave files are DXF, not DWG; no separate RECOVER mode in the file readers (SAVETIME, Drawing Recovery, AUDIT and RECOVER landed with #406; AUDITCTL `.adt` log landed) | `engine/src/autosave.rs`, `engine/src/audit.rs` | Low-medium (web users) | 2–4 | | F5 | Associative arrays (ASsociative, Levels, polar ROWs, ARRAYEDIT, ARRAYCLOSE) landed (#448); left: grip editing of arrays (count/spacing grips), ARRAYPATH is not associative, ARRAYEDIT has no item deletion (CTRL+click) and no Key point base points, levels only shift Z (no 3D view) | `cmd/array.rs`, `cmd/array/edit.rs` | Medium | 4–6 | | F7 | Dimensions: no DIMSTYLE manager dialog; no smart DIM; DIMALTTD/DIMALTTZ, DIMUPT and DIMTXTDIRECTION not modelled; jog height and break size not style settings; DIMBREAK breaks don't follow moved objects; with DIMTFILL 1 the written `*D` block and EXPLODE keep no background mask (a WIPEOUT over the text box would), and a true-color DIMTFILLCLR is written to DXF as the nearest ACI (style variables, DIMJOGGED, DIMJOGLINE, DIMBREAK, DIMEDIT, DIMINSPECT and QDIM modes done, #507; the DIMTFILL/DIMTFILLCLR text background done) | `doc/src/tables.rs`, `cmd/annotate_dimedit.rs`, `cmd/annotate_qdim.rs` | Medium | 10–15 | @@ -157,9 +157,6 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-24 | minor | COMPAREEXPORT (typed, or Export on the comparison bar) opens the comparison as a new untitled drawing, `compare_ vs .dwg`: this drawing's objects in one group and the other drawing's differing objects in a second group, in the comparison colors (green, red, gray for objects in both), block contents and style colors included: F22 narrowed | | 2026-10-24 | minor | DIMTFILL and DIMTFILLCLR: a dimension's text background (none, the drawing's background color, or a color) hides what is drawn under the text; SETVAR, DIMOVERRIDE and style fields, DIMSTYLE groups 69 and 70 in DXF from R2007 (CADCraft xdata before), and a SOLID in the `*D` block and from EXPLODE for DIMTFILL 2: F7 narrowed | | 2026-10-22 | minor | APPLOAD typed or from Tools ▸ Load Application opens a `.lsp` file browser starting in the last-used folder (kept in the preferences); a picked file loads interactively like a typed name (routines that ask for input wait), the web says to drop the file (no file system), and the JSON form `{path}` reads the path as given and returns the commands the file defined, never opening a dialog (#1820): E1 narrowed | -| 2026-10-20 | minor | F3: dynamic block base point parameters (an action that moves one moves the reference's insertion point), alignment grips (onto the nearest object, turned along it) and lookup tables that set and read angles, flip states, XY distances and positions; checked against AutoCAD's output | -| 2026-10-19 | minor | F3: dynamic block scale actions (by a distance, or an XY parameter's diagonal) and polar stretch actions (turn, stretch the frame, rotate-only objects) change references as AutoCAD does; checked against AutoCAD's output | -| 2026-10-19 | minor | F3: dynamic block polar (Distance1, Angle1) and XY (X Distance1, Y Distance1) parameters in Properties and as grips, and their array actions repeat the objects as AutoCAD does; checked against AutoCAD's output | | 2026-10-16 | minor | ALIASEDIT typed or from Tools ▸ Customize opens the Command Aliases dialog (user aliases next to the built-in ones; Add, Edit, Remove; OK, Cancel, Apply), #1381: U12 and E5 narrowed | | 2026-10-16 | minor | MOCORO (Tools ▸ Express Tools ▸ Move/Copy/Rotate): select objects and a base point once, then Move, Copy, Rotate, Scale, Base and Undo until eXit, one undo step; JSON form `{base, ops}`: E3 narrowed | | 2026-10-16 | minor | MLEDIT Merged Tee (MT): the first multiline's outer elements stop at the second one's near side, which opens, and its inner elements run on to the second one's inner element: F21 narrowed, hours unchanged | @@ -170,7 +167,6 @@ Detail: [localization-parity.md](localization-parity.md). | 2026-10-15 | minor | BREAKLINE (Tools ▸ Express Tools ▸ Break-line Symbol): one polyline between two points with a break symbol, Block/Size/Extension options, size times DIMSCALE: E3 narrowed | | 2026-10-15 | minor | TXT2MTXT (Tools ▸ Express Tools ▸ Convert Text to Mtext): selected TEXT, and MTEXT, combined into one MTEXT top-down or in selection order with optional word wrap, or one MTEXT per TEXT; SEttings remembered for the session: E3 narrowed | | 2026-10-13 | minor | Selection window gesture preference (PICKDRAG 0/2) added to Options ▸ Selection and saved in the profile (U6), with Portuguese and Ukrainian labels | -| 2026-10-13 | minor | F3: dynamic block rotation and flip parameters (Angle1, Flip state1) with their rotate and flip actions, Properties and grips; checked against AutoCAD's output | | 2026-10-12 | minor | Object transparency (entity, ByLayer, ByBlock) is drawn: on screen (TRANSPARENCYDISPLAY, on by default), in PNG/SVG exports, and in plots when the page setup's "Plot transparency" is on (PDF alpha, PNG blending, SVG opacity; PLOTTRANSPARENCYOVERRIDE): F14 narrowed | | 2026-10-12 | minor | Hatch and Gradient dialog (HATCH, GRADIENT; HPDLGMODE) and Hatch Edit dialog (HATCHEDIT, right-click, double-click a hatch): F13 narrowed to Preview, Inherit Properties and boundary add/remove in edit mode | | 2026-10-12 | minor | A bare system variable name typed at the command line (ORTHOMODE, GRIDMODE…) runs SETVAR on that variable, as in AutoCAD; U10 narrowed | From 34d889619c5e42e4e0fb93e70ac7e1fa6069f903 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:18:48 -0600 Subject: [PATCH 048/187] Tests: the DWG scale action test matches the Scale struct variant Co-Authored-By: Claude Sonnet 5.5 --- crates/io/tests/it/dynblock_read.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/tests/it/dynblock_read.rs b/crates/io/tests/it/dynblock_read.rs index 189a2305b..c84d4189f 100644 --- a/crates/io/tests/it/dynblock_read.rs +++ b/crates/io/tests/it/dynblock_read.rs @@ -110,7 +110,7 @@ fn a_scale_action_survives_a_dwg_save() { use acadrust::objects::{DynamicBlockData, DynamicBlockObject, ObjectType}; let d = read_dxf(dxf(&with_scale_action()).as_bytes()).unwrap(); let before = dynamic_block(&d, "Door").unwrap(); - assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale)), "{:?}", before.actions); + assert!(before.actions.iter().any(|a| a.node == 7 && matches!(a.kind, ActionKind::Scale { .. })), "{:?}", before.actions); let dwg = cadcraft_io::write(&d, "x.dwg").unwrap(); let doc = acadrust::DwgReader::from_stream(std::io::Cursor::new(&dwg)).read().unwrap(); From 0829bfa0eb30407bf73e5330880696fb6199ea89 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:10:41 +0100 Subject: [PATCH 049/187] feat(io, render): draw the proxy graphics of ACAD_PROXY_ENTITY (#2646) An ACAD_PROXY_ENTITY carries the picture its application left for programs without it (groups 92/160 and 310); AutoCAD draws it with PROXYSHOW 1. CADCraft read these entities but drew nothing, so AutoCAD Mechanical balloons, notes and the like were missing from screen, plots and extents. - doc: a decoder for the proxy graphics (ODA DWG specification, "Proxy Entity Graphics") into read-only entities: circles, arcs, polylines, filled polygons (solid hatch), TEXT/TEXT2 and their Unicode forms, colour, layer, linetype, lineweight, ltscale, fill and model matrices. Bounds-checked, with capped sizes and counts. TEXT2 draws the number of characters its length field gives. - io: Unknown gets `graphics`, filled for ACAD_PROXY_ENTITY while the DXF (and so the DWG bridge) is read. The graphics index layers and linetypes by the file's table order, which the reader keeps; CADCraft's own tables are ordered differently. The raw tags are written back unchanged. - render, extents, prims: the graphics draw and measure like block contents (layer 0 and ByBlock are the proxy's own), and can be picked. --- crates/doc/src/entity.rs | 10 +- crates/doc/src/entity/proxy.rs | 668 ++++++++++++++++++ crates/doc/src/extents.rs | 10 + crates/engine/tests/save_reports_not_saved.rs | 8 +- crates/io/src/dxf_read.rs | 3 + crates/io/src/dxf_read/entities.rs | 5 + crates/io/src/dxf_read/tables.rs | 5 + crates/io/src/roundtrip/tests.rs | 8 +- crates/io/tests/it/acis_data_store.rs | 2 +- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/proxy_graphics.rs | 134 ++++ crates/io/tests/it/roundtrip/unknown.rs | 2 +- crates/render/src/blocks.rs | 16 + crates/render/src/draw.rs | 3 +- crates/render/src/tests.rs | 25 + crates/ui-egui/tests/save_loss.rs | 2 +- 16 files changed, 892 insertions(+), 10 deletions(-) create mode 100644 crates/doc/src/entity/proxy.rs create mode 100644 crates/io/tests/it/proxy_graphics.rs diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index a516137fa..ac12de19b 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -43,6 +43,7 @@ mod curves; mod dim; mod fill; mod layout; +mod proxy; mod text; mod wipeout; @@ -52,12 +53,18 @@ pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, Polyface pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader}; pub use fill::{Gradient, Hatch, HatchLoop}; pub use layout::{Image, Table, TableCell, Viewport}; +pub use proxy::{ProxyTables, proxy_entities}; pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign}; pub use wipeout::Wipeout; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Unknown { pub dxf_type: String, pub tags: Vec, + /// What an ACAD_PROXY_ENTITY draws: its proxy graphics as read-only entities, made when the + /// drawing is read (the graphics refer to table rows by their place in the file). Drawn and + /// measured like block contents; saving writes `tags` unchanged. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub graphics: Vec, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -257,7 +264,8 @@ 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())], - EntityKind::Unknown(_) => Vec::new(), + // What its proxy graphics draw, so a proxy can be picked and snapped to. + EntityKind::Unknown(u) => u.graphics.iter().flat_map(|g| g.kind.prims()).collect(), } } diff --git a/crates/doc/src/entity/proxy.rs b/crates/doc/src/entity/proxy.rs new file mode 100644 index 000000000..e4a45649d --- /dev/null +++ b/crates/doc/src/entity/proxy.rs @@ -0,0 +1,668 @@ +//! The proxy graphics an ACAD_PROXY_ENTITY carries (DXF groups 92/160 and 310): the picture +//! the owning application left for programs that don't have it, drawn as AutoCAD draws it with +//! PROXYSHOW 1. The layout follows the Open Design Alliance's public DWG specification +//! ("Proxy Entity Graphics"): a header (total size, chunk count), then chunks of (size, type, +//! data), sizes in bytes including the 8-byte chunk header, all little-endian. +//! +//! The picture becomes ordinary, read-only entities: drawn and measured like the contents of a +//! block, with layer 0, ByBlock colour, linetype and lineweight standing for the proxy's own +//! until a chunk sets them. Chunks CADCraft doesn't decode (meshes, shells, lightweight +//! polylines, materials) are skipped. + +use super::{Arc, Circle, Common, Entity, EntityKind, Handle, Hatch, HatchLoop, Line, Lineweight, LwPolyline, Text, Unknown}; +use cadcraft_color::{Color, Rgb}; +use cadcraft_geom::{PolyVertex, Vec2, Vec3}; + +/// Bytes of proxy graphics read at most from one entity. +const MAX_BYTES: usize = 16 << 20; +/// Entities made at most from one entity's proxy graphics. +const MAX_ENTITIES: usize = 100_000; +/// Vertices read at most from one polyline or polygon chunk. +const MAX_VERTICES: usize = 1_000_000; +/// Matrices pushed at most. +const MAX_MATRICES: usize = 64; + +/// The table names proxy graphics refer to by index, in the order of the file's tables. +#[derive(Clone, Debug, Default)] +pub struct ProxyTables { + /// LAYER records in file order. + pub layers: Vec, + /// LTYPE records in file order, without ByBlock and ByLayer (indices count only the others). + pub linetypes: Vec, + /// Text styles (name, font file) in file order: a text chunk names its font, and the first + /// style with that font draws it. + pub styles: Vec<(String, String)>, +} + +impl Unknown { + /// The proxy graphics bytes of an ACAD_PROXY_ENTITY: the 310 groups after its size group + /// (92, or 160 in newer files), cut to that size. Empty for other records, for an entity + /// without graphics and for one whose data isn't hex. + pub fn proxy_graphics_bytes(&self) -> Vec { + if !self.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") { + return Vec::new(); + } + let Some(at) = self.tags.iter().position(|t| t.code == 92 || t.code == 160) else { return Vec::new() }; + let size = self.tags.get(at).and_then(|t| t.value.trim().parse::().ok()).unwrap_or(0).min(MAX_BYTES); + let mut out = Vec::with_capacity(size); + for t in self.tags.iter().skip(at + 1).take_while(|t| t.code == 310) { + // Damaged data draws nothing rather than a picture cut at a guess. + if !push_hex(&mut out, &t.value) { + return Vec::new(); + } + if out.len() >= size { + break; + } + } + out.truncate(size); + out + } +} + +/// Append the bytes of hex string `s`. False on a character that isn't a hex digit. +fn push_hex(out: &mut Vec, s: &str) -> bool { + let digits: Vec = s.trim().bytes().collect(); + for pair in digits.chunks(2) { + let (Some(&hi), Some(&lo)) = (pair.first(), pair.get(1)) else { return false }; + let (Some(hi), Some(lo)) = ((hi as char).to_digit(16), (lo as char).to_digit(16)) else { return false }; + out.push((hi * 16 + lo) as u8); + } + true +} + +/// The entities the proxy graphics `bytes` draw, all with `handle` (the proxy's): selecting one +/// selects the proxy. +pub fn proxy_entities(bytes: &[u8], tables: &ProxyTables, handle: Handle) -> Vec { + let mut r = Decoder { + tables, + handle, + pen: Common { layer: "0".into(), color: Color::ByBlock, linetype: "ByBlock".into(), lineweight: Lineweight::ByBlock, ..Common::default() }, + fill: false, + matrices: Vec::new(), + out: Vec::new(), + }; + let mut at = 8; + while let (Some(size), Some(kind)) = (u32_at(bytes, at), u32_at(bytes, at + 4)) { + let size = size as usize; + if size < 8 || r.out.len() >= MAX_ENTITIES { + break; + } + let Some(data) = bytes.get(at + 8..at.saturating_add(size)) else { break }; + r.chunk(kind, data); + at += size; + } + r.out +} + +struct Decoder<'a> { + tables: &'a ProxyTables, + handle: Handle, + /// Layer, colour, linetype and lineweight for the entities that follow. + pen: Common, + fill: bool, + /// Model transforms pushed by PUSH_MATRIX, innermost last (row-major 3x4 of the 4x4). + matrices: Vec<[f64; 12]>, + out: Vec, +} + +impl Decoder<'_> { + fn chunk(&mut self, kind: u32, data: &[u8]) { + let mut b = Bytes { data, at: 0 }; + match kind { + // CIRCLE: centre, radius, normal. + 2 => { + if let (Some(c), Some(r)) = (b.point(), b.f64()) { + self.circle(c, r); + } + } + // CIRCLE_3P: three points on it. + 3 => { + if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) + && let Some((c, r)) = circle_through(self.xy(p1), self.xy(p2), self.xy(p3)) + { + self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r })); + } + } + // CIRCULAR_ARC: centre, radius, normal, start vector, sweep angle (around the normal). + 4 => { + if let (Some(c), Some(r), Some(n), Some(v), Some(sweep)) = (b.point(), b.f64(), b.point(), b.point(), b.f64()) { + self.arc(c, r, n, v, sweep); + } + } + // CIRCULAR_ARC_3P: start, a point on the arc, end. + 5 => { + if let (Some(p1), Some(p2), Some(p3)) = (b.point(), b.point(), b.point()) { + self.arc_3p(self.xy(p1), self.xy(p2), self.xy(p3)); + } + } + // POLYLINE and POLYGON: a count, then the points. + 6 | 7 => { + let Some(n) = b.u32() else { return }; + let n = (n as usize).min(MAX_VERTICES); + let pts: Vec = (0..n).map_while(|_| b.point()).map(|p| self.xy(p)).collect(); + self.polyline(pts, kind == 7); + } + // TEXT: position, normal, direction, height, width factor, oblique, string. + 10 => { + if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) { + let s = b.string(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() }); + } + } + // TEXT2: position, normal, direction, string, length (the characters drawn), raw + // flag, height, width factor, oblique, tracking, five style flags, font, big font. + 11 => { + if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) { + let s = b.string(); + let s = first_chars(s, b.u32()); + b.skip(4); + if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) { + b.skip(8 + 20); + let font = b.string(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font }); + } + } + } + // UNICODE_TEXT: as TEXT with a UTF-16 string. + 36 => { + if let (Some(p), Some(_), Some(dir), Some(h), Some(w), Some(o)) = (b.point(), b.point(), b.point(), b.f64(), b.f64(), b.f64()) { + let s = b.unicode(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font: String::new() }); + } + } + // UNICODE_TEXT2: as TEXT2 with UTF-16 strings, and bold, italic, charset, pitch and + // the typeface before the font file. + 38 => { + if let (Some(p), Some(_), Some(dir)) = (b.point(), b.point(), b.point()) { + let s = b.unicode(); + let s = first_chars(s, b.u32()); + b.skip(4); + if let (Some(h), Some(w), Some(o)) = (b.f64(), b.f64(), b.f64()) { + b.skip(8 + 20 + 16); + let _typeface = b.unicode(); + let font = b.unicode(); + self.text(TextChunk { p, dir, height: h, width: w, oblique: o, value: s, font }); + } + } + } + // ATTRIBUTE_COLOR: ACI, 0 ByBlock, 256 ByLayer. + 14 => { + if let Some(c) = b.u32() { + self.pen.color = Color::from_aci(i16::try_from(c).unwrap_or(256)); + } + } + // ATTRIBUTE_LAYER: index into the layer table; an index past it leaves the layer. + 16 => { + if let Some(name) = b.u32().and_then(|i| self.tables.layers.get(i as usize)) { + self.pen.layer = name.clone(); + } + } + // ATTRIBUTE_LINETYPE: index into the linetypes other than ByBlock and ByLayer; + // 32766 is ByBlock, 32767 and anything past the table ByLayer. + 18 => { + if let Some(i) = b.u32() { + self.pen.linetype = match i { + 32766 => "ByBlock".into(), + _ => self.tables.linetypes.get(i as usize).cloned().unwrap_or_else(|| "ByLayer".into()), + }; + } + } + // ATTRIBUTE_FILL: the next polygon is filled. + 20 => self.fill = b.u32().is_some_and(|f| f != 0), + // ATTRIBUTE_TRUE_COLOR: a colour with its method in the top byte. + 22 => { + if let Some(v) = b.u32() { + self.pen.color = match v >> 24 { + 0xC0 => Color::ByLayer, + 0xC1 => Color::ByBlock, + 0xC2 => Color::True(Rgb::from_u32(v & 0x00FF_FFFF)), + 0xC3 => Color::from_aci((v & 0xFF) as i16), + _ => self.pen.color, + }; + } + } + // ATTRIBUTE_LINEWEIGHT: hundredths of a millimetre, or -1 ByLayer, -2 ByBlock, + // -3 the default. + 23 => { + if let Some(v) = b.u32() { + self.pen.lineweight = Lineweight::from_dxf(i16::try_from(v as i32).unwrap_or(-1)); + } + } + // ATTRIBUTE_LTSCALE. + 24 => { + if let Some(s) = b.f64().filter(|s| s.is_finite() && *s > 0.0) { + self.pen.ltscale = s; + } + } + // PUSH_MATRIX, PUSH_MATRIX2: a 4x4 model transform for what follows; POP_MATRIX. + 29 | 30 => { + let m: Vec = (0..16).map_while(|_| b.f64()).collect(); + if let Some(m) = m.get(..12).and_then(|m| <[f64; 12]>::try_from(m).ok()) + && m.iter().all(|x| x.is_finite()) + && self.matrices.len() < MAX_MATRICES + { + self.matrices.push(m); + } + } + 31 => { + self.matrices.pop(); + } + _ => {} + } + } + + fn push(&mut self, kind: EntityKind) { + if self.out.len() < MAX_ENTITIES { + self.out.push(Entity { handle: self.handle, common: self.pen.clone(), kind }); + } + } + + /// `p` through the pushed matrices, innermost first, in the XY plane. + fn xy(&self, p: Vec3) -> Vec2 { + let mut p = p; + for m in self.matrices.iter().rev() { + p = Vec3::new( + m[0] * p.x + m[1] * p.y + m[2] * p.z + m[3], + m[4] * p.x + m[5] * p.y + m[6] * p.z + m[7], + m[8] * p.x + m[9] * p.y + m[10] * p.z + m[11], + ); + } + p.xy() + } + + /// How much the pushed matrices scale lengths (1 without any). + fn scale(&self) -> f64 { + self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product() + } + + fn circle(&mut self, c: Vec3, r: f64) { + let r = r * self.scale(); + if r.is_finite() && r > 0.0 { + let c = self.xy(c); + self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r })); + } + } + + fn arc(&mut self, c: Vec3, r: f64, normal: Vec3, start: Vec3, sweep: f64) { + if !(r.is_finite() && r > 0.0 && sweep.is_finite() && sweep != 0.0) || start.xy().len() < 1e-12 { + return; + } + // The start point and the end point (the start vector turned by the sweep around the + // normal: clockwise in plan for a normal pointing down), through the matrices. + let dir = if normal.z < 0.0 { -1.0 } else { 1.0 }; + let a0 = start.y.atan2(start.x); + let a1 = a0 + dir * sweep; + let on = |a: f64| c + Vec3::new(r * a.cos(), r * a.sin(), 0.0); + let mid = on((a0 + a1) / 2.0); + if sweep.abs() >= std::f64::consts::TAU - 1e-9 { + return self.circle(c, r); + } + self.arc_3p(self.xy(on(a0)), self.xy(mid), self.xy(on(a1))); + } + + /// The arc from `p1` through `p2` to `p3`. + fn arc_3p(&mut self, p1: Vec2, p2: Vec2, p3: Vec2) { + let Some((c, r)) = circle_through(p1, p2, p3) else { + return self.polyline(vec![p1, p3], false); + }; + let ang = |p: Vec2| (p.y - c.y).atan2(p.x - c.x); + let (a1, a2, a3) = (ang(p1), ang(p2), ang(p3)); + let ccw = |from: f64, to: f64| (to - from).rem_euclid(std::f64::consts::TAU); + // Counter-clockwise from p1 to p3 when p2 lies on that way, else from p3 to p1. + let (start, end) = if ccw(a1, a2) <= ccw(a1, a3) { (a1, a3) } else { (a3, a1) }; + self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end })); + } + + fn polyline(&mut self, pts: Vec, polygon: bool) { + let fill = std::mem::take(&mut self.fill); + if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() { + return; + } + if polygon && fill && pts.len() >= 3 { + let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect(); + return self.push(EntityKind::Hatch(Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + })); + } + match pts.as_slice() { + [a, b] if !polygon => self.push(EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) })), + _ => { + let vertices = pts.iter().map(|&p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect(); + self.push(EntityKind::LwPolyline(LwPolyline { vertices, closed: polygon, const_width: 0.0, elevation: 0.0, plinegen: false })); + } + } + } + + fn text(&mut self, t: TextChunk) { + let TextChunk { p, dir, height, width, oblique, value, font } = t; + let font = font.as_str(); + let height = height * self.scale(); + if !(height.is_finite() && height > 0.0) || value.is_empty() { + return; + } + let at = self.xy(p); + let towards = self.xy(p + dir) - at; + let rotation = if towards.len() > 1e-12 { towards.y.atan2(towards.x) } else { 0.0 }; + let stem = |f: &str| f.trim().rsplit(['/', '\\']).next().unwrap_or_default().split('.').next().unwrap_or_default().to_ascii_lowercase(); + let style = self + .tables + .styles + .iter() + .find(|(_, f)| !font.is_empty() && stem(f) == stem(font)) + .map(|(n, _)| n.clone()) + .unwrap_or_else(|| "Standard".into()); + self.push(EntityKind::Text(Text { + insert: at.to3(0.0), + align_pt: None, + height, + value, + rotation, + width_factor: if width.is_finite() && width > 0.0 { width } else { 1.0 }, + oblique: if oblique.is_finite() { oblique } else { 0.0 }, + style, + halign: Default::default(), + valign: Default::default(), + })); + } +} + +/// The first `length` characters of `s`: a text chunk may carry more text than it draws (the +/// rest of a note, drawn by the chunks after it). No length, or one past the end, keeps it all. +fn first_chars(s: String, length: Option) -> String { + match length.map(|n| n as usize) { + Some(n) if n > 0 && n < s.chars().count() => s.chars().take(n).collect(), + _ => s, + } +} + +/// A text chunk: position, direction, height, width factor, oblique, string and font file. +struct TextChunk { + p: Vec3, + dir: Vec3, + height: f64, + width: f64, + oblique: f64, + value: String, + font: String, +} + +/// The circle through three points (centre, radius), if they aren't on one line. +fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> { + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + if !d.is_finite() || d.abs() < 1e-12 { + return None; + } + let (a2, b2, c2) = (a.x * a.x + a.y * a.y, b.x * b.x + b.y * b.y, c.x * c.x + c.y * c.y); + let center = + Vec2::new((a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / d, (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / d); + let r = (a - center).len(); + (center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r)) +} + +fn u32_at(bytes: &[u8], at: usize) -> Option { + bytes.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) +} + +/// A reader over one chunk's data. Strings are padded to four bytes. +struct Bytes<'a> { + data: &'a [u8], + at: usize, +} + +impl Bytes<'_> { + fn take(&mut self, n: usize) -> Option<&[u8]> { + let s = self.data.get(self.at..self.at.checked_add(n)?)?; + self.at += n; + Some(s) + } + fn skip(&mut self, n: usize) { + self.at = self.at.saturating_add(n); + } + fn u32(&mut self) -> Option { + self.take(4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) + } + fn f64(&mut self) -> Option { + self.take(8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes) + } + fn point(&mut self) -> Option { + let p = Vec3::new(self.f64()?, self.f64()?, self.f64()?); + (p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(p) + } + fn align(&mut self) { + self.at = self.at.saturating_add((4 - self.at % 4) % 4); + } + /// A zero-terminated string in the drawing's code page; bytes above 0x7F as Latin-1. + fn string(&mut self) -> String { + let rest = self.data.get(self.at..).unwrap_or_default(); + let end = rest.iter().position(|&c| c == 0).unwrap_or(rest.len()); + let s: String = rest.iter().take(end).map(|&c| c as char).collect(); + self.at += end + 1; + self.align(); + s + } + /// A UTF-16 string ended by a zero code unit. + fn unicode(&mut self) -> String { + let rest = self.data.get(self.at..).unwrap_or_default(); + let units: Vec = rest.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).take_while(|&u| u != 0).collect(); + self.at += units.len() * 2 + 2; + self.align(); + String::from_utf16_lossy(&units) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::RawTag; + + fn chunk(kind: u32, data: &[u8]) -> Vec { + let mut d = data.to_vec(); + d.resize(d.len().div_ceil(4) * 4, 0); + let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec(); + out.extend(kind.to_le_bytes()); + out.extend(d); + out + } + fn graphics(chunks: &[Vec]) -> Vec { + let body: Vec = chunks.concat(); + let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec(); + out.extend((chunks.len() as u32).to_le_bytes()); + out.extend(body); + out + } + fn pt(x: f64, y: f64) -> Vec { + [x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect() + } + fn tables() -> ProxyTables { + ProxyTables { + layers: vec!["0".into(), "BALLOONS".into()], + linetypes: vec!["Continuous".into(), "DASHED".into()], + styles: vec![("Standard".into(), "txt".into()), ("ISO".into(), "isocp.shx".into())], + } + } + + /// A balloon as AutoCAD Mechanical stores one: layer, colour, a circle, the leader and the + /// number as TEXT2. + #[test] + fn a_balloon_becomes_circle_line_and_text() { + let mut text2 = pt(173.0, 112.0); + text2.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter())); + text2.extend(pt(1.0, 0.0)); + text2.extend(b"12\0\0"); + text2.extend(2i32.to_le_bytes()); + text2.extend(0i32.to_le_bytes()); + for v in [6.0f64, 1.0, 0.0, 0.0] { + text2.extend(v.to_le_bytes()); + } + text2.extend([0u8; 20]); + text2.extend(b"ISOCP.SHX\0\0\0\0\0"); + let mut circle = pt(175.0, 115.0); + circle.extend(6.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0).iter().take(16).chain(1.0f64.to_le_bytes().iter())); + let mut leader = 2u32.to_le_bytes().to_vec(); + leader.extend(pt(170.0, 111.0)); + leader.extend(pt(150.0, 90.0)); + let g = graphics(&[chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text2)]); + let es = proxy_entities(&g, &tables(), Handle(0x35)); + assert_eq!(es.len(), 3); + assert!(es.iter().all(|e| e.handle == Handle(0x35) && e.common.layer == "BALLOONS" && e.common.color == Color::Index(1))); + assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(175.0, 115.0, 0.0) && c.radius == 6.0)); + assert!(matches!(&es[1].kind, EntityKind::Line(l) if l.b == Vec3::new(150.0, 90.0, 0.0))); + assert!(matches!(&es[2].kind, EntityKind::Text(t) if t.value == "12" && t.height == 6.0 && t.style == "ISO" && t.rotation == 0.0)); + } + + /// A TEXT2 chunk draws only as many characters as its length says. + #[test] + fn text2_draws_its_length() { + let text2 = |value: &[u8], length: i32| { + let mut t = pt(0.0, 0.0); + t.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + t.extend(pt(1.0, 0.0)); + t.extend(value); + t.extend(vec![0u8; 4 - value.len() % 4]); + t.extend(length.to_le_bytes()); + t.extend(1i32.to_le_bytes()); + for v in [2.5f64, 1.0, 0.0, 0.0] { + t.extend(v.to_le_bytes()); + } + t.extend([0u8; 20]); + t.extend(b"txt\0"); + let es = proxy_entities(&graphics(&[chunk(11, &t)]), &tables(), Handle(1)); + match es.first().map(|e| &e.kind) { + Some(EntityKind::Text(t)) => t.value.clone(), + other => panic!("{other:?}"), + } + }; + assert_eq!(text2(b"two lines\\Pof text", 9), "two lines"); + assert_eq!(text2(b"whole", 0), "whole"); + assert_eq!(text2(b"whole", 99), "whole"); + } + + /// Without layer and colour chunks the picture takes the proxy's own (layer 0, ByBlock). + #[test] + fn unset_traits_are_the_proxys() { + let mut leader = 3u32.to_le_bytes().to_vec(); + for (x, y) in [(0.0, 0.0), (10.0, 0.0), (10.0, 5.0)] { + leader.extend(pt(x, y)); + } + let es = proxy_entities( + &graphics(&[chunk(6, &leader), chunk(16, &u32::MAX.to_le_bytes()), chunk(18, &32766u32.to_le_bytes())]), + &tables(), + Handle(1), + ); + let e = es.first().expect("polyline"); + assert_eq!( + (e.common.layer.as_str(), e.common.color, e.common.linetype.as_str(), e.common.lineweight), + ("0", Color::ByBlock, "ByBlock", Lineweight::ByBlock) + ); + assert!(matches!(&e.kind, EntityKind::LwPolyline(p) if p.vertices.len() == 3 && !p.closed)); + } + + #[test] + fn a_filled_polygon_is_a_solid_hatch_and_fill_applies_once() { + let mut tri = 3u32.to_le_bytes().to_vec(); + for (x, y) in [(0.0, 0.0), (4.0, 0.0), (2.0, 3.0)] { + tri.extend(pt(x, y)); + } + let es = proxy_entities(&graphics(&[chunk(20, &1u32.to_le_bytes()), chunk(7, &tri), chunk(7, &tri)]), &tables(), Handle(1)); + assert!(matches!(&es[0].kind, EntityKind::Hatch(h) if h.solid && h.loops[0].vertices.len() == 3)); + assert!(matches!(&es[1].kind, EntityKind::LwPolyline(p) if p.closed)); + } + + /// A quarter arc counter-clockwise from 0°, and the same sweep around a downward normal, + /// which runs clockwise in plan (from 0° to -90°). + #[test] + fn arcs_follow_their_normal() { + let arc = |nz: f64| { + let mut a = pt(0.0, 0.0); + a.extend(2.0f64.to_le_bytes()); + a.extend([0.0f64, 0.0, nz].iter().flat_map(|v| v.to_le_bytes())); + a.extend(pt(1.0, 0.0)); + a.extend(std::f64::consts::FRAC_PI_2.to_le_bytes()); + a.extend(0u32.to_le_bytes()); + match proxy_entities(&graphics(&[chunk(4, &a)]), &tables(), Handle(1)).first().map(|e| e.kind.clone()) { + Some(EntityKind::Arc(a)) => (a.start, a.end, a.radius), + other => panic!("{other:?}"), + } + }; + let (s, e, r) = arc(1.0); + assert!(s.abs() < 1e-9 && (e - std::f64::consts::FRAC_PI_2).abs() < 1e-9 && (r - 2.0).abs() < 1e-9); + let (s, e, _) = arc(-1.0); + assert!((s + std::f64::consts::FRAC_PI_2).abs() < 1e-9 && e.abs() < 1e-9, "{s} {e}"); + } + + #[test] + fn a_pushed_matrix_moves_what_follows_until_popped() { + let mut m = [0.0f64; 16]; + (m[0], m[5], m[10], m[15], m[3], m[7]) = (2.0, 2.0, 1.0, 1.0, 100.0, 50.0); + let mut circle = pt(1.0, 1.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + let push: Vec = m.iter().flat_map(|v| v.to_le_bytes()).collect(); + let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(31, &[]), chunk(2, &circle)]), &tables(), Handle(1)); + assert!(matches!(&es[0].kind, EntityKind::Circle(c) if c.center == Vec3::new(102.0, 52.0, 0.0) && c.radius == 2.0)); + assert!(matches!(&es[1].kind, EntityKind::Circle(c) if c.center == Vec3::new(1.0, 1.0, 0.0) && c.radius == 1.0)); + } + + #[test] + fn the_bytes_come_from_the_310_groups_after_the_size() { + let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; + let u = Unknown { + dxf_type: "ACAD_PROXY_ENTITY".into(), + tags: vec![tag(90, "498"), tag(92, "5"), tag(310, "0102"), tag(310, "030405FF"), tag(93, "0")], + graphics: Vec::new(), + }; + assert_eq!(u.proxy_graphics_bytes(), [1, 2, 3, 4, 5]); + let other = Unknown { dxf_type: "ACAD_PROXY_OBJECT".into(), ..u.clone() }; + assert!(other.proxy_graphics_bytes().is_empty()); + let bad = Unknown { tags: vec![tag(92, "4"), tag(310, "01zz")], ..u }; + assert!(bad.proxy_graphics_bytes().is_empty()); + } + + /// Truncated chunks, sizes past the end, huge counts and garbage draw what they can and + /// never panic. + #[test] + fn hostile_graphics_do_not_panic() { + let mut huge = u32::MAX.to_le_bytes().to_vec(); + huge.extend(pt(1.0, 1.0)); + let mut nan = pt(f64::NAN, 0.0); + nan.extend(1.0f64.to_le_bytes()); + let cases: Vec> = vec![ + Vec::new(), + vec![0; 7], + graphics(&[chunk(6, &huge)]), + graphics(&[chunk(2, &nan)]), + graphics(&[chunk(11, &[0xFF; 30])]), + graphics(&[chunk(38, &[0x41; 77])]), + graphics(&[chunk(29, &[1; 40])]), + graphics(&[chunk(31, &[]), chunk(31, &[])]), + [graphics(&[chunk(2, &pt(0.0, 0.0))]), vec![0xFF; 9]].concat(), + { + let mut g = graphics(&[]); + g.extend(4u32.to_le_bytes()); + g.extend(2u32.to_le_bytes()); + g + }, + { + let mut g = graphics(&[]); + g.extend(1_000u32.to_le_bytes()); + g.extend(2u32.to_le_bytes()); + g + }, + ]; + for g in cases { + let _ = proxy_entities(&g, &tables(), Handle(1)); + } + } +} diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index e44809df4..0e4f7e0eb 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -196,6 +196,16 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap< } b } + // A proxy measures as its proxy graphics draw (layer 0 in them is the proxy's layer). + EntityKind::Unknown(u) if !u.graphics.is_empty() => { + if depth >= MAX_BLOCK_DEPTH { + return Bounds2::EMPTY; + } + u.graphics + .iter() + .filter(|g| in_block_visible(d, g, off_counts)) + .fold(Bounds2::EMPTY, |b, g| b.union(&bounds_in(d, g, depth + 1, blocks, off_counts))) + } EntityKind::Dimension(dm) => { let pts: Vec = match dm.kind { crate::DimKind::Linear { .. } | crate::DimKind::Aligned | crate::DimKind::ArcLength => vec![dm.defpt.xy(), dm.p13.xy(), dm.p14.xy()], diff --git a/crates/engine/tests/save_reports_not_saved.rs b/crates/engine/tests/save_reports_not_saved.rs index 80192bf53..833f03325 100644 --- a/crates/engine/tests/save_reports_not_saved.rs +++ b/crates/engine/tests/save_reports_not_saved.rs @@ -8,7 +8,7 @@ use cadcraft_engine::doc::{Block, Common, Drawing, EntityKind, RawTag, Space, Un use serde_json::json; fn unknown(kind: &str) -> EntityKind { - EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] }) + EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() }) } #[test] @@ -129,6 +129,7 @@ fn saving_sat_text_solids_as_dxf_2013_reports_them() { RawTag { code: 1, value: "400 1 1 0".into() }, RawTag { code: 3, value: "End-of-ACIS-data".into() }, ], + graphics: Vec::new(), }); d.add(&Space::Model, Common::default(), sat).unwrap(); let mut s = Session::empty(); @@ -158,7 +159,7 @@ fn a_dxf_2013_loss_is_known_before_saving() { set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"0\nEOF\n".to_vec()), plot: None }); let sat = |d: &mut Drawing| { let tags = vec![RawTag { code: 8, value: "0".into() }, RawTag { code: 1, value: "400 1 1 0".into() }]; - d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags })).unwrap(); + d.add(&Space::Model, Common::default(), EntityKind::Unknown(Unknown { dxf_type: "REGION".into(), tags, graphics: Vec::new() })).unwrap(); }; let mut modern = Drawing::new_imperial(); modern.header.set_str("ACADVER", "AC1032"); @@ -194,6 +195,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() { RawTag { code: 1, value: "400 1 1 0".into() }, RawTag { code: 3, value: "End-of-ACIS-data".into() }, ], + graphics: Vec::new(), }); d.add(&Space::Model, Common::default(), sat).unwrap(); d.blocks.insert("Door".into(), std::sync::Arc::new(Block::new("Door"))); @@ -214,7 +216,7 @@ fn the_note_counts_the_host_drawing_while_a_block_is_edited() { fn a_dwg_keeps_sat_text_solids_only_before_2013() { use cadcraft_engine::cmd::file::{Version, not_saved_as}; let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; - let solid = |tags: Vec| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags }); + let solid = |tags: Vec| EntityKind::Unknown(Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() }); let mut d = Drawing::new_imperial(); d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(1, "400 1 1 0")])).unwrap(); d.add(&Space::Model, Common::default(), solid(vec![tag(100, "AcDbModelerGeometry"), tag(70, "1")])).unwrap(); diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 2dcb14fc0..1d4254d7a 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -61,6 +61,9 @@ struct Rx { block_arrays: HashMap, /// LAYER record handle (upper case) → layer name (VIEWPORT group 331/341 frozen layers). layers: HashMap, + /// Layer, linetype and text style names in the order of the file's tables, which proxy + /// graphics refer to by index (the drawing's own tables are ordered differently). + proxy_tables: cadcraft_doc::ProxyTables, } /// Read a DXF file into a drawing. diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 6ca0f30d1..5659f965a 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -281,6 +281,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef other => EntityKind::Unknown(Unknown { dxf_type: other.to_string(), tags: tags.iter().map(|tg| RawTag { code: tg.code, value: tg.str() }).collect(), + graphics: Vec::new(), }), }; Some((c, k)) @@ -438,6 +439,10 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option { /// needs the file's handle maps. pub(super) fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &mut Rx) { match (kind, k) { + // Its proxy graphics, with the table indices resolved while the file's order is known. + ("ACAD_PROXY_ENTITY", EntityKind::Unknown(u)) => { + u.graphics = cadcraft_doc::proxy_entities(&u.proxy_graphics_bytes(), &rx.proxy_tables, h); + } ("DIMENSION", EntityKind::Dimension(dm)) => { dm.overrides = crate::dxf_ext::read_dstyle(tags, &rx.styles, &rx.brs, &rx.ltypes); dm.assoc = crate::dxf_ext::read_assoc(tags); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index c914ea9f5..b082c3583 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -289,6 +289,7 @@ fn index_table_handles(recs: &[(String, Vec)], rx: &mut Rx) { let (Some(handle), Some(name)) = (table.s(5), table.s(2)) else { continue }; match kind.as_str() { "STYLE" => { + rx.proxy_tables.styles.push((name.clone(), table.s(3).unwrap_or_default())); rx.styles.insert(handle.trim().to_ascii_uppercase(), name); } "BLOCK_RECORD" => { @@ -300,9 +301,13 @@ fn index_table_handles(recs: &[(String, Vec)], rx: &mut Rx) { rx.brs.insert(handle.trim().to_ascii_uppercase(), name); } "LTYPE" => { + if !name.eq_ignore_ascii_case("ByBlock") && !name.eq_ignore_ascii_case("ByLayer") { + rx.proxy_tables.linetypes.push(name.clone()); + } rx.ltypes.insert(handle.trim().to_ascii_uppercase(), name); } "LAYER" => { + rx.proxy_tables.layers.push(name.clone()); rx.layers.insert(handle.trim().to_ascii_uppercase(), name); } _ => {} diff --git a/crates/io/src/roundtrip/tests.rs b/crates/io/src/roundtrip/tests.rs index 2107fb48f..c75389102 100644 --- a/crates/io/src/roundtrip/tests.rs +++ b/crates/io/src/roundtrip/tests.rs @@ -39,7 +39,11 @@ fn drawing() -> Drawing { d.add( &Space::Model, Common::default(), - EntityKind::Unknown(Unknown { dxf_type: "ACME_WIDGET".into(), tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")] }), + EntityKind::Unknown(Unknown { + dxf_type: "ACME_WIDGET".into(), + tags: vec![tag(100, "AcDbEntity"), tag(10, "1.0"), tag(20, "2.0")], + graphics: Vec::new(), + }), ) .unwrap(); d.add(&Space::Paper("Layout1".into()), Common::default(), line((1.0, 1.0), (2.0, 2.0))).unwrap(); @@ -516,7 +520,7 @@ fn corpus_round_trip_report() { #[test] fn types_the_dwg_writer_cannot_write_are_reported_lost() { use corpus::{CorpusReport, FileReport, Format, round_trip}; - let unknown = |t: &str, tags: Vec| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags }); + let unknown = |t: &str, tags: Vec| EntityKind::Unknown(Unknown { dxf_type: t.into(), tags, graphics: Vec::new() }); let mut d = Drawing::new_metric(); let widget = vec![tag(100, "AcDbEntity"), tag(100, "AcmeWidget"), tag(10, "1.0"), tag(20, "2.0"), tag(30, "0.0")]; d.add(&Space::Model, Common::default(), unknown("ACME_WIDGET", widget.clone())).unwrap(); diff --git a/crates/io/tests/it/acis_data_store.rs b/crates/io/tests/it/acis_data_store.rs index f0ad2039c..ab23da78e 100644 --- a/crates/io/tests/it/acis_data_store.rs +++ b/crates/io/tests/it/acis_data_store.rs @@ -164,7 +164,7 @@ fn sat_text_is_told_by_its_subclass_and_a_geometry_record() { use cadcraft_doc::foreign::{Foreign, sat_text_acis}; use cadcraft_doc::{Handle, RawTag, Unknown}; let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; - let solid = |tags: Vec| Unknown { dxf_type: "3DSOLID".into(), tags }; + let solid = |tags: Vec| Unknown { dxf_type: "3DSOLID".into(), tags, graphics: Vec::new() }; let none = std::collections::BTreeSet::new(); let h = Handle(0x2B); // A stray 1 or 3 outside AcDbModelerGeometry is not SAT text. diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 289e87806..d2b615acd 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -60,6 +60,7 @@ mod plot_model_png_scale; mod plot_styles; mod polyface_roundtrip; mod portable_fonts; +mod proxy_graphics; mod region_roundtrip; mod roundtrip; mod roundtrip_audit; diff --git a/crates/io/tests/it/proxy_graphics.rs b/crates/io/tests/it/proxy_graphics.rs new file mode 100644 index 000000000..aa245102b --- /dev/null +++ b/crates/io/tests/it/proxy_graphics.rs @@ -0,0 +1,134 @@ +//! ACAD_PROXY_ENTITY draws its proxy graphics (#2646): read from DXF with the table indices of the +//! file, measured in the extents, and written back unchanged. + +use cadcraft_doc::color::Color; +use cadcraft_doc::{EntityKind, Space}; +use cadcraft_io::{read_dxf, write_dxf}; + +fn chunk(kind: u32, data: &[u8]) -> Vec { + let mut d = data.to_vec(); + d.resize(d.len().div_ceil(4) * 4, 0); + let mut out = ((8 + d.len()) as u32).to_le_bytes().to_vec(); + out.extend(kind.to_le_bytes()); + out.extend(d); + out +} + +fn pt(x: f64, y: f64) -> Vec { + [x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// A balloon: layer 1 of the file's LAYER table, colour 1, a circle, a leader and the number. +fn balloon() -> Vec { + let mut circle = pt(175.0, 115.0); + circle.extend(6.0f64.to_le_bytes()); + circle.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + let mut leader = 2u32.to_le_bytes().to_vec(); + leader.extend(pt(170.8, 110.8)); + leader.extend(pt(150.0, 90.0)); + let mut text = pt(172.9, 112.0); + text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + text.extend(pt(1.0, 0.0)); + text.extend(b"1\0\0\0"); + text.extend(1i32.to_le_bytes()); + text.extend(0i32.to_le_bytes()); + for v in [6.0f64, 1.0, 0.0, 0.0] { + text.extend(v.to_le_bytes()); + } + text.extend([0u8; 20]); + text.extend(b"isocp.shx\0\0\0\0\0\0\0"); + let chunks = [chunk(16, &1u32.to_le_bytes()), chunk(14, &1u32.to_le_bytes()), chunk(2, &circle), chunk(6, &leader), chunk(11, &text)]; + let body = chunks.concat(); + let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec(); + out.extend((chunks.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// A DXF whose LAYER table holds 0 and BALLOONS only (CADCraft keeps Defpoints at index 1 of +/// its own table), a text style on isocp.shx, a line and one proxy balloon. +fn file() -> String { + let graphics = balloon(); + let hex: Vec = graphics.chunks(127).map(|c| c.iter().map(|b| format!("{b:02X}")).collect()).collect(); + let mut tags: Vec<(i32, String)> = vec![(0, "SECTION".into()), (2, "CLASSES".into())]; + for (c, v) in [(0, "CLASS"), (1, "SYNBALLOON"), (2, "SynBalloon"), (3, "SyntheticProxyApp"), (90, "0"), (280, "0"), (281, "1"), (0, "ENDSEC")] { + tags.push((c, v.into())); + } + for (c, v) in [ + (0, "SECTION"), + (2, "TABLES"), + (0, "TABLE"), + (2, "LAYER"), + (0, "LAYER"), + (5, "10"), + (2, "0"), + (62, "7"), + (0, "LAYER"), + (5, "11"), + (2, "BALLOONS"), + (62, "3"), + (0, "ENDTAB"), + (0, "TABLE"), + (2, "STYLE"), + (0, "STYLE"), + (5, "12"), + (2, "ISO"), + (3, "isocp.shx"), + (0, "ENDTAB"), + (0, "ENDSEC"), + (0, "SECTION"), + (2, "ENTITIES"), + (0, "LINE"), + (5, "20"), + (8, "0"), + (10, "50"), + (20, "40"), + (11, "150"), + (21, "90"), + (0, "ACAD_PROXY_ENTITY"), + (5, "21"), + (100, "AcDbEntity"), + (8, "0"), + (100, "AcDbProxyEntity"), + (90, "498"), + (91, "500"), + (95, "0"), + (70, "0"), + ] { + tags.push((c, v.into())); + } + tags.push((92, graphics.len().to_string())); + tags.extend(hex.into_iter().map(|h| (310, h))); + for (c, v) in [(93, "0"), (94, "0"), (0, "ENDSEC"), (0, "EOF")] { + tags.push((c, v.into())); + } + tags.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect() +} + +#[test] +fn a_proxy_draws_its_graphics_with_the_files_table_indices() { + let d = read_dxf(file().as_bytes()).expect("read"); + let proxy = d.model.iter().find(|e| matches!(e.kind, EntityKind::Unknown(_))).expect("proxy"); + let EntityKind::Unknown(u) = &proxy.kind else { unreachable!() }; + let kinds: Vec<(&str, &str, Color)> = u.graphics.iter().map(|g| (g.kind.dxf_name(), g.common.layer.as_str(), g.common.color)).collect(); + // Layer index 1 is BALLOONS, the file's second layer, not CADCraft's Defpoints. + assert_eq!(kinds, [("CIRCLE", "BALLOONS", Color::Index(1)), ("LINE", "BALLOONS", Color::Index(1)), ("TEXT", "BALLOONS", Color::Index(1))]); + assert!(matches!(&u.graphics[2].kind, EntityKind::Text(t) if t.value == "1" && t.style == "ISO")); + // The extents reach the balloon (the line alone ends at 150, 90). + let b = d.extents(&Space::Model); + assert!(b.max.x >= 181.0 && b.max.y >= 121.0, "{b:?}"); +} + +#[test] +fn a_proxy_is_written_back_unchanged_and_draws_again() { + let d = read_dxf(file().as_bytes()).expect("read"); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + let graphics = |d: &cadcraft_doc::Drawing| { + d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) => Some((u.proxy_graphics_bytes(), u.graphics.len())), + _ => None, + }) + }; + assert_eq!(graphics(&again), graphics(&d)); + assert_eq!(graphics(&d).map(|g| g.1), Some(3)); +} diff --git a/crates/io/tests/it/roundtrip/unknown.rs b/crates/io/tests/it/roundtrip/unknown.rs index 5883a078c..f4d33cb22 100644 --- a/crates/io/tests/it/roundtrip/unknown.rs +++ b/crates/io/tests/it/roundtrip/unknown.rs @@ -27,7 +27,7 @@ fn drawing() -> Drawing { RawTag { code: 30, value: "3.75".into() }, RawTag { code: 330, value: target.hex() }, ]; - d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags }))); + d.model.push(Entity::new(handle, EntityKind::Unknown(Unknown { dxf_type: "SYNTHETIC_WIDGET".into(), tags, graphics: Vec::new() }))); d.model.push(Entity::new(target, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 6.0, 7.0) }))); d } diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index ad4689682..3de611216 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -40,6 +40,22 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> { } } +/// A proxy entity draws its proxy graphics as AutoCAD does with PROXYSHOW 1, like block contents: +/// layer 0 and ByBlock in the picture stand for the proxy's own layer and properties. Other +/// unknown records draw nothing. +pub(crate) fn proxy(b: &mut Builder, ctx: &Ctx, e: &Entity, u: &cadcraft_doc::Unknown) { + if u.graphics.is_empty() || ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH { + return; + } + let sub = Ctx { block_pstyle: b.named, block_transparency: b.transparency, ..sub_ctx(ctx, e, Mat3::IDENTITY) }; + for g in &u.graphics { + if !b.expand() { + break; + } + entity(b, &sub, g); + } +} + pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc::Insert, rgb: Ink) { if ctx.depth >= cadcraft_doc::MAX_BLOCK_DEPTH { return; diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index e73659675..1e5dd9ab9 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -1,4 +1,4 @@ -use super::blocks::{insert, sub_ctx}; +use super::blocks::{insert, proxy, sub_ctx}; use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks}; use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT}; use super::props::{resolve, transparency}; @@ -128,6 +128,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { } } EntityKind::Insert(ins) => insert(b, ctx, e, ins, rgb), + EntityKind::Unknown(u) => proxy(b, ctx, e, u), EntityKind::Dimension(dm) => draw_dimension(b, ctx, e, dm, lw, lt.as_ref(), ltscale), EntityKind::Hatch(h) => hatch::draw(b, ctx, e, h, rgb, lw, tol), EntityKind::MLine(m) => mline::draw(b, ctx, e, m, rgb, lw, tol), diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index e4b314ff5..b1d1eb69f 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1148,3 +1148,28 @@ 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 proxy draws its proxy graphics like block contents: layer 0 and ByBlock in the picture are +/// the proxy's own, and the proxy's layer hides all of it. +#[test] +fn proxy_graphics_draw_like_block_contents() { + let mut d = Drawing::new_imperial(); + d.layers.push(cadcraft_doc::Layer { name: "Notes".into(), color: Color::Index(3), ..Default::default() }); + let byblock = Common { color: Color::ByBlock, ..Default::default() }; + let graphics = vec![ + block_entity(7, byblock, EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })), + block_entity( + 7, + Common { color: Color::Index(1), ..Default::default() }, + EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(15.0, 0.0, 0.0), radius: 5.0 }), + ), + ]; + let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics }); + d.add(&Space::Model, Common { layer: "Notes".into(), ..Default::default() }, proxy).unwrap(); + let l = build(&d, &Space::Model, &Options::default()); + assert_eq!(l.prims.iter().map(|p| p.color).collect::>(), [Rgb(0, 255, 0), Rgb(255, 0, 0)]); + let b = d.extents(&Space::Model); + assert!((b.min.x, b.max.x, b.max.y) == (0.0, 20.0, 5.0), "{b:?}"); + d.layer_mut("Notes").unwrap().frozen = true; + assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty()); +} diff --git a/crates/ui-egui/tests/save_loss.rs b/crates/ui-egui/tests/save_loss.rs index cdb212f94..eed77c7ea 100644 --- a/crates/ui-egui/tests/save_loss.rs +++ b/crates/ui-egui/tests/save_loss.rs @@ -15,7 +15,7 @@ use cadcraft_ui_egui::{CadApp, Services, menus}; const ORIGINAL: &[u8] = b"original"; fn unknown(kind: &str) -> EntityKind { - EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }] }) + EntityKind::Unknown(Unknown { dxf_type: kind.into(), tags: vec![RawTag { code: 8, value: "0".into() }], graphics: Vec::new() }) } /// A drawing with objects of `types`, which DWG can't keep, opened from a DWG file on disk. From 44a4e05506f3e800621230bc3e7b6607363feb09 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Tue, 3 Nov 2026 09:10:55 +0100 Subject: [PATCH 050/187] contributors: add whaslbeck --- contributors/people.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 8bb73b9ea..125a97e1d 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -109,3 +109,8 @@ real_name = "Andrea Brandi" [people.qinshah] sync_github_name = true + +[people.whaslbeck] +real_name = "Walter Haslbeck" +display_name = "Walter Haslbeck" +sync_github_name = false From e36d1fde4bfdd2f2c18eb78578b4a3f4f71af6a9 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:26:32 +0100 Subject: [PATCH 051/187] fix(doc): read UTF-16 proxy text with as_chunks (clippy chunks_exact_to_as_chunks); document the decoder's helpers --- crates/doc/src/entity/proxy.rs | 21 ++++++++++++++++++++- crates/io/tests/it/proxy_graphics.rs | 2 ++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/entity/proxy.rs b/crates/doc/src/entity/proxy.rs index e4a45649d..850cf1f6e 100644 --- a/crates/doc/src/entity/proxy.rs +++ b/crates/doc/src/entity/proxy.rs @@ -106,6 +106,7 @@ struct Decoder<'a> { } impl Decoder<'_> { + /// Decode one chunk of type `kind`: draw it, or change the pen for what follows. fn chunk(&mut self, kind: u32, data: &[u8]) { let mut b = Bytes { data, at: 0 }; match kind { @@ -251,6 +252,7 @@ impl Decoder<'_> { } } + /// Add an entity drawn with the current pen (up to [`MAX_ENTITIES`]). fn push(&mut self, kind: EntityKind) { if self.out.len() < MAX_ENTITIES { self.out.push(Entity { handle: self.handle, common: self.pen.clone(), kind }); @@ -275,6 +277,7 @@ impl Decoder<'_> { self.matrices.iter().map(|m| (m[0] * m[5] - m[1] * m[4]).abs().sqrt()).product() } + /// A full circle around `c`, through the pushed matrices. fn circle(&mut self, c: Vec3, r: f64) { let r = r * self.scale(); if r.is_finite() && r > 0.0 { @@ -283,6 +286,7 @@ impl Decoder<'_> { } } + /// An arc around `c` from the direction `start`, turned by `sweep` around `normal`. fn arc(&mut self, c: Vec3, r: f64, normal: Vec3, start: Vec3, sweep: f64) { if !(r.is_finite() && r > 0.0 && sweep.is_finite() && sweep != 0.0) || start.xy().len() < 1e-12 { return; @@ -313,6 +317,8 @@ impl Decoder<'_> { self.push(EntityKind::Arc(Arc { center: c.to3(0.0), radius: r, start, end })); } + /// A polyline, or a closed polygon: filled (a solid hatch) when ATTRIBUTE_FILL asked for it, + /// which applies to this one polygon only. fn polyline(&mut self, pts: Vec, polygon: bool) { let fill = std::mem::take(&mut self.fill); if pts.iter().any(|p| !p.is_finite()) || pts.is_empty() { @@ -344,6 +350,7 @@ impl Decoder<'_> { } } + /// A single-line text, its style the first one whose font file the chunk names. fn text(&mut self, t: TextChunk) { let TextChunk { p, dir, height, width, oblique, value, font } = t; let font = font.as_str(); @@ -410,6 +417,7 @@ fn circle_through(a: Vec2, b: Vec2, c: Vec2) -> Option<(Vec2, f64)> { (center.is_finite() && r.is_finite() && r > 0.0).then_some((center, r)) } +/// The little-endian u32 at `at`, if `bytes` holds one there. fn u32_at(bytes: &[u8], at: usize) -> Option { bytes.get(at..at.checked_add(4)?).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) } @@ -421,24 +429,30 @@ struct Bytes<'a> { } impl Bytes<'_> { + /// The next `n` bytes, if there are that many. fn take(&mut self, n: usize) -> Option<&[u8]> { let s = self.data.get(self.at..self.at.checked_add(n)?)?; self.at += n; Some(s) } + /// Pass over `n` bytes (reads after the end then find nothing). fn skip(&mut self, n: usize) { self.at = self.at.saturating_add(n); } + /// A little-endian u32. fn u32(&mut self) -> Option { self.take(4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) } + /// A little-endian double. fn f64(&mut self) -> Option { self.take(8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes) } + /// Three doubles, if all are finite. fn point(&mut self) -> Option { let p = Vec3::new(self.f64()?, self.f64()?, self.f64()?); (p.x.is_finite() && p.y.is_finite() && p.z.is_finite()).then_some(p) } + /// Move on to the next multiple of four bytes, where padded strings end. fn align(&mut self) { self.at = self.at.saturating_add((4 - self.at % 4) % 4); } @@ -454,7 +468,8 @@ impl Bytes<'_> { /// A UTF-16 string ended by a zero code unit. fn unicode(&mut self) -> String { let rest = self.data.get(self.at..).unwrap_or_default(); - let units: Vec = rest.chunks_exact(2).map(|p| u16::from_le_bytes([p[0], p[1]])).take_while(|&u| u != 0).collect(); + let (pairs, _) = rest.as_chunks::<2>(); + let units: Vec = pairs.iter().map(|&p| u16::from_le_bytes(p)).take_while(|&u| u != 0).collect(); self.at += units.len() * 2 + 2; self.align(); String::from_utf16_lossy(&units) @@ -466,6 +481,7 @@ mod tests { use super::*; use crate::RawTag; + /// A chunk of type `kind`, its data padded to four bytes. fn chunk(kind: u32, data: &[u8]) -> Vec { let mut d = data.to_vec(); d.resize(d.len().div_ceil(4) * 4, 0); @@ -474,6 +490,7 @@ mod tests { out.extend(d); out } + /// Proxy graphics: the header (total size, chunk count), then the chunks. fn graphics(chunks: &[Vec]) -> Vec { let body: Vec = chunks.concat(); let mut out = ((8 + body.len()) as u32).to_le_bytes().to_vec(); @@ -481,9 +498,11 @@ mod tests { out.extend(body); out } + /// A point in the XY plane as three doubles. fn pt(x: f64, y: f64) -> Vec { [x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect() } + /// Two layers, two linetypes and two text styles. fn tables() -> ProxyTables { ProxyTables { layers: vec!["0".into(), "BALLOONS".into()], diff --git a/crates/io/tests/it/proxy_graphics.rs b/crates/io/tests/it/proxy_graphics.rs index aa245102b..5a099ddb9 100644 --- a/crates/io/tests/it/proxy_graphics.rs +++ b/crates/io/tests/it/proxy_graphics.rs @@ -5,6 +5,7 @@ use cadcraft_doc::color::Color; use cadcraft_doc::{EntityKind, Space}; use cadcraft_io::{read_dxf, write_dxf}; +/// A proxy graphics chunk of type `kind`, its data padded to four bytes. fn chunk(kind: u32, data: &[u8]) -> Vec { let mut d = data.to_vec(); d.resize(d.len().div_ceil(4) * 4, 0); @@ -14,6 +15,7 @@ fn chunk(kind: u32, data: &[u8]) -> Vec { out } +/// A point in the XY plane as three doubles. fn pt(x: f64, y: f64) -> Vec { [x, y, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect() } From 50a1f833ad54e98cbe5ccac025ebaeccb55298f8 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:38:29 +0100 Subject: [PATCH 052/187] fix(engine, doc): keep proxies out of every selection; leave out proxy circles and texts a matrix moves out of range A proxy's graphics are drawn, measured and snapped to, but no command can edit a proxy, and saving writes its record as read: a MOVE that took it in left it behind, a COPY stacked a second one on top. So no selection takes a proxy in: picks, windows, fences, polygons, ALL, Last, SELECTALL, group members and QSELECT leave it out (`select::selectable`). A test moves a window round a line and a proxy: the line moves, the proxy stays. A circle centre or text point that a finite but huge pushed matrix moves past the largest float is left out, as a polyline's points already were, so no infinity reaches the extents. --- crates/doc/src/entity/proxy.rs | 34 ++++++++++++++++++++++-- crates/engine/src/cmd/edit.rs | 4 ++- crates/engine/src/cmd/groups/pick.rs | 2 +- crates/engine/src/cmd/modify/stretch.rs | 11 ++++++-- crates/engine/src/cmd/qselect.rs | 8 ++++-- crates/engine/src/select.rs | 9 ++++--- crates/engine/src/session/interactive.rs | 6 +++-- crates/engine/src/tests.rs | 31 +++++++++++++++++++++ 8 files changed, 92 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/entity/proxy.rs b/crates/doc/src/entity/proxy.rs index 850cf1f6e..2589f7be7 100644 --- a/crates/doc/src/entity/proxy.rs +++ b/crates/doc/src/entity/proxy.rs @@ -280,8 +280,8 @@ impl Decoder<'_> { /// A full circle around `c`, through the pushed matrices. fn circle(&mut self, c: Vec3, r: f64) { let r = r * self.scale(); - if r.is_finite() && r > 0.0 { - let c = self.xy(c); + let c = self.xy(c); + if r.is_finite() && r > 0.0 && c.is_finite() { self.push(EntityKind::Circle(Circle { center: c.to3(0.0), radius: r })); } } @@ -359,6 +359,9 @@ impl Decoder<'_> { return; } let at = self.xy(p); + if !at.is_finite() { + return; + } let towards = self.xy(p + dir) - at; let rotation = if towards.len() > 1e-12 { towards.y.atan2(towards.x) } else { 0.0 }; let stem = |f: &str| f.trim().rsplit(['/', '\\']).next().unwrap_or_default().split('.').next().unwrap_or_default().to_ascii_lowercase(); @@ -634,6 +637,33 @@ mod tests { assert!(matches!(&es[1].kind, EntityKind::Circle(c) if c.center == Vec3::new(1.0, 1.0, 0.0) && c.radius == 1.0)); } + /// A finite matrix can still move a point past the largest float: a circle or a text that + /// would land there is left out, as a polyline is, so no infinity reaches the extents. + #[test] + fn what_a_matrix_moves_out_of_range_is_left_out() { + let mut m = [0.0f64; 16]; + (m[0], m[5], m[10], m[15], m[3]) = (1.0, 1.0, 1.0, 1.0, 1.7e308); + let push: Vec = m.iter().flat_map(|v| v.to_le_bytes()).collect(); + let mut circle = pt(1e308, 0.0); + circle.extend(1.0f64.to_le_bytes()); + circle.extend(pt(0.0, 0.0)); + let mut text = pt(1e308, 0.0); + text.extend([0.0f64, 0.0, 1.0].iter().flat_map(|v| v.to_le_bytes())); + text.extend(pt(1.0, 0.0)); + text.extend(b"far\0"); + text.extend(0i32.to_le_bytes()); + text.extend(1i32.to_le_bytes()); + for v in [2.5f64, 1.0, 0.0, 0.0] { + text.extend(v.to_le_bytes()); + } + text.extend([0u8; 20]); + text.extend(b"txt\0"); + let es = proxy_entities(&graphics(&[chunk(29, &push), chunk(2, &circle), chunk(11, &text)]), &tables(), Handle(1)); + assert!(es.is_empty(), "{es:?}"); + // The same text without the matrix is drawn: the chunk itself is sound. + assert_eq!(proxy_entities(&graphics(&[chunk(11, &text)]), &tables(), Handle(1)).len(), 1); + } + #[test] fn the_bytes_come_from_the_310_groups_after_the_size() { let tag = |code: i32, value: &str| RawTag { code, value: value.into() }; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 754248cd3..93940baa5 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -559,7 +559,9 @@ fn run_selectall(s: &mut Session, _p: &Value) -> Result { let d = s.doc()?; let hs: Vec = d .space(&space) - .map(|st| st.iter().filter(|e| d.is_visible(e) && d.layer(&e.common.layer).is_none_or(|l| !l.locked)).map(|e| e.handle).collect()) + .map(|st| { + st.iter().filter(|e| crate::select::selectable(d, e) && d.layer(&e.common.layer).is_none_or(|l| !l.locked)).map(|e| e.handle).collect() + }) .unwrap_or_default(); let n = hs.len(); s.set_selection(hs); diff --git a/crates/engine/src/cmd/groups/pick.rs b/crates/engine/src/cmd/groups/pick.rs index 7a9833876..c42aad4c8 100644 --- a/crates/engine/src/cmd/groups/pick.rs +++ b/crates/engine/src/cmd/groups/pick.rs @@ -56,7 +56,7 @@ pub(crate) fn expand(s: &Session, hs: Vec) -> Vec { } let Some(g) = d.groups.get(*gi) else { continue }; for m in &g.members { - if store.get(*m).is_some_and(|e| d.is_visible(e)) && seen.insert(*m) { + if store.get(*m).is_some_and(|e| crate::select::selectable(d, e)) && seen.insert(*m) { out.push(*m); } } diff --git a/crates/engine/src/cmd/modify/stretch.rs b/crates/engine/src/cmd/modify/stretch.rs index a277f9774..ed65f7da3 100644 --- a/crates/engine/src/cmd/modify/stretch.rs +++ b/crates/engine/src/cmd/modify/stretch.rs @@ -267,8 +267,15 @@ impl StretchM { self.removing = false; None } - "all" => Some(store.map(|st| st.iter().filter(|e| d.is_visible(e)).map(|e| e.handle).collect()).unwrap_or_default()), - "l" | "last" => Some(store.and_then(|st| st.last()).map(|e| vec![e.handle]).unwrap_or_default()), + "all" => { + Some(store.map(|st| st.iter().filter(|e| crate::select::selectable(d, e)).map(|e| e.handle).collect()).unwrap_or_default()) + } + "l" | "last" => Some( + store + .and_then(|st| st.iter().filter(|e| !matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).last()) + .map(|e| vec![e.handle]) + .unwrap_or_default(), + ), "p" | "previous" => Some(s.state()?.previous_selection.clone()), _ => { s.echo("*Invalid selection*"); diff --git a/crates/engine/src/cmd/qselect.rs b/crates/engine/src/cmd/qselect.rs index 2c5330371..8ff5e9dcd 100644 --- a/crates/engine/src/cmd/qselect.rs +++ b/crates/engine/src/cmd/qselect.rs @@ -212,14 +212,18 @@ fn type_matches(e: &Entity, ty: Option<&str>) -> bool { } } -/// The candidate objects: the whole edit space, or the current selection. +/// The candidate objects: the whole edit space (without proxies, which no selection takes in), or +/// the current selection. fn candidates(s: &Session, p: &Value) -> Result> { let apply = str_param(p, "applyTo").unwrap_or("drawing").to_ascii_lowercase(); if apply.starts_with("sel") || apply == "current" { return Ok(s.selection()); } let space = s.space(); - Ok(s.doc()?.space(&space).map(|st| st.iter().take(MAX_SCAN).map(|e| e.handle).collect()).unwrap_or_default()) + Ok(s.doc()? + .space(&space) + .map(|st| st.iter().take(MAX_SCAN).filter(|e| !matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).map(|e| e.handle).collect()) + .unwrap_or_default()) } fn run_qselect(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 6721cdad8..52d108133 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -145,8 +145,11 @@ fn in_box(pts: impl Iterator, angle: f64, p: Vec2) -> bool { !b.is_empty() && b.contains(turn(p)) } -fn selectable(d: &Drawing, e: &Entity) -> bool { - d.is_visible(e) +/// Whether a selection may take `e` in: a visible object that commands can edit. A proxy (or +/// another record CADCraft keeps as it was read) is drawn and snapped to, but never selected: +/// commands can't edit it, and saving writes its record as it was read. +pub(crate) fn selectable(d: &Drawing, e: &Entity) -> bool { + d.is_visible(e) && !matches!(e.kind, EntityKind::Unknown(_)) } /// Entities to test, in the order to test them, each with its bounds when already known. @@ -373,7 +376,7 @@ pub fn select_polygon(d: &Drawing, space: &Space, poly: &[Vec2], crossing: bool) pub fn select_group(d: &Drawing, space: &Space, name: &str) -> Option> { let g = d.groups.iter().find(|g| g.name.eq_ignore_ascii_case(name.trim()))?; let store = d.space(space)?; - Some(g.members.iter().copied().filter(|h| store.get(*h).is_some_and(|e| d.is_visible(e))).collect()) + Some(g.members.iter().copied().filter(|h| store.get(*h).is_some_and(|e| selectable(d, e))).collect()) } /// A selection mode typed at "Select objects", collecting its points before it selects. diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index aa66bd4c5..aa32043dc 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -216,8 +216,10 @@ impl Session { let d = self.doc()?; let store = d.space(&space); let picked = match tl.as_str() { - "all" => store.map(|s| s.iter().filter(|e| d.is_visible(e)).map(|e| e.handle).collect()), - "l" | "last" => store.and_then(|s| s.last()).map(|e| vec![e.handle]), + "all" => store.map(|s| s.iter().filter(|e| select::selectable(d, e)).map(|e| e.handle).collect()), + "l" | "last" => store + .and_then(|s| s.iter().filter(|e| !matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).last()) + .map(|e| vec![e.handle]), "p" | "previous" => Some(self.state()?.previous_selection.clone()), _ => None, }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fec3fbb18..a5076fe7b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1490,3 +1490,34 @@ fn setvar_rejects_non_finite_text_for_real_variables() { } } } + +#[test] +fn a_proxy_is_drawn_but_no_selection_takes_it_in() { + // A proxy's graphics are drawn and measured, but saving writes its record unchanged: an edit + // could not hold. So a window round a line and a proxy, ALL, SELECTALL and a pick on the + // proxy's graphics leave the proxy out, and MOVE moves the line alone. + use cadcraft_doc::{Common, Entity, Handle, Line, Space, Unknown, entity_bounds}; + use cadcraft_geom::Vec3; + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let line = s.doc().unwrap().model.last().unwrap().handle; + let drawn = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) })); + let unknown = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![drawn] }; + let proxy = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Unknown(unknown)).unwrap(); + let bounds = |s: &Session| entity_bounds(s.doc().unwrap(), s.doc().unwrap().entity(proxy).unwrap(), 0); + let before = bounds(&s); + assert!(!before.is_empty(), "the proxy measures as its graphics"); + + s.idle_click(Vec2::new(5.0, 5.0), false).unwrap(); + assert_eq!(s.selection(), Vec::::new(), "a pick on the proxy's graphics"); + s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap(); + s.idle_click(Vec2::new(11.0, 6.0), false).unwrap(); + assert_eq!(s.selection(), vec![line], "a window round both"); + s.execute("selectall", &json!({})).unwrap(); + assert_eq!(s.selection(), vec![line], "SELECTALL"); + + s.execute("move", &json!({"delta": [0, 20]})).unwrap(); + let d = s.doc().unwrap(); + assert!(matches!(&d.entity(line).unwrap().kind, EntityKind::Line(l) if l.a.y == 20.0), "the line moved"); + assert_eq!(bounds(&s), before, "the proxy stayed where its record puts it"); +} From ce4b33ade237acce1657874147437b5b14a12cb9 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:42:57 +0100 Subject: [PATCH 053/187] fix(engine): Last takes the last selectable object; SELECT by handles leaves proxies out Last skipped only proxies, so with a proxy drawn last it could take an object on a layer turned off or frozen before it. It now takes the last object a selection may take in (`select::selectable`), at "Select objects" and in STRETCH. SELECT given handles outright leaves proxies out as well; other named objects are kept as before. The test covers both. --- crates/engine/src/cmd/edit.rs | 4 +++- crates/engine/src/cmd/modify/stretch.rs | 5 +---- crates/engine/src/session/interactive.rs | 4 +--- crates/engine/src/tests.rs | 19 +++++++++++++++++++ 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 93940baa5..644473f42 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -589,7 +589,9 @@ fn run_select(s: &mut Session, p: &Value) -> Result { } else if let Some(f) = points_param(p, "fence") { crate::select::select_fence(s.doc()?, &space, &f) } else { - targets(s, p)? + // Handles named outright, less the proxies: no selection takes one in. + let d = s.doc()?; + targets(s, p)?.into_iter().filter(|h| !d.entity(*h).is_some_and(|e| matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_)))).collect() }; let mut sel = if add { s.selection() } else { Vec::new() }; sel.extend(picked); diff --git a/crates/engine/src/cmd/modify/stretch.rs b/crates/engine/src/cmd/modify/stretch.rs index ed65f7da3..7e6db1347 100644 --- a/crates/engine/src/cmd/modify/stretch.rs +++ b/crates/engine/src/cmd/modify/stretch.rs @@ -271,10 +271,7 @@ impl StretchM { Some(store.map(|st| st.iter().filter(|e| crate::select::selectable(d, e)).map(|e| e.handle).collect()).unwrap_or_default()) } "l" | "last" => Some( - store - .and_then(|st| st.iter().filter(|e| !matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).last()) - .map(|e| vec![e.handle]) - .unwrap_or_default(), + store.and_then(|st| st.iter().filter(|e| crate::select::selectable(d, e)).last()).map(|e| vec![e.handle]).unwrap_or_default(), ), "p" | "previous" => Some(s.state()?.previous_selection.clone()), _ => { diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index aa32043dc..5a03444fc 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -217,9 +217,7 @@ impl Session { let store = d.space(&space); let picked = match tl.as_str() { "all" => store.map(|s| s.iter().filter(|e| select::selectable(d, e)).map(|e| e.handle).collect()), - "l" | "last" => store - .and_then(|s| s.iter().filter(|e| !matches!(e.kind, cadcraft_doc::EntityKind::Unknown(_))).last()) - .map(|e| vec![e.handle]), + "l" | "last" => store.and_then(|s| s.iter().filter(|e| select::selectable(d, e)).last()).map(|e| vec![e.handle]), "p" | "previous" => Some(self.state()?.previous_selection.clone()), _ => None, }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a5076fe7b..a7ad541c8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1501,6 +1501,12 @@ fn a_proxy_is_drawn_but_no_selection_takes_it_in() { let mut s = Session::new(); s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); let line = s.doc().unwrap().model.last().unwrap().handle; + // A line on a layer turned off, drawn before the proxy. + s.execute("layer.new", &json!({"name": "Hidden", "current": true})).unwrap(); + s.execute("line", &json!({"points": [[0, -10], [10, -10]]})).unwrap(); + let hidden = s.doc().unwrap().model.last().unwrap().handle; + s.execute("layer.current", &json!({"name": "0"})).unwrap(); + s.execute("layer.set", &json!({"name": "Hidden", "on": false})).unwrap(); let drawn = Entity::new(Handle(0), EntityKind::Line(Line { a: Vec3::new(0.0, 5.0, 0.0), b: Vec3::new(10.0, 5.0, 0.0) })); let unknown = Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics: vec![drawn] }; let proxy = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Unknown(unknown)).unwrap(); @@ -1520,4 +1526,17 @@ fn a_proxy_is_drawn_but_no_selection_takes_it_in() { let d = s.doc().unwrap(); assert!(matches!(&d.entity(line).unwrap().kind, EntityKind::Line(l) if l.a.y == 20.0), "the line moved"); assert_eq!(bounds(&s), before, "the proxy stayed where its record puts it"); + + // Handles named outright leave the proxy out too. + s.execute("select", &json!({"handles": [proxy.hex(), line.hex()]})).unwrap(); + assert_eq!(s.selection(), vec![line], "SELECT by handles"); + + // Last skips the proxy drawn last and the line on the layer turned off: it is the first line. + s.set_selection(Vec::new()); + s.start("erase").unwrap(); + s.input(Input::Text("L".into())).unwrap(); + s.input(Input::Enter).unwrap(); + let d = s.doc().unwrap(); + assert!(d.entity(line).is_none(), "Last took the visible line"); + assert!(d.entity(hidden).is_some() && d.entity(proxy).is_some(), "the hidden line and the proxy are kept"); } From 6ed01dea96aae91f731e6281a228fd27184f037c Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:33:07 +0100 Subject: [PATCH 054/187] fix(io): layer and linetype tables keep the file's order, so saved proxies keep their layers; Last searches from the top Proxy graphics name layers and linetypes by their index in the file's tables, and saving writes the proxy unchanged. The drawing's LAYER table started with CADCraft's 0 and Defpoints and took the file's layers after them, so a file without Defpoints at index 1 was saved with its layers shifted: reopened, the proxy's graphics went to Defpoints, which never plots. Reading now orders the layer and linetype tables as the file lists them (ByBlock and ByLayer first), with what CADCraft adds after them. The round-trip test checks that the reopened graphics stay on BALLOONS. Last searches the store from the top down (`EntityStore::iter_rev`) and stops at the first selectable object instead of scanning the whole space. --- crates/doc/src/store.rs | 5 +++++ crates/engine/src/cmd/modify/stretch.rs | 6 +++--- crates/engine/src/session/interactive.rs | 2 +- crates/io/src/dxf_read.rs | 24 ++++++++++++++++++++++++ crates/io/tests/it/proxy_graphics.rs | 14 ++++++++++++++ 5 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/store.rs b/crates/doc/src/store.rs index 00b04970e..1b26a0514 100644 --- a/crates/doc/src/store.rs +++ b/crates/doc/src/store.rs @@ -57,6 +57,10 @@ impl EntityStore { pub fn iter(&self) -> impl Iterator> + '_ { self.chunks.iter().flat_map(|c| c.items.iter()) } + /// Iterate from the top of the draw order down. + pub fn iter_rev(&self) -> impl Iterator> + '_ { + self.chunks.iter().rev().flat_map(|c| c.items.iter().rev()) + } pub fn handles(&self) -> Vec { self.iter().map(|e| e.handle).collect() } @@ -346,6 +350,7 @@ mod tests { } assert!(s.move_next_to(Handle(1), Handle(3), true)); assert_eq!(order(&s), [2, 3, 1, 4, 5]); + assert_eq!(s.iter_rev().map(|e| e.handle.0).collect::>(), [5, 4, 1, 3, 2], "top down"); assert!(s.move_next_to(Handle(5), Handle(2), false)); assert_eq!(order(&s), [5, 2, 3, 1, 4]); assert!(!s.move_next_to(Handle(5), Handle(5), true)); diff --git a/crates/engine/src/cmd/modify/stretch.rs b/crates/engine/src/cmd/modify/stretch.rs index 7e6db1347..ca6e455ac 100644 --- a/crates/engine/src/cmd/modify/stretch.rs +++ b/crates/engine/src/cmd/modify/stretch.rs @@ -270,9 +270,9 @@ impl StretchM { "all" => { Some(store.map(|st| st.iter().filter(|e| crate::select::selectable(d, e)).map(|e| e.handle).collect()).unwrap_or_default()) } - "l" | "last" => Some( - store.and_then(|st| st.iter().filter(|e| crate::select::selectable(d, e)).last()).map(|e| vec![e.handle]).unwrap_or_default(), - ), + "l" | "last" => { + Some(store.and_then(|st| st.iter_rev().find(|e| crate::select::selectable(d, e))).map(|e| vec![e.handle]).unwrap_or_default()) + } "p" | "previous" => Some(s.state()?.previous_selection.clone()), _ => { s.echo("*Invalid selection*"); diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 5a03444fc..28615759c 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -217,7 +217,7 @@ impl Session { let store = d.space(&space); let picked = match tl.as_str() { "all" => store.map(|s| s.iter().filter(|e| select::selectable(d, e)).map(|e| e.handle).collect()), - "l" | "last" => store.and_then(|s| s.iter().filter(|e| select::selectable(d, e)).last()).map(|e| vec![e.handle]), + "l" | "last" => store.and_then(|s| s.iter_rev().find(|e| select::selectable(d, e))).map(|e| vec![e.handle]), "p" | "previous" => Some(self.state()?.previous_selection.clone()), _ => None, }; diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 1d4254d7a..51bec13c0 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -66,6 +66,26 @@ struct Rx { proxy_tables: cadcraft_doc::ProxyTables, } +/// Order `items` as the file's table lists them (`order`, names in any case), after the `pinned` +/// names: records the file doesn't have keep their order after the file's own. A file without +/// that table changes nothing. +fn keep_file_order(items: &mut [T], name: impl Fn(&T) -> &str, order: &[String], pinned: &[&str]) { + if order.is_empty() { + return; + } + let mut place: HashMap = HashMap::new(); + for (i, n) in order.iter().enumerate() { + place.entry(n.to_ascii_lowercase()).or_insert(i); + } + items.sort_by_key(|it| { + let n = name(it); + match pinned.iter().position(|p| p.eq_ignore_ascii_case(n)) { + Some(i) => (0, i), + None => place.get(&n.to_ascii_lowercase()).map_or((2, 0), |&i| (1, i)), + } + }); +} + /// Read a DXF file into a drawing. pub fn read(bytes: &[u8]) -> Result { read_budgeted(bytes, 4_000_000) @@ -123,6 +143,10 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { _ => {} } } + // Proxy graphics name layers and linetypes by their place in the file's tables, and saving + // writes them unchanged: the tables keep the file's order, with what CADCraft adds after it. + keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]); + keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]); // A file CADCraft wrote names its own next handle (#495): its table records and objects // are numbered above it and rebuilt on save, so following $HANDSEED would drift every save. let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim())); diff --git a/crates/io/tests/it/proxy_graphics.rs b/crates/io/tests/it/proxy_graphics.rs index 5a099ddb9..b75aa6e91 100644 --- a/crates/io/tests/it/proxy_graphics.rs +++ b/crates/io/tests/it/proxy_graphics.rs @@ -133,4 +133,18 @@ fn a_proxy_is_written_back_unchanged_and_draws_again() { }; assert_eq!(graphics(&again), graphics(&d)); assert_eq!(graphics(&d).map(|g| g.1), Some(3)); + // The saved LAYER table keeps the file's order, so index 1 is still BALLOONS (CADCraft's + // Defpoints comes after it) and the reopened graphics stay on that layer. + let layers = |d: &cadcraft_doc::Drawing| -> Vec { + d.model + .iter() + .find_map(|e| match &e.kind { + EntityKind::Unknown(u) => Some(u.graphics.iter().map(|g| g.common.layer.clone()).collect()), + _ => None, + }) + .unwrap_or_default() + }; + assert_eq!(layers(&again), ["BALLOONS"; 3]); + let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["0", "BALLOONS", "Defpoints"]); } From 34b4899eee602cd70bfa027959b22556e73602f7 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck <8794773+whaslbeck@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:04:25 +0100 Subject: [PATCH 055/187] fix(io): text styles keep the file's order too, so a saved proxy text keeps its style A proxy text takes the first style whose font file it names. The drawing's styles started with CADCraft's Standard, which the file's Standard replaced in place, so a file listing ISO before Standard (both on the same font) was saved with Standard first, and the reopened text took it. Reading now keeps the STYLE table in the file's order as well. Test: `a_proxy_text_keeps_its_style_after_a_save`. --- crates/io/src/dxf_read.rs | 3 +++ crates/io/tests/it/proxy_graphics.rs | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 51bec13c0..7945820a6 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -147,6 +147,9 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result { // writes them unchanged: the tables keep the file's order, with what CADCraft adds after it. keep_file_order(&mut d.layers, |l| &l.name, &rx.proxy_tables.layers, &[]); keep_file_order(&mut d.linetypes, |l| &l.name, &rx.proxy_tables.linetypes, &["ByBlock", "ByLayer"]); + // A proxy text takes the first style on its font, so the styles keep the file's order too. + let styles: Vec = rx.proxy_tables.styles.iter().map(|(n, _)| n.clone()).collect(); + keep_file_order(&mut d.text_styles, |s| &s.name, &styles, &[]); // A file CADCraft wrote names its own next handle (#495): its table records and objects // are numbered above it and rebuilt on save, so following $HANDSEED would drift every save. let own_seed = objs.xrecord_text(crate::dxf_ext::HANDSEED_KEY).and_then(|t| Handle::parse_hex(t.trim())); diff --git a/crates/io/tests/it/proxy_graphics.rs b/crates/io/tests/it/proxy_graphics.rs index b75aa6e91..653a0af69 100644 --- a/crates/io/tests/it/proxy_graphics.rs +++ b/crates/io/tests/it/proxy_graphics.rs @@ -148,3 +148,25 @@ fn a_proxy_is_written_back_unchanged_and_draws_again() { let names: Vec<&str> = again.layers.iter().map(|l| l.name.as_str()).collect(); assert_eq!(names, ["0", "BALLOONS", "Defpoints"]); } + +/// A proxy text takes the first style on its font. With ISO and then Standard both on +/// isocp.shx, it is ISO, and stays ISO after a save: CADCraft's own Standard, which the file's +/// replaces, would otherwise come first in the saved STYLE table. +#[test] +fn a_proxy_text_keeps_its_style_after_a_save() { + let iso = "0\nSTYLE\n5\n12\n2\nISO\n3\nisocp.shx\n"; + let src = file().replacen(iso, &format!("{iso}0\nSTYLE\n5\n13\n2\nStandard\n3\nisocp.shx\n"), 1); + let style = |d: &cadcraft_doc::Drawing| { + d.model.iter().find_map(|e| match &e.kind { + EntityKind::Unknown(u) => u.graphics.iter().find_map(|g| match &g.kind { + EntityKind::Text(t) => Some(t.style.clone()), + _ => None, + }), + _ => None, + }) + }; + let d = read_dxf(src.as_bytes()).expect("read"); + assert_eq!(style(&d).as_deref(), Some("ISO")); + let again = read_dxf(write_dxf(&d).as_bytes()).expect("reopen"); + assert_eq!(style(&again).as_deref(), Some("ISO"), "after a save"); +} From 9eb81b3588b3e0a47f37e2002c3fa4adc05336cf Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Sat, 7 Nov 2026 03:01:02 +0400 Subject: [PATCH 056/187] i18n(ka): Georgian for 20 new strings Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/i18n/ka.tsv | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e40f492c7..3c4c7d739 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1472,3 +1472,23 @@ menu View ხედი Text to find მოსაძებნი ტექსტი Whole words მთლიანი სიტყვები Nothing found ვერაფერი მოიძებნა + Multiple Insert მრავალჯერადი ჩასმა + Ctrl+Enter to apply გამოსაყენებლად: Ctrl+Enter + Edit Text ტექსტის რედაქტირება + The drawing changed. Close the window and open it again. ნახაზი შეიცვალა. დახურეთ ფანჯარა და ხელახლა გახსენით. + DView დინამიკური ხედი + Raster Image Reference... რასტრული გამოსახულების მიმართვა... + Raster Images რასტრული გამოსახულებები + Clip Xref გარე მიმართვის მოჭრა + Xref გარე მიმართვა + Xref Clip Frame გარე მიმართვის მოჭრის ჩარჩო + Backup copies are off, so the current file will be replaced. სარეზერვო ასლები გამორთულია, ამიტომ მიმდინარე ფაილი ჩანაცვლდება. + DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. DXF 2010 და უფრო ძველი ვერსიები მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. + DXF keeps them. Use Save As to keep them in the drawing. DXF მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. + Save Anyway მაინც შენახვა + Save cancelled: {path} was not changed. შენახვა გაუქმდა: {path} არ შეცვლილა. + Saving {name} will remove content ფაილში {name} შენახვისას შიგთავსის ნაწილი წაიშლება + The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. მიმდინარე ფაილი არასრული ჩანს, ამიტომ {name} უცვლელი რჩება, მიმდინარე ფაილი კი ჩანაცვლდება. + The current file is kept as {name} until the next save. მიმდინარე ფაილი შემდეგ შენახვამდე შენარჩუნდება სახელით {name}. + This format can't keep these objects yet: {objects}. ეს ფორმატი ამ ობიექტებს ჯერ ვერ ინახავს: {objects}. + {count} more types კიდევ {count} ტიპი From 53cebb9020ef4fdce870df6fa20afa0f8455b6b6 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:14:07 +0300 Subject: [PATCH 057/187] i18n(ar): tell Trim, Stretch and Extend apart, and call Point a point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trim read «حدود التشذيب» ("trim boundaries"), Stretch read «تمديد», the same word as Extend, and Point read «تأشير», the word the catalog uses for Dimension. Trim is now «تشذيب», and its two selection prompts match it (they said «قص», which is also Cut). Stretch, its grip and vertex items and its selection prompt use «مط». Point is «نقطة», as in Point Style and Single Point. Written from the meaning of the English strings. --- crates/ui-egui/src/i18n/ar.tsv | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 3d3921b28..0f963384e 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -406,7 +406,7 @@ Grip Option خيار المقبض Grip Rotate تدوير بالمقبض Grip Scale تحجيم بالمقبض - Grip Stretch تمديد بالمقبض + Grip Stretch مط بالمقبض Grip size حجم المقبض Group تجميع Group Edit تحرير المجموعة @@ -703,7 +703,7 @@ Plotter Manager مدير الطابعات Plotter Manager... مدير الطابعات... Plus/minus زائد/ناقص - Point تأشير + Point نقطة Point Filters مرشحات النقطة Point Style... نمط النقطة... Polar (distance < angle) قطبي (المسافة < الزاوية) @@ -872,15 +872,15 @@ Select object حدد كائناً Select object to dimension حدد كائناً لتأشيره Select object to divide حدد كائناً لتقسيمه - Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للقص + Select object to extend or shift-select to trim حدد كائناً لتمديده أو حدد مع Shift للتشذيب Select object to measure حدد كائناً لقياسه Select object to offset حدد كائناً لإزاحته - Select object to trim or shift-select to extend حدد كائناً لقصه أو حدد مع Shift للتمديد + Select object to trim or shift-select to extend حدد كائناً لتشذيبه أو حدد مع Shift للتمديد Select objects حدد كائنات Select objects (crossing window first corner) حدد كائنات (الزاوية الأولى لنافذة التقاطع) Select objects first, then choose a command حدد الكائنات أولاً ثم اختر أمراً Select objects to array. حدد كائنات لتكوين مصفوفة. - Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمديدها بنافذة التقاطع أو مضلع التقاطع... + Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لمطها بنافذة التقاطع أو مضلع التقاطع... Select objects: حدد كائنات: Select one polyline (Multiple is available through the JSON form). حدد متعدد خطوط واحداً (يتوفر الوضع المتعدد عبر نموذج JSON). Select path curve حدد منحنى المسار @@ -1083,8 +1083,8 @@ Start, End, Radius بداية، نهاية، نصف قطر Status الحالة Status Bar شريط الحالة - Stretch تمديد - Stretch Vertex تمديد رأس + Stretch مط + Stretch Vertex مط رأس Style: Standard النمط: Standard Subtract طرح Sweep كنس @@ -1133,7 +1133,7 @@ Track orthogonally only تعقب متعامد فقط Track using all polar angle settings تعقب باستخدام كل إعدادات الزوايا القطبية Transparency شفافية - Trim حدود التشذيب + Trim تشذيب True Color لون حقيقي Turn All Layers On تشغيل كل الطبقات Turn Off Layer إيقاف طبقة From 17da6ab38a5ea2e5ada1d64bc510186dafeeb7e3 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:29:56 +0300 Subject: [PATCH 058/187] =?UTF-8?q?i18n(ar):=20call=20Stretch=20=C2=AB?= =?UTF-8?q?=D8=AA=D9=85=D8=B7=D9=8A=D8=B7=C2=BB,=20in=20the=20same=20form?= =?UTF-8?q?=20as=20the=20other=20edit=20verbs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/i18n/ar.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 0f963384e..ed5c53135 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -406,7 +406,7 @@ Grip Option خيار المقبض Grip Rotate تدوير بالمقبض Grip Scale تحجيم بالمقبض - Grip Stretch مط بالمقبض + Grip Stretch تمطيط بالمقبض Grip size حجم المقبض Group تجميع Group Edit تحرير المجموعة @@ -880,7 +880,7 @@ Select objects (crossing window first corner) حدد كائنات (الزاوية الأولى لنافذة التقاطع) Select objects first, then choose a command حدد الكائنات أولاً ثم اختر أمراً Select objects to array. حدد كائنات لتكوين مصفوفة. - Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لمطها بنافذة التقاطع أو مضلع التقاطع... + Select objects to stretch by crossing-window or crossing-polygon... حدد كائنات لتمطيطها بنافذة التقاطع أو مضلع التقاطع... Select objects: حدد كائنات: Select one polyline (Multiple is available through the JSON form). حدد متعدد خطوط واحداً (يتوفر الوضع المتعدد عبر نموذج JSON). Select path curve حدد منحنى المسار @@ -1083,8 +1083,8 @@ Start, End, Radius بداية، نهاية، نصف قطر Status الحالة Status Bar شريط الحالة - Stretch مط - Stretch Vertex مط رأس + Stretch تمطيط + Stretch Vertex تمطيط رأس Style: Standard النمط: Standard Subtract طرح Sweep كنس From 2dd428dc2d700269f989a308c2c552ff716f9f92 Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Sat, 7 Nov 2026 08:48:19 +0100 Subject: [PATCH 059/187] i18n(sv): translate 41 new strings Brings the Swedish catalog up to date with upstream main (865fa9af). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/sv.tsv | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f34f32ca5..25eef1d1c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1483,3 +1483,44 @@ menu Modify Ändra 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. + DView DView + Keyboard Shortcuts... Kortkommandon... + Multiple Insert Infoga flera + Raster Image Reference... Rasterbildsreferens... + Raster Images Rasterbilder + Clip Xref Beskär xref + Xref Xref + Xref Clip Frame Beskärningsram för xref + A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Ett kortkommando du anger går före CADCrafts eget. Ändringar gäller direkt och sparas till nästa gång. + Alias files (PGP) Aliasfiler (PGP) + Aliases are saved in your CADCraft profile and survive restarts. Alias sparas i din CADCraft-profil och finns kvar efter omstart. + Back to CADCraft's shortcut Tillbaka till CADCrafts kortkommando + Command Mode Kommandoläge + Default Mode Standardläge + Edit Mode Redigeringsläge + ENTER ENTER + Import and replace Importera och ersätt + Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. Importera: det finns ingen fildialogruta här; kör ALIASEDIT med filens innehåll i dess textparameter. + Importing a file replaces your {n} aliases, and any changes not applied yet. Om du importerar en fil ersätts dina {n} alias och alla ändringar du inte har använt än. + Import… Importera… + Keep my aliases Behåll mina alias + Keyboard Shortcuts Kortkommandon + Longer click duration: Längd för längre klick: + milliseconds millisekunder + Needs Ctrl, Alt or a function key Kräver Ctrl, Alt eller en funktionstangent + No objects selected and no command running: Inga objekt markerade och inget kommando körs: + Objects selected and no command running: Objekt markerade och inget kommando körs: + Press the keys Tryck på tangenterna + Repeat last command Upprepa senaste kommandot + Replaces the shortcut of {commands} Ersätter kortkommandot för {commands} + Right-Click Customization Anpassning av högerklick + Right-Click Customization... Anpassning av högerklick... + Run ALIASEDIT with the file's contents using its text parameter. Kör ALIASEDIT med filens innehåll i dess textparameter. + Shortcut Menu Snabbmeny + Shortcut Menu: always enabled Snabbmeny: alltid aktiverad + Shortcut Menu: enabled when command options are present Snabbmeny: aktiverad när det finns kommandoalternativ + Turn on time-sensitive right-click Slå på tidskänsligt högerklick + Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. När det är avstängt gör ett högerklick under ett pågående kommando det som Anpassning av högerklick anger för kommandoläget. + While a command runs, a quick click is Enter and a longer click opens the shortcut menu. Medan ett kommando körs är ett snabbt klick Enter och ett längre klick öppnar snabbmenyn. + While a command runs: Medan ett kommando körs: + {n} more warnings; see the command line. {n} varningar till; se kommandoraden. From bc7f41d5387fa8c81fce6db80f220ddc8a9929a0 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 8 Nov 2026 00:25:32 +1100 Subject: [PATCH 060/187] Select: a blank MTEXT is picked inside its box (#2810) A blank or whitespace-only MTEXT has no glyph strokes and empty drawn bounds, so a click inside it, and the spatial index, missed it. It is now picked (and window/crossing selected) in its width x text-height box, placed by its attachment point and rotation. --- crates/engine/src/select.rs | 124 ++++++++++++++++++++++++++++++++++- crates/engine/src/spatial.rs | 3 +- 2 files changed, 124 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index b5ef2dc9f..c127f3047 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -97,7 +97,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min); let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_)) || matches!(e.kind, EntityKind::Tolerance(_)); - if (filled && entity_bounds(d, e, 0).contains(p)) || in_text(d, e, p) { + if (filled && pick_bounds(d, e).contains(p)) || in_text(d, e, p) { best = 0.0; } // A solid hatch fills its loops with odd parity under its island style, as it is drawn, not @@ -159,8 +159,45 @@ fn selectable(d: &Drawing, e: &Entity) -> bool { /// Entities to test, in the order to test them, each with its bounds when already known. pub(crate) type Cands<'a> = Box)> + 'a>; +/// Whether an MTEXT's contents draw nothing (empty, or only spaces and `\~`): it has no glyph +/// strokes, and the document's bounds for it are empty so it stays out of the drawing extents. +fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool { + t.contents.replace(r"\~", " ").chars().all(char::is_whitespace) +} + +/// The box a blank MTEXT is picked in (#2810): its width (the text height when it has none) by its +/// text height, placed by its attachment point and turned by its rotation about the insertion +/// point. `None` for any other entity, or a blank MTEXT without a usable size or position. +pub(crate) fn blank_mtext_box(e: &Entity) -> Option { + let EntityKind::MText(t) = &e.kind else { return None }; + if !is_blank_mtext(t) || !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { + return None; + } + let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height }; + let h = t.height; + let dx = match t.attach { + 2 | 5 | 8 => -w / 2.0, + 3 | 6 | 9 => -w, + _ => 0.0, + }; + let top = match t.attach { + 4..=6 => h / 2.0, + 7..=9 => h, + _ => 0.0, + }; + let corners = [Vec2::new(dx, top), Vec2::new(dx + w, top), Vec2::new(dx + w, top - h), Vec2::new(dx, top - h)]; + Some(Bounds2::from_points(corners.map(|c| t.insert.xy() + c.rotate(t.rotation)))) +} + +/// The box `e` is selected by: its drawn bounds, or for a blank MTEXT (whose drawn bounds are +/// empty) the box it is picked in. +pub(crate) fn pick_bounds(d: &Drawing, e: &Entity) -> Bounds2 { + let b = entity_bounds(d, e, 0); + if b.is_empty() { blank_mtext_box(e).unwrap_or(b) } else { b } +} + pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Bounds2 { - known.unwrap_or_else(|| entity_bounds(d, e, 0)) + known.unwrap_or_else(|| pick_bounds(d, e)) } pub(crate) fn is_infinite(e: &Entity) -> bool { @@ -514,6 +551,89 @@ mod tests { assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line)); } + fn mtext_at(contents: &str, attach: u8, rotation: f64) -> EntityKind { + EntityKind::MText(cadcraft_doc::MText { + insert: Vec3::new(0.0, 0.0, 0.0), + height: 2.5, + width: 10.0, + attach, + rotation, + style: "Standard".into(), + contents: contents.into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }) + } + + /// A blank MTEXT has no strokes and empty drawn bounds, but it is still an object: a click + /// inside its width x height box picks it, and a click outside does not (#2810). + #[test] + fn a_blank_mtext_is_picked_inside_its_box() { + for contents in ["", " ", r"\~ "] { + let mut d = Drawing::new_metric(); + let h = d.add(&Space::Model, Common::default(), mtext_at(contents, 1, 0.0)).unwrap(); + let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.1); + assert_eq!(at(5.0, -1.0), Some(h), "{contents:?}"); + assert_eq!(at(0.5, -2.0), Some(h), "{contents:?}"); + assert_eq!(at(5.0, 3.0), None, "above the box, {contents:?}"); + assert_eq!(at(12.0, -1.0), None, "right of the box, {contents:?}"); + assert_eq!(pick_all(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), vec![h]); + let w = Bounds2::new(Vec2::new(4.0, -2.0), Vec2::new(6.0, -1.0)); + assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing {contents:?}"); + } + } + + /// The box follows the attachment point and the rotation, and a width of 0 falls back to the + /// text height. + #[test] + fn a_blank_mtext_box_follows_attachment_and_rotation() { + let mut d = Drawing::new_metric(); + // Middle-centre: the box spans x -5..5, y -1.25..1.25. + let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, 0.0)).unwrap(); + let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05); + assert_eq!(at(&d, -4.0, 1.0), Some(h)); + assert_eq!(at(&d, 4.0, -1.0), Some(h)); + assert_eq!(at(&d, 4.0, 2.0), None); + // Turned a quarter turn about the insertion point: the box spans x -1.25..1.25, y -5..5. + let mut d = Drawing::new_metric(); + let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 5, std::f64::consts::FRAC_PI_2)).unwrap(); + assert_eq!(at(&d, 1.0, 4.0), Some(h)); + assert_eq!(at(&d, 4.0, 1.0), None); + // No width: as wide as the text is high. + let mut d = Drawing::new_metric(); + let EntityKind::MText(mut t) = mtext_at("", 1, 0.0) else { panic!("mtext") }; + t.width = 0.0; + let h = d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + assert_eq!(at(&d, 2.0, -1.0), Some(h)); + assert_eq!(at(&d, 5.0, -1.0), None); + } + + /// A drawing large enough for the spatial index must still offer a blank MTEXT as a candidate. + #[test] + fn a_blank_mtext_is_picked_in_an_indexed_drawing() { + let mut d = Drawing::new_metric(); + for i in 0..(crate::spatial::MIN_INDEXED + 10) { + let y = 100.0 + i as f64; + let l = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) }); + d.add(&Space::Model, Common::default(), l).unwrap(); + } + let h = d.add(&Space::Model, Common::default(), mtext_at("", 1, 0.0)).unwrap(); + assert!(spatial::index(&d, &Space::Model).is_some()); + assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.1), Some(h)); + assert_eq!(pick(&d, &Space::Model, Vec2::new(5.0, 3.0), 0.1), None); + } + + /// Text with words is still picked by its drawn box only. + #[test] + fn a_click_far_from_a_normal_mtext_misses() { + let mut d = Drawing::new_metric(); + let h = d.add(&Space::Model, Common::default(), mtext_at("AB", 1, 0.0)).unwrap(); + assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, -1.0), 0.1), Some(h)); + assert_eq!(pick(&d, &Space::Model, Vec2::new(8.0, -1.0), 0.1), None); + assert_eq!(pick(&d, &Space::Model, Vec2::new(1.0, 5.0), 0.1), None); + } + /// 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] diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 6740707c0..53234668c 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -53,7 +53,8 @@ impl ChunkIx { if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) { infinite.push(u32::try_from(i).unwrap_or(u32::MAX)); } - entity_bounds_cached(d, e, 0, &mut cache) + let b = entity_bounds_cached(d, e, 0, &mut cache); + if b.is_empty() { crate::select::blank_mtext_box(e).unwrap_or(b) } else { b } }) .collect(); let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); From 89817444f2ad64ddd2d1c0e2040e3746bca06e7e Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 8 Nov 2026 11:16:01 +1100 Subject: [PATCH 061/187] Select: a turned blank MTEXT is picked in its turned box (#2810) A click on a blank MTEXT is tested in its box turned with the text, not the axis-aligned box around it (the spatial index and windows keep the larger box). One helper holds the frame geometry for both. --- crates/engine/src/select.rs | 42 ++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index c127f3047..aa51201b5 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -97,7 +97,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min); let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_)) || matches!(e.kind, EntityKind::Tolerance(_)); - if (filled && pick_bounds(d, e).contains(p)) || in_text(d, e, p) { + if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(e, p) || in_text(d, e, p) { best = 0.0; } // A solid hatch fills its loops with odd parity under its island style, as it is drawn, not @@ -165,10 +165,11 @@ fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool { t.contents.replace(r"\~", " ").chars().all(char::is_whitespace) } -/// The box a blank MTEXT is picked in (#2810): its width (the text height when it has none) by its -/// text height, placed by its attachment point and turned by its rotation about the insertion -/// point. `None` for any other entity, or a blank MTEXT without a usable size or position. -pub(crate) fn blank_mtext_box(e: &Entity) -> Option { +/// The frame a blank MTEXT is picked in (#2810): its insertion point, rotation and the box before +/// turning (`x0, x1, y0, y1` about the insertion point): its width (the text height when it has +/// none) by its text height, placed by its attachment point. `None` for any other entity, or a +/// blank MTEXT without a usable size or position. +fn blank_mtext_frame(e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { let EntityKind::MText(t) = &e.kind else { return None }; if !is_blank_mtext(t) || !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { return None; @@ -185,8 +186,22 @@ pub(crate) fn blank_mtext_box(e: &Entity) -> Option { 7..=9 => h, _ => 0.0, }; - let corners = [Vec2::new(dx, top), Vec2::new(dx + w, top), Vec2::new(dx + w, top - h), Vec2::new(dx, top - h)]; - Some(Bounds2::from_points(corners.map(|c| t.insert.xy() + c.rotate(t.rotation)))) + Some((t.insert.xy(), t.rotation, [dx, dx + w, top - h, top])) +} + +/// The box around a blank MTEXT's turned frame, for the spatial index and windows (a crossing +/// window may catch a little extra near a corner, as it does for other text). +pub(crate) fn blank_mtext_box(e: &Entity) -> Option { + let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(e)?; + let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)]; + Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot)))) +} + +/// Whether `p` is on a blank MTEXT: inside its box turned with the text, not the larger box around it. +fn in_blank_mtext(e: &Entity, p: Vec2) -> bool { + let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(e) else { return false }; + let q = (p - o).rotate(-rot); + q.x >= x0 && q.x <= x1 && q.y >= y0 && q.y <= y1 } /// The box `e` is selected by: its drawn bounds, or for a blank MTEXT (whose drawn bounds are @@ -609,6 +624,19 @@ mod tests { assert_eq!(at(&d, 5.0, -1.0), None); } + /// A turned blank MTEXT is hit in its turned box, not in the axis-aligned box around it (whose + /// empty corners lie off the text). + #[test] + fn a_turned_blank_mtext_is_picked_in_its_turned_box() { + let mut d = Drawing::new_metric(); + let h = d.add(&Space::Model, Common::default(), mtext_at(" ", 1, 30f64.to_radians())).unwrap(); + let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05); + // Local (5, -1.25), the centre of the box. + assert_eq!(at(4.955, 1.418), Some(h)); + // Inside the box around the turned one, but local (2.87, 2.96) is above the text. + assert_eq!(at(1.0, 4.0), None); + } + /// A drawing large enough for the spatial index must still offer a blank MTEXT as a candidate. #[test] fn a_blank_mtext_is_picked_in_an_indexed_drawing() { From f04ca5144e5e5d32198679ba819232fbefe02f40 Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 8 Nov 2026 14:03:57 +1100 Subject: [PATCH 062/187] Size a blank MTEXT's pick box at the current annotation scale An annotative blank MTEXT is picked in the box it draws at CANNOSCALE, and not at all while that scale hides it, as its drawn bounds already are. --- crates/engine/src/select.rs | 56 +++++++++++++++++++++++++++++------- crates/engine/src/spatial.rs | 2 +- 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index aa51201b5..153adfdcc 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -97,7 +97,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min); let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_)) || matches!(e.kind, EntityKind::Tolerance(_)); - if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(e, p) || in_text(d, e, p) { + if (filled && entity_bounds(d, e, 0).contains(p)) || in_blank_mtext(d, e, p) || in_text(d, e, p) { best = 0.0; } // A solid hatch fills its loops with odd parity under its island style, as it is drawn, not @@ -167,15 +167,26 @@ fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool { /// The frame a blank MTEXT is picked in (#2810): its insertion point, rotation and the box before /// turning (`x0, x1, y0, y1` about the insertion point): its width (the text height when it has -/// none) by its text height, placed by its attachment point. `None` for any other entity, or a -/// blank MTEXT without a usable size or position. -fn blank_mtext_frame(e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { +/// none) by its text height, placed by its attachment point, at the size it draws at the current +/// annotation scale. `None` for any other entity, a blank MTEXT without a usable size or position, +/// or an annotative one the current annotation scale hides. +fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { let EntityKind::MText(t) = &e.kind else { return None }; if !is_blank_mtext(t) || !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { return None; } - let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height }; - let h = t.height; + // Sized as `anno_scaled` sizes it; the insertion point stays. + let f = match d.anno_draw(e) { + cadcraft_doc::AnnoDraw::Plain => 1.0, + cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f, + cadcraft_doc::AnnoDraw::Scaled(_) => 1.0, + cadcraft_doc::AnnoDraw::Hidden => return None, + }; + let w = f * if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height }; + let h = f * t.height; + if !w.is_finite() || !h.is_finite() { + return None; + } let dx = match t.attach { 2 | 5 | 8 => -w / 2.0, 3 | 6 | 9 => -w, @@ -191,15 +202,15 @@ fn blank_mtext_frame(e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { /// The box around a blank MTEXT's turned frame, for the spatial index and windows (a crossing /// window may catch a little extra near a corner, as it does for other text). -pub(crate) fn blank_mtext_box(e: &Entity) -> Option { - let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(e)?; +pub(crate) fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option { + let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(d, e)?; let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)]; Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot)))) } /// Whether `p` is on a blank MTEXT: inside its box turned with the text, not the larger box around it. -fn in_blank_mtext(e: &Entity, p: Vec2) -> bool { - let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(e) else { return false }; +fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool { + let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(d, e) else { return false }; let q = (p - o).rotate(-rot); q.x >= x0 && q.x <= x1 && q.y >= y0 && q.y <= y1 } @@ -208,7 +219,7 @@ fn in_blank_mtext(e: &Entity, p: Vec2) -> bool { /// empty) the box it is picked in. pub(crate) fn pick_bounds(d: &Drawing, e: &Entity) -> Bounds2 { let b = entity_bounds(d, e, 0); - if b.is_empty() { blank_mtext_box(e).unwrap_or(b) } else { b } + if b.is_empty() { blank_mtext_box(d, e).unwrap_or(b) } else { b } } pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Bounds2 { @@ -637,6 +648,29 @@ mod tests { assert_eq!(at(1.0, 4.0), None); } + /// An annotative blank MTEXT is picked in the box it draws at the current annotation scale, + /// and not at all while that scale hides it. + #[test] + fn an_annotative_blank_mtext_is_picked_at_its_drawn_size() { + let mut d = Drawing::new_metric(); + d.header.set_str("CANNOSCALE", "1:2"); + let half = d.anno_scale("1:2").cloned().unwrap(); + let common = Common { anno_scales: vec![half], ..Common::default() }; + // Middle-centre at 1:2: twice the size, x -10..10, y -2.5..2.5. + let h = d.add(&Space::Model, common, mtext_at(" ", 5, 0.0)).unwrap(); + let at = |d: &Drawing, x: f64, y: f64| pick(d, &Space::Model, Vec2::new(x, y), 0.05); + assert_eq!(at(&d, 8.0, 2.0), Some(h), "inside the scaled box"); + assert_eq!(at(&d, 11.0, 0.0), None, "outside the scaled box"); + let w = Bounds2::new(Vec2::new(7.0, 1.0), Vec2::new(9.0, 2.0)); + assert_eq!(select_window(&d, &Space::Model, w, true), vec![h], "crossing the scaled box"); + // At 1:1 with only supported scales shown, the object is hidden: nothing to pick. + d.header.set_str("CANNOSCALE", "1:1"); + d.header.set_i64("ANNOALLVISIBLE", 0); + assert_eq!(at(&d, 0.0, 0.0), None, "hidden"); + let w = Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(1.0, 1.0)); + assert!(select_window(&d, &Space::Model, w, true).is_empty(), "hidden, crossing"); + } + /// A drawing large enough for the spatial index must still offer a blank MTEXT as a candidate. #[test] fn a_blank_mtext_is_picked_in_an_indexed_drawing() { diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 53234668c..8aedaf6a2 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -54,7 +54,7 @@ impl ChunkIx { infinite.push(u32::try_from(i).unwrap_or(u32::MAX)); } let b = entity_bounds_cached(d, e, 0, &mut cache); - if b.is_empty() { crate::select::blank_mtext_box(e).unwrap_or(b) } else { b } + if b.is_empty() { crate::select::blank_mtext_box(d, e).unwrap_or(b) } else { b } }) .collect(); let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); From 410bdc733facbdbd19d61041f15a640f9858eb0a Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sun, 8 Nov 2026 07:24:34 +0300 Subject: [PATCH 063/187] i18n(ar): test that Stretch, Trim and Point keep words of their own --- crates/ui-egui/src/i18n/tests.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2d13612df..3fd7e1c49 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -656,3 +656,19 @@ fn vietnamese_takes_one_form_and_needs_a_font_with_its_letters() { assert_eq!(Preference::Vietnamese.name(), "Vietnamese"); } } + +/// Arabic gives Stretch, Trim and Point words of their own: Stretch read «تمديد» like Extend, +/// Trim's prompts said «قص» like Cut, and Point read «تأشير», the catalog's word for dimensioning. +#[test] +fn arabic_tells_stretch_trim_and_point_from_their_neighbours() { + for (a, b) in [("Stretch", "Extend"), ("Trim", "Cut"), ("Point", "Dimension")] { + assert_ne!(tr("ar", a), tr("ar", b), "{a} and {b} share a word"); + } + for (prompt, verb) in [ + ("Select object to trim or shift-select to extend", "تشذيب"), + ("Select object to extend or shift-select to trim", "تشذيب"), + ("Select objects to stretch by crossing-window or crossing-polygon...", "تمطيط"), + ] { + assert!(tr("ar", prompt).contains(verb), "{prompt}"); + } +} From 2ef9cf67cfd884ab71895f42c87ea1ac97913e7c Mon Sep 17 00:00:00 2001 From: SBaksa Date: Mon, 9 Nov 2026 13:08:36 +1100 Subject: [PATCH 064/187] Select: a blank MLEADER text is picked inside its box (#2810) Share the blank MTEXT frame with multileader picking and extend the candidate bounds used by both scans and the spatial index. Cover empty and whitespace boxes and preserve normal text picking. --- crates/engine/src/select.rs | 71 ++++++++++++++++++++++++++++++------ crates/engine/src/spatial.rs | 2 +- 2 files changed, 60 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 153adfdcc..ec57774a6 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -171,11 +171,15 @@ fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool { /// annotation scale. `None` for any other entity, a blank MTEXT without a usable size or position, /// or an annotative one the current annotation scale hides. fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { - let EntityKind::MText(t) = &e.kind else { return None }; + let (t, landing) = match &e.kind { + EntityKind::MText(t) => (t, None), + EntityKind::MLeader(m) => (m.text.as_ref()?, Some(m.landing.xy())), + _ => return None, + }; if !is_blank_mtext(t) || !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { return None; } - // Sized as `anno_scaled` sizes it; the insertion point stays. + // Match the drawn annotation size and the multileader text offset from its landing. let f = match d.anno_draw(e) { cadcraft_doc::AnnoDraw::Plain => 1.0, cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f, @@ -184,7 +188,12 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { }; let w = f * if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height }; let h = f * t.height; - if !w.is_finite() || !h.is_finite() { + let insert = t.insert.xy(); + let insert = match landing { + Some(landing) if f != 1.0 => landing + (insert - landing) * f, + _ => insert, + }; + if !w.is_finite() || !h.is_finite() || !insert.is_finite() { return None; } let dx = match t.attach { @@ -197,12 +206,12 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { 7..=9 => h, _ => 0.0, }; - Some((t.insert.xy(), t.rotation, [dx, dx + w, top - h, top])) + Some((insert, t.rotation, [dx, dx + w, top - h, top])) } /// The box around a blank MTEXT's turned frame, for the spatial index and windows (a crossing /// window may catch a little extra near a corner, as it does for other text). -pub(crate) fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option { +fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option { let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(d, e)?; let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)]; Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot)))) @@ -215,17 +224,15 @@ fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool { q.x >= x0 && q.x <= x1 && q.y >= y0 && q.y <= y1 } -/// The box `e` is selected by: its drawn bounds, or for a blank MTEXT (whose drawn bounds are -/// empty) the box it is picked in. -pub(crate) fn pick_bounds(d: &Drawing, e: &Entity) -> Bounds2 { - let b = entity_bounds(d, e, 0); - if b.is_empty() { blank_mtext_box(d, e).unwrap_or(b) } else { b } +/// Drawn bounds extended by a blank MTEXT frame, including a multileader's text content. +/// Use the same bounds for a scan and for the spatial index. +pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 { + blank_mtext_box(d, e).map_or(drawn, |frame| drawn.union(&frame)) } pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Bounds2 { - known.unwrap_or_else(|| pick_bounds(d, e)) + known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0))) } - pub(crate) fn is_infinite(e: &Entity) -> bool { matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) } @@ -610,6 +617,46 @@ mod tests { } } + #[test] + fn a_blank_mleader_text_is_picked_inside_its_box() { + for contents in [" ", ""] { + let mut s = crate::Session::new(); + let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap(); + let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap(); + // The command omits the text object for an empty string. Preserve the box here to + // exercise a stored empty MTEXT, which can still exist in an imported MLEADER. + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") }; + m.text.as_mut().unwrap().contents = contents.into(); + }) + .unwrap(); + let d = s.doc().unwrap(); + let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") }; + let t = m.text.as_ref().unwrap(); + let p = t.insert.xy() + Vec2::new(t.height / 2.0, -t.height / 4.0); + let aperture = t.height / 100.0; + assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "{contents:?}"); + + let d = s.doc_mut().unwrap(); + for i in 0..spatial::MIN_INDEXED { + let y = 100.0 + i as f64; + let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(50.0, y, 0.0), b: Vec3::new(60.0, y, 0.0) }); + d.add(&Space::Model, Common::default(), line).unwrap(); + } + assert!(spatial::index(d, &Space::Model).is_some()); + assert_eq!(pick(d, &Space::Model, p, aperture), Some(h), "indexed {contents:?}"); + } + } + + #[test] + fn a_pick_away_from_normal_mleader_text_and_lines_misses() { + let mut s = crate::Session::new(); + s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 10]], "text": "Visible" })).unwrap(); + assert_eq!(pick(s.doc().unwrap(), &Space::Model, Vec2::new(2.0, 8.0), 0.05), None); + } + /// The box follows the attachment point and the rotation, and a width of 0 falls back to the /// text height. #[test] diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 8aedaf6a2..776d5a826 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -54,7 +54,7 @@ impl ChunkIx { infinite.push(u32::try_from(i).unwrap_or(u32::MAX)); } let b = entity_bounds_cached(d, e, 0, &mut cache); - if b.is_empty() { crate::select::blank_mtext_box(d, e).unwrap_or(b) } else { b } + crate::select::pick_bounds(d, e, b) }) .collect(); let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); From bb36fab20e6f70f7a4052480b0df314959ed9e54 Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Mon, 9 Nov 2026 12:11:19 -0500 Subject: [PATCH 065/187] fix(engine): retain hatch direction in mirror commands and previews --- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/modify/select_then.rs | 34 +++-- crates/engine/src/cmd/modify/transform.rs | 25 +++- crates/engine/tests/mirror_hatch_direction.rs | 127 ++++++++++++++++++ 4 files changed, 172 insertions(+), 16 deletions(-) create mode 100644 crates/engine/tests/mirror_hatch_direction.rs diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 367dacc65..a11d952bc 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -36,7 +36,7 @@ pub(crate) use oops::{Erased, erase_kept}; use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; 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}; +use transform::{mirror_entities, mirror_kind, run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; pub(crate) use trim::{Edges, extend, trim}; pub fn specs() -> Vec { diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index 009a95281..d8a0443b6 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -2,7 +2,8 @@ use super::break_join::join; use super::explode::explode; use super::transform::{at_elevation, erase, scale_entities, transform_entities}; use super::{ - Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line, number, + Accept, EngineError, EntityKind, Handle, Input, Interactive, Mat3, Prompt, Result, SelOutcome, SelectPhase, Session, Step, Vec2, line, + mirror_entities, mirror_kind, number, }; // ---------------- interactive ---------------- @@ -248,10 +249,11 @@ impl SelectThen { } } -/// Objects whose text MIRROR keeps readable instead of mirroring it with the geometry. -fn keeps_reading_when_mirrored(k: &EntityKind) -> bool { +/// Objects MIRROR must preview individually: readable text and hatches retaining fill direction. +fn needs_mirror_preview(k: &EntityKind) -> bool { match k { EntityKind::Insert(i) => !i.attribs.is_empty(), + EntityKind::Hatch(h) => !h.solid || h.gradient.is_some(), k => matches!( k, EntityKind::Text(_) @@ -265,8 +267,8 @@ fn keeps_reading_when_mirrored(k: &EntityKind) -> bool { } } -/// Text objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn. -const MAX_MIRROR_TEXT_PREVIEW: usize = 1000; +/// Objects transformed for each frame of a MIRROR preview (on the CPU); more are not drawn. +const MAX_MIRROR_OBJECT_PREVIEW: usize = 1000; /// A finite length greater than zero (rejects 0, negatives, NaN and infinity). fn positive_length(v: Option) -> Option { @@ -364,7 +366,7 @@ impl Interactive for SelectThen { if self.ask_erase { let yes = matches!(&i, Input::Keyword(k) if k == "Yes") || matches!(&i, Input::Text(t) if t.trim().to_ascii_lowercase().starts_with('y')); let (a, b) = (self.pts[0], self.pts[1]); - transform_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?; + mirror_entities(s, &self.objs, &Mat3::mirror(a, b), !yes)?; s.set_selection(Vec::new()); return Ok(Step::Done); } @@ -484,7 +486,11 @@ impl Interactive for SelectThen { .filter_map(|h| d.entity(*h)) .map(|e| { let mut k = e.kind.clone(); - k.transform(&m); + if self.op == Op::Mirror { + mirror_kind(&mut k, &m); + } else { + k.transform(&m); + } k }) .collect(); @@ -508,19 +514,19 @@ impl Interactive for SelectThen { if self.op != Op::Mirror { return Some(crate::prompt::Drag { handles: self.objs.clone(), matrix, extra, clipboard: false }); } - // Mirrored text keeps reading left to right (MIRRTEXT 0), which the matrix alone can't - // draw: those objects are transformed one by one, the rest is mirrored on the GPU. + // Readable text and unchanged hatch directions cannot be drawn by reflecting their + // already-rendered primitives: preview those objects individually, the rest on the GPU. let d = s.doc().ok()?; let mut handles = Vec::with_capacity(self.objs.len()); - let mut texts = 0; + let mut individual = 0; for h in &self.objs { let Some(e) = d.entity(*h) else { continue }; - if !keeps_reading_when_mirrored(&e.kind) { + if !needs_mirror_preview(&e.kind) { handles.push(*h); - } else if texts < MAX_MIRROR_TEXT_PREVIEW { - texts += 1; + } else if individual < MAX_MIRROR_OBJECT_PREVIEW { + individual += 1; let mut k = e.kind.clone(); - k.transform(&matrix); + mirror_kind(&mut k, &matrix); extra.push(k); } } diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index df43f782c..0ee3317eb 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -1,3 +1,4 @@ +use cadcraft_doc::EntityKind; use cadcraft_geom::Vec3; use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, erase_kept, f64_req, json, point_param, point_req, targets}; @@ -9,6 +10,28 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: edit_entities(s, hs, copy, |e| e.kind.transform(m)) } +/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary. +/// Keep this in the command layer: a reflection of an entire inserted block still transforms +/// all of its contents, rather than applying the policy for individually selected hatches. +pub(super) fn mirror_kind(k: &mut EntityKind, m: &Mat3) { + let angles = match k { + EntityKind::Hatch(h) => Some((h.angle, h.gradient.as_ref().map(|g| g.angle))), + _ => None, + }; + k.transform(m); + if let (EntityKind::Hatch(h), Some((angle, gradient_angle))) = (k, angles) { + h.angle = angle; + if let (Some(g), Some(angle)) = (&mut h.gradient, gradient_angle) { + g.angle = angle; + } + } +} + +pub(super) fn mirror_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { + refuse_ole_frames(s, hs, m, copy)?; + edit_entities(s, hs, copy, |e| mirror_kind(&mut e.kind, m)) +} + /// Scale `hs` by `f` about `base` in 3D, as AutoCAD 2024's SCALE does: about the base point's XY, /// and every height of the objects about its Z, their thickness too. pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result> { @@ -159,6 +182,6 @@ pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result { return Err(bad("mirror", "mirror line points coincide")); } let erase_src = bool_or(p, "erase", false); - let r = transform_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?; + let r = mirror_entities(s, &hs, &Mat3::mirror(a, b), !erase_src)?; Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } diff --git a/crates/engine/tests/mirror_hatch_direction.rs b/crates/engine/tests/mirror_hatch_direction.rs new file mode 100644 index 000000000..1f47ccd2a --- /dev/null +++ b/crates/engine/tests/mirror_hatch_direction.rs @@ -0,0 +1,127 @@ +//! MIRROR retains a hatch pattern's direction by default, while reflecting its boundary. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{EntityKind, Handle, Hatch}; +use cadcraft_engine::geom::Vec2; +use serde_json::{Value, json}; + +fn fixture() -> (Session, Handle) { + fixture_with(json!({"pattern": "ANSI31", "angle": 30})) +} + +fn fixture_with(mut params: Value) -> (Session, Handle) { + let mut s = Session::new(); + let outline = s.execute("rectang", &json!({"p1": [2, 1], "p2": [8, 4]})).unwrap()["handle"].clone(); + params["handles"] = json!([outline]); + params["associative"] = json!(false); + let result = s.execute("hatch", ¶ms).unwrap(); + let h = result["handles"][0].as_str().unwrap(); + let h = Handle::parse_hex(h).unwrap(); + (s, h) +} + +fn hatch(s: &Session, h: Handle) -> Hatch { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Hatch(h) => h.clone(), + _ => panic!("expected hatch"), + } +} + +#[test] +fn diagonal_mirror_keeps_pattern_direction_and_reflects_boundary() { + let (mut s, source) = fixture(); + let before = hatch(&s, source); + let result = s.execute("mirror", &json!({"handles": [source.hex()], "p1": [0, 0], "p2": [10, 10]})).unwrap(); + let mirrored = Handle::parse_hex(result["handles"][0].as_str().unwrap()).unwrap(); + let after = hatch(&s, mirrored); + assert!((after.angle - before.angle).abs() < 1e-12, "pattern turned from {} to {} degrees", before.angle.to_degrees(), after.angle.to_degrees()); + for (a, b) in before.loops[0].vertices.iter().zip(&after.loops[0].vertices) { + assert!((a.p.x - b.p.y).abs() < 1e-12); + assert!((a.p.y - b.p.x).abs() < 1e-12); + } + assert_eq!(hatch(&s, source), before, "retained source is unchanged"); + let saved = cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap(); + let EntityKind::Hatch(saved) = &saved.entity(mirrored).unwrap().kind else { panic!("hatch lost on save") }; + assert!((saved.angle - before.angle).abs() < 1e-12); +} + +#[test] +fn typed_mirror_previews_match_the_result_and_undo_redo() { + let (mut s, h) = fixture(); + let before = hatch(&s, h); + s.set_selection(vec![h]); + s.cmdline("MIRROR 0,0").unwrap(); + let cursor = Vec2::new(10., 10.); + let previews = s.preview(cursor); + let preview = previews + .iter() + .find_map(|e| match &e.kind { + EntityKind::Hatch(h) => Some(h), + _ => None, + }) + .unwrap(); + assert_eq!(preview.angle, before.angle); + let (drag, _) = s.drag(cursor).unwrap(); + assert!(!drag.handles.contains(&h), "GPU reflection would turn the hatch pattern"); + let drag_hatch = drag + .extra + .iter() + .find_map(|k| match k { + EntityKind::Hatch(h) => Some(h), + _ => None, + }) + .unwrap(); + assert_eq!(drag_hatch, preview); + s.cmdline("10,10").unwrap(); + s.cmdline("Y").unwrap(); + assert!(s.running.is_none()); + let after = hatch(&s, h); + assert_eq!(&after, preview); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(hatch(&s, h), before); + s.execute("redo", &json!({})).unwrap(); + assert_eq!(hatch(&s, h), after); +} + +#[test] +fn another_pattern_and_gradient_directions_are_retained() { + for gradient in [false, true] { + let (mut s, h) = fixture(); + if gradient { + s.execute("hatchedit", &json!({"handles": [h.hex()], "gradient": {"name": "LINEAR", "angle": 20}})).unwrap(); + } else { + s.execute("hatchedit", &json!({"handles": [h.hex()], "pattern": "ANSI32"})).unwrap(); + } + let before = hatch(&s, h); + s.execute("mirror", &json!({"handles": [h.hex()], "p1": [1, 2], "p2": [5, -1], "erase": true})).unwrap(); + let after = hatch(&s, h); + assert_eq!(after.angle, before.angle); + assert_eq!(after.pattern, before.pattern); + assert_eq!(after.pattern_lines, before.pattern_lines); + assert_eq!(after.gradient, before.gradient); + } +} + +#[test] +fn custom_pattern_line_families_are_not_reflected() { + let (mut s, h) = fixture_with(json!({ + "pattern": "ORIGINAL", "angle": 30, + "patternText": "*ORIGINAL,Original asymmetric regression pattern\n17,0.2,0.4,0.3,0.8,0.5,-0.2\n67,0.1,0.3,0.2,0.9,0.1,-0.4\n" + })); + let before = hatch(&s, h); + assert_eq!(before.pattern_lines.len(), 2); + s.execute("mirror", &json!({"handles": [h.hex()], "p1": [0, 0], "p2": [10, 10], "erase": true})).unwrap(); + let after = hatch(&s, h); + assert_eq!(after.angle, before.angle); + assert_eq!(after.pattern_lines, before.pattern_lines); +} + +#[test] +fn solid_fills_can_still_use_the_gpu_preview() { + let (mut s, h) = fixture_with(json!({"pattern": "SOLID"})); + s.set_selection(vec![h]); + s.cmdline("MIRROR 0,0").unwrap(); + let (drag, _) = s.drag(Vec2::new(10., 10.)).unwrap(); + assert!(drag.handles.contains(&h)); + assert!(!drag.extra.iter().any(|k| matches!(k, EntityKind::Hatch(_)))); +} From fb9a833144be5fc93e729957f4180f2e1b52cb78 Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Mon, 9 Nov 2026 12:42:59 -0500 Subject: [PATCH 066/187] test: handle macOS rejection of non-Unicode filenames --- apps/cadcraft-cli/tests/it/usage.rs | 21 ++++++++++++++++++++- crates/engine/tests/read_file_unicode.rs | 3 ++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/cadcraft-cli/tests/it/usage.rs b/apps/cadcraft-cli/tests/it/usage.rs index 2e9f6e907..feb99348d 100644 --- a/apps/cadcraft-cli/tests/it/usage.rs +++ b/apps/cadcraft-cli/tests/it/usage.rs @@ -818,7 +818,8 @@ fn non_unicode_arguments() { assert!(err.starts_with("error: invalid UTF-8 was detected"), "{err}"); } -/// An output name that isn't valid Unicode is written as given: only its extension picks the format. +/// An output name that isn't valid Unicode reaches the filesystem unchanged: only its extension +/// picks the format. Filesystems that reject the name must report their write error. #[cfg(unix)] #[test] fn non_unicode_output_names() { @@ -835,6 +836,18 @@ fn non_unicode_output_names() { let code = cadcraft_cli::run(args, &mut out, &mut err); (code, String::from_utf8_lossy(&err).into_owned()) }; + // APFS rejects invalid UTF-8 names (EILSEQ), although Unix paths can represent them. + // Probe this scratch filesystem rather than assuming every macOS volume behaves alike. + let probe = latin1("probe"); + let rejected_name: Option = match std::fs::write(&probe, b"") { + Ok(()) => { + std::fs::remove_file(&probe).expect("remove filename probe"); + None + } + #[cfg(target_os = "macos")] + Err(e) if e.raw_os_error() == Some(92) => Some(e.to_string()), // Darwin EILSEQ + Err(e) => panic!("unexpected filename probe error: {e}"), + }; let b = s.0.join("b.dxf"); let cases: [(Vec, std::path::PathBuf); 3] = [ (vec!["sample".into(), "bracket".into(), latin1("dxf").into()], latin1("dxf")), @@ -843,6 +856,12 @@ fn non_unicode_output_names() { ]; for (args, path) in cases { let (code, err) = run(args.clone()); + if let Some(ref filesystem_error) = rejected_name { + assert_eq!(code, 1, "{args:?}: {err}"); + assert!(err.contains(filesystem_error), "{args:?}: {err}"); + assert!(!path.exists(), "{path:?}"); + continue; + } assert_eq!(code, 0, "{args:?}: {err}"); assert!(path.exists(), "{path:?}"); assert!(std::fs::metadata(&path).expect("stat output").len() > 0, "{path:?}"); diff --git a/crates/engine/tests/read_file_unicode.rs b/crates/engine/tests/read_file_unicode.rs index 4c3c520e8..6732a1063 100644 --- a/crates/engine/tests/read_file_unicode.rs +++ b/crates/engine/tests/read_file_unicode.rs @@ -17,7 +17,8 @@ fn read_file_refuses_a_name_that_is_not_unicode() { let good = dir.join("good.dxf"); let bad = dir.join(OsString::from_vec(b"bad-\xff.dxf".to_vec())); std::fs::write(&good, b"0\nEOF\n").unwrap(); - std::fs::write(&bad, b"0\nEOF\n").unwrap(); + // Validation precedes filesystem access; macOS filesystems may reject this name. + assert!(!bad.exists()); let e = read_file(&bad).err().expect("a non-Unicode name is refused"); assert!(e.contains("not valid Unicode") && e.contains("bad-"), "{e}"); assert!(read_file(&good).is_ok()); From 57e32b0cdd15ed85b32f67ce6002e65138aca265 Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Mon, 9 Nov 2026 13:32:08 -0500 Subject: [PATCH 067/187] fix(engine): honor non-associative DIMASSOC mode --- crates/engine/src/cmd/annotate/common.rs | 5 +- crates/engine/tests/dimassoc_mode.rs | 107 +++++++++++++++++++++++ 2 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 crates/engine/tests/dimassoc_mode.rs diff --git a/crates/engine/src/cmd/annotate/common.rs b/crates/engine/src/cmd/annotate/common.rs index 6854b4fb4..fc1871b4d 100644 --- a/crates/engine/src/cmd/annotate/common.rs +++ b/crates/engine/src/cmd/annotate/common.rs @@ -39,7 +39,7 @@ pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option, a if aligned { DimKind::Aligned } else { DimKind::Linear { rotation: rotation.unwrap_or_else(|| auto_rotation(p1, p2, at)) } } } -/// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints, +/// Add a dimension. With DIMASSOC 2, definition points that sit on object endpoints, /// vertices or centres are attached to them (associative dimensions). pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result { let mut k = k; @@ -68,7 +68,8 @@ pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result { } pub(super) fn assoc_enabled(s: &Session) -> bool { - s.doc().map(|d| d.header.i64("DIMASSOC", 2) != 0).unwrap_or(false) + // Mode 1 keeps a dimension as one object without linking it to source geometry. + s.doc().map(|d| d.header.i64("DIMASSOC", 2) == 2).unwrap_or(false) } pub(super) fn with_assoc(k: EntityKind, assoc: Vec) -> EntityKind { diff --git a/crates/engine/tests/dimassoc_mode.rs b/crates/engine/tests/dimassoc_mode.rs new file mode 100644 index 000000000..4d6ebeb7a --- /dev/null +++ b/crates/engine/tests/dimassoc_mode.rs @@ -0,0 +1,107 @@ +//! DIMASSOC 1 creates dimension objects without coupling them to source geometry; 2 couples them. +use cadcraft_engine::Session; +use cadcraft_engine::doc::{Dimension, EntityKind, Handle}; +use serde_json::{Value, json}; + +fn handle(v: &Value) -> Handle { + Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap() +} + +fn dimension(s: &Session, h: Handle) -> Dimension { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Dimension(d) => d.clone(), + other => panic!("expected dimension, got {other:?}"), + } +} + +fn line(s: &mut Session, a: [i32; 2], b: [i32; 2]) -> Handle { + let v = s.execute("line", &json!({"points": [a, b]})).unwrap(); + Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap() +} + +fn mode(s: &mut Session, n: i32) { + s.execute("setvar", &json!({"name": "DIMASSOC", "value": n})).unwrap(); +} + +#[test] +fn linear_dimensions_respect_the_mode_through_edits_and_dxf() { + for n in [1, 2] { + for typed in [false, true] { + let mut s = Session::new(); + mode(&mut s, n); + let source = line(&mut s, [0, 0], [10, 0]); + let d = if typed { + s.cmdline("dimlinear 0,0 10,0 5,4").unwrap(); + s.last_dim.unwrap() + } else { + handle(&s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap()) + }; + assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, typed{typed}"); + let saved = cadcraft_io::write_dxf(s.doc().unwrap()); + let has_link = saved.lines().any(|l| l.trim() == "DIMASSOC"); + assert_eq!(has_link, n == 2, "mode{n}: only associative dimensions save a DIMASSOC object"); + let mut reopened = Session::new(); + reopened.open_drawing(cadcraft_io::read_dxf(saved.as_bytes()).unwrap(), "roundtrip.dxf", None); + for session in [&mut s, &mut reopened] { + session.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap(); + let edited = dimension(session, d); + assert_eq!(edited.p14.x, if n == 2 { 15.0 } else { 10.0 }); + assert_eq!(cadcraft_engine::render::dimension_in(session.doc().unwrap(), &edited).measurement, if n == 2 { 15.0 } else { 10.0 }); + session.undo().unwrap(); + assert_eq!(dimension(session, d).p14.x, 10.0); + session.redo().unwrap(); + assert_eq!(dimension(session, d).p14.x, edited.p14.x); + } + } + } +} + +#[test] +fn indexed_chains_and_qdim_respect_the_mode() { + for n in [1, 2] { + for cmd in ["dimcontinue", "dimbaseline", "qdim"] { + let mut s = Session::new(); + mode(&mut s, n); + let source = line(&mut s, [0, 0], [10, 0]); + s.execute("point", &json!({"at": [20, 0]})).unwrap(); + s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]})).unwrap(); + let params = if cmd == "qdim" { json!({"handles": [source.hex()], "at": [5, 6]}) } else { json!({"points": [[20, 0]]}) }; + let out = s.execute(cmd, ¶ms).unwrap(); + let hs = out["handles"].as_array().unwrap(); + assert!(!hs.is_empty()); + for h in hs { + let d = dimension(&s, Handle::parse_hex(h.as_str().unwrap()).unwrap()); + assert_eq!(d.assoc.len(), if n == 2 { 2 } else { 0 }, "mode{n}, {cmd}"); + } + } + } +} + +#[test] +fn explicit_angular_links_respect_the_mode() { + for n in [1, 2] { + let mut s = Session::new(); + mode(&mut s, n); + let a = line(&mut s, [0, 0], [10, 0]); + let b = line(&mut s, [0, 0], [0, 10]); + let d = handle(&s.execute("dimangular", &json!({"lines": [a.hex(), b.hex()], "at": [4, 4]})).unwrap()); + assert_eq!(dimension(&s, d).assoc.len(), if n == 2 { 4 } else { 0 }); + } +} + +#[test] +fn mode_change_keeps_existing_links_and_allows_explicit_reassociation() { + let mut s = Session::new(); + let source = line(&mut s, [0, 0], [10, 0]); + let params = json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 4]}); + let existing = handle(&s.execute("dimlinear", ¶ms).unwrap()); + mode(&mut s, 1); + let new = handle(&s.execute("dimlinear", ¶ms).unwrap()); + assert_eq!(dimension(&s, existing).assoc.len(), 2); + assert!(dimension(&s, new).assoc.is_empty()); + s.execute("dimreassociate", &json!({"handles": [new.hex()]})).unwrap(); + assert_eq!(dimension(&s, new).assoc.len(), 2); + s.execute("properties.set", &json!({"handles": [source.hex()], "end": [15, 0]})).unwrap(); + assert_eq!(dimension(&s, existing).p14.x, 15.0); + assert_eq!(dimension(&s, new).p14.x, 15.0); +} From 52dfb93b8bc8f44f38e43ae4aba43b371875847c Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Mon, 9 Nov 2026 13:52:30 -0500 Subject: [PATCH 068/187] fix(io): retain DIMASSOC in drawings and templates --- crates/dwg/src/lib.rs | 5 +- crates/engine/tests/dimassoc_template.rs | 31 ++++++++++ crates/io/src/dxf_write/header.rs | 3 +- crates/io/tests/dimassoc_header.rs | 78 ++++++++++++++++++++++++ 4 files changed, 114 insertions(+), 3 deletions(-) create mode 100644 crates/engine/tests/dimassoc_template.rs create mode 100644 crates/io/tests/dimassoc_header.rs diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 4d1eee279..806081ba4 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -804,9 +804,9 @@ mod native { dropped } - /// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.3) leaves out of + /// Header variables the DWG reader fills in but acadrust's DXF writer (0.6.6) leaves out of /// the HEADER section: (name, group code, value). - fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 7] { + fn unwritten_header_vars(h: &acadrust::document::HeaderVariables) -> [(&'static str, i32, String); 8] { [ // DWG holds radians; `$ANGBASE` is in degrees. ("$ANGBASE", 50, h.angle_base.to_degrees().to_string()), @@ -816,6 +816,7 @@ mod native { ("$CHAMFERB", 40, h.chamfer_distance_b.to_string()), ("$ELEVATION", 40, h.elevation.to_string()), ("$THICKNESS", 40, h.thickness.to_string()), + ("$DIMASSOC", 280, h.dimension_associativity.to_string()), ] } diff --git a/crates/engine/tests/dimassoc_template.rs b/crates/engine/tests/dimassoc_template.rs new file mode 100644 index 000000000..19b0d9d89 --- /dev/null +++ b/crates/engine/tests/dimassoc_template.rs @@ -0,0 +1,31 @@ +//! A saved template carries the drawing's DIMASSOC mode into a new drawing. +#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use serde_json::json; + +#[path = "support/temp_dir.rs"] +mod temp_dir; + +#[test] +fn setvar_saveas_and_new_from_a_real_template_keep_dimassoc() { + set_io(IoHooks { + read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|e| e.to_string()), + write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + let dir = temp_dir::TempDir::new("dimassoc-template"); + for mode in [0, 1, 2] { + let mut s = Session::new(); + s.execute("setvar", &json!({"name": "DIMASSOC", "value": mode})).unwrap(); + let path = dir.path_str(&format!("mode-{mode}.dwt")); + s.execute("saveas", &json!({"path": path})).unwrap(); + s.execute("new", &json!({"template": path})).unwrap(); + assert_eq!(s.execute("getvar", &json!({"name": "DIMASSOC"})).unwrap()["value"], mode); + assert!(s.state().unwrap().path.is_none(), "the new drawing is independent from its template"); + s.execute("setvar", &json!({"name": "DIMASSOC", "value": (mode + 1) % 3})).unwrap(); + s.execute("new", &json!({"template": path})).unwrap(); + assert_eq!(s.execute("getvar", &json!({"name": "DIMASSOC"})).unwrap()["value"], mode, "editing the new drawing leaves the template intact"); + } +} diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 14dbfee73..68637fc2a 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -26,6 +26,7 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("CELTSCALE", 40), ("DIMSCALE", 40), ("DIMSTYLE", 2), + ("DIMASSOC", 280), ("LUNITS", 70), ("LUPREC", 70), ("AUNITS", 70), @@ -122,7 +123,7 @@ pub(super) fn header_vars(w: &mut W, d: &Drawing) { w.f(c, f); } } - (c @ (62 | 70 | 290 | 370), v) => { + (c @ (62 | 70 | 280 | 290 | 370), v) => { if let Some(i) = v.as_i64() { w.s(9, format!("${name}")); w.i(c, i); diff --git a/crates/io/tests/dimassoc_header.rs b/crates/io/tests/dimassoc_header.rs new file mode 100644 index 000000000..2b64ac60a --- /dev/null +++ b/crates/io/tests/dimassoc_header.rs @@ -0,0 +1,78 @@ +//! DIMASSOC is a drawing variable, written as HEADER group 280, independently of DIMSTYLE. +use cadcraft_doc::Drawing; +use cadcraft_io::{SaveOptions, Version, read_dxf, write, write_with}; + +fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> { + let tags = cadcraft_dxf::parse(bytes).unwrap(); + let header = cadcraft_dxf::sections(&tags).into_iter().find(|s| s.name == "HEADER").unwrap(); + let mut found = Vec::new(); + for pair in header.tags.windows(2) { + if pair[0].code == 9 && pair[0].str() == "$DIMASSOC" { + found.push((pair[1].code, pair[1].i64())); + } + } + found +} + +#[test] +fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() { + for mode in [0, 1, 2] { + let mut d = Drawing::new_metric(); + d.header.set_i64("DIMASSOC", mode); + for version in [Version::R2000, Version::R2004, Version::R2007, Version::R2018] { + for binary in [false, true] { + let bytes = write_with(&d, "setting.dxf", &SaveOptions { version: Some(version), binary }).unwrap(); + assert_eq!(dimassoc_groups(&bytes), [(280, mode)], "{version:?}, binary{binary}"); + let back = read_dxf(&bytes).unwrap(); + assert_eq!(back.header.i64("DIMASSOC", -1), mode); + } + } + } +} + +#[test] +fn an_imported_mode_can_be_changed_without_a_stale_or_duplicate_header() { + let source = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$DIMASSOC\n280\n1\n0\nENDSEC\n0\nEOF\n"; + let mut d = read_dxf(source).unwrap(); + assert_eq!(d.header.i64("DIMASSOC", -1), 1); + for mode in [1, 0, 2] { + d.header.set_i64("DIMASSOC", mode); + let bytes = write(&d, "edited.dxf").unwrap(); + assert_eq!(dimassoc_groups(&bytes), [(280, mode)]); + d = read_dxf(&bytes).unwrap(); + assert_eq!(d.header.i64("DIMASSOC", -1), mode); + } +} + +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +mod native { + use super::*; + use cadcraft_io::read; + use std::io::Cursor; + + #[test] + fn dwg_decode_keeps_the_mode_even_when_the_dxf_bridge_omits_it() { + for mode in [0, 1, 2] { + let mut source = acadrust::CadDocument::new(); + source.header.dimension_associativity = mode; + let bytes = acadrust::DwgWriter::write_to_vec(&source).unwrap(); + let back = read(&bytes, "source.dwg").unwrap(); + assert_eq!(back.header.i64("DIMASSOC", -1), i64::from(mode)); + } + } + + #[test] + fn dwg_and_dwt_keep_the_mode_in_the_native_header_and_after_reopen() { + for mode in [0, 1, 2] { + let mut d = Drawing::new_metric(); + d.header.set_i64("DIMASSOC", mode); + for name in ["setting.dwg", "setting.dwt"] { + let bytes = write(&d, name).unwrap(); + let native = acadrust::DwgReader::from_stream(Cursor::new(&bytes)).read().unwrap(); + assert_eq!(i64::from(native.header.dimension_associativity), mode, "{name}: native header"); + let back = read(&bytes, name).unwrap(); + assert_eq!(back.header.i64("DIMASSOC", -1), mode, "{name}: reopened variable"); + } + } + } +} From 392b0e16789fe20f2adddcccd07ab21865c5db22 Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Mon, 9 Nov 2026 15:53:57 -0500 Subject: [PATCH 069/187] PR2979: document DIMASSOC persistence contracts --- crates/engine/tests/dimassoc_template.rs | 1 + crates/io/src/dxf_write/header.rs | 1 + crates/io/tests/dimassoc_header.rs | 5 +++++ 3 files changed, 7 insertions(+) diff --git a/crates/engine/tests/dimassoc_template.rs b/crates/engine/tests/dimassoc_template.rs index 19b0d9d89..a0c21b30c 100644 --- a/crates/engine/tests/dimassoc_template.rs +++ b/crates/engine/tests/dimassoc_template.rs @@ -8,6 +8,7 @@ use serde_json::json; #[path = "support/temp_dir.rs"] mod temp_dir; +/// A saved template supplies each new drawing with its mode and remains independent of later edits. #[test] fn setvar_saveas_and_new_from_a_real_template_keep_dimassoc() { set_io(IoHooks { diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 68637fc2a..a9da48f0e 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -97,6 +97,7 @@ fn dim_header_vars(w: &mut W, d: &Drawing) { } } +/// Write modelled HEADER variables with their declared DXF group types, then retained extras. pub(super) fn header_vars(w: &mut W, d: &Drawing) { for (name, code) in HEADER_VARS { let Some(v) = d.header.get(name) else { continue }; diff --git a/crates/io/tests/dimassoc_header.rs b/crates/io/tests/dimassoc_header.rs index 2b64ac60a..6e44b93d9 100644 --- a/crates/io/tests/dimassoc_header.rs +++ b/crates/io/tests/dimassoc_header.rs @@ -2,6 +2,7 @@ use cadcraft_doc::Drawing; use cadcraft_io::{SaveOptions, Version, read_dxf, write, write_with}; +/// Extract every DIMASSOC HEADER entry so duplicate or mistyped values fail the assertions. fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> { let tags = cadcraft_dxf::parse(bytes).unwrap(); let header = cadcraft_dxf::sections(&tags).into_iter().find(|s| s.name == "HEADER").unwrap(); @@ -14,6 +15,7 @@ fn dimassoc_groups(bytes: &[u8]) -> Vec<(i32, i64)> { found } +/// All supported modes use group 280 and survive each tested DXF version and encoding. #[test] fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() { for mode in [0, 1, 2] { @@ -30,6 +32,7 @@ fn new_drawing_modes_use_group_280_in_ascii_and_binary_dxf() { } } +/// Editing an imported mode replaces its stored value without emitting a second HEADER entry. #[test] fn an_imported_mode_can_be_changed_without_a_stale_or_duplicate_header() { let source = b"0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$DIMASSOC\n280\n1\n0\nENDSEC\n0\nEOF\n"; @@ -50,6 +53,7 @@ mod native { use cadcraft_io::read; use std::io::Cursor; + /// The DWG reader supplements DIMASSOC when the intermediate DXF writer omits it. #[test] fn dwg_decode_keeps_the_mode_even_when_the_dxf_bridge_omits_it() { for mode in [0, 1, 2] { @@ -61,6 +65,7 @@ mod native { } } + /// DWG drawings and templates retain every mode in both the native header and readback. #[test] fn dwg_and_dwt_keep_the_mode_in_the_native_header_and_after_reopen() { for mode in [0, 1, 2] { From 4f51d0c6556234b0fa5c2c6b6a2a8d08aa354b2e Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Mon, 9 Nov 2026 15:57:12 -0500 Subject: [PATCH 070/187] PR2977: document dimension associativity policy and tests --- crates/engine/src/cmd/annotate/common.rs | 2 ++ crates/engine/tests/dimassoc_mode.rs | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/crates/engine/src/cmd/annotate/common.rs b/crates/engine/src/cmd/annotate/common.rs index fc1871b4d..b9685e24d 100644 --- a/crates/engine/src/cmd/annotate/common.rs +++ b/crates/engine/src/cmd/annotate/common.rs @@ -35,6 +35,7 @@ fn auto_rotation(p1: Vec2, p2: Vec2, at: Vec2) -> f64 { if outside_x && !outside_y { std::f64::consts::FRAC_PI_2 } else { 0.0 } } +/// Choose the linear dimension orientation from explicit rotation or the placement point. pub(super) fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option, aligned: bool) -> DimKind { if aligned { DimKind::Aligned } else { DimKind::Linear { rotation: rotation.unwrap_or_else(|| auto_rotation(p1, p2, at)) } } } @@ -67,6 +68,7 @@ pub(super) fn add_dim(s: &mut Session, k: EntityKind) -> Result { Ok(h) } +/// Only DIMASSOC mode 2 attaches newly created dimensions to their source geometry. pub(super) fn assoc_enabled(s: &Session) -> bool { // Mode 1 keeps a dimension as one object without linking it to source geometry. s.doc().map(|d| d.header.i64("DIMASSOC", 2) == 2).unwrap_or(false) diff --git a/crates/engine/tests/dimassoc_mode.rs b/crates/engine/tests/dimassoc_mode.rs index 4d6ebeb7a..306b2453c 100644 --- a/crates/engine/tests/dimassoc_mode.rs +++ b/crates/engine/tests/dimassoc_mode.rs @@ -3,10 +3,12 @@ use cadcraft_engine::Session; use cadcraft_engine::doc::{Dimension, EntityKind, Handle}; use serde_json::{Value, json}; +/// Read the single entity handle returned by a dimension command. fn handle(v: &Value) -> Handle { Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap() } +/// Clone the asserted dimension so later edits can be compared with its previous state. fn dimension(s: &Session, h: Handle) -> Dimension { match &s.doc().unwrap().entity(h).unwrap().kind { EntityKind::Dimension(d) => d.clone(), @@ -14,15 +16,18 @@ fn dimension(s: &Session, h: Handle) -> Dimension { } } +/// Create a synthetic source line and return its first entity handle. fn line(s: &mut Session, a: [i32; 2], b: [i32; 2]) -> Handle { let v = s.execute("line", &json!({"points": [a, b]})).unwrap(); Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap() } +/// Set the drawing-wide associativity mode before creating the test dimensions. fn mode(s: &mut Session, n: i32) { s.execute("setvar", &json!({"name": "DIMASSOC", "value": n})).unwrap(); } +/// Typed and JSON dimensions retain their mode through DXF, source edits, undo and redo. #[test] fn linear_dimensions_respect_the_mode_through_edits_and_dxf() { for n in [1, 2] { @@ -56,6 +61,7 @@ fn linear_dimensions_respect_the_mode_through_edits_and_dxf() { } } +/// Continue, Baseline and Quick Dimension attach source links only in mode 2. #[test] fn indexed_chains_and_qdim_respect_the_mode() { for n in [1, 2] { @@ -77,6 +83,7 @@ fn indexed_chains_and_qdim_respect_the_mode() { } } +/// Even explicitly selected angular source lines produce associations only in mode 2. #[test] fn explicit_angular_links_respect_the_mode() { for n in [1, 2] { @@ -89,6 +96,7 @@ fn explicit_angular_links_respect_the_mode() { } } +/// Changing the creation mode preserves old links and does not disable explicit reassociation. #[test] fn mode_change_keeps_existing_links_and_allows_explicit_reassociation() { let mut s = Session::new(); From 0ef5093530e8a9106d796a31c2d39eb8bcca6548 Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Mon, 9 Nov 2026 16:04:33 -0500 Subject: [PATCH 071/187] PR2969: document mirror fill policy and regression coverage --- crates/engine/src/cmd/modify/select_then.rs | 3 +++ crates/engine/src/cmd/modify/transform.rs | 2 ++ crates/engine/tests/mirror_hatch_direction.rs | 8 ++++++++ 3 files changed, 13 insertions(+) diff --git a/crates/engine/src/cmd/modify/select_then.rs b/crates/engine/src/cmd/modify/select_then.rs index d8a0443b6..65060770d 100644 --- a/crates/engine/src/cmd/modify/select_then.rs +++ b/crates/engine/src/cmd/modify/select_then.rs @@ -349,6 +349,7 @@ impl Interactive for SelectThen { _ => Prompt::new("", Accept::POINT), } } + /// Advance the selected transform command, applying MIRROR fill policy at commit. fn input(&mut self, s: &mut Session, i: Input) -> Result { if !self.sel.done { match self.sel.feed(s, &i)? { @@ -458,6 +459,7 @@ impl Interactive for SelectThen { _ => Ok(Step::Continue), } } + /// Build bounded transform previews, retaining readable text and hatch fill directions. fn preview(&self, s: &Session, c: Vec2) -> Vec { if self.op == Op::Rotate && self.reference { return self.rotate_reference_preview(s, c); @@ -497,6 +499,7 @@ impl Interactive for SelectThen { out.push(line(base, c)); out } + /// Separate shared GPU transforms from objects that need an individual MIRROR preview. fn drag(&self, s: &Session, c: Vec2) -> Option { if (self.op == Op::Rotate && self.reference) || !self.sel.done { return None; diff --git a/crates/engine/src/cmd/modify/transform.rs b/crates/engine/src/cmd/modify/transform.rs index 0ee3317eb..6225517da 100644 --- a/crates/engine/src/cmd/modify/transform.rs +++ b/crates/engine/src/cmd/modify/transform.rs @@ -27,6 +27,7 @@ pub(super) fn mirror_kind(k: &mut EntityKind, m: &Mat3) { } } +/// Reflect selected entities with the command policy that retains individual hatch fill directions. pub(super) fn mirror_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result> { refuse_ole_frames(s, hs, m, copy)?; edit_entities(s, hs, copy, |e| mirror_kind(&mut e.kind, m)) @@ -174,6 +175,7 @@ pub(super) fn run_scale(s: &mut Session, p: &Value) -> Result { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::>() })) } +/// Validate MIRROR parameters and apply the reflection, optionally replacing the source entities. pub(super) fn run_mirror(s: &mut Session, p: &Value) -> Result { let hs = targets(s, p)?; let a = point_req("mirror", p, "p1")?; diff --git a/crates/engine/tests/mirror_hatch_direction.rs b/crates/engine/tests/mirror_hatch_direction.rs index 1f47ccd2a..48d155aef 100644 --- a/crates/engine/tests/mirror_hatch_direction.rs +++ b/crates/engine/tests/mirror_hatch_direction.rs @@ -5,10 +5,12 @@ use cadcraft_engine::doc::{EntityKind, Handle, Hatch}; use cadcraft_engine::geom::Vec2; use serde_json::{Value, json}; +/// Create a rectangular hatch with an oblique pattern direction for reflection checks. fn fixture() -> (Session, Handle) { fixture_with(json!({"pattern": "ANSI31", "angle": 30})) } +/// Create a nonassociative rectangular hatch with the supplied synthetic fill parameters. fn fixture_with(mut params: Value) -> (Session, Handle) { let mut s = Session::new(); let outline = s.execute("rectang", &json!({"p1": [2, 1], "p2": [8, 4]})).unwrap()["handle"].clone(); @@ -20,6 +22,7 @@ fn fixture_with(mut params: Value) -> (Session, Handle) { (s, h) } +/// Clone the asserted hatch so its geometry and fill can be compared across edits. fn hatch(s: &Session, h: Handle) -> Hatch { match &s.doc().unwrap().entity(h).unwrap().kind { EntityKind::Hatch(h) => h.clone(), @@ -27,6 +30,7 @@ fn hatch(s: &Session, h: Handle) -> Hatch { } } +/// A diagonal mirror reflects the boundary while retaining the fill direction through DXF readback. #[test] fn diagonal_mirror_keeps_pattern_direction_and_reflects_boundary() { let (mut s, source) = fixture(); @@ -45,6 +49,7 @@ fn diagonal_mirror_keeps_pattern_direction_and_reflects_boundary() { assert!((saved.angle - before.angle).abs() < 1e-12); } +/// Typed MIRROR previews and committed geometry agree, including undo and redo. #[test] fn typed_mirror_previews_match_the_result_and_undo_redo() { let (mut s, h) = fixture(); @@ -83,6 +88,7 @@ fn typed_mirror_previews_match_the_result_and_undo_redo() { assert_eq!(hatch(&s, h), after); } +/// Patterned and gradient fills keep their definitions when the mirrored result replaces its source. #[test] fn another_pattern_and_gradient_directions_are_retained() { for gradient in [false, true] { @@ -102,6 +108,7 @@ fn another_pattern_and_gradient_directions_are_retained() { } } +/// Original asymmetric pattern families retain their line definitions under reflection. #[test] fn custom_pattern_line_families_are_not_reflected() { let (mut s, h) = fixture_with(json!({ @@ -116,6 +123,7 @@ fn custom_pattern_line_families_are_not_reflected() { assert_eq!(after.pattern_lines, before.pattern_lines); } +/// Solid hatches remain eligible for the shared GPU reflection preview. #[test] fn solid_fills_can_still_use_the_gpu_preview() { let (mut s, h) = fixture_with(json!({"pattern": "SOLID"})); From 0e40437d8fb59ce484d444a9de69f4c97552442c Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 11 Nov 2026 02:06:36 +0400 Subject: [PATCH 072/187] =?UTF-8?q?i18n(ka):=20Export=20=3D=20=E1=83=94?= =?UTF-8?q?=E1=83=A5=E1=83=A1=E1=83=9E=E1=83=9D=E1=83=A0=E1=83=A2=E1=83=98?= =?UTF-8?q?=E1=83=A0=E1=83=94=E1=83=91=E1=83=90,=20Print=20=3D=20=E1=83=91?= =?UTF-8?q?=E1=83=94=E1=83=AD=E1=83=93=E1=83=95=E1=83=90=20(the=20wording?= =?UTF-8?q?=20used=20across=20the=20Craft=20apps)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/i18n/ka.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3c4c7d739..d113f6815 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -340,7 +340,7 @@ Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა Explode დაშლა Explode Attributes to Text ატრიბუტების ტექსტად დაშლა - Export ექსპორტი + Export ექსპორტირება Export Table ცხრილის ექსპორტი Export to PDF... PDF-ად ექსპორტი... Express Tools Express Tools @@ -707,8 +707,8 @@ Previous Change წინა ცვლილება Previous Layer წინა შრე Primitives პრიმიტივები - Print დაბეჭდვა - Print... დაბეჭდვა... + Print ბეჭდვა + Print... ბეჭდვა... Properties თვისებები Properties Inspector თვისებების ინსპექტორი Properties: თვისებები: @@ -1242,7 +1242,7 @@ Animation effects ანიმაციის ეფექტები Interface scale ინტერფეისის მასშტაბი Import... იმპორტი... - Export... ექსპორტი... + Export... ექსპორტირება... Batch Publish... პაკეტური გამოქვეყნება... Scale List... მასშტაბების სია... Annotative Object Scale ანოტაციური ობიექტის მასშტაბი From a0ce65ef0677bd8449c7fd2d9cadf894e31e4ae6 Mon Sep 17 00:00:00 2001 From: SBaksa <18648812+SBaksa@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:04:12 +1100 Subject: [PATCH 073/187] Select: a blank MLEADER text box also catches a crossing window; share the annotation scaling (#2810) Blank MTEXT frames use cadcraft_doc::anno_scaled, is_blank_mtext no longer allocates, and the crossing test accepts the frame. Out-of-reach blank frames no longer use up snap candidate or intersection slots. Adds tests for each. --- crates/engine/src/select.rs | 151 ++++++++++++++++++++++++++++++------ crates/engine/src/snap.rs | 42 ++++++++++ 2 files changed, 168 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index ec57774a6..35bfa0016 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -161,38 +161,43 @@ pub(crate) type Cands<'a> = Box /// Whether an MTEXT's contents draw nothing (empty, or only spaces and `\~`): it has no glyph /// strokes, and the document's bounds for it are empty so it stays out of the drawing extents. +/// Called for every MTEXT when the spatial index is built, so it does not allocate. fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool { - t.contents.replace(r"\~", " ").chars().all(char::is_whitespace) + t.contents.split(r"\~").all(|s| s.chars().all(char::is_whitespace)) } -/// The frame a blank MTEXT is picked in (#2810): its insertion point, rotation and the box before -/// turning (`x0, x1, y0, y1` about the insertion point): its width (the text height when it has -/// none) by its text height, placed by its attachment point, at the size it draws at the current -/// annotation scale. `None` for any other entity, a blank MTEXT without a usable size or position, -/// or an annotative one the current annotation scale hides. +/// The frame a blank MTEXT is picked in (#2810), for a top-level MTEXT and for a multileader's +/// MTEXT content: its insertion point, rotation and the box before turning (`x0, x1, y0, y1` +/// about the insertion point): its width (the text height when it has none) by its text height, +/// placed by its attachment point, at the size it draws at the current annotation scale (the +/// shared `anno_scaled`, which also moves a multileader's text about its landing). `None` for any +/// other entity, a multileader without text content, a blank MTEXT without a usable size or +/// position, or an annotative one the current annotation scale hides. fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { - let (t, landing) = match &e.kind { - EntityKind::MText(t) => (t, None), - EntityKind::MLeader(m) => (m.text.as_ref()?, Some(m.landing.xy())), - _ => return None, - }; - if !is_blank_mtext(t) || !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { - return None; - } - // Match the drawn annotation size and the multileader text offset from its landing. let f = match d.anno_draw(e) { cadcraft_doc::AnnoDraw::Plain => 1.0, cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f, cadcraft_doc::AnnoDraw::Scaled(_) => 1.0, cadcraft_doc::AnnoDraw::Hidden => return None, }; - let w = f * if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height }; - let h = f * t.height; - let insert = t.insert.xy(); - let insert = match landing { - Some(landing) if f != 1.0 => landing + (insert - landing) * f, - _ => insert, + let scaled; + let e = if f != 1.0 { + scaled = cadcraft_doc::anno_scaled(e, f); + &scaled + } else { + e }; + let t = match &e.kind { + EntityKind::MText(t) => t, + EntityKind::MLeader(m) => m.text.as_ref()?, + _ => return None, + }; + if !is_blank_mtext(t) || !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { + return None; + } + let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height }; + let h = t.height; + let insert = t.insert.xy(); if !w.is_finite() || !h.is_finite() || !insert.is_finite() { return None; } @@ -209,15 +214,17 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { Some((insert, t.rotation, [dx, dx + w, top - h, top])) } -/// The box around a blank MTEXT's turned frame, for the spatial index and windows (a crossing -/// window may catch a little extra near a corner, as it does for other text). +/// The box around a blank MTEXT's turned frame (a top-level MTEXT or a multileader's MTEXT +/// content), for the spatial index and windows (a crossing window may catch a little extra near a +/// corner, as it does for other text). fn blank_mtext_box(d: &Drawing, e: &Entity) -> Option { let (o, rot, [x0, x1, y0, y1]) = blank_mtext_frame(d, e)?; let corners = [Vec2::new(x0, y1), Vec2::new(x1, y1), Vec2::new(x1, y0), Vec2::new(x0, y0)]; Some(Bounds2::from_points(corners.map(|c| o + c.rotate(rot)))) } -/// Whether `p` is on a blank MTEXT: inside its box turned with the text, not the larger box around it. +/// Whether `p` is on a blank MTEXT or a multileader's blank MTEXT content: inside its box turned +/// with the text, not the larger box around it. fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool { let Some((o, rot, [x0, x1, y0, y1])) = blank_mtext_frame(d, e) else { return false }; let q = (p - o).rotate(-rot); @@ -230,6 +237,21 @@ pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 { blank_mtext_box(d, e).map_or(drawn, |frame| drawn.union(&frame)) } +/// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn +/// geometry (expanded by `aperture`) misses `probe` and no blank text insertion point is inside +/// it. Such an entity is for picking and selection, not a snap candidate. +pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, aperture: f64) -> bool { + if blank_mtext_box(d, e).is_none() { + return false; + } + let insert = match &e.kind { + EntityKind::MText(t) => Some(t.insert.xy()), + EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.insert.xy()), + _ => None, + }; + !insert.is_some_and(|p| probe.contains(p)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe) +} + pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Bounds2 { known.unwrap_or_else(|| pick_bounds(d, e, entity_bounds(d, e, 0))) } @@ -361,6 +383,10 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option, bx: &Bo if hit || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_))) { return true; } + // Likewise inside a blank MTEXT's frame (a multileader's too), where picking also selects it. + if blank_mtext_box(d, e).is_some_and(|frame| frame.contains_box(bx)) { + return true; + } // SOLID/TRACE are filled polygons. A crossing window wholly within the // fill must select them even when it does not touch their outline. Check // the polygon, not just its bounding rectangle (which can cover empty @@ -603,6 +629,9 @@ mod tests { /// inside its width x height box picks it, and a click outside does not (#2810). #[test] fn a_blank_mtext_is_picked_inside_its_box() { + let blank = |c: &str| matches!(mtext_at(c, 1, 0.0), EntityKind::MText(t) if is_blank_mtext(&t)); + assert!(!blank(r"a\~")); + assert!(blank(r"\~ \~")); for contents in ["", " ", r"\~ "] { let mut d = Drawing::new_metric(); let h = d.add(&Space::Model, Common::default(), mtext_at(contents, 1, 0.0)).unwrap(); @@ -653,8 +682,80 @@ mod tests { #[test] fn a_pick_away_from_normal_mleader_text_and_lines_misses() { let mut s = crate::Session::new(); - s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 10]], "text": "Visible" })).unwrap(); + let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 10]], "text": "Visible" })).unwrap(); + let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap(); assert_eq!(pick(s.doc().unwrap(), &Space::Model, Vec2::new(2.0, 8.0), 0.05), None); + // Give the text a wide box: a click inside it, right of the glyphs and off the leader, is + // still a miss, since only blank text is picked by its frame. + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") }; + m.text.as_mut().unwrap().width = 5.0; + }) + .unwrap(); + let d = s.doc().unwrap(); + let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") }; + let t = m.text.as_ref().unwrap(); + let p = t.insert.xy() + Vec2::new(t.width * 0.8, 0.0); + assert_eq!(pick(d, &Space::Model, p, 0.02), None, "right of the glyphs, inside the frame"); + assert_eq!(pick(d, &Space::Model, t.insert.xy() + Vec2::new(0.3, 0.0), 0.02), Some(h), "on the glyphs"); + } + + /// A multileader whose text is blank, with the text 6 units right of the landing, 4 wide and + /// 2 high, attached top-left. + fn blank_mleader(s: &mut crate::Session) -> Handle { + let result = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap(); + let h = Handle::parse_hex(result["handle"].as_str().unwrap()).unwrap(); + s.doc_mut() + .unwrap() + .modify_entity(h, |e| { + let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") }; + let landing = m.landing; + let t = m.text.as_mut().unwrap(); + t.insert = landing + Vec3::new(6.0, 0.0, 0.0); + t.width = 4.0; + t.height = 2.0; + t.attach = 1; + t.rotation = 0.0; + }) + .unwrap(); + h + } + + /// A crossing window wholly inside a blank multileader text's box selects it, as a click does. + #[test] + fn a_crossing_window_inside_a_blank_mleader_text_box_selects_it() { + let mut s = crate::Session::new(); + let h = blank_mleader(&mut s); + let d = s.doc().unwrap(); + let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") }; + let o = m.text.as_ref().unwrap().insert.xy(); + let inside = Bounds2::new(o + Vec2::new(1.0, -1.5), o + Vec2::new(2.0, -0.5)); + assert_eq!(select_window(d, &Space::Model, inside, true), vec![h]); + let outside = Bounds2::new(o + Vec2::new(5.0, -1.5), o + Vec2::new(6.0, -0.5)); + assert!(select_window(d, &Space::Model, outside, true).is_empty()); + } + + /// An annotative multileader's blank text is picked where it draws at the current annotation + /// scale: its size and its offset from the landing both scale. + #[test] + fn an_annotative_blank_mleader_text_is_picked_at_its_drawn_offset_and_size() { + let mut s = crate::Session::new(); + let h = blank_mleader(&mut s); + let d = s.doc_mut().unwrap(); + d.header.set_str("CANNOSCALE", "1:2"); + let half = d.anno_scale("1:2").cloned().unwrap(); + d.modify_entity(h, |e| e.common.anno_scales = vec![half]).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") }; + let l = m.landing.xy(); + // At 1:2 the box is 8 x 4 from the landing + (12, 0) (top-left): x 12..20, y -4..0. + let at = |x: f64, y: f64| pick(d, &Space::Model, l + Vec2::new(x, y), 0.02); + assert_eq!(at(16.0, -1.0), Some(h), "inside the scaled box, outside the unscaled one"); + assert_eq!(at(19.5, -3.5), Some(h), "far corner of the scaled box"); + assert_eq!(at(8.0, -1.0), None, "inside the unscaled box, outside the scaled one"); + assert_eq!(at(22.0, -1.0), None, "right of the scaled box"); } /// The box follows the attachment point and the rotation, and a width of 0 falls back to the diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 061b0772b..b3e9abfa8 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -423,6 +423,11 @@ fn gather_in( if !inf && !crate::select::bounds_of(d, e, known).expand(aperture).intersects(&probe) { continue; } + // A blank MTEXT frame covering the cursor is for picking: it neither uses up the candidate + // limit nor the intersection slots unless its insertion point or drawn geometry is in reach. + if !inf && crate::select::blank_frame_only(d, e, &probe, aperture) { + continue; + } count += 1; if count > 2000 { break; @@ -1088,6 +1093,43 @@ mod tests { assert_eq!(m.point, Vec2::new(5.0, 0.0)); } + /// Blank MTEXT frames over the cursor are for picking: thousands of them, with their insertion + /// points out of reach, must not crowd a real endpoint out of the snap candidates (#2810). + #[test] + fn blank_mtext_frames_do_not_crowd_out_snap_candidates() { + for line_first in [true, false] { + let mut d = Drawing::new_metric(); + let line = EntityKind::Line(Line { a: Vec3::new(5.2, -1.0, 0.0), b: Vec3::new(30.0, -1.0, 0.0) }); + if line_first { + d.add(&Space::Model, Common::default(), line.clone()).unwrap(); + } + for _ in 0..2100 { + let t = cadcraft_doc::MText { + insert: Vec3::new(0.0, 0.0, 0.0), + height: 2.5, + width: 10.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: " ".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + } + if !line_first { + d.add(&Space::Model, Common::default(), line).unwrap(); + } + // The cursor is inside every box (x 0..10, y -2.5..0), 0.2 from the line's end. + let h = osnap(&d, &Space::Model, Vec2::new(5.0, -1.0), 0.5, mode::END, None, false).unwrap(); + assert_eq!(h.point, Vec2::new(5.2, -1.0), "line first: {line_first}"); + // A blank MTEXT whose insertion point is in the aperture keeps its INS snap. + let h = osnap(&d, &Space::Model, Vec2::new(0.1, -0.1), 0.5, mode::INS, None, false).unwrap(); + assert_eq!(h.point, Vec2::new(0.0, 0.0), "line first: {line_first}"); + } + } + #[test] fn intersection() { let d = drawing(); From 2697456c9c5d51de81e69f141a4a38e6e46537d7 Mon Sep 17 00:00:00 2001 From: SBaksa <18648812+SBaksa@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:39:38 +1100 Subject: [PATCH 074/187] Select: a blank MTEXT frame is only scaled for blank text, and its snap check uses the drawn insertion point (#2810) --- crates/engine/src/select.rs | 73 ++++++++++++++++++++++++++++++------- crates/engine/src/snap.rs | 58 +++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 35bfa0016..e3c23e3df 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -174,6 +174,15 @@ fn is_blank_mtext(t: &cadcraft_doc::MText) -> bool { /// other entity, a multileader without text content, a blank MTEXT without a usable size or /// position, or an annotative one the current annotation scale hides. fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { + // Kind and blankness first: scaling clones the entity, so only blank text pays for it. + let text = match &e.kind { + EntityKind::MText(t) => t, + EntityKind::MLeader(m) => m.text.as_ref()?, + _ => return None, + }; + if !is_blank_mtext(text) { + return None; + } let f = match d.anno_draw(e) { cadcraft_doc::AnnoDraw::Plain => 1.0, cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f, @@ -192,7 +201,7 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { EntityKind::MLeader(m) => m.text.as_ref()?, _ => return None, }; - if !is_blank_mtext(t) || !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { + if !t.height.is_finite() || t.height <= 0.0 || !t.insert.xy().is_finite() || !t.rotation.is_finite() { return None; } let w = if t.width.is_finite() && t.width > 0.0 { t.width } else { t.height }; @@ -234,22 +243,42 @@ fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool { /// Drawn bounds extended by a blank MTEXT frame, including a multileader's text content. /// Use the same bounds for a scan and for the spatial index. pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 { - blank_mtext_box(d, e).map_or(drawn, |frame| drawn.union(&frame)) + let Some(frame) = blank_mtext_box(d, e) else { return drawn }; + // The snap points are in the bounds too, so a probe on one finds the entity in the index. + blank_snap_points(d, e).into_iter().fold(drawn.union(&frame), |b, p| b.union(&Bounds2::from_points([p]))) +} + +/// The insertion points a blank MTEXT (or a multileader with blank text) can be snapped at, or +/// empty for any other entity: the drawn (scaled) text insertion point, the stored (unscaled) +/// ones snap offers, and a multileader's block content's, unscaled and scaled. +fn blank_snap_points(d: &Drawing, e: &Entity) -> Vec { + let Some((drawn_insert, _, _)) = blank_mtext_frame(d, e) else { return Vec::new() }; + let mut points = vec![drawn_insert]; + match &e.kind { + EntityKind::MText(t) => points.push(t.insert.xy()), + EntityKind::MLeader(m) => { + points.extend(m.text.as_ref().map(|t| t.insert.xy())); + points.extend(m.block.as_ref().map(|b| b.insert.xy())); + if let cadcraft_doc::AnnoDraw::Scaled(f) = d.anno_draw(e) + && f.is_finite() + && f > 0.0 + && f != 1.0 + && let EntityKind::MLeader(sm) = &cadcraft_doc::anno_scaled(e, f).kind + { + points.extend(sm.block.as_ref().map(|b| b.insert.xy())); + } + } + _ => {} + } + points } /// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn -/// geometry (expanded by `aperture`) misses `probe` and no blank text insertion point is inside -/// it. Such an entity is for picking and selection, not a snap candidate. +/// geometry (expanded by `aperture`) misses `probe` and no blank text insertion point (scaled or +/// stored) is inside it. Such an entity is for picking and selection, not a snap candidate. pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, aperture: f64) -> bool { - if blank_mtext_box(d, e).is_none() { - return false; - } - let insert = match &e.kind { - EntityKind::MText(t) => Some(t.insert.xy()), - EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.insert.xy()), - _ => None, - }; - !insert.is_some_and(|p| probe.contains(p)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe) + let points = blank_snap_points(d, e); + !points.is_empty() && !points.iter().any(|p| probe.contains(*p)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe) } pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Bounds2 { @@ -702,6 +731,24 @@ mod tests { assert_eq!(pick(d, &Space::Model, t.insert.xy() + Vec2::new(0.3, 0.0), 0.02), Some(h), "on the glyphs"); } + /// Only blank MTEXT has a frame: an annotative non-blank MTEXT and an annotative LINE have none + /// (and the kind and blankness are decided before any annotation scaling). + #[test] + fn only_blank_mtext_has_a_frame_even_when_annotative() { + let mut d = Drawing::new_metric(); + d.header.set_str("CANNOSCALE", "1:2"); + let half = d.anno_scale("1:2").cloned().unwrap(); + let common = || Common { anno_scales: vec![half.clone()], ..Common::default() }; + let text = d.add(&Space::Model, common(), mtext_at("Visible", 1, 0.0)).unwrap(); + let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(5.0, 0.0, 0.0) }); + let line = d.add(&Space::Model, common(), line).unwrap(); + let blank = d.add(&Space::Model, common(), mtext_at(" ", 1, 0.0)).unwrap(); + for (h, framed) in [(text, false), (line, false), (blank, true)] { + let e = d.entity(h).unwrap(); + assert_eq!(blank_mtext_frame(&d, e).is_some(), framed); + } + } + /// A multileader whose text is blank, with the text 6 units right of the landing, 4 wide and /// 2 high, attached top-left. fn blank_mleader(s: &mut crate::Session) -> Handle { diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index b3e9abfa8..6fbd5c396 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -1130,6 +1130,64 @@ mod tests { } } + /// A blank annotative multileader (text 6 right of its landing, 4 x 2, at 1:2) among 2100 blank + /// MTEXT frames over the cursor. `block_at` also gives it a block content at that offset from + /// the landing. Returns the INS snap at `landing + probe` (aperture 0.5). + fn crowded_blank_mleader_ins(block_at: Option, probe: Vec2) -> Option { + let mut s = crate::Session::new(); + let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap(); + let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + let landing = { + let d = s.doc_mut().unwrap(); + d.header.set_str("CANNOSCALE", "1:2"); + let half = d.anno_scale("1:2").cloned().unwrap(); + d.modify_entity(h, |e| { + e.common.anno_scales = vec![half]; + let EntityKind::MLeader(m) = &mut e.kind else { panic!("mleader") }; + let landing = m.landing; + let t = m.text.as_mut().unwrap(); + t.insert = landing + Vec3::new(6.0, 0.0, 0.0); + t.width = 4.0; + t.height = 2.0; + t.attach = 1; + t.rotation = 0.0; + if let Some(x) = block_at { + m.block = Some(cadcraft_doc::Insert { insert: landing + Vec3::new(x, 0.0, 0.0), ..Default::default() }); + } + }) + .unwrap(); + let EntityKind::MLeader(m) = &d.entity(h).unwrap().kind else { panic!("mleader") }; + m.landing.xy() + }; + let cursor = landing + probe; + // Blank frames (10 x 2.5, top-left at the insert) cover the cursor; their inserts do not. + let d = s.doc_mut().unwrap(); + for _ in 0..2100 { + let t = cadcraft_doc::MText { + insert: Vec3::new(cursor.x - 5.0, cursor.y + 1.0, 0.0), + height: 2.5, + width: 10.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: " ".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + } + osnap(d, &Space::Model, cursor, 0.5, mode::INS, None, false).map(|h| h.point - landing) + } + + /// An annotative blank multileader keeps its INS snap (the stored, unscaled insertion point) + /// among thousands of blank frames, and so does its block content. + #[test] + fn annotative_blank_mleader_keeps_its_ins_snaps_among_blank_frames() { + assert_eq!(crowded_blank_mleader_ins(None, Vec2::new(6.1, -0.1)), Some(Vec2::new(6.0, 0.0)), "text"); + assert_eq!(crowded_blank_mleader_ins(Some(30.0), Vec2::new(30.1, -0.1)), Some(Vec2::new(30.0, 0.0)), "block"); + } + #[test] fn intersection() { let d = drawing(); From cf9f3a7ea31389e94048a4493034c23aa75afa61 Mon Sep 17 00:00:00 2001 From: SBaksa <18648812+SBaksa@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:33:58 +1100 Subject: [PATCH 075/187] Select: a blank MTEXT's bounds stay what it draws, and only the insertion points snap offers keep it a snap candidate (#2810) --- crates/engine/src/select.rs | 76 ++++++++++++++++++++++++------------- crates/engine/src/snap.rs | 16 +++++++- 2 files changed, 65 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index e3c23e3df..1620ce36c 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -243,41 +243,31 @@ fn in_blank_mtext(d: &Drawing, e: &Entity, p: Vec2) -> bool { /// Drawn bounds extended by a blank MTEXT frame, including a multileader's text content. /// Use the same bounds for a scan and for the spatial index. pub(crate) fn pick_bounds(d: &Drawing, e: &Entity, drawn: Bounds2) -> Bounds2 { - let Some(frame) = blank_mtext_box(d, e) else { return drawn }; - // The snap points are in the bounds too, so a probe on one finds the entity in the index. - blank_snap_points(d, e).into_iter().fold(drawn.union(&frame), |b, p| b.union(&Bounds2::from_points([p]))) + match blank_mtext_box(d, e) { + Some(frame) => drawn.union(&frame), + None => drawn, + } } -/// The insertion points a blank MTEXT (or a multileader with blank text) can be snapped at, or -/// empty for any other entity: the drawn (scaled) text insertion point, the stored (unscaled) -/// ones snap offers, and a multileader's block content's, unscaled and scaled. -fn blank_snap_points(d: &Drawing, e: &Entity) -> Vec { - let Some((drawn_insert, _, _)) = blank_mtext_frame(d, e) else { return Vec::new() }; - let mut points = vec![drawn_insert]; +/// The insertion points snap's INS mode offers for a blank MTEXT or multileader (the stored +/// points); empty for any other entity. +fn blank_snap_points(e: &Entity) -> Vec { + // select.rs blank_snap_points must offer the same points as snap.rs's INS arms. match &e.kind { - EntityKind::MText(t) => points.push(t.insert.xy()), - EntityKind::MLeader(m) => { - points.extend(m.text.as_ref().map(|t| t.insert.xy())); - points.extend(m.block.as_ref().map(|b| b.insert.xy())); - if let cadcraft_doc::AnnoDraw::Scaled(f) = d.anno_draw(e) - && f.is_finite() - && f > 0.0 - && f != 1.0 - && let EntityKind::MLeader(sm) = &cadcraft_doc::anno_scaled(e, f).kind - { - points.extend(sm.block.as_ref().map(|b| b.insert.xy())); - } + EntityKind::MText(t) if is_blank_mtext(t) => vec![t.insert.xy()], + EntityKind::MLeader(m) if m.text.as_ref().is_some_and(is_blank_mtext) => { + m.text.iter().map(|t| t.insert.xy()).chain(m.block.iter().map(|b| b.insert.xy())).collect() } - _ => {} + _ => Vec::new(), } - points } /// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn -/// geometry (expanded by `aperture`) misses `probe` and no blank text insertion point (scaled or -/// stored) is inside it. Such an entity is for picking and selection, not a snap candidate. +/// geometry (expanded by `aperture`) misses `probe` and none of the insertion points INS offers +/// (text or block content) is inside it. Such an entity is for picking and selection, not a snap +/// candidate. pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, aperture: f64) -> bool { - let points = blank_snap_points(d, e); + let points = blank_snap_points(e); !points.is_empty() && !points.iter().any(|p| probe.contains(*p)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe) } @@ -1106,4 +1096,38 @@ mod hatch_pattern_pick_tests { let d = solid_hatch(loops(), 2); assert!(pick(&d, &Space::Model, Vec2::new(5.0, 5.0), 0.05).is_some()); } + + /// A window around everything a blank multileader draws (its geometry and its text frame) + /// selects it, at either annotation scale: the stored insertion points snap offers do not + /// widen the box a window has to contain (#2810). + #[test] + fn window_around_a_blank_multileader_still_selects_it() { + use cadcraft_geom::Vec3; + for scale in ["1:2", "2:1"] { + let mut s = crate::Session::new(); + let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [20, 0]], "text": " " })).unwrap(); + let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); + let d = s.doc_mut().unwrap(); + d.header.set_str("CANNOSCALE", scale); + let sc = d.anno_scale(scale).cloned().unwrap(); + d.modify_entity(h, |e| { + e.common.anno_scales = vec![sc]; + let EntityKind::MLeader(m) = &mut e.kind else { return }; + let landing = m.landing; + if let Some(t) = m.text.as_mut() { + t.insert = landing + Vec3::new(6.0, 0.0, 0.0); + t.width = 4.0; + t.height = 2.0; + t.attach = 1; + t.rotation = 0.0; + } + }) + .unwrap(); + let d = &*d; + let e = d.entity(h).unwrap(); + let frame = blank_mtext_box(d, e).expect("a blank multileader has a frame"); + let bx = entity_bounds(d, e, 0).union(&frame).expand(0.01); + assert!(select_window(d, &Space::Model, bx, false).contains(&h), "scale {scale}"); + } + } } diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 6fbd5c396..47d4932e1 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -443,6 +443,7 @@ fn gather_in( } EntityKind::AttDef(a) => cands.push((mode::INS, a.text.justify_point())), // A multileader: its text's insertion point, or its block content's. + // select.rs blank_snap_points must offer the same points. EntityKind::MLeader(m) => { cands.extend(m.text.iter().map(|t| (mode::INS, t.insert.xy()))); cands.extend(m.block.iter().map(|b| (mode::INS, b.insert.xy()))); @@ -1139,6 +1140,14 @@ mod tests { let h = cadcraft_doc::Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap(); let landing = { let d = s.doc_mut().unwrap(); + if block_at.is_some() { + // A block whose geometry (a line 60 long) covers its base point, at the stored insertion + // and, drawn at 1:2 about the landing, at the scaled one too. + let mut blk = cadcraft_doc::Block::new("BLK"); + let line = EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(60.0, 0.0, 0.0) }); + blk.entities.push(cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), line)); + d.blocks.insert("BLK".into(), std::sync::Arc::new(blk)); + } d.header.set_str("CANNOSCALE", "1:2"); let half = d.anno_scale("1:2").cloned().unwrap(); d.modify_entity(h, |e| { @@ -1152,7 +1161,12 @@ mod tests { t.attach = 1; t.rotation = 0.0; if let Some(x) = block_at { - m.block = Some(cadcraft_doc::Insert { insert: landing + Vec3::new(x, 0.0, 0.0), ..Default::default() }); + m.block = Some(cadcraft_doc::Insert { + block: "BLK".into(), + insert: landing + Vec3::new(x, 0.0, 0.0), + scale: Vec3::new(1.0, 1.0, 1.0), + ..Default::default() + }); } }) .unwrap(); From 72f07e5cd14c9a2eeed6e7968cf28b5f8fbb00da Mon Sep 17 00:00:00 2001 From: SBaksa <18648812+SBaksa@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:05:58 +1100 Subject: [PATCH 076/187] Select: a blank MTEXT's frame follows layout orientation, and its insertion points keep it a snap candidate only when INS is on and within the aperture (#2810) A top-level MTEXT with a non-zero AcadAnnoPO value is drawn upright, so its pick frame no longer turns with the stored rotation. Insertion points now keep a blank frame in the snap pool only when INS is enabled and the point is within the aperture circle, not just the square probe. --- crates/engine/src/select.rs | 30 ++++++++++++++++++++----- crates/engine/src/snap.rs | 44 ++++++++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 1620ce36c..00a369c04 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -220,7 +220,10 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { 7..=9 => h, _ => 0.0, }; - Some((insert, t.rotation, [dx, dx + w, top - h, top])) + // A top-level MTEXT that matches the layout orientation is drawn and measured upright, as the + // renderer and the extents do; a multileader keeps the stored rotation of its text. + let rotation = if matches!(e.kind, EntityKind::MText(_)) && e.common.matches_layout_orientation() { 0.0 } else { t.rotation }; + Some((insert, rotation, [dx, dx + w, top - h, top])) } /// The box around a blank MTEXT's turned frame (a top-level MTEXT or a multileader's MTEXT @@ -263,12 +266,13 @@ fn blank_snap_points(e: &Entity) -> Vec { } /// Whether `e` is within reach of a snap probe only through its blank MTEXT frame: the drawn -/// geometry (expanded by `aperture`) misses `probe` and none of the insertion points INS offers -/// (text or block content) is inside it. Such an entity is for picking and selection, not a snap -/// candidate. -pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, aperture: f64) -> bool { +/// geometry (expanded by `aperture`) misses `probe`, and no insertion point INS would offer (text +/// or block content) is a candidate: one counts only when `ins` is on and it is within `aperture` +/// of `cursor`, the distance snap accepts a candidate by (a corner of the square probe is not). +/// Such an entity is for picking and selection, not a snap candidate. +pub(crate) fn blank_frame_only(d: &Drawing, e: &Entity, probe: &Bounds2, cursor: Vec2, aperture: f64, ins: bool) -> bool { let points = blank_snap_points(e); - !points.is_empty() && !points.iter().any(|p| probe.contains(*p)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe) + !points.is_empty() && !(ins && points.iter().any(|p| p.dist(cursor) <= aperture)) && !entity_bounds(d, e, 0).expand(aperture).intersects(probe) } pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option) -> Bounds2 { @@ -820,6 +824,20 @@ mod tests { assert_eq!(at(&d, 5.0, -1.0), None); } + /// A top-level MTEXT that matches the layout orientation is drawn upright, ignoring its stored + /// rotation, so its frame is the unturned one (the renderer and the extents do the same). + #[test] + fn rotated_blank_mtext_matching_layout_orientation_is_picked_in_its_unrotated_frame() { + let mut d = Drawing::new_metric(); + let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() }; + let common = Common { xdata: vec![tag(1001, "AcadAnnoPO"), tag(1070, "1")], ..Common::default() }; + let h = d.add(&Space::Model, common, mtext_at(" ", 1, std::f64::consts::FRAC_PI_2)).unwrap(); + let at = |x: f64, y: f64| pick(&d, &Space::Model, Vec2::new(x, y), 0.05); + // Unrotated frame x 0..10, y -2.5..0; the rotated one would be x 0..2.5, y 0..10. + assert_eq!(at(5.0, -1.0), Some(h), "inside the unrotated frame"); + assert_eq!(at(1.0, 5.0), None, "inside only the rotated frame"); + } + /// A turned blank MTEXT is hit in its turned box, not in the axis-aligned box around it (whose /// empty corners lie off the text). #[test] diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 47d4932e1..95027afeb 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -425,7 +425,7 @@ fn gather_in( } // A blank MTEXT frame covering the cursor is for picking: it neither uses up the candidate // limit nor the intersection slots unless its insertion point or drawn geometry is in reach. - if !inf && crate::select::blank_frame_only(d, e, &probe, aperture) { + if !inf && crate::select::blank_frame_only(d, e, &probe, cursor, aperture, osmode & mode::INS != 0) { continue; } count += 1; @@ -1131,6 +1131,48 @@ mod tests { } } + /// 2001 blank MTEXT frames covering `cursor` (insertion points at `ins_at`), drawn before a + /// LINE whose end is at `cursor`: the END snap found with `osmode`. + fn crowded_blank_frames_end_snap(ins_at: Vec2, cursor: Vec2, aperture: f64, osmode: u32) -> Option { + let mut d = Drawing::new_metric(); + for _ in 0..2001 { + let t = cadcraft_doc::MText { + insert: Vec3::new(ins_at.x, ins_at.y, 0.0), + height: 2.5, + width: 10.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: " ".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); + } + d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::new(cursor.x, cursor.y, 0.0), b: Vec3::new(30.0, cursor.y, 0.0) })) + .unwrap(); + osnap(&d, &Space::Model, cursor, aperture, osmode, None, false).map(|h| h.point) + } + + /// An insertion point in a corner of the square probe is farther than the aperture from the + /// cursor, so snap would never accept it: its frame must not crowd out an END snap. + #[test] + fn blank_insertion_points_in_the_probe_corner_do_not_crowd_out_an_end_snap() { + let cursor = Vec2::new(5.0, -1.0); + let ap = 0.5; + let corner = Vec2::new(cursor.x - 0.9 * ap, cursor.y + 0.9 * ap); + assert!(corner.dist(cursor) > ap, "outside the circle, inside the square probe"); + assert_eq!(crowded_blank_frames_end_snap(corner, cursor, ap, mode::END | mode::INS), Some(cursor)); + } + + /// With INS off a blank MTEXT's insertion point is no snap candidate, even right at the cursor. + #[test] + fn blank_insertion_points_with_ins_off_do_not_crowd_out_an_end_snap() { + let cursor = Vec2::new(5.0, -1.0); + assert_eq!(crowded_blank_frames_end_snap(cursor, cursor, 0.5, mode::END), Some(cursor)); + } + /// A blank annotative multileader (text 6 right of its landing, 4 x 2, at 1:2) among 2100 blank /// MTEXT frames over the cursor. `block_at` also gives it a block content at that offset from /// the landing. Returns the INS snap at `landing + probe` (aperture 0.5). From 086bd8a8652dd65b5d672b01edb9a508e98d35f5 Mon Sep 17 00:00:00 2001 From: SBaksa <18648812+SBaksa@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:24:17 +1100 Subject: [PATCH 077/187] Select: say why a blank MTEXT frame is upright, and when its insertion points keep it a snap candidate (#2810) --- crates/engine/src/select.rs | 4 ++-- crates/engine/src/snap.rs | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 00a369c04..df984ae79 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -220,8 +220,8 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> { 7..=9 => h, _ => 0.0, }; - // A top-level MTEXT that matches the layout orientation is drawn and measured upright, as the - // renderer and the extents do; a multileader keeps the stored rotation of its text. + // A top-level MTEXT that matches the layout orientation is drawn upright (the renderer draws + // non-blank text that way), so its blank frame is too; a multileader keeps its text's stored rotation. let rotation = if matches!(e.kind, EntityKind::MText(_)) && e.common.matches_layout_orientation() { 0.0 } else { t.rotation }; Some((insert, rotation, [dx, dx + w, top - h, top])) } diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 95027afeb..d79dd2740 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -424,7 +424,8 @@ fn gather_in( continue; } // A blank MTEXT frame covering the cursor is for picking: it neither uses up the candidate - // limit nor the intersection slots unless its insertion point or drawn geometry is in reach. + // limit nor the intersection slots unless its drawn geometry is in reach, or INS is on and an + // insertion point is within the aperture. if !inf && crate::select::blank_frame_only(d, e, &probe, cursor, aperture, osmode & mode::INS != 0) { continue; } From c17cbc9c732dcd0f0bfd9cfb9975e41a21480b5f Mon Sep 17 00:00:00 2001 From: YannFR81 Date: Wed, 11 Nov 2026 18:22:47 +0100 Subject: [PATCH 078/187] i18n(fr): consistent French CAD terminology in existing rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the French catalog: harmonises rows already on main, without touching the rows added by #2102. - Command-line prompts use the imperative (Sélectionnez, Spécifiez, Entrez), as the other prompts already did; menu and button labels keep the infinitive. - A dimension object and its style are "cote" / "style de cote"; "Cotation" stays for the Dimension menu and Quick Dimension. - Model space is "espace objet", Array is "réseau", a layout is a "présentation", tracking is "repérage" (object snap and polar). Rebased on main after #2563: the prompts that lost their trailing "or" keep the imperative wording on their new keys. The docs/localization-parity.md row is left to the maintainers, as AGENTS.md asks. Original wording written from CADCraft's English strings; no proprietary localization resources were used. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01C4cGqxCFJD1m28x2aqwf7Q --- ATTRIBUTION.md | 2 +- crates/ui-egui/src/i18n/fr.tsv | 200 ++++++++++++++++----------------- 2 files changed, 101 insertions(+), 101 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 7cc7495e5..80dc7f763 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -68,7 +68,7 @@ Generated-in-code assets are original and have no file to list: | `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker | | `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | +| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star; terminology pass by @YannFR81 | Original French translations of CADCraft English strings; AI-assisted consistency pass (imperative prompts, cote/espace objet/réseau/présentation) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | | `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker | | `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted); terminology corrections: Andrea Brandi (@starise) with OpenAI Codex (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; targeted Chamfer terminology review by a native speaker | diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 477407a5a..75a1f89cd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -160,7 +160,7 @@ Delete Supprimer Delete Column Supprimer la colonne Delete Constraints Supprimer les contraintes - Delete Dimension Style Supprimer le style de cotation + Delete Dimension Style Supprimer le style de cote Delete Duplicate Objects Supprimer les objets en double Delete Layer Supprimer le calque Delete Layer State Supprimer l'état des calques @@ -172,17 +172,17 @@ Description Description Deselect All Désélectionner tout Diameter Diamètre - Dim style Style de cotation + Dim style Style de cote Dimension Cotation - Dimension Space Espace entre cotations - Dimension Style Override Substitution de style de cotation - Dimension Style... Style de cotation... - Dimension Text Edit Modifier le texte de cotation - Dimension style Style de cotation + Dimension Space Espacement des cotes + Dimension Style Override Substitution de style de cote + Dimension Style... Style de cote... + Dimension Text Edit Modifier le texte de cote + Dimension style Style de cote Dimensional Constraint Contrainte dimensionnelle Dimensional Constraint Parameters Paramètres de contraintes dimensionnelles Dimensional Constraints Contraintes dimensionnelles - Disassociate Dimensions Dissocier les cotations + Disassociate Dimensions Dissocier les cotes Display name Nom d'affichage Distance Distance Divide Diviser @@ -200,7 +200,7 @@ Drawing Limits Limites du dessin Drawing Utilities Utilitaires de dessin Drawings (DWG, DXF) Dessins (DWG, DXF) - Dynamic Dimensions Cotations dynamiques + Dynamic Dimensions Cotes dynamiques Dynamic Input Saisie dynamique Dynamic Input (F12) Saisie dynamique (F12) E Est @@ -233,9 +233,9 @@ Enter degree of spline Entrez le degré de la spline Enter delta angle Entrez l'écart d'angle Enter delta length Entrez l'écart de longueur - Enter dimension text Entrez le texte de cotation - Enter dimension text (<> = measurement) Entrez le texte de cotation (<> = mesure) - Enter dimension value or [name=expression] Entrez la valeur de cotation ou [name=expression] + Enter dimension text Entrez le texte de cote + Enter dimension text (<> = measurement) Entrez le texte de cote (<> = mesure) + Enter dimension value or [name=expression] Entrez la valeur de cote ou [name=expression] Enter dimension variable name to override Entrez le nom de la variable de cotation à substituer Enter justification type Entrez le type de justification Enter leader text Entrez le texte du repère @@ -254,10 +254,10 @@ Enter rectangle length Entrez la longueur du rectangle Enter rectangle width Entrez la largeur du rectangle Enter scale factor Entrez le facteur d'échelle - Enter text Entrer le texte - Enter text (use \P for new paragraphs) Entrer le texte (utilisez \P pour les nouveaux paragraphes) - Enter the number of segments Entrer le nombre de segments - Enter twist direction of helix Entrer le sens de vrillage de l'hélice + Enter text Entrez le texte + Enter text (use \P for new paragraphs) Entrez le texte (utilisez \P pour les nouveaux paragraphes) + Enter the number of segments Entrez le nombre de segments + Enter twist direction of helix Entrez le sens de vrillage de l'hélice Entire drawing Tout le dessin Equal Égalité Erase Effacer @@ -482,8 +482,8 @@ Object Snap Accrochage aux objets Object Snap (F3) Accrochage aux objets (F3) Object Snap On (F3) Activer l'accrochage aux objets (F3) - Object Snap Tracking Suivi de l'accrochage aux objets - Object Snap Tracking (F11) Suivi de l'accrochage aux objets (F11) + Object Snap Tracking Repérage par accrochage aux objets + Object Snap Tracking (F11) Repérage par accrochage aux objets (F11) Object type: Type d'objet : Off Désactivé Offset Décalage @@ -539,7 +539,7 @@ New STB Nouvelle STB New style Nouveau style Reset Panel Layout Réinitialiser la disposition des panneaux - Use for this layout Utiliser pour cet espace + Use for this layout Utiliser pour cette présentation Display plot styles Afficher les styles de tracé No plot style tables. Aucune table de styles de tracé. A built-in table: editing it keeps an edited copy in the drawing. Table intégrée : sa modification conserve une copie modifiée dans le dessin. @@ -560,9 +560,9 @@ Point Filters Filtres de points Point Style... Style de point... Polar Array Réseau polaire - Polar Tracking Recherche polaire - Polar Tracking (F10) Recherche polaire (F10) - Polar Tracking On (F10) Activer la recherche polaire (F10) + Polar Tracking Repérage polaire + Polar Tracking (F10) Repérage polaire (F10) + Polar Tracking On (F10) Activer le repérage polaire (F10) Polar: {distance} < {angle}° Polaire : {distance} < {angle}° Polygon Polygone Polygonal Polygonal @@ -645,77 +645,77 @@ Search for parameter Rechercher un paramètre Second and next points: Deuxième point et points suivants : Select Sélectionner - Select 2D polyline Sélectionner une polyligne 2D + Select 2D polyline Sélectionnez une polyligne 2D Select All Sélectionner tout Select Objects Sélectionner les objets - Select a 2D polyline. Sélectionner une polyligne 2D. - Select a block reference. Sélectionner une référence de bloc. - Select a circle or arc. Sélectionner un cercle ou un arc. - Select a closed polyline Sélectionner une polyligne fermée - Select a closed polyline, circle, ellipse or closed spline. Sélectionner une polyligne fermée, un cercle, une ellipse ou une spline fermée. - Select a closed polyline. Sélectionner une polyligne fermée. - Select a curve as the path. Sélectionner une courbe comme trajectoire. - Select a dimension constraint type Sélectionner un type de contrainte dimensionnelle - Select a line object Sélectionner une ligne - Select a line object. Sélectionner une ligne. - Select a line or an arc. Sélectionner une ligne ou un arc. - Select a line or polyline segment Sélectionner une ligne ou un segment de polyligne - Select a line, arc or open polyline. Sélectionner une ligne, un arc ou une polyligne ouverte. - Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionner une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire. - Select a line, circle, arc or polyline segment. Sélectionner une ligne, un cercle, un arc ou un segment de polyligne. - Select a line. Sélectionner une ligne. + Select a 2D polyline. Sélectionnez une polyligne 2D. + Select a block reference. Sélectionnez une référence de bloc. + Select a circle or arc. Sélectionnez un cercle ou un arc. + Select a closed polyline Sélectionnez une polyligne fermée + Select a closed polyline, circle, ellipse or closed spline. Sélectionnez une polyligne fermée, un cercle, une ellipse ou une spline fermée. + Select a closed polyline. Sélectionnez une polyligne fermée. + Select a curve as the path. Sélectionnez une courbe comme trajectoire. + Select a dimension constraint type Sélectionnez un type de contrainte dimensionnelle + Select a line object Sélectionnez une ligne + Select a line object. Sélectionnez une ligne. + Select a line or an arc. Sélectionnez une ligne ou un arc. + Select a line or polyline segment Sélectionnez une ligne ou un segment de polyligne + Select a line, arc or open polyline. Sélectionnez une ligne, un arc ou une polyligne ouverte. + Select a line, arc, circle, polyline, ellipse or spline as the path. Sélectionnez une ligne, un arc, un cercle, une polyligne, une ellipse ou une spline comme trajectoire. + Select a line, circle, arc or polyline segment. Sélectionnez une ligne, un cercle, un arc ou un segment de polyligne. + Select a line. Sélectionnez une ligne. Add to Working Set Ajouter au jeu de travail Edit Reference In-Place Modifier la référence sur place Save Reference Edits Enregistrer les modifications de la référence Working Set Jeu de travail Xref and Block In-place Editing Édition sur place des xrefs et des blocs - Select a polyline. Sélectionner une polyligne. - Select a text, mtext, attribute definition or dimension. Sélectionner un texte, un texte multiligne, une définition d'attribut ou une cote. - Select an annotation object Sélectionner un objet d'annotation - Select an arc or circle Sélectionner un arc ou un cercle - Select an arc. Sélectionner un arc. - Select an object Sélectionner un objet - Select an object to change Sélectionner un objet à modifier - Select an object to measure Sélectionner un objet à mesurer - Select an object. Sélectionner un objet. - Select an open curve. Sélectionner une courbe ouverte. - Select an open line, arc, polyline, ellipse arc or spline. Sélectionner une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts. - Select arc or circle Sélectionner un arc ou un cercle - Select arc or polyline arc segment Sélectionner un arc ou un segment d'arc de polyligne - Select arc style Sélectionner un style d'arc - Select arc, circle, line Sélectionner un arc, un cercle, une ligne - Select at least two objects to join. Sélectionner au moins deux objets à joindre. - Select circle or arc to add center mark Sélectionner un cercle ou un arc pour ajouter une marque de centre - Select closed objects (regions, closed polylines, circles). Sélectionner des objets fermés (régions, polylignes fermées, cercles). - Select first line Sélectionner la première ligne - Select first line or arc Sélectionner la première ligne ou le premier arc - Select first object Sélectionner le premier objet - Select first point Sélectionner le premier point - Select nested objects to copy Sélectionner des objets imbriqués à copier - Select object Sélectionner un objet - Select object to dimension Sélectionner un objet à coter - Select object to divide Sélectionner un objet à diviser - Select object to extend or shift-select to trim Sélectionner un objet à prolonger ou sélectionner avec Maj pour rogner - Select object to measure Sélectionner un objet à mesurer - Select object to offset Sélectionner un objet à décaler - Select object to trim or shift-select to extend Sélectionner un objet à rogner ou sélectionner avec Maj pour prolonger - Select objects Sélectionner les objets - Select objects (crossing window first corner) Sélectionner les objets (premier coin de la fenêtre de capture) - Select objects to array. Sélectionner les objets à répartir en réseau. - Select objects to stretch by crossing-window or crossing-polygon... Sélectionner les objets à étirer par fenêtre de capture ou polygone de capture... - Select objects: Sélectionner les objets : - Select one polyline (Multiple is available through the JSON form). Sélectionner une polyligne (l'option Multiple est disponible via le formulaire JSON). - Select path curve Sélectionner la courbe de trajectoire - Select point or object Sélectionner un point ou un objet - Select polyline Sélectionner une polyligne - Select second line Sélectionner la deuxième ligne - Select second line or shift-select to apply corner Sélectionner la deuxième ligne ou sélectionner avec Maj pour former le coin - Select second object Sélectionner le deuxième objet - Select second object or shift-select to apply corner Sélectionner le deuxième objet ou sélectionner avec Maj pour former le coin - Select second point Sélectionner le deuxième point - Select spline Sélectionner une spline - Select symmetry line Sélectionner l'axe de symétrie - Select two points Sélectionner deux points + Select a polyline. Sélectionnez une polyligne. + Select a text, mtext, attribute definition or dimension. Sélectionnez un texte, un texte multiligne, une définition d'attribut ou une cote. + Select an annotation object Sélectionnez un objet d'annotation + Select an arc or circle Sélectionnez un arc ou un cercle + Select an arc. Sélectionnez un arc. + Select an object Sélectionnez un objet + Select an object to change Sélectionnez un objet à modifier + Select an object to measure Sélectionnez un objet à mesurer + Select an object. Sélectionnez un objet. + Select an open curve. Sélectionnez une courbe ouverte. + Select an open line, arc, polyline, ellipse arc or spline. Sélectionnez une ligne, un arc, une polyligne, un arc elliptique ou une spline ouverts. + Select arc or circle Sélectionnez un arc ou un cercle + Select arc or polyline arc segment Sélectionnez un arc ou un segment d'arc de polyligne + Select arc style Sélectionnez un style d'arc + Select arc, circle, line Sélectionnez un arc, un cercle, une ligne + Select at least two objects to join. Sélectionnez au moins deux objets à joindre. + Select circle or arc to add center mark Sélectionnez un cercle ou un arc pour ajouter une marque de centre + Select closed objects (regions, closed polylines, circles). Sélectionnez des objets fermés (régions, polylignes fermées, cercles). + Select first line Sélectionnez la première ligne + Select first line or arc Sélectionnez la première ligne ou le premier arc + Select first object Sélectionnez le premier objet + Select first point Sélectionnez le premier point + Select nested objects to copy Sélectionnez des objets imbriqués à copier + Select object Sélectionnez un objet + Select object to dimension Sélectionnez un objet à coter + Select object to divide Sélectionnez un objet à diviser + Select object to extend or shift-select to trim Sélectionnez un objet à prolonger ou sélectionnez avec Maj pour rogner + Select object to measure Sélectionnez un objet à mesurer + Select object to offset Sélectionnez un objet à décaler + Select object to trim or shift-select to extend Sélectionnez un objet à rogner ou sélectionnez avec Maj pour prolonger + Select objects Sélectionnez les objets + Select objects (crossing window first corner) Sélectionnez les objets (premier coin de la fenêtre de capture) + Select objects to array. Sélectionnez les objets à répartir en réseau. + Select objects to stretch by crossing-window or crossing-polygon... Sélectionnez les objets à étirer par fenêtre de capture ou polygone de capture... + Select objects: Sélectionnez les objets : + Select one polyline (Multiple is available through the JSON form). Sélectionnez une polyligne (l'option Multiple est disponible via le formulaire JSON). + Select path curve Sélectionnez la courbe de trajectoire + Select point or object Sélectionnez un point ou un objet + Select polyline Sélectionnez une polyligne + Select second line Sélectionnez la deuxième ligne + Select second line or shift-select to apply corner Sélectionnez la deuxième ligne ou sélectionnez avec Maj pour former le coin + Select second object Sélectionnez le deuxième objet + Select second object or shift-select to apply corner Sélectionnez le deuxième objet ou sélectionnez avec Maj pour former le coin + Select second point Sélectionnez le deuxième point + Select spline Sélectionnez une spline + Select symmetry line Sélectionnez l'axe de symétrie + Select two points Sélectionnez deux points Selection Cycling Cycle de sélection Send to Back Envoyer à l'arrière-plan Set Current Définir comme courant @@ -746,18 +746,18 @@ Snap and Grid Accrochage et grille Solid Solide Sort Trier - Specify a point Spécifier un point - Specify a scale for the hatch pattern Spécifier une échelle pour le motif de hachures - Specify a second extension line origin Spécifier l'origine de la deuxième ligne d'attache - Specify an angle for the hatch pattern Spécifier un angle pour le motif de hachures - Specify angle end point Spécifier le point final de l'angle - Specify angle of dimension line Spécifier l'angle de la ligne de cote - Specify angle of dimension text Spécifier l'angle du texte de cote - Specify angle start point Spécifier le point de départ de l'angle - Specify angle vertex Spécifier le sommet de l'angle - Specify angle vertex point Spécifier le point du sommet de l'angle - Specify arc length dimension location Spécifier l'emplacement de la cote de longueur d'arc - Specify axis endpoint of ellipse Spécifier l'extrémité de l'axe de l'ellipse + Specify a point Spécifiez un point + Specify a scale for the hatch pattern Spécifiez une échelle pour le motif de hachures + Specify a second extension line origin Spécifiez l'origine de la deuxième ligne d'attache + Specify an angle for the hatch pattern Spécifiez un angle pour le motif de hachures + Specify angle end point Spécifiez le point final de l'angle + Specify angle of dimension line Spécifiez l'angle de la ligne de cote + Specify angle of dimension text Spécifiez l'angle du texte de cote + Specify angle start point Spécifiez le point de départ de l'angle + Specify angle vertex Spécifiez le sommet de l'angle + Specify angle vertex point Spécifiez le point du sommet de l'angle + Specify arc length dimension location Spécifiez l'emplacement de la cote de longueur d'arc + Specify axis endpoint of ellipse Spécifiez l'extrémité de l'axe de l'ellipse Specify base diameter Spécifiez le diamètre de la base Specify base point Spécifiez le point de base Specify base point or displacement (drag with the middle mouse button for realtime pan) Spécifiez le point de base ou le déplacement (faites glisser avec le bouton central de la souris pour un panoramique en temps réel) @@ -767,7 +767,7 @@ Specify center of polygon Spécifiez le centre du polygone Specify center point for circle Spécifiez le point central du cercle Specify center point of arc Spécifiez le point central de l'arc - Specify center point of array Spécifiez le point central de la matrice + Specify center point of array Spécifiez le point central du réseau Specify center point of base Spécifiez le point central de la base Specify corner of viewport Spécifiez le coin de la fenêtre Specify corner of window, enter a scale factor (nX or nXP) Spécifiez le coin de la fenêtre, entrez un facteur d'échelle (nX ou nXP) @@ -893,7 +893,7 @@ Sweep Balayage Switch Drawing Changer de dessin Switch Layout Changer de présentation - Switch between model space in a viewport and paper space Basculer entre l'espace modèle dans une fenêtre et l'espace papier + Switch between model space in a viewport and paper space Basculer entre l'espace objet dans une fenêtre et l'espace papier Symmetric Symétrie Synchronize Attributes Synchroniser les attributs Toggle PICKADD (off: each pick replaces the selection) Basculer PICKADD (désactivé : chaque sélection remplace la sélection existante) From 4e482cf617558cd074cf50f939b54b9e4b1b19e4 Mon Sep 17 00:00:00 2001 From: YannFR81 Date: Wed, 11 Nov 2026 18:26:14 +0100 Subject: [PATCH 079/187] i18n(fr): align four shared rows with #2580 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dimension Space, Dimension Style Override and Object Snap Tracking (with its F11 variant) are also changed by #2580. Use one wording in both pull requests so they merge in either order: - Dimension Space: "Espacer les cotes" (menu labels keep the infinitive) - Dimension Style Override: "Remplacement de style de cote" - Object Snap Tracking: "Repérage d'accrochage aux objets", as #2102 already uses for Object Snap Tracking Settings --- crates/ui-egui/src/i18n/fr.tsv | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 75a1f89cd..adb5c4aef 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -174,8 +174,8 @@ Diameter Diamètre Dim style Style de cote Dimension Cotation - Dimension Space Espacement des cotes - Dimension Style Override Substitution de style de cote + Dimension Space Espacer les cotes + Dimension Style Override Remplacement de style de cote Dimension Style... Style de cote... Dimension Text Edit Modifier le texte de cote Dimension style Style de cote @@ -482,8 +482,8 @@ Object Snap Accrochage aux objets Object Snap (F3) Accrochage aux objets (F3) Object Snap On (F3) Activer l'accrochage aux objets (F3) - Object Snap Tracking Repérage par accrochage aux objets - Object Snap Tracking (F11) Repérage par accrochage aux objets (F11) + Object Snap Tracking Repérage d'accrochage aux objets + Object Snap Tracking (F11) Repérage d'accrochage aux objets (F11) Object type: Type d'objet : Off Désactivé Offset Décalage From e09870949defd3ae76f370bf2895082489041b59 Mon Sep 17 00:00:00 2001 From: mo <131036780+mbolling@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:26:14 -0500 Subject: [PATCH 080/187] fix(fonts): a Thai ligature keeps every character it stands for as text A font may draw a consonant and its below vowel as one ligature glyph: GNU FreeSerif's Thai liga lookup replaces tho than + sara u with a single tailless form. glyph_chars gave each glyph of a cluster at most one character, so the characters left over in the cluster were dropped and sara u was missing from the shaped text records. glyph_chars now returns the characters each glyph shows, and the cluster's last glyph takes any that are left over. push_glyph records one text glyph per character against the same outline. Co-Authored-By: Claude Opus 5.5 --- crates/fonts/src/complex.rs | 37 ++++++++++++++++++++++--------------- crates/fonts/src/lib.rs | 14 +++++++------- 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/crates/fonts/src/complex.rs b/crates/fonts/src/complex.rs index ce2fbcb61..abfa3bbe5 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -130,13 +130,13 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 *p += Vec2::new(dy * shear, dy); } let origin = Vec2::new(x + g.dx * k + dy * shear, dy); - let text = shows + let texts = shows .get(n) - .copied() + .into_iter() .flatten() .filter(|c| !c.is_whitespace()) - .and_then(|c| ttf::text_glyph_at(&outline, c, origin, h / outline.cap, wf, shear)); - out.push_glyph(contours, text); + .filter_map(|c| ttf::text_glyph_at(&outline, *c, origin, h / outline.cap, wf, shear)); + out.push_glyph(contours, texts); } let adv = g.advance * k; let (u, o) = flags(g.cluster); @@ -248,14 +248,15 @@ fn shape_run(face: &Face, cs: &[char], r: Range, rtl: bool) -> Vec /// longer one (a hostile run of thousands of stacked marks) take its characters in order. const MAX_MATCHED_CLUSTER: usize = 32; -/// The character each glyph of a left-to-right run shows, for output that keeps text as text +/// The characters each glyph of a left-to-right run shows, for output that keeps text as text /// ([`crate::TextGlyph`]). The shaper reorders, splits and substitutes glyphs inside a cluster /// (a letter with its marks), so within each cluster a glyph that is a character's own glyph /// takes that character first, then the other glyphs take the cluster's remaining characters in /// order. Each character is shown once: a glyph left over (the second half of a split Thai sara -/// am) shows none and is drawn as an outline only. -fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec> { - let mut out: Vec> = vec![None; glyphs.len()]; +/// am) shows none and is drawn as an outline only; characters left over (a ligature such as ฐ +/// with sara u below) are all shown by the cluster's last glyph. +fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec> { + let mut out: Vec> = vec![Vec::new(); glyphs.len()]; let mut i = 0; while let Some(cluster) = glyphs.get(i).map(|g| g.cluster) { let j = glyphs.iter().skip(i).position(|g| g.cluster != cluster).map_or(glyphs.len(), |n| i + n); @@ -269,13 +270,16 @@ fn glyph_chars(face: &Face, cs: &[char], glyphs: &[Glyph], end: usize) -> Vec = std::iter::once('ก').chain(std::iter::repeat_n('\u{0E48}', MAX_CHARS)).collect(); let gs: Vec = (0..long.len()).map(|_| glyph(0)).collect(); let shows = glyph_chars(&face, &long, &gs, long.len()); - assert_eq!(shows.first(), Some(&Some('ก'))); - assert!(shows.iter().all(Option::is_some)); + assert_eq!(shows.first(), Some(&vec!['ก'])); + assert!(shows.iter().all(|s| s.len() == 1)); } /// An installed font with Thai, or `None` (the tests then skip). diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index c41898cee..65772265a 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -405,15 +405,15 @@ pub struct TextGlyph { } impl Shaped { - /// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`]. - /// An empty outline is retained only when text metadata needs its slot. - pub(crate) fn push_glyph(&mut self, contours: Vec>, text: Option) { - if contours.is_empty() && text.is_none() { + /// Add a glyph outline and, when it is a font glyph, its [`TextGlyph`] (one per character it + /// shows: a ligature shows several). An empty outline is retained only when text metadata + /// needs its slot. + pub(crate) fn push_glyph(&mut self, contours: Vec>, text: impl IntoIterator) { + let (outline, before) = (self.glyphs.len(), self.text.len()); + self.text.extend(text.into_iter().map(|t| TextGlyph { outline, ..t })); + if contours.is_empty() && self.text.len() == before { return; } - if let Some(t) = text { - self.text.push(TextGlyph { outline: self.glyphs.len(), ..t }); - } self.glyphs.push(contours); } /// Apply a point transform to every vertex (an affine map: text glyphs keep their axes). From 6ac52455d99ca017860210372ae5596b358c11d2 Mon Sep 17 00:00:00 2001 From: YannFR81 Date: Wed, 11 Nov 2026 23:30:10 +0100 Subject: [PATCH 081/187] i18n(fr): credit the terminology review in the catalog header --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index adb5c4aef..47a8632c2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1,4 +1,4 @@ -# CADCraft French interface catalog — original translations by @pechnikov2026-star. +# CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81. # License: MIT OR Apache-2.0 (the repository LICENSE-MIT and LICENSE-APACHE). # Written from CADCraft's English strings; no proprietary translations were copied. # UTF-8: contextEnglish sourceFrench translation. From ad596f1e4123801391c0d91c9480b9da2294dd16 Mon Sep 17 00:00:00 2001 From: Walter Haslbeck Date: Thu, 12 Nov 2026 07:48:07 +0100 Subject: [PATCH 082/187] fix(io): skip sampling arcs for the tilt check when the extrusion is on the Z axis `tilted` took its points eagerly, so every bulged edge of every LWPOLYLINE and HATCH loop was tessellated on read, also with extrusion +Z or -Z, where no point can move and the answer is always "not tilted". It now takes the points as a closure and returns before gathering them when the normal's x and y are exactly 0. For such a normal `Mat4::ocs` is the identity or (-x, y, -z), so the result is the same as before. --- crates/io/src/dxf_read/common.rs | 33 ++++++++++++++++++++++++++---- crates/io/src/dxf_read/entities.rs | 4 ++-- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/io/src/dxf_read/common.rs b/crates/io/src/dxf_read/common.rs index 59dcf7107..f2d111ac0 100644 --- a/crates/io/src/dxf_read/common.rs +++ b/crates/io/src/dxf_read/common.rs @@ -119,15 +119,17 @@ pub(super) fn ocs_n(n: Vec3, p: Vec3) -> Vec3 { /// 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 { +/// the origin to be moved visibly is projected. The points are only gathered for a normal off +/// the Z axis: along it (x and y exactly 0, as in nearly every drawing) nothing moves, and +/// sampling every arc of every object for that would be wasted. +pub(super) fn tilted>(n: Vec3, pts: impl FnOnce() -> I) -> bool { + if !n.is_finite() || n.len() < 1e-12 || (n.x == 0.0 && n.y == 0.0) { 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()) { + 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()); @@ -204,3 +206,26 @@ pub(super) fn plan_of_tilted(n: Vec3, elevation: f64, vertices: &[PolyVertex], c 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) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A normal on the Z axis, either way up and of any length, moves no point, so [`tilted`] + /// answers without sampling the object's arcs; any other normal gathers them. + #[test] + fn a_normal_on_the_z_axis_gathers_no_points() { + let gathered = std::cell::Cell::new(0); + let pts = || { + gathered.set(gathered.get() + 1); + vec![Vec3::new(1.0, 2.0, 3.0)] + }; + for n in [Vec3::Z, Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 0.0, 2.5), Vec3::new(-0.0, 0.0, -0.1)] { + assert!(!tilted(n, pts), "{n:?}"); + } + assert_eq!(gathered.get(), 0); + assert!(tilted(Vec3::new(0.0, 0.5, -0.75f64.sqrt()), pts)); + assert!(!tilted(Vec3::new(0.0, 1e-15, 1.0), pts), "noise in a plan normal still moves nothing visible"); + assert_eq!(gathered.get(), 2); + } +} diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index 2e4b6ff14..ab5f6e384 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -84,7 +84,7 @@ fn lwpolyline(tags: &[Tag], c: &mut 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, run_points(&verts, elevation, flags & 1 != 0)) { + 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); @@ -238,7 +238,7 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef "HATCH" => { let mut k = hatch(tags, &t)?; if let EntityKind::Hatch(h) = &mut k - && tilted(c.extrusion, h.loops.iter().flat_map(|l| run_points(&l.vertices, h.elevation, true))) + && 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. From a1964aa9c57b6db291fda36424e61c54188b3afa Mon Sep 17 00:00:00 2001 From: tirael Date: Thu, 12 Nov 2026 10:28:41 +0100 Subject: [PATCH 083/187] Options: turn off the update check at start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Options ▸ User Preferences gets "Check for updates when CADCraft starts" (on by default, desktop only). Off, the startup check and its "Update and Restart" prompt never run; Help ▸ Check for Updates… still checks. The choice is the OPTIONS JSON key `checkUpdatesAtStart`, kept in the profile and restored by Reset to Defaults, for people who manage updates themselves (an offline machine, a package manager, a pinned version). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/it.tsv | 2 ++ crates/ui-egui/src/i18n/uk.tsv | 2 ++ crates/ui-egui/src/options.rs | 15 +++++++++++++ crates/ui-egui/src/options/dialog.rs | 9 ++++++++ crates/ui-egui/src/updates_ui.rs | 32 +++++++++++++++++++++++++++- 5 files changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8920337bd..1c9c07f41 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1398,3 +1398,5 @@ menu Modify Edita 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 + Check for updates when CADCraft starts Controlla gli aggiornamenti all'avvio di CADCraft + Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Se disattivato, CADCraft non propone mai un aggiornamento da solo; Aiuto ▸ Verifica aggiornamenti… continua a controllare. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0c661892c..39f5ed74b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1422,3 +1422,5 @@ ENTER Клавіша Enter Shortcut Menu: always enabled Контекстне меню: завжди Shortcut Menu: enabled when command options are present Контекстне меню: коли команда має параметри + Check for updates when CADCraft starts Перевіряти оновлення під час запуску CADCraft + Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Якщо вимкнено, CADCraft ніколи сам не пропонує оновлення; Довідка ▸ Перевірити оновлення… усе одно перевіряє. diff --git a/crates/ui-egui/src/options.rs b/crates/ui-egui/src/options.rs index d81b77f7a..86290f42e 100644 --- a/crates/ui-egui/src/options.rs +++ b/crates/ui-egui/src/options.rs @@ -152,6 +152,9 @@ pub struct UiOptions { 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, + /// Look for a newer release when the app starts and offer to install it (desktop). Off, + /// only Help ▸ Check for Updates… looks. + pub check_updates_at_start: bool, } impl Default for UiOptions { @@ -167,6 +170,7 @@ impl Default for UiOptions { right_click_edit: IdleClick::Menu, right_click_command: CommandClick::Menu, interface_scale: 1.0, + check_updates_at_start: true, } } } @@ -238,6 +242,7 @@ struct UiChanges { right_click_edit: Option, right_click_command: Option, interface_scale: Option, + check_updates_at_start: Option, } fn color_param(key: &str, v: &Value) -> Result, String> { @@ -291,6 +296,7 @@ fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result { "rightClickCommand" => { c.right_click_command = Some(CommandClick::parse(text()?).ok_or("rightClickCommand must be menu, enter or menuWithOptions")?) } + "checkUpdatesAtStart" => c.check_updates_at_start = Some(v.as_bool().ok_or("checkUpdatesAtStart must be true or false")?), k if k.eq_ignore_ascii_case("SAVETIME") => { let max = cadcraft_engine::autosave::MAX_SAVETIME; let n = v @@ -336,6 +342,7 @@ fn ui_json(app: &CadApp) -> Map { 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.insert("checkUpdatesAtStart".into(), json!(o.check_updates_at_start)); m } @@ -413,6 +420,9 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result { app.options.time_sensitive_right_click = b; } apply_right_click(&mut app.options, &ui); + if let Some(b) = ui.check_updates_at_start { + app.options.check_updates_at_start = b; + } Ok(report(app)) } @@ -465,6 +475,7 @@ impl CadApp { "rightClickEdit": self.options.right_click_edit.as_str(), "rightClickCommand": self.options.right_click_command.as_str(), "interfaceScale": self.options.interface_scale, + "checkUpdatesAtStart": self.options.check_updates_at_start, }) .to_string() } @@ -497,6 +508,7 @@ impl CadApp { "rightClickEdit", "rightClickCommand", "interfaceScale", + "checkUpdatesAtStart", ] { if let Some(value) = v.get(key) { let _ = parse_ui(key, value, &mut c); @@ -525,6 +537,9 @@ impl CadApp { if let Some(n) = c.interface_scale { self.options.interface_scale = n; } + if let Some(b) = c.check_updates_at_start { + self.options.check_updates_at_start = b; + } } } diff --git a/crates/ui-egui/src/options/dialog.rs b/crates/ui-egui/src/options/dialog.rs index 951ca78d8..a8b165b70 100644 --- a/crates/ui-egui/src/options/dialog.rs +++ b/crates/ui-egui/src/options/dialog.rs @@ -578,6 +578,15 @@ fn preferences(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map if right_click { right_click_window(&app.options, ui.ctx(), &mut right_click, changes); } + // The web build is always the latest: there is nothing to check for there. + if !cfg!(target_arch = "wasm32") { + ui.add_space(6.0); + let mut check = app.options.check_updates_at_start; + if ui.checkbox(&mut check, crate::tl!("Check for updates when CADCraft starts")).changed() { + changes.insert("checkUpdatesAtStart".into(), json!(check)); + } + hint(ui, crate::tl!("Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks.")); + } ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique(RIGHT_CLICK), right_click)); } diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index ccd9733b4..d8abf975a 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -40,12 +40,19 @@ pub fn check_now(app: &mut CadApp) { app.updates_rt.result_echoed = false; } +/// Whether the startup check runs: the host asked for it and the user did not turn it off +/// (Options ▸ User Preferences, `checkUpdatesAtStart`). +fn checks_at_start(app: &CadApp) -> bool { + app.updates_rt.enabled && app.options.check_updates_at_start +} + /// Start the checks and collect the answers. pub fn tick(app: &mut CadApp, ctx: &egui::Context) { + let at_start = checks_at_start(app); let rt = &mut app.updates_rt; if std::mem::take(&mut rt.check_requested) { rt.updater.check_now(ctx); - } else if rt.enabled { + } else if at_start { rt.updater.check_at_start(ctx); } rt.updater.tick(ctx); @@ -118,4 +125,27 @@ mod tests { } assert!(!result_window_shows(&Status::Idle, false)); } + + /// The startup check runs only where the host enabled it and the user did not turn it off; + /// the choice is kept in the profile and set through the OPTIONS JSON form. + #[test] + fn the_startup_check_can_be_turned_off() { + let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + assert!(!checks_at_start(&app), "tests and the web never check"); + app.enable_update_check(); + assert!(checks_at_start(&app), "on by default"); + let r = app.run("options", serde_json::json!({ "checkUpdatesAtStart": false })).unwrap(); + assert_eq!(r["checkUpdatesAtStart"], false); + assert!(!checks_at_start(&app)); + assert!(app.run("options", serde_json::json!({ "checkUpdatesAtStart": "no" })).is_err()); + // Kept across restarts. + let profile = app.profile_json(); + let mut next = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); + next.enable_update_check(); + next.load_profile(&profile); + assert!(!checks_at_start(&next)); + // Reset to Defaults turns it back on. + app.run("options", serde_json::json!({ "reset": true })).unwrap(); + assert!(checks_at_start(&app)); + } } From 1f56cef64ebaee62ededbb519427dd805b7d9f19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:36:47 -0800 Subject: [PATCH 084/187] fix(engine): image loaders start a file only while its largest size still fits the loaded-image limit When a drawing opened, each image loader checked the decoded total against the 2 GB limit before decoding and added the image's size only after, so up to four images of up to 512 MB each could decode at once past the limit. A loader now starts a file only while the images decoded so far, plus the largest image each file being decoded can become, fit under the limit, and otherwise waits for a file to finish. With no other file being decoded one file always starts, so the total runs past the limit by one image at most, as it does with a single loader. A file that fails to decode counts nothing. --- crates/engine/src/cmd/image.rs | 129 +++++++++++++++++++++++++++++++-- 1 file changed, 122 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index daf46557b..60becab87 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -4,8 +4,8 @@ //! the drawing as a crossed-out frame. use std::collections::{BTreeMap, BTreeSet}; -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use cadcraft_doc::{Drawing, EntityKind, Image, Raster}; use cadcraft_geom::Vec2; @@ -22,6 +22,9 @@ const MAX_IMAGE_FILES: usize = 1000; const MAX_IMAGE_BYTES: u64 = 256 << 20; /// Most decoded pixel bytes kept per drawing; images past it stay unloaded. const MAX_LOADED_BYTES: u64 = 2 << 30; +/// Most bytes one decoded image takes: the image reader decodes at most 128 million pixels, four +/// bytes each (`cadcraft_io::raster::MAX_IMAGE_PIXELS`). +const MAX_DECODED_BYTES: u64 = 512_000_000; /// Most image files decoded at the same time when a drawing opens. const MAX_LOADERS: usize = 4; /// Longest image path taken from a caller. @@ -166,13 +169,11 @@ fn over_limit(path: &str) -> String { /// what opening a drawing with large images waits for). The results are in the order of `paths`. fn decode_files(paths: &[&str], host: Option<&str>) -> Vec> { // Decoded bytes so far, shared by the loaders: past the limit no further file is started. - let decoded_bytes = AtomicU64::new(0); + let budget = Budget::default(); let load = |path: &str| -> std::result::Result { - if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES { - return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20)); - } + let mut decoding = budget.start().ok_or_else(|| format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20))?; let r = read_file(path, host).and_then(|bytes| decode(&bytes))?; - decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed); + decoding.bytes = bytes_of(&r); Ok(r) }; let mut results: Vec>> = paths.iter().map(|_| None).collect(); @@ -203,6 +204,83 @@ fn decode_files(paths: &[&str], host: Option<&str>) -> Vec, + /// Signaled when a file finishes decoding. + finished: Condvar, +} + +/// Decoded bytes so far, and how many files are being decoded. +#[derive(Default)] +struct Spent { + decoded: u64, + decoding: u64, +} + +/// Whether a loader may start decoding a file. +#[derive(Debug, PartialEq)] +enum Admit { + Start, + /// Not until another file finishes. + Wait, + /// The images decoded so far are past the limit. + Full, +} + +impl Spent { + /// A file starts while the images decoded so far, and the largest image each file being + /// decoded can become, fit under `limit`. A file always starts when no other one is being + /// decoded, so that the images run past `limit` by one image at most. + fn admit(&mut self, limit: u64, largest: u64) -> Admit { + if self.decoded > limit { + return Admit::Full; + } + let reserved = self.decoding.saturating_add(1).saturating_mul(largest); + if self.decoding > 0 && self.decoded.saturating_add(reserved) > limit { + return Admit::Wait; + } + self.decoding = self.decoding.saturating_add(1); + Admit::Start + } + + /// A file finished decoding into `bytes` (0 when it failed). + fn finish(&mut self, bytes: u64) { + self.decoding = self.decoding.saturating_sub(1); + self.decoded = self.decoded.saturating_add(bytes); + } +} + +impl Budget { + /// Wait until a file may start decoding; `None` once the images decoded so far are past the + /// limit. + fn start(&self) -> Option> { + let mut spent = self.spent.lock().unwrap_or_else(PoisonError::into_inner); + loop { + match spent.admit(MAX_LOADED_BYTES, MAX_DECODED_BYTES) { + Admit::Start => return Some(Decoding { budget: self, bytes: 0 }), + Admit::Full => return None, + Admit::Wait => spent = self.finished.wait(spent).unwrap_or_else(PoisonError::into_inner), + } + } + } +} + +/// A file being decoded. Dropping it counts `bytes` as decoded and lets a waiting loader check +/// again, also when the decoding failed. +struct Decoding<'a> { + budget: &'a Budget, + bytes: u64, +} + +impl Drop for Decoding<'_> { + fn drop(&mut self) { + self.budget.spent.lock().unwrap_or_else(PoisonError::into_inner).finish(self.bytes); + self.budget.finished.notify_all(); + } +} + /// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large /// image needs several hundred megabytes while it is decoded) and no more than there are files. fn loader_count(files: usize) -> usize { @@ -351,3 +429,40 @@ fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value { }; json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) }) } + +#[cfg(test)] +mod tests { + use super::*; + + /// A file starts only while the largest image each file being decoded can become still fits, + /// one file always starts when none is being decoded, and none starts past the limit. + #[test] + fn loaders_start_files_within_the_limit() { + let mut s = Spent::default(); + // Room for two of the largest images. + assert_eq!(s.admit(10, 4), Admit::Start); + assert_eq!(s.admit(10, 4), Admit::Start); + assert_eq!(s.admit(10, 4), Admit::Wait); + s.finish(3); + assert_eq!(s.admit(10, 4), Admit::Wait, "3 decoded and two files that can become 4 each are past 10"); + s.finish(5); + // Over the limit only by the one file being decoded. + assert_eq!(s.admit(10, 4), Admit::Start); + s.finish(4); + assert_eq!(s.admit(10, 4), Admit::Full); + // A failed file counts nothing. + let mut s = Spent::default(); + assert_eq!(s.admit(10, 4), Admit::Start); + s.finish(0); + assert_eq!((s.decoded, s.decoding), (0, 0)); + } + + /// Files that fail still let the other loaders go on: every file gets a result. + #[test] + fn decode_files_finishes_when_every_file_fails() { + let paths = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png"]; + let results = decode_files(&paths, None); + assert_eq!(results.len(), paths.len()); + assert!(results.iter().all(std::result::Result::is_err), "none of these files exists"); + } +} From f833ab96f5bea718bc75adc7d55994a1bd433176 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:45:26 -0800 Subject: [PATCH 085/187] Images: IMAGEATTACH refuses a wrongly typed at, scale, rotation or name A value of the wrong type for `at`, `scale`, `rotation` or `name` was taken as omitted, so `"scale": "big"` attached an image one drawing unit wide and `"at": "nowhere"` put it at 0,0. Each is now refused with an error. An omitted or null value still takes its default. --- crates/engine/src/cmd/image.rs | 23 +++++++++++++++++++---- crates/engine/tests/image_attach.rs | 6 ++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index daf46557b..ce2488ad3 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -12,7 +12,7 @@ use cadcraft_geom::Vec2; use serde_json::{Value, json}; use super::file::base64_decode; -use super::{CommandSpec, bad, f64_or, point_param, str_param}; +use super::{CommandSpec, bad, point_value, str_param}; use crate::{Result, Session}; /// Most image files loaded per drawing. @@ -247,6 +247,9 @@ pub(crate) fn run_imageattach(s: &mut Session, p: &Value) -> Result { return Err(bad(ID, "`path` is too long")); } let place = placement(p)?; + if p.get("name").is_some_and(|n| !(n.is_null() || n.is_string())) { + return Err(bad(ID, "`name` must be text")); + } let raster = pixels(s, p, &path)?; let (w, h) = (f64::from(raster.width()), f64::from(raster.height())); // One pixel in drawing units, along the image's bottom edge (`u`) and its left edge (`v`). @@ -284,18 +287,30 @@ struct Placement { /// `at`, `rotation` and the width (`width`, else `scale`: an image is one unit wide at scale 1). fn placement(p: &Value) -> Result { - let at = point_param(p, "at").unwrap_or(Vec2::ZERO); + let at = match p.get("at") { + None | Some(Value::Null) => Vec2::ZERO, + Some(v) => point_value(v).ok_or_else(|| bad(ID, "`at` must be a point"))?, + }; if !(at.x.is_finite() && at.y.is_finite()) { return Err(bad(ID, "`at` must be a point")); } let width = match p.get("width") { Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?, - None => f64_or(p, "scale", 1.0), + None => number(p, "scale")?.unwrap_or(1.0), }; if !(width.is_finite() && width > 0.0) { return Err(bad(ID, "`scale` and `width` must be greater than zero")); } - Ok(Placement { at, rotation: f64_or(p, "rotation", 0.0).to_radians(), width }) + let rotation = number(p, "rotation")?.unwrap_or(0.0); + Ok(Placement { at, rotation: rotation.to_radians(), width }) +} + +/// The number `key` of `p`: `None` when it is omitted or null, an error when it is not a number. +fn number(p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v.as_f64().filter(|x| x.is_finite()).map(Some).ok_or_else(|| bad(ID, format!("`{key}` must be a number"))), + } } /// The pixels of the image at `path`: decoded from `data` when the caller hands the file over, diff --git a/crates/engine/tests/image_attach.rs b/crates/engine/tests/image_attach.rs index 864d968a5..45def34a8 100644 --- a/crates/engine/tests/image_attach.rs +++ b/crates/engine/tests/image_attach.rs @@ -133,6 +133,12 @@ fn bad_input_is_refused_and_changes_nothing() { json!({ "path": "a.png", "data": data, "width": -3 }), json!({ "path": "a.png", "data": data, "width": "wide" }), json!({ "path": "a.png", "data": data, "width": 1e-320 }), + // A value of the wrong type is refused, not taken as omitted. + json!({ "path": "a.png", "data": data, "scale": "big" }), + json!({ "path": "a.png", "data": data, "rotation": "right" }), + json!({ "path": "a.png", "data": data, "at": "nowhere" }), + json!({ "path": "a.png", "data": data, "at": [1] }), + json!({ "path": "a.png", "data": data, "name": 7 }), json!({ "path": "x".repeat(5000), "data": data }), ] { assert!(s.execute("imageattach", &p).is_err(), "{p}"); From 7c580ec8cc0818780e7e38d9f002f52ed86d41fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:06:28 -0800 Subject: [PATCH 086/187] Images: IMAGEATTACH refuses a wrongly typed scale when width is given placement read `scale` only when `width` was omitted, so a call with both a valid `width` and `"scale": "big"` attached the image. `scale` is now checked first; a valid `width` still takes precedence. --- crates/engine/src/cmd/image.rs | 4 +++- crates/engine/tests/image_attach.rs | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index ce2488ad3..a03090d37 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -294,9 +294,11 @@ fn placement(p: &Value) -> Result { if !(at.x.is_finite() && at.y.is_finite()) { return Err(bad(ID, "`at` must be a point")); } + // `scale` is checked even when `width` takes precedence over it. + let scale = number(p, "scale")?; let width = match p.get("width") { Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?, - None => number(p, "scale")?.unwrap_or(1.0), + None => scale.unwrap_or(1.0), }; if !(width.is_finite() && width > 0.0) { return Err(bad(ID, "`scale` and `width` must be greater than zero")); diff --git a/crates/engine/tests/image_attach.rs b/crates/engine/tests/image_attach.rs index 45def34a8..a06d951bc 100644 --- a/crates/engine/tests/image_attach.rs +++ b/crates/engine/tests/image_attach.rs @@ -135,6 +135,7 @@ fn bad_input_is_refused_and_changes_nothing() { json!({ "path": "a.png", "data": data, "width": 1e-320 }), // A value of the wrong type is refused, not taken as omitted. json!({ "path": "a.png", "data": data, "scale": "big" }), + json!({ "path": "a.png", "data": data, "width": 2, "scale": "big" }), json!({ "path": "a.png", "data": data, "rotation": "right" }), json!({ "path": "a.png", "data": data, "at": "nowhere" }), json!({ "path": "a.png", "data": data, "at": [1] }), From 32d5bd85db93dde8a5400d4a649961b58f38fb30 Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Sun, 15 Nov 2026 15:46:19 +0100 Subject: [PATCH 087/187] i18n(sv): update the Swedish catalog Brings the Swedish catalog up to date with upstream main (7064a685). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/sv.tsv | 493 +++++++++++++++++++++++++++++++++ 1 file changed, 493 insertions(+) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 935ae1e99..f7547266e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1527,3 +1527,496 @@ menu Modify Ändra # ArtCraft feature naming Additional Tools Ytterligare verktyg + Grid Rutnät + Ortho Orto + Workspace Arbetslayout + Settings Inställningar + Preferences Inställningar + Refresh Uppdatera + Current: Aktuell: + Continuous Kontinuerlig + Displayed layers Visade lager + Black Svart + Gray Grå + Grey Grå + Orange Orange + Purple Lila + Brown Brun + Pink Rosa + Rename Byt namn + Select Color Välj färg + Layer filters Lagerfilter + Dashed Streckad + Dotted Prickad + Dashdot Streckprickad + Hidden Dold + Phantom Fantom + Clear selection Rensa markering + Model Space Modellrymd + Plot Settings Plottinställningar + Perimeter Omkrets + Polar Polär + Lineweight Display Visning av linjetjocklek + Annotation Anteckning + Annotative Annotativ + Insertion point Insättningspunkt + Base point Baspunkt + Scale factor Skalfaktor + Rotation angle Rotationsvinkel + X coordinate X-koordinat + Y coordinate Y-koordinat + Z coordinate Z-koordinat + Cancel operation Avbryt åtgärden + Reset Återställ + Update Fields Uppdatera fält + Edit Xref in Place Redigera xref på plats + New UCS Nytt UCS + World Världen + Face Yta + Origin Origo + LwPolyline LwPolyline + New Sheet Set... Ny ritningsuppsättning... + Open Sheet Set... Öppna ritningsuppsättning... + Clear Menu Rensa meny + Attach... Koppla... + Export Layout to Model... Exportera layout till modell... + Package Drawing... Paketera ritning... + DWG Compare... DWG-jämförelse... + Markup Import... Importera kommentarer... + Share... Dela... + Undo Group of commands Ångra kommandogrupp + Constrained Orbit Begränsad kretsning + Free Orbit Fri kretsning + Camera Kamera + Adjust Distance Justera avstånd + Swivel Svängning + 3D Views 3D-vyer + Viewpoint Vypunkt + Plan View Planvy + Current UCS Aktuellt UCS + World UCS Världs-UCS + Named UCS Namngivna UCS + Bottom Nederkant + Front Framifrån + Back Tillbaka + SW Isometric SV-isometrisk + SE Isometric Isometrisk SO + NE Isometric Isometrisk NO + NW Isometric Isometrisk NV + Hide Dölj + Visual Styles Visuella stilar + 2D Wireframe 2D-trådram + Wireframe Trådram + Realistic Realistisk + Conceptual Konceptuell + Shaded Skuggad + Shaded with Edges Skuggad med kanter + Shades of Gray Gråtoner + Sketchy Skissartad + X-Ray Genomskinlig + Render Rendera + New Point Light Nytt punktljus + New Spotlight Ny strålkastare + New Distant Light Nytt avlägset ljus + Light Glyphs Ljusglyfer + Materials Browser Materialbläddrare + Enter Full Screen Visa i helskärm + PDF Underlay... PDF-underlägg... + Field... Fält... + Layout from Template... Layout från mall... + ACIS File... ACIS-fil... + Drawing Exchange Binary... Drawing Exchange Binary... + Spelling Stavning + Linetype Manager Linjetypshanterare + Color Selector Färgväljare + Object Properties Objektegenskaper + Width Bredd + Position Position + Object Snap Settings Inställningar för objektfäste + Polar Tracking Settings Inställningar för polär spårning + Explode Block Lös upp block + Block Name Blocknamn + Coordinate Koordinat + Coordinates Koordinater + Properties Palette Egenskapspalett + Save Changes Spara ändringar + Discard Changes Ignorera ändringar + Are you sure? Är du säker? + Create Skapa + Fit Anpassa + Specify center point Ange centrumpunkt + Align block with object? Justera blocket mot objektet? + Guide crosshairs along cloud path Led hårkorset längs molnets bana + Erase polyline? Radera polylinje? + Calculate rectangle dimensions based on Beräkna rektangelns mått utifrån + Erase source objects? Radera källobjekt? + Object selected is not a polyline. Do you want to turn it into one? Det markerade objektet är inte en polylinje. Vill du göra om det till en? + Scale objects based on alignment points? Skala objekt utifrån justeringspunkter? + Specify radius Ange radie + Specify diameter Ange diameter + Specify opposite corner point Ange motsatt hörnpunkt + Pick internal point Välj inre punkt + {n} commit {n} commit + {n} contributor {n} bidragsgivare + (1, 2, 4, 8, 16, 32, 64, 128, or 256) (1, 2, 4, 8, 16, 32, 64, 128 eller 256) + + >> Expression >> Uttryck + Associate the hatch with the new boundary? Associera skrafferingen med den nya gränsen? + Associative dimension priority Prioritet för associativa mått + Breakline extension distance Förlängningsavstånd för brytlinje + Breakline symbol size Symbolstorlek för brytlinje + Choose mode for selected object conversion Välj läge för konvertering av markerade objekt + Combine collinear objects that meet end to end Kombinera kolinjära objekt som möts ände mot ände + Combine collinear objects that partially overlap Kombinera kolinjära objekt som delvis överlappar + Combine identical rows? Kombinera identiska rader? + Combine layer property changes into one undo step? Kombinera ändringar av lageregenskaper till ett ångringssteg? + Combine text into a single MTEXT? Kombinera text till en enda MTEXT? + Combine zooms and pans into one undo step? Kombinera zoomningar och panoreringar till ett ångringssteg? + Constant? Konstant? + Convert Lines and Arcs to polylines Konvertera linjer och bågar till polylinjer + Create associative array Skapa associativ array + Delete old boundary(s)? Ta bort gamla gräns(er)? + Drafting mode? Ritläge? + Edit attributes one at a time? Redigera attributen ett i taget? + Edit only attributes visible on screen? Redigera endast attribut som syns på skärmen? + Edit path for which xref(s) Redigera sökväg för vilka xref:ar + Enter Trim mode option Ange alternativ för trimningsläge + Enter UNDO Auto mode Ange UNDO Auto-läge + Enter X scale factor, specify opposite corner Ange X-skalfaktor, ange motsatt hörn + Enter a boundary loop number to remove (starting at 1) Ange numret på gränsloopen som ska tas bort (börjar på 1) + Enter a configuration option Ange ett konfigurationsalternativ + Enter a default viewport visibility option Ange ett alternativ för standardsynlighet i vyfönster + Enter a group description Ange en gruppbeskrivning + Enter a group name Ange ett gruppnamn + Enter a group option Ange ett gruppalternativ + Enter a hatch option Ange ett skrafferingsalternativ + Enter a loaded linetype name Ange namnet på en inläst linjetyp + Enter a name for the new plotter Ange ett namn på den nya plottern + Enter a new name for the group Ange ett nytt namn på gruppen + Enter a plotter option Ange ett plotteralternativ + Enter a plotting preference Ange en plottningsinställning + Enter a projection option Ange ett projektionsalternativ + Enter a property to turn on or off Ange en egenskap att slå på eller av + Enter a scale factor (nX or nXP) Ange en skalfaktor (nX eller nXP) + Enter a text edit mode option Ange ett alternativ för textredigeringsläge + Enter an UNDO control option Ange ett alternativ för UNDO-kontroll + Enter an annotation option Ange ett anteckningsalternativ + Enter an implied edge extension mode Ange ett läge för underförstådd kantförlängning + Enter an option [Add/Remove] Ange ett alternativ [Add/Remove] + Enter an option to change Ange ett alternativ att ändra + Enter array type Ange arraytyp + Enter attribute tag Ange attributtagg + Enter attribute tag specification Ange specifikation för attributtagg + Enter attribute value specification Ange specifikation för attributvärde + Enter attribute visibility setting Ange inställning för attributsynlighet + Enter block name or select a block reference Ange blocknamn eller markera en blockreferens + Enter block name or select a block reference [?] Ange blocknamn eller markera en blockreferens [?] + Enter block name specification Ange specifikation för blocknamn + Enter block(s) to list Ange block att lista + Enter choice, 1 to 5 Ange val, 1 till 5 + Enter clipping option Ange klippningsalternativ + Enter color name or number (1-255) Ange färgnamn eller -nummer (1-255) + Enter column type Ange kolumntyp + Enter decimal places of accuracy (0 to 16) Ange noggrannhet i antal decimaler (0 till 16) + Enter distance between rows or specify unit cell (---) Ange avstånd mellan rader eller ange enhetscell (---) + Enter file name Ange filnamn + Enter first angle constraint Ange första vinkelvillkor + Enter first line of annotation text or Ange första raden av kommentarstexten eller + Enter first tolerance value Ange första toleransvärde + Enter fit tolerance Ange anpassningstolerans + Enter fuzz distance Ange fuzz-avstånd + Enter group description Ange gruppbeskrivning + Enter group name Ange gruppnamn + Enter group name(s) to list Ange gruppnamn att lista + Enter inspection rate Ange granskningshastighet + Enter inspection shape Ange granskningsform + Enter justification Ange justering + Enter knot parameterization Ange knutparametrisering + Enter label (press ENTER for none) Ange etikett (tryck på ENTER för ingen) + Enter layer description Ange lagerbeskrivning + Enter layer name Ange lagernamn + Enter layer name to make current Ange namnet på lagret som ska bli aktuellt + Enter layer name(s) to change default viewport visibility Ange lagernamn för att ändra standardsynlighet i vyfönster + Enter layer name(s) to list Ange lagernamn att lista + Enter layer option for offset objects Ange lageralternativ för förskjutna objekt + Enter layout name for copy Ange layoutnamn för kopian + Enter layout name(s) to list Ange layoutnamn att lista + Enter layout option Ange layoutalternativ + Enter layout to make current Ange layout som ska bli aktuell + Enter layout to rename Ange layout att byta namn på + Enter layout to save to template Ange layout att spara som mall + Enter leader format option Ange formatalternativ för hänvisningslinje + Enter line spacing factor or distance Ange radavståndsfaktor eller avstånd + Enter line spacing type Ange typ av radavstånd + Enter linetype(s) to load Ange linjetyp(er) att läsa in + Enter lineweight (0.0mm - 2.11mm) Ange linjetjocklek (0,0 mm - 2,11 mm) + Enter magnification or height Ange förstoring eller höjd + Enter maximum part height Ange maximal delhöjd + Enter mline editing option Ange redigeringsalternativ för multilinje + Enter mline style name or [?] Ange namn på multilinjestil eller [?] + Enter name for new layer (becomes the current layer) Ange namn på nytt lager (blir aktuellt lager) + Enter name for new scale Ange namn på ny skala + Enter name for new viewport configuration Ange namn på ny vyfönsterkonfiguration + Enter name list for new layer(s) Ange namnlista för nya lager + Enter name of block to manage Ange namn på block att hantera + Enter name of block to sync Ange namn på block att synkronisera + Enter name of breakline symbol block (. for the built-in symbol) Ange namn på block för brytlinjesymbol (. för den inbyggda symbolen) + Enter name of drawing file to recover Ange namn på ritningsfil att återställa + Enter name of existing block Ange namn på befintligt block + Enter name of layout to copy Ange namn på layout att kopiera + Enter name of layout to delete Ange namn på layout att ta bort + Enter name of linetype file Ange namn på linjetypsfil + Enter name of new layout Ange namn på ny layout + Enter name of output file Ange namn på utdatafil + Enter name of scale to delete Ange namn på skala att ta bort + Enter name of script file Ange namn på skriptfil + Enter name of viewport configuration to restore Ange namn på vyfönsterkonfiguration att återställa + Enter name(s) of new layers frozen in all viewports Ange namn på nya lager som är frusna i alla vyfönster + Enter name(s) of viewport configurations to delete Ange namn på vyfönsterkonfigurationer att ta bort + Enter name(s) of viewport configurations to list Ange namn på vyfönsterkonfigurationer att lista + Enter name(s) to purge Ange namn att rensa + Enter named scale to add Ange namngiven skala att lägga till + Enter named scale to delete Ange namngiven skala att ta bort + Enter new color Ange ny färg + Enter new default value Ange nytt standardvärde + Enter new group name Ange nytt gruppnamn + Enter new layer name Ange nytt lagernamn + Enter new layout name Ange nytt layoutnamn + Enter new linetype name Ange nytt linjetypsnamn + Enter new linetype scale factor Ange ny linjetypsskalfaktor + Enter new lineweight Ange ny linjetjocklek + Enter new order Ange ny ordning + Enter new prompt Ange ny ledtext + Enter new string Ange ny sträng + Enter new tag Ange ny tagg + Enter new text style Ange ny textstil + Enter new value for CONSTRAINTINFER Ange nytt värde för CONSTRAINTINFER + Enter new value for PICKSTYLE Ange nytt värde för PICKSTYLE + Enter new value for THICKNESS Ange nytt värde för THICKNESS + Enter new value for XCLIPFRAME Ange nytt värde för XCLIPFRAME + Enter next line of annotation text Ange nästa rad med kommentarstext + Enter next line of text (empty line to finish) Ange nästa textrad (tom rad för att slutföra) + Enter number of actions Ange antal åtgärder + Enter number of columns (|||) Ange antal kolumner (|||) + Enter number of digits to right of decimal point (0 to 8) Ange antal siffror till höger om decimaltecknet (0 till 8) + Enter number of fractional places for display of angles (0 to 8) Ange antal decimaler för visning av vinklar (0 till 8) + Enter number of items in array Ange antal objekt i arrayen + Enter number of rows (---) Ange antal rader (---) + Enter object ordering option Ange alternativ för objektordning + Enter object type to rename Ange objekttyp att byta namn på + Enter obliquing angle (press ENTER for none) Ange lutningsvinkel (tryck på ENTER för ingen) + Enter old group name Ange gammalt gruppnamn + Enter old layer name Ange gammalt lagernamn + Enter option Ange alternativ + Enter option [Save/Discard reference changes] Ange alternativ [Spara/Släng referensändringar] + Enter properties to match (SELECTSIMILARMODE bit code) Ange egenskaper att matcha (bitkod för SELECTSIMILARMODE) + Enter property to change Ange egenskap att ändra + Enter scale ratio (paper units:drawing units) Ange skalkvot (pappersenheter:ritningsenheter) + Enter second angle constraint Ange andra vinkelvillkoret + Enter second tolerance value Ange andra toleransvärdet + Enter spline creation method Ange metod för att skapa spline + Enter string to change Ange sträng att ändra + Enter style name Ange stilnamn + Enter symbol type to bind Ange symboltyp att bädda in + Enter target layer name Ange namn på mållager + Enter template file name Ange namn på mallfil + Enter the distance between rows or specify unit cell (---) Ange avståndet mellan rader eller ange enhetscell (---) + Enter the drawing to compare with (an open drawing's name or a file path) Ange ritningen att jämföra med (namnet på en öppen ritning eller en sökväg) + Enter the maximum points for leader line Ange största antal punkter för hänvisningslinjen + Enter the name of the block to replace Ange namnet på blocket som ska ersättas + Enter the number of columns (|||) Ange antal kolumner (|||) + Enter the number of items in the array Ange antal objekt i arrayen + Enter the number of levels Ange antal nivåer + Enter the number of operations to undo Ange antal åtgärder att ångra + Enter the number of rows Ange antal rader + Enter the number of rows (---) Ange antal rader (---) + Enter the output Ange utdata + Enter the paper name Ange pappersnamnet + Enter the paper width,height in mm Ange pappersbredd,höjd i mm + Enter the plotter to add a paper size to Ange plottern som en pappersstorlek ska läggas till för + Enter the plotter to delete Ange plottern att ta bort + Enter the type of array Ange typ av array + Enter tolerance location Ange toleransens placering + Enter transparency value Ange genomskinlighetsvärde + Enter transparency value (0-90) Ange genomskinlighetsvärde (0-90) + Enter trim method Ange trimningsmetod + Enter type of dimension editing Ange typ av måttredigering + Enter type of unused objects to purge Ange typ av oanvända objekt att rensa + Enter type of value modification Ange typ av värdeändring + Enter value Ange värde + Enter variable name Ange variabelnamn + Enter view name to restore Ange namn på vy att återställa + Enter view name to save Ange namn på vy att spara + Enter view name(s) to delete Ange namn på vyer att ta bort + Enter view name(s) to list Ange namn på vyer att lista + Enter viewport arrangement Ange vyfönsterarrangemang + Enter viewport configuration name Ange namn på vyfönsterkonfiguration + Enter what to pick Ange vad som ska väljas + Enter xref(s) to list Ange xref att lista + Erase source object after offsetting? Radera källobjektet efter förskjutning? + First point of mid Första punkt för mittpunkt + First tracking point Första spårningspunkt + Fix any errors detected? Åtgärda upptäckta fel? + Get from the drawing or [Point/Distance/Angle/Intersection] Hämta från ritningen eller [Punkt/Avstånd/Vinkel/Skärningspunkt] + Indicate dimension point to add Ange måttpunkt att lägga till + Indicate dimension point to remove Ange måttpunkt att ta bort + Internal error; press Enter to end the command Internt fel; tryck på Enter för att avsluta kommandot + Invisible? Osynlig? + Island detection style Stil för identifiering av öar + Keep associative objects Behåll associativa objekt + Lock the view of viewports? Lås vyn i vyfönster? + Measure angles clockwise? Mäta vinklar medurs? + New color Ny färg + Next point (Press ENTER to end tracking) Nästa punkt (tryck på ENTER för att avsluta spårning) + No mark: undo everything? Inget märke: ångra allt? + Number of objects to move Antal objekt att flytta + Optimize segments within polylines Optimera segment i polylinjer + Pick a table cell Välj en tabellcell + Pick an internal point for the new boundary Välj en inre punkt för den nya gränsen + Red, Green, Blue Röd, grön, blå + Red,Green,Blue Röd,grön,blå + Reset the scale list to the defaults? Återställ skallistan till standardvärdena? + Rotate arrayed items? Rotera objekten i arrayen? + Rotate arrayed objects? Rotera arrayobjekten? + Save changes to array? Spara ändringar i arrayen? + Save layer settings with views? Spara lagerinställningar med vyer? + Second point of mid Andra punkt för mittpunkt + Select a block Markera ett block + Select a content type Välj en innehållstyp + Select a leader type Välj en typ av hänvisningslinje + Select a multileader Markera en multihänvisningslinje + Select a table Markera en tabell + Select a viewport Markera ett vyfönster + Select an item in array to replace Markera ett objekt i arrayen som ska ersättas + Select an object to copy Markera ett objekt att kopiera + Select array Markera array + Select attributes Markera attribut + Select base dimension Markera basmått + Select base point of replacement objects Markera baspunkt för ersättningsobjekten + Select boundary objects (Enter finds them) Markera gränsobjekt (Enter hittar dem) + Select clipping object Markera beskärningsobjekt + Select closed boundary objects to add Markera slutna gränsobjekt att lägga till + Select destination object(s) Markera målobjekt + Select dimension Markera mått + Select dimension to add jog Markera mått att lägga till knäck på + Select dimension to add/remove break Markera mått för att lägga till/ta bort brytning + Select dimensions to space Markera mått att fördela + Select grip to edit array Markera grepp för att redigera arrayen + Select group Markera grupp + Select hatch object Markera skrafferingsobjekt + Select item in array Markera objekt i arrayen + Select jog to remove Markera knäck att ta bort + Select mline Markera multilinje + Select multileader to align to or [Options] Markera multihänvisningslinje att justera mot eller [Alternativ] + Select new datum point Markera ny referenspunkt + Select object on target layer Markera objekt på mållagret + Select object to break dimension Markera objekt som ska bryta måttet + Select object to clip viewport Markera objekt att beskära vyfönstret med + Select object to count or [List/Spaces] Markera objekt att räkna eller [Lista/Blanksteg] + Select objects to add to the group Markera objekt att lägga till i gruppen + Select objects to erase or Markera objekt att radera eller + Select objects to remove from the group Markera objekt att ta bort från gruppen + Select reference objects Markera referensobjekt + Select replacement objects Markera ersättningsobjekt + Select source object Markera källobjekt + Select viewport to clip Markera vyfönster att beskära + Select viewports Markera vyfönster + Sort text top-down? Sortera text uppifrån och ned? + Specify Z scale factor or Ange skalfaktor för Z eller + Specify a fit tolerance Ange en anpassningstolerans + Specify a point on the spline Ange en punkt på splinen + Specify a precision Ange en precision + Specify base point of objects Ange objektens baspunkt + Specify block attachment Ange blockets anslutning + Specify center location override Ange åsidosatt placering för centrum + Specify center of isocircle Ange isocirkelns centrum + Specify center of view box Ange vyrutans centrum + Specify chamfer angle from the first line Ange fasvinkel från första linjen + Specify chamfer length on the first line Ange faslängd på första linjen + Specify change point Ange ändringspunkt + Specify clipping boundary or select invert option Ange beskärningsgräns eller välj alternativet Invertera + Specify collected multileader location or [Vertical/Horizontal/Wrap] Ange placering för samlad multihänvisningslinje eller [Lodrät/Vågrät/Radbryt] + Specify column height Ange kolumnhöjd + Specify control point Ange styrpunkt + Specify direction Ange riktning + Specify direction (first point) Ange riktning (första punkten) + Specify direction (second point) Ange riktning (andra punkten) + Specify direction of chord for arc Ange kordans riktning för bågen + Specify direction of vertex tangent Ange riktning för hörnpunktens tangent + Specify displacement Ange förskjutning + Specify displacement base point Ange baspunkt för förskjutning + Specify distance between columns (|||) Ange avstånd mellan kolumner (|||) + Specify end tangent Ange sluttangent + Specify existing fit point Ange befintlig anpassningspunkt + Specify first break point Ange första brytpunkten + Specify first corner of the unit cell Ange enhetscellens första hörn + Specify first fence point Ange första staketpunkten + Specify first point for arc length dimension Ange första punkten för båglängdsmått + Specify first point for breakline Ange första punkten för brytlinje + Specify first point or [Options] Ange första punkten eller [Alternativ] + Specify fourth point or Ange fjärde punkten eller + Specify gutter width Ange bredd på spaltmellanrum + Specify included angle for arc Ange medelpunktsvinkel för bågen + Specify insertion point of the table Ange tabellens insättningspunkt + Specify jog location Ange placering för knäcken + Specify jog location (or press ENTER) Ange placering för knäcken (eller tryck på ENTER) + Specify leader arrowhead location or [Remove leaders] Ange placering för hänvisningslinjens pilspets eller [Ta bort hänvisningslinjer] + Specify leader start point Ange hänvisningslinjens startpunkt + Specify leaders to remove Ange hänvisningslinjer att ta bort + Specify leaders to remove or [Add leaders] Ange hänvisningslinjer att ta bort eller [Lägg till hänvisningslinjer] + Specify length of line Ange linjens längd + Specify linetype name Ange linjetypens namn + Specify location for break symbol Ange placering för brytsymbol + Specify location of the text Ange textens placering + Specify new angle Ange ny vinkel + Specify new block insertion point Ange blockets nya insättningspunkt + Specify new block rotation angle Ange blockets nya rotationsvinkel + Specify new circle radius Ange cirkelns nya radie + Specify new elevation Ange nytt höjdläge + Specify new fit point Ange ny anpassningspunkt + Specify new height Ange ny höjd + Specify new length Ange ny längd + Specify new linetype scale Ange ny linjetypsskala + Specify new location Ange ny placering + Specify new location for dimension text Ange ny placering för måttal + Specify new point on spline Ange ny punkt på splinen + Specify new text insertion point Ange textens nya insättningspunkt + Specify new thickness Ange ny tjocklek + Specify next fence point Ange nästa staketpunkt + Specify number of columns Ange antal kolumner + Specify other corner Ange andra hörnet + Specify quadrant Ange kvadrant + Specify reference angle Ange referensvinkel + Specify reference length Ange referenslängd + Specify rotation around major axis Ange rotation kring storaxeln + Specify scale factor for XYZ axes Ange skalfaktor för XYZ-axlarna + Specify second point for arc length dimension Ange andra punkten för båglängdsmått + Specify second point for breakline Ange andra punkten för brytlinje + Specify size of view box Ange vyrutans storlek + Specify spacing Ange avstånd + Specify temporary OTRACK point Ange tillfällig OTRACK-punkt + Specify text height Ange texthöjd + Specify the angle between items Ange vinkeln mellan objekten + Specify the angle to fill (+=ccw, -=cw) Ange vinkel att fylla (+=moturs, -=medurs) + Specify the distance between columns (|||) Ange avståndet mellan kolumner (|||) + Specify the incrementing elevation between rows Ange höjdökningen mellan rader + Specify the new angle Ange den nya vinkeln + Specify the pattern origin Ange mönstrets origo + Specify the reference angle Ange referensvinkeln + Specify third point Ange tredje punkten + Specify tolerance Ange tolerans + Specify view twist angle Ange vyns vridningsvinkel + Specify width Ange bredd + Specify zoom scale factor Ange skalfaktor för zoom + Type of boundary object Typ av gränsobjekt + Type something to find Skriv något att söka efter + Use landing Använd anslutningslinje + Verify each name to be purged? Bekräfta varje namn som ska rensas? + Where should the data go? Var ska data hamna? + Word-wrap text? Radbryt text? + Remove objects Ta bort objekt + Select geometry to dimension Markera geometri att måttsätta + Select annotative objects Markera annotativa objekt + Specify total width Ange total bredd + Specify column width Ange kolumnbredd + Specify control point Ange styrpunkt From 9b05dbed437051e34824125abb50d22fc440cc40 Mon Sep 17 00:00:00 2001 From: markmonkey <17867174+markmonkey@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:40:39 +0800 Subject: [PATCH 088/187] Reuse existing drawing tabs when reopening paths --- crates/ui-egui/src/lib.rs | 26 ++++- crates/ui-egui/src/opening.rs | 20 ++++ crates/ui-egui/tests/recent_files.rs | 4 +- crates/ui-egui/tests/reopen_drawing.rs | 153 +++++++++++++++++++++++++ docs/gaps.md | 2 +- docs/ui-parity.md | 4 +- 6 files changed, 204 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/tests/reopen_drawing.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 890732449..29169d945 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -740,7 +740,8 @@ impl CadApp { /// Open the drawing at `path`. Natively the file is read on a worker thread while an /// "Opening ..." card shows ([`opening`]); [`Self::finish_opening`] adds it when ready. On the - /// web it opens at once. + /// web it opens at once. An already open drawing is selected without re-reading it, retaining + /// its unsaved edits and view; window drops and Open Recent use this same entry point. pub fn open_path(&mut self, path: &Path) { // A LISP file (dropped on the window): loaded as APPLOAD loads it. if is_lisp_file(path) { @@ -750,6 +751,9 @@ impl CadApp { } return; } + if self.select_open_drawing(path) { + return; + } #[cfg(not(target_arch = "wasm32"))] { self.opening.start(path); @@ -768,6 +772,10 @@ impl CadApp { /// OPEN is reported. Called every frame. pub fn finish_opening(&mut self) { for (path, outcome) in self.opening.poll() { + // A drawing may have been opened or saved at this path while the read was pending. + if self.select_open_drawing(&path) { + continue; + } // A recent file that is gone can never be opened again: drop it from the list. A path // whose existence can't be checked (a folder that denies access) stays. if outcome.is_err() && matches!(path.try_exists(), Ok(false)) { @@ -785,6 +793,22 @@ impl CadApp { } } + /// Reuse the existing document through the normal tab-switch command, including symlink paths. + fn select_open_drawing(&mut self, path: &Path) -> bool { + let existing = self.session.docs.iter().position(|d| d.path.as_deref().is_some_and(|p| opening::same_path(Path::new(p), path))); + let Some(index) = existing else { return false }; + match self.run("document.switch", json!({"index": index})) { + Ok(_) => { + self.ui.start_tab = false; + if let Some(path) = self.session.docs.get(index).and_then(|d| d.path.clone()) { + self.remember_recent(path); + } + } + Err(error) => self.open_failed(error), + } + true + } + /// Load a LISP file: its routine runs and may wait for the user (APPLOAD typed or from the /// menu runs this way too). fn load_lisp(&mut self, name: &str, text: &str) { diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index d6ae999c8..ba2016781 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -13,6 +13,22 @@ use crate::theme::Tokens; type Outcome = Result; +/// Compare file paths without requiring the file to still exist. Native aliases are resolved so +/// a symlink and its target share a drawing; web paths can only be compared directly. +pub(crate) fn same_path(a: &Path, b: &Path) -> bool { + if a == b { + return true; + } + #[cfg(not(target_arch = "wasm32"))] + { + a.canonicalize().ok().zip(b.canonicalize().ok()).is_some_and(|(a, b)| a == b) + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + struct Job { path: PathBuf, started: Instant, @@ -28,6 +44,10 @@ pub struct Opening { impl Opening { /// Start reading `path` on a worker thread. pub fn start(&mut self, path: &Path) { + // Repeated events can arrive before the first background read completes. + if self.jobs.iter().any(|j| same_path(&j.path, path)) { + return; + } let (tx, rx) = channel(); let p = path.to_path_buf(); let spawned = std::thread::Builder::new().name("cadcraft-open".into()).spawn(move || { diff --git a/crates/ui-egui/tests/recent_files.rs b/crates/ui-egui/tests/recent_files.rs index 34aa6e2e8..a8c3d6a10 100644 --- a/crates/ui-egui/tests/recent_files.rs +++ b/crates/ui-egui/tests/recent_files.rs @@ -70,11 +70,11 @@ fn opened_drawings_are_listed_newest_first_and_survive_a_restart() { let labels: Vec<_> = items.iter().map(|(l, _)| l.as_str()).collect(); assert_eq!(labels, ["plan.dxf", "section.dwg", "Clear Recent Files"]); - // Choosing an item opens that file and moves it to the top. + // Choosing an already open item selects its tab and moves it to the top. let before = app.session.docs.len(); menus::activate(&mut app, &items[1].1); settle(&mut app); - assert_eq!(app.session.docs.len(), before + 1); + assert_eq!(app.session.docs.len(), before); assert_eq!(app.session.state().ok().and_then(|s| s.path.clone()), Some(section.clone())); assert_eq!(app.ui.recent_files, [section.clone(), plan.clone()]); diff --git a/crates/ui-egui/tests/reopen_drawing.rs b/crates/ui-egui/tests/reopen_drawing.rs new file mode 100644 index 000000000..b5554dd20 --- /dev/null +++ b/crates/ui-egui/tests/reopen_drawing.rs @@ -0,0 +1,153 @@ +//! Reopening a path selects the existing drawing, preserving edits, even across Finder events. +#![cfg(not(target_arch = "wasm32"))] + +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::Drawing; +use cadcraft_ui_egui::{CadApp, Services}; +use serde_json::json; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +struct Files(PathBuf); + +impl Files { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!("cadcraft-reopen-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&root).unwrap(); + set_io(IoHooks { read: |_, _| Ok(Drawing::new_metric()), write: |_, _| Ok(Vec::new()), plot: None }); + Self(root) + } + + fn drawing(&self, name: &str) -> PathBuf { + let path = self.0.join(name); + // Synthetic input: the test reader returns an empty drawing for any bytes. + std::fs::write(&path, b"0\nEOF\n").unwrap(); + path + } +} + +impl Drop for Files { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn app() -> CadApp { + CadApp::new(Session::empty(), Services::default()) +} + +fn open(app: &mut CadApp, path: &Path) { + app.open_path(path); +} + +fn settle(app: &mut CadApp) { + let deadline = Instant::now() + Duration::from_secs(10); + while app.opening.busy() { + app.finish_opening(); + assert!(Instant::now() < deadline, "background OPEN did not finish"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn reopening_dwg_and_dxf_preserves_edits_view_and_recent_files() { + let files = Files::new(); + for name in ["检查井 成果.dwg", "管网 检测.dxf"] { + let path = files.drawing(name); + let mut app = app(); + open(&mut app, &path); + settle(&mut app); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let before = app.session.state().unwrap().clone(); + app.run("new", json!({})).unwrap(); + let count = app.session.docs.len(); + app.ui.start_tab = true; + open(&mut app, &path); + assert!(!app.opening.busy(), "an existing drawing must not be re-read"); + let after = app.session.state().unwrap(); + assert_eq!(after.uid, before.uid); + assert_eq!(after.doc, before.doc); + assert_eq!(after.view(), before.view()); + assert_eq!(after.undo.len(), before.undo.len()); + assert!(after.is_dirty()); + assert_eq!(app.session.docs.len(), count); + assert!(!app.ui.start_tab); + assert_eq!(app.ui.recent_files.first().map(String::as_str), path.to_str()); + } +} + +#[test] +fn reopening_a_deleted_file_keeps_the_unsaved_drawing() { + let files = Files::new(); + let path = files.drawing("deleted.dxf"); + let mut app = app(); + open(&mut app, &path); + settle(&mut app); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let uid = app.session.state().unwrap().uid; + std::fs::remove_file(&path).unwrap(); + app.run("new", json!({})).unwrap(); + open(&mut app, &path); + assert!(!app.opening.busy()); + assert_eq!(app.session.state().unwrap().uid, uid); + assert!(app.session.state().unwrap().is_dirty()); +} + +#[test] +fn repeated_requests_while_loading_add_one_tab_per_file() { + let files = Files::new(); + let first = files.drawing("first.dxf"); + let second = files.drawing("second.dwg"); + let mut app = app(); + open(&mut app, &first); + open(&mut app, &first); + open(&mut app, &second); + open(&mut app, &first); + settle(&mut app); + assert_eq!(app.session.docs.len(), 2); + assert!(app.session.docs.iter().any(|d| d.path.as_deref() == first.to_str())); + assert!(app.session.docs.iter().any(|d| d.path.as_deref() == second.to_str())); +} + +#[cfg(unix)] +#[test] +fn symlinks_share_both_pending_reads_and_existing_dirty_tabs() { + let files = Files::new(); + let path = files.drawing("drawing.dxf"); + let alias = files.0.join("alias.dxf"); + std::os::unix::fs::symlink(&path, &alias).unwrap(); + let mut app = app(); + open(&mut app, &path); + open(&mut app, &alias); + settle(&mut app); + assert_eq!(app.session.docs.len(), 1); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let uid = app.session.state().unwrap().uid; + app.run("new", json!({})).unwrap(); + open(&mut app, &alias); + assert!(!app.opening.busy()); + assert_eq!(app.session.docs.len(), 2); + assert_eq!(app.session.state().unwrap().uid, uid); + assert!(app.session.state().unwrap().is_dirty()); +} + +#[test] +fn a_read_finishing_after_the_path_is_opened_keeps_existing_edits() { + let files = Files::new(); + let path = files.drawing("pending.dxf"); + let mut app = app(); + open(&mut app, &path); + // Simulate another OPEN/Save As assigning this path before the UI polls the background read. + app.run("new", json!({})).unwrap(); + app.session.state_mut().unwrap().path = path.to_str().map(str::to_string); + app.run("circle", json!({"center": [1, 2], "radius": 3})).unwrap(); + let uid = app.session.state().unwrap().uid; + settle(&mut app); + assert_eq!(app.session.docs.len(), 1); + assert_eq!(app.session.state().unwrap().uid, uid); + assert!(app.session.state().unwrap().is_dirty()); + assert_eq!(app.session.doc().unwrap().entity_count(), 1); +} diff --git a/docs/gaps.md b/docs/gaps.md index 289f0b4be..d3999acd4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -127,7 +127,7 @@ Detail: [localization-parity.md](localization-parity.md). |---|---|---| | 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: 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 | +| P3 | macOS file associations: opening `.dxf` from Finder fails (#158; Finder-delivery PRs #683, #1347 and #1503 are open) | 1–2 | ## Ecosystem and automation diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1c3bdd3be..facdadd60 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-27 · **Change:** minor (WIPEOUT closure-aware grips; previously: re-audit of the evidence text against main 41d9b5e95: point entry, tracking, Dynamic Input, grips, scripts, views; percentages not re-measured; previously: distinct polyline midpoint grips) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (WIPEOUT closure-aware grips; previously: re-audit of the evidence text against main 41d9b5e95: point entry, tracking, Dynamic Input, grips, scripts, views; percentages not re-measured; previously: distinct polyline midpoint grips; previously: reopening a drawing path selects its existing tab) · **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 @@ -162,6 +162,7 @@ dimensions are edited). |---|---|---| | 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 | +| Reopening an existing drawing through window drop / Open Recent | not re-measured | existing tab; edits, undo and view retained; native symlinks share a tab | | 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) | | Layer Properties Manager (filters, states, VP overrides) | yes | yes | @@ -208,6 +209,7 @@ dimensions are edited). | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Shared path opening reuses existing drawing tabs and pending reads, preserving edits, undo and view | | 2026-10-27 | minor | WIPEOUT grips treat implicit and explicit closure alike; moving the first vertex carries the closing marker, and moving endpoints together keeps both corners editable. Open/closed polyline flags and coincident polyline vertices remain independent (#2256) | | 2026-10-26 | minor | Browser host stores bounded, validated panel layout separately from drawing state; malformed or unsupported records retain defaults. Native workspace storage is unchanged. | | 2026-10-24 | minor | Re-audit against main 41d9b5e95: evidence text for TK and typed snap overrides, PolarSnap, Dynamic Input, hot-grip options, dynamic block grips, SCRIPT, ZOOM Realtime/Dynamic, named views and VPORTS; headline no longer lists selection cycling as missing; the 48% and the area percentages are not re-measured | From 95aefd183d1a530df3b1689276b2edf06d0ce1f1 Mon Sep 17 00:00:00 2001 From: Cody Vogt <18035288+codyvogt@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:27:37 -0600 Subject: [PATCH 089/187] Tests: block references built in tests give the clip main added Co-Authored-By: Claude Opus 5.5 --- crates/io/tests/it/dynblock_array.rs | 1 + crates/io/tests/it/dynblock_params.rs | 2 ++ crates/io/tests/it/dynblock_rotate_flip.rs | 1 + crates/io/tests/it/dynblock_scale_polar.rs | 1 + 4 files changed, 5 insertions(+) diff --git a/crates/io/tests/it/dynblock_array.rs b/crates/io/tests/it/dynblock_array.rs index 0bcba7c64..5903f1c79 100644 --- a/crates/io/tests/it/dynblock_array.rs +++ b/crates/io/tests/it/dynblock_array.rs @@ -38,6 +38,7 @@ fn reference(block: &str) -> (Drawing, Handle) { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); (d, r) diff --git a/crates/io/tests/it/dynblock_params.rs b/crates/io/tests/it/dynblock_params.rs index 78e309dfd..1a3f634df 100644 --- a/crates/io/tests/it/dynblock_params.rs +++ b/crates/io/tests/it/dynblock_params.rs @@ -50,6 +50,7 @@ fn reference_to(block: &str, rotation: f64) -> (Drawing, Handle) { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); (d, r) @@ -274,6 +275,7 @@ fn a_lookup_cell_that_isnt_a_number_is_refused() { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); let before = insert(&d, r).block.clone(); diff --git a/crates/io/tests/it/dynblock_rotate_flip.rs b/crates/io/tests/it/dynblock_rotate_flip.rs index cceef1739..b89efd83e 100644 --- a/crates/io/tests/it/dynblock_rotate_flip.rs +++ b/crates/io/tests/it/dynblock_rotate_flip.rs @@ -47,6 +47,7 @@ fn symbol_from(src: &str) -> (Drawing, Handle) { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); (d, r) diff --git a/crates/io/tests/it/dynblock_scale_polar.rs b/crates/io/tests/it/dynblock_scale_polar.rs index 4cf5e0f58..69f745fd3 100644 --- a/crates/io/tests/it/dynblock_scale_polar.rs +++ b/crates/io/tests/it/dynblock_scale_polar.rs @@ -42,6 +42,7 @@ fn reference(block: &str) -> (Drawing, Handle) { rows: 1, col_spacing: 0.0, row_spacing: 0.0, + clip: None, }; let r = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), EntityKind::Insert(ins)).unwrap(); (d, r) From a0f3f25760026bb7bfd766d9c7af2a14c180a10a Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 18 Nov 2026 04:54:20 +0400 Subject: [PATCH 090/187] i18n(ka): update the Georgian catalog --- crates/ui-egui/src/i18n/ka.tsv | 63 +++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e29940844..a8642b87c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -340,7 +340,7 @@ Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა Explode დაშლა Explode Attributes to Text ატრიბუტების ტექსტად დაშლა - Export ექსპორტი + Export ექსპორტირება Export Table ცხრილის ექსპორტი Export to PDF... PDF-ად ექსპორტი... Express Tools Express Tools @@ -707,8 +707,8 @@ Previous Change წინა ცვლილება Previous Layer წინა შრე Primitives პრიმიტივები - Print დაბეჭდვა - Print... დაბეჭდვა... + Print ბეჭდვა + Print... ბეჭდვა... Properties თვისებები Properties Inspector თვისებების ინსპექტორი Properties: თვისებები: @@ -1242,7 +1242,7 @@ Animation effects ანიმაციის ეფექტები Interface scale ინტერფეისის მასშტაბი Import... იმპორტი... - Export... ექსპორტი... + Export... ექსპორტირება... Batch Publish... პაკეტური გამოქვეყნება... Scale List... მასშტაბების სია... Annotative Object Scale ანოტაციური ობიექტის მასშტაბი @@ -1472,6 +1472,61 @@ menu View ხედი Text to find მოსაძებნი ტექსტი Whole words მთლიანი სიტყვები Nothing found ვერაფერი მოიძებნა + Multiple Insert მრავალჯერადი ჩასმა + Ctrl+Enter to apply გამოსაყენებლად: Ctrl+Enter + Edit Text ტექსტის რედაქტირება + The drawing changed. Close the window and open it again. ნახაზი შეიცვალა. დახურეთ ფანჯარა და ხელახლა გახსენით. + DView დინამიკური ხედი + Raster Image Reference... რასტრული გამოსახულების მიმართვა... + Raster Images რასტრული გამოსახულებები + Clip Xref გარე მიმართვის მოჭრა + Xref გარე მიმართვა + Xref Clip Frame გარე მიმართვის მოჭრის ჩარჩო + Backup copies are off, so the current file will be replaced. სარეზერვო ასლები გამორთულია, ამიტომ მიმდინარე ფაილი ჩანაცვლდება. + DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. DXF 2010 და უფრო ძველი ვერსიები მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. + DXF keeps them. Use Save As to keep them in the drawing. DXF მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. + Save Anyway მაინც შენახვა + Save cancelled: {path} was not changed. შენახვა გაუქმდა: {path} არ შეცვლილა. + Saving {name} will remove content ფაილში {name} შენახვისას შიგთავსის ნაწილი წაიშლება + The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. მიმდინარე ფაილი არასრული ჩანს, ამიტომ {name} უცვლელი რჩება, მიმდინარე ფაილი კი ჩანაცვლდება. + The current file is kept as {name} until the next save. მიმდინარე ფაილი შემდეგ შენახვამდე შენარჩუნდება სახელით {name}. + This format can't keep these objects yet: {objects}. ეს ფორმატი ამ ობიექტებს ჯერ ვერ ინახავს: {objects}. + {count} more types კიდევ {count} ტიპი # ArtCraft feature naming Additional Tools დამატებითი ხელსაწყოები + +# Keyboard Shortcuts, Right-Click Customization, alias import + 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-ის საკუთარზე. ცვლილებები მაშინვე მოქმედებს და შემდეგი ჯერისთვისაც ინახება. + Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. გამორთვისას ბრძანების შესრულების დროს მარჯვენა დაწკაპება იმას აკეთებს, რაც „მარჯვენა დაწკაპების მორგებაში“ ბრძანების რეჟიმისთვის არის არჩეული. + 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 კონტექსტური მენიუ: ჩართული, როცა ბრძანებას ვარიანტები აქვს + Import: there is no file dialog here; run ALIASEDIT with the file's contents using its text parameter. იმპორტი: აქ ფაილის არჩევის დიალოგი არ არის; გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს. + Aliases are saved in your CADCraft profile and survive restarts. ფსევდონიმები თქვენს CADCraft-ის პროფილში ინახება და გადატვირთვის შემდეგაც რჩება. + Import… იმპორტი… + Run ALIASEDIT with the file's contents using its text parameter. გაუშვით ALIASEDIT და ფაილის შიგთავსი გადაეცით მის text პარამეტრს. + Importing a file replaces your {n} aliases, and any changes not applied yet. ფაილის იმპორტი ჩაანაცვლებს თქვენს ფსევდონიმებს ({n}) და ჯერ გამოუყენებელ ცვლილებებს. + Import and replace იმპორტი და ჩანაცვლება + Keep my aliases ჩემი ფსევდონიმების შენარჩუნება + {n} more warnings; see the command line. კიდევ {n} გაფრთხილება; იხილეთ ბრძანების სტრიქონი. From b84f6a89946d690081db0847d75fcbf0cf8f0a83 Mon Sep 17 00:00:00 2001 From: Davit Matchakhelidze Date: Wed, 18 Nov 2026 04:55:22 +0400 Subject: [PATCH 091/187] i18n(ka): leave the rows of #2900 to that PR --- crates/ui-egui/src/i18n/ka.tsv | 28 ++++------------------------ 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a8642b87c..51f461c81 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -340,7 +340,7 @@ Exclude from new selection set ახალი მონიშნულიდან გამორიცხვა Explode დაშლა Explode Attributes to Text ატრიბუტების ტექსტად დაშლა - Export ექსპორტირება + Export ექსპორტი Export Table ცხრილის ექსპორტი Export to PDF... PDF-ად ექსპორტი... Express Tools Express Tools @@ -707,8 +707,8 @@ Previous Change წინა ცვლილება Previous Layer წინა შრე Primitives პრიმიტივები - Print ბეჭდვა - Print... ბეჭდვა... + Print დაბეჭდვა + Print... დაბეჭდვა... Properties თვისებები Properties Inspector თვისებების ინსპექტორი Properties: თვისებები: @@ -1242,7 +1242,7 @@ Animation effects ანიმაციის ეფექტები Interface scale ინტერფეისის მასშტაბი Import... იმპორტი... - Export... ექსპორტირება... + Export... ექსპორტი... Batch Publish... პაკეტური გამოქვეყნება... Scale List... მასშტაბების სია... Annotative Object Scale ანოტაციური ობიექტის მასშტაბი @@ -1472,26 +1472,6 @@ menu View ხედი Text to find მოსაძებნი ტექსტი Whole words მთლიანი სიტყვები Nothing found ვერაფერი მოიძებნა - Multiple Insert მრავალჯერადი ჩასმა - Ctrl+Enter to apply გამოსაყენებლად: Ctrl+Enter - Edit Text ტექსტის რედაქტირება - The drawing changed. Close the window and open it again. ნახაზი შეიცვალა. დახურეთ ფანჯარა და ხელახლა გახსენით. - DView დინამიკური ხედი - Raster Image Reference... რასტრული გამოსახულების მიმართვა... - Raster Images რასტრული გამოსახულებები - Clip Xref გარე მიმართვის მოჭრა - Xref გარე მიმართვა - Xref Clip Frame გარე მიმართვის მოჭრის ჩარჩო - Backup copies are off, so the current file will be replaced. სარეზერვო ასლები გამორთულია, ამიტომ მიმდინარე ფაილი ჩანაცვლდება. - DXF 2010 and earlier keep them. Use Save As to keep them in the drawing. DXF 2010 და უფრო ძველი ვერსიები მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. - DXF keeps them. Use Save As to keep them in the drawing. DXF მათ ინახავს. ნახაზში მათ შესანარჩუნებლად გამოიყენეთ „შენახვა როგორც“. - Save Anyway მაინც შენახვა - Save cancelled: {path} was not changed. შენახვა გაუქმდა: {path} არ შეცვლილა. - Saving {name} will remove content ფაილში {name} შენახვისას შიგთავსის ნაწილი წაიშლება - The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. მიმდინარე ფაილი არასრული ჩანს, ამიტომ {name} უცვლელი რჩება, მიმდინარე ფაილი კი ჩანაცვლდება. - The current file is kept as {name} until the next save. მიმდინარე ფაილი შემდეგ შენახვამდე შენარჩუნდება სახელით {name}. - This format can't keep these objects yet: {objects}. ეს ფორმატი ამ ობიექტებს ჯერ ვერ ინახავს: {objects}. - {count} more types კიდევ {count} ტიპი # ArtCraft feature naming Additional Tools დამატებითი ხელსაწყოები From 8725cc48b2f5648391fc81727fbc0dc228c59c2d Mon Sep 17 00:00:00 2001 From: Patrik Lermon Date: Thu, 19 Nov 2026 10:21:05 +0100 Subject: [PATCH 092/187] i18n(sv): translate 172 new strings Brings the Swedish catalog up to date with upstream main (a770fa5a). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/sv.tsv | 173 ++++++++++++++++++++++++++++++++- 1 file changed, 172 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e31643871..557cd6dfa 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1560,7 +1560,6 @@ menu Modify Ändra Workspace Arbetslayout Settings Inställningar Preferences Inställningar - Refresh Uppdatera Current: Aktuell: Continuous Kontinuerlig Displayed layers Visade lager @@ -2048,3 +2047,175 @@ menu Modify Ändra Specify total width Ange total bredd Specify column width Ange kolumnbredd Specify control point Ange styrpunkt +